Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat: add attended remote control and refine shared viewing (#482)

AAA24e9b639a8f1
diff --git a/.agents/skills/context-consistency/SKILL.md b/.agents/skills/context-consistency/SKILL.md
index c750fbe4..90f90e8d 100644
--- a/.agents/skills/context-consistency/SKILL.md
+++ b/.agents/skills/context-consistency/SKILL.md
@@ -1,10 +1,9 @@
---
name: context-consistency
description: >
- Review repeated meanings across Piik code, UI, copy, lifecycle and documentation.
- Use for cross-surface or cross-layer consistency work, recurring fixes in sibling
- paths, and requested repository-wide standardization audits. Locate common
- ownership gaps while preserving differences justified by context.
+ Trace shared meanings and owners across Piik code, UI, copy and lifecycle.
+ Use for cross-surface consistency work, recurring sibling-path defects or
+ repository standardization audits; not every isolated edit.
---
# Context Consistency
@@ -31,7 +30,7 @@ stand in for coverage. Review-only work must not alter product sources.
## Trace Before Comparing
Follow a concrete producer through state/normalization, effects, consumers and
-cleanup. Record the subject, asserted fact or requested outcome, authority,
+cleanup. Establish the subject, asserted fact or requested outcome, authority,
scope/generation, lifetime and user intent. Use a small comparison table only
when there are multiple variants to compare.
@@ -55,7 +54,8 @@ When fixes are authorized, choose the smallest coherent correction at the
existing owner and update its reachable consumers. Share implementation where
the semantics and lifetime match; use narrow adapters for real runtime or
presentation differences. A similar name or repeated syntax is not sufficient
-reason to merge states or introduce a generic manager.
+reason to merge states or introduce a generic manager. Visual consistency
+preserves meaning and interaction without forcing every scene into one template.
If the intended semantics are unresolved, put that decision in
[TODO](../../../docs/todo.md) and continue independent checks. Do not turn a
diff --git a/.agents/skills/ponytail/SKILL.md b/.agents/skills/ponytail/SKILL.md
index 02c0712c..2f6a3ce4 100644
--- a/.agents/skills/ponytail/SKILL.md
+++ b/.agents/skills/ponytail/SKILL.md
@@ -1,120 +1,75 @@
---
name: ponytail
description: >
- Forces the laziest solution that actually works, simplest, shortest, most
- minimal. Channels a senior dev who has seen everything: question whether the
- task needs to exist at all (YAGNI), reach for the standard library before
- custom code, native platform features before dependencies, one line before
- fifty. Supports intensity levels: lite, full (default), ultra. Use on ANY
- coding task: writing, adding, refactoring, fixing, reviewing, or designing
- code, and choosing libraries or dependencies. Also use whenever the user
- says "ponytail", "be lazy", "lazy mode", "simplest solution", "minimal
- solution", "yagni", "do less", or "shortest path", or complains about
- over-engineering, bloat, boilerplate, or unnecessary dependencies. Do NOT
- use for non-coding requests (general knowledge, prose, translation,
- summaries, recipes).
-argument-hint: "[lite|full|ultra]"
+ Choose the smallest coherent implementation for Piik coding, code review,
+ refactoring and implementation design, including dependency choices.
+ Also use when Ponytail or YAGNI is requested; not for ordinary prose or status.
license: MIT
---
-# Ponytail
+# Ponytail · Piik
-You are a lazy senior developer. Lazy means efficient, not careless. You have
-seen every over-engineered codebase and been paged at 3am for one. The best
-code is the code never written.
+Reduce what Piik must own while delivering the complete requested experience.
+This is an implementation method under [AGENTS.md](../../../AGENTS.md), not
+permission to reduce scope or defer design. The repo adaptation and license are
+documented in [UPSTREAM.md](./UPSTREAM.md).
-## Persistence
+## Understand The Responsibility
-ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if
-unsure. Off only: "stop ponytail" / "normal mode". Default: **full**.
-Switch: `/ponytail lite|full|ultra`.
+Read the affected owner and actual flow before choosing a solution. Establish
+the user outcome, state/resource lifetime and consumers that must keep working.
+For a bug, trace where the incorrect fact or action first arises and check
+sibling callers of that owner. Correct that boundary instead of adding a guard
+to each symptom. A shared guard is useful only if it restores the real contract.
-## The ladder
+For UI, inspect the existing interaction and visual primitives before adding a
+control, panel, status or animation. A reused component must still have the
+right meaning, placement and lifecycle; reuse alone does not establish design
+quality. Different responsibilities need not look or behave identically.
-Stop at the first rung that holds:
+## Choose The Smallest Coherent Design
-1. **Does this need to exist at all?** Speculative need = skip it, say so in one line. (YAGNI)
-2. **Already in this codebase?** A helper, util, type, or pattern that already lives here → reuse it. Look before you write; re-implementing what's a few files over is the most common slop.
-3. **Stdlib does it?** Use it.
-4. **Native platform feature covers it?** `<input type="date">` over a picker lib, CSS over JS, DB constraint over app code.
-5. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do.
-6. **Can it be one line?** One line.
-7. **Only then:** the minimum code that works.
+Use this order to find a sufficient solution, not as a mandatory research tour:
-The ladder is a reflex, not a research project — but it runs *after* you
-understand the problem, not instead of it. Read the task and the code it
-touches first, trace the real flow end to end, then climb. Two rungs work →
-take the higher one and move on. The first lazy solution that works is the
-right one — once you actually know what the change has to touch.
+1. Remove speculative additions that the requested outcome does not need.
+2. Reuse the existing owner, component or helper when its semantics and lifetime fit.
+3. Prefer standard-library, native-platform or already-installed capabilities.
+4. Use a mature dependency when it reduces total ownership more than custom code.
+5. Implement the remaining behavior in a cohesive module with a narrow interface.
-**Bug fix = root cause, not symptom.** A report names a symptom. Before you
-edit, grep every caller of the function you're about to touch. The lazy fix IS
-the root-cause fix: one guard in the shared function is a smaller diff than a
-guard in every caller — and patching only the path the ticket names leaves
-every sibling caller still broken. Fix it once, where all callers route through.
+Compare user effort, state, dependencies and maintenance, not just lines or file
+count. A larger correction is justified when it removes competing writers or
+finishes the affected flow. Keep readable code and clear boundaries rather than
+compressing logic into a one-liner or one oversized file.
-## Rules
+Add an abstraction, setting or extension point only for a current responsibility,
+real consumer or accepted contract. Do not build scaffolding for hypothetical
+features. Preserve necessary platform adapters; a single implementation alone
+does not prove an interface is wasteful. Inspect existing protections before
+removing them, and preserve authorization, data integrity, accessibility and
+published compatibility.
-- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes.
-- No boilerplate, no scaffolding "for later", later can scaffold for itself.
-- Deletion over addition. Boring over clever, clever is what someone decodes at 3am.
-- Fewest files possible. Shortest working diff wins — but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug.
-- Complex request? Ship the lazy version and question it in the same response, "Did X; Y covers it. Need full X? Say so." Never stall on an answer you can default.
-- Two stdlib options, same size? Take the one that's correct on edge cases. Lazy means writing less code, not picking the flimsier algorithm.
-- Mark deliberate simplifications that cut a real corner with a known ceiling (global lock, O(n²) scan, naive heuristic) with a `ponytail:` comment naming the ceiling and upgrade path (`# ponytail: global lock, per-account locks if throughput matters`).
+Comment non-obvious constraints and reasons at their owner. Avoid slogans,
+restated code or speculative upgrade plans in comments. Remove replaced private
+paths within scope; keep useful provenance and required license notices.
-## Output
+## Verify And Finish
-Code first. Then at most three short lines: what was skipped, when to add it.
-No essays, no feature tours, no design notes. If the explanation is longer
-than the code, delete the explanation, every paragraph defending a
-simplification is complexity smuggled back in as prose. Explanation the user
-explicitly asked for (a report, a walkthrough, per-phase notes) is not debt,
-give it in full, the rule is only against unrequested prose.
+Verify the requested behavior at the affected boundary using the project's
+existing checks. New mechanisms need evidence for their actual success,
+failure and lifecycle behavior; a test for each branch or helper is not the
+goal. Use [Stop That Shit](../stop-that-shit/SKILL.md) to keep verification
+proportionate; required checks and delivery remain in
+[CONTRIBUTING.md](../../../CONTRIBUTING.md).
-Pattern: `[code] → skipped: [X], add when [Y].`
+Check the result against the intended experience and remove unnecessary
+additions. Report the outcome, meaningful evidence and material limits at the
+detail the user needs. Do not ship an easier subset as completion or impose a
+fixed response length.
-## Intensity
+## Optional Intensity
-| Level | What change |
-|-------|------------|
-| **lite** | Build what's asked, but name the lazier alternative in one line. User picks. |
-| **full** | The ladder enforced. Stdlib and native first. Shortest diff, shortest explanation. Default. |
-| **ultra** | YAGNI extremist. Deletion before addition. Ship the one-liner and challenge the rest of the requirement in the same breath. |
-
-Example: "Add a cache for these API responses."
-- lite: "Done, cache added. FYI: `functools.lru_cache` covers this in one line if you'd rather not own a cache class."
-- full: "`@lru_cache(maxsize=1000)` on the fetch function. Skipped custom cache class, add when lru_cache measurably falls short."
-- ultra: "No cache until a profiler says so. When it does: `@lru_cache`. A hand-rolled TTL cache class is a bug farm with a hit rate."
-
-## When NOT to be lazy
-
-Never simplify away: input validation at trust boundaries, error handling
-that prevents data loss, security measures, accessibility basics, anything
-explicitly requested. User insists on the full version → build it, no
-re-arguing.
-
-Never lazy about understanding the problem. The ladder shortens the
-solution, never the reading. Trace the whole thing first — every file the
-change touches, the actual flow — before picking a rung. Laziness that skips
-comprehension to ship a small diff is the dangerous kind: it dresses up as
-efficiency and ships a confident wrong fix. Read fully, then be lazy.
-
-Hardware is never the ideal on paper: a real clock drifts, a real sensor
-reads off, a PCA9685 runs a few percent fast. Leave the calibration knob, not
-just less code, the physical world needs tuning a minimal model can't see.
-
-Lazy code without its check is unfinished. Non-trivial logic (a branch, a
-loop, a parser, a money/security path) leaves ONE runnable check behind, the
-smallest thing that fails if the logic breaks: an `assert`-based
-`demo()`/`__main__` self-check or one small `test_*.py`. No frameworks, no
-fixtures, no per-function suites unless asked. Trivial one-liners need no
-test, YAGNI applies to tests too.
-
-## Boundaries
-
-Ponytail governs what you build, not how you talk (pair with Caveman for
-terse prose). "stop ponytail" / "normal mode": revert. Level persists until
-changed or session end.
-
-The shortest path to done is the right path.
+Default **full** applies the method above. If requested, **lite** focuses on the
+scoped implementation and obvious reuse; **ultra** more aggressively removes
+unnecessary ownership within that scope. These levels change simplification
+effort, never the requested result, design quality, authority or verification.
diff --git a/.agents/skills/ponytail/UPSTREAM.md b/.agents/skills/ponytail/UPSTREAM.md
index ef123a89..59bfa855 100644
--- a/.agents/skills/ponytail/UPSTREAM.md
+++ b/.agents/skills/ponytail/UPSTREAM.md
@@ -3,6 +3,9 @@
[Ponytail](https://github.com/DietrichGebert/ponytail) by DietrichGebert, pinned to
[`974d940a1c5344210874150b98ff0d2c861fab6a`](https://github.com/DietrichGebert/ponytail/tree/974d940a1c5344210874150b98ff0d2c861fab6a).
-`SKILL.md` is the unmodified `skills/ponytail/SKILL.md` from that revision;
-`LICENSE` is its unmodified root MIT license. The skill has no required local
-references. Upstream plugins, hooks, examples, and other skills are not vendored.
+`SKILL.md` adapts `skills/ponytail/SKILL.md` from that revision to Piik's project
+authority, design standard and proportionate verification. It keeps reuse and
+root-cause simplicity, without forced session modes, shortened deliverables,
+fixed response limits or per-branch test requirements. `LICENSE` remains the
+unmodified upstream MIT license. Upstream plugins, hooks, examples and other
+skills are not vendored.
diff --git a/.agents/skills/stop-that-shit/SKILL.md b/.agents/skills/stop-that-shit/SKILL.md
index 64e84c53..fef94f86 100644
--- a/.agents/skills/stop-that-shit/SKILL.md
+++ b/.agents/skills/stop-that-shit/SKILL.md
@@ -1,11 +1,9 @@
---
name: stop-that-shit
description: >
- Keep Piik work proportionate and finish the requested result. Apply during
- implementation, debugging and review, especially when speculative defenses,
- repeated testing, compatibility scaffolding, research loops or cautious
- narration displace useful progress. Also use when the user invokes Stop That
- Shit or asks to remove overengineering.
+ Keep Piik implementation, debugging and review proportionate and complete.
+ Use to control speculative defenses, research or verification loops, and
+ when Stop That Shit or removal of overengineering is requested.
license: MIT
---
@@ -17,23 +15,21 @@ Piik 是供朋友分享的小项目。优先简单、好用、漂亮和实际效
不要按假想的百万级规模设计,不要追求覆盖一切极端情况、无限兼容或零风险。
复杂度、验证时间和维护负担都是真实成本。用户已经授权的合理工作,应当推进到可用结果。
-这是用户要求的提炼,也是本地工作尺度。与 [Ponytail](../ponytail/SKILL.md) 一起使用;
-新方法、新机制必须完整验证其实际行为。减负针对重复测试和无用防御,不降低验证质量。
-[AGENTS.md](../../../AGENTS.md) 和 [CONTRIBUTING.md](../../../CONTRIBUTING.md)
-继续拥有权限、产品约束和交付流程。
+这是工作尺度与收口方法;[Ponytail](../ponytail/SKILL.md) 负责实现取舍。
+[AGENTS.md](../../../AGENTS.md) 规定权限与设计质量,
+[CONTRIBUTING.md](../../../CONTRIBUTING.md) 规定交付流程。
+新方法、新机制必须完整验证实际行为。减负不降低体验、审美或验证质量。
## 直接执行
-- **先理解,再动手。** 沿实际调用链找到错误最早出现的位置,在现有职责内修复。
- 已有代码、标准库、平台或依赖能完成就复用。允许改够必要的地方,不以最少行数牺牲根因修复。
- **让研究产生实现。** 参考相关的一手实现,选出简单、可逆的方案就做对照。
一旦信息足够做决定,停止搜集同类材料。上游也有问题不等于只能接受;检查现有配置、
- 接口和小范围补丁。不能证明绝对安全,不是停止一个已授权实验的理由。
+ 接口和小范围补丁。研究或审查任务仍按其授权范围交付,不自动变成实现。
- **防御放在真实边界。** 保留鉴权、外部输入校验和必要的资源释放;内部已验证事实直接使用。
- 不逐层重复校验,不用空值、假成功或静默兜底掩盖错误。新增重试、状态、开关或限制必须
- 对当前可达问题有作用;“以后可能用上”“以防万一”不构成理由。
-- **兼容只服务现有承诺。** 按已发布的兼容约定处理真实消费者;不为废弃实验、未发布旧代码
- 或想象中的客户端保留双读写、别名和迁移层。不要把内部实现变化一律升级成协议问题。
+ 不逐层重复校验,不用空值、假成功或静默兜底掩盖错误。现有保护的用途不明时先追踪,
+ 不能凭“没出过事”删除。新增重试、状态、开关或限制要解决实际问题或已承诺的边界,
+ 不必等到事故发生,也不为假想规模或未来消费者铺路。兼容承诺由
+ [版本规范](../../../docs/standards/versioning.md) 决定。
- **新机制要验完整。** 沿实际调用链验证预期效果及受影响的主路径,覆盖相关的失败、恢复
和生命周期行为;不能用一个 happy path 或孤立单测宣称完成。复用现有检查和复现,缺口
补有效回归。小文案、布局和可逆低影响改动不默认新增单元测试;不为每个分支、私有函数
@@ -45,7 +41,8 @@ Piik 是供朋友分享的小项目。优先简单、好用、漂亮和实际效
不留注释代码、停用分支、过渡接口或长篇历史说明。仅用于本次调查的探针留在 ignored
工作目录;值得长期保留的事实更新现有文档所有者,不再建一套审计账本。
- **交付有用结果。** 已授权的必要工作继续做,不停在计划、风险清单或“可以继续”。
- 功能完成、相关检查通过且没有已知阻断就收口;真正受阻时说明具体缺口和已尝试的方法。
+ 请求的体验与职责完整、相关检查通过且没有已知阻断就收口;不能以“能跑”代替验收。
+ 真正受阻时说明具体缺口和已尝试的方法。
不把未知说成已解决,也不把所有未知都变成发布门槛。汇报结果和影响决定的限制即可,
不用测试数量、长免责声明、反复道歉或未来待办替代成果。
@@ -60,12 +57,5 @@ Piik 是供朋友分享的小项目。优先简单、好用、漂亮和实际效
这些是做判断的尺度,不要求为它们生成清单、报告或新工具。
-## 参考与取舍
-
-2026-10-16 查阅;以下经验结合项目需求独立整理,社区反馈是案例,不是模型效果的统计证明。
-
-- [Stop That Shit](https://github.com/lennney/stop-that-shit/blob/0.2.4/skills/stop-that-shit/SKILL.md):额外动作须有当前用途,任务要完成,验证循环要结束。
-- [STSS](https://github.com/lennney/stop-that-shit/blob/0.2.4/skills/stss/SKILL.md):只保留影响读者决定的限定,减少自我辩护。
-- [Avoid Over-Defensive Programming](https://github.com/aravelo7/codex-agent-skills/blob/main/skills/avoid-overdefensive-programming/SKILL.md):修正错误源头,避免假成功和静默兜底;不引入其逐分支报告流程。
-- [Ponytail](../ponytail/SKILL.md):复用现成能力,选最小正确实现;新机制验证完整,已回答的问题及时收口。
-- [社区案例:小任务膨胀](https://www.reddit.com/r/codex/comments/1vf5elq/how_do_you_stop_codexclaude_from_overengineering/)与[重复实现和返工](https://www.reddit.com/r/codex/comments/1ujnwxb/codex_quality_issues_in_realworld_coding_ignored/):检查实际 diff 与交付价值,避免用更多流程治理过多流程。
+参考来源与取舍保留在[上下文治理研究](../../../docs/research/agent-context-governance.md#instructions-and-skills),
+不作为每次任务必读材料。
diff --git a/AGENTS.md b/AGENTS.md
index 289adab3..a00fdac9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,18 +1,31 @@
# Project Instructions
+## Aesthetic And Design Standard
+
+Apply these constraints and relevant skills throughout every conversation turn,
+feature and action. Piik requires a polished experience and clear engineering:
+high aesthetic standards cover UI, interaction, functional boundaries, lifecycle
+and code. Working behavior alone is insufficient. Preserve the product's intent,
+usability, coherence, maintainability and appropriate extensibility.
+
+Before changing behavior or presentation, establish the intended user flow,
+state/resource owner, lifecycle and what would demonstrate a complete result.
+Inspect existing components and mature approaches, then choose the simplest
+coherent design that meets those needs. Simplicity must not discard requested
+functionality, visual quality or necessary safety. Design and verify at the
+scale of the change; routine design choices within an authorized task need no
+separate design document or approval.
+Detailed criteria stay in [visual language](./docs/standards/visual-language.md)
+and [engineering](./docs/standards/engineering.md).
+
## Authority And Scope
-- Read and follow the complete repo-tracked
- [`ponytail` skill](./.agents/skills/ponytail/SKILL.md) before coding, review,
- or design work. It is required guidance for the smallest correct result;
- project authority and delivery constraints remain owned here.
-- Apply Piik's [Stop That Shit](./.agents/skills/stop-that-shit/SKILL.md) to
- implementation, debugging and review. Verify new mechanisms completely at
- the affected boundaries; remove speculative defenses and repeated checks
- that add no evidence. Proportionate work must still deliver the full result.
- Within higher-priority instructions, the latest explicit user decision defines
the task. Review, research, implementation, deployment, and cleanup grant only
the authority inherent in that task type.
+- This file owns project-wide constraints; linked standards own domain rules,
+ CONTRIBUTING owns delivery, and skills supply task methods. A skill, reference
+ example or audit suggestion cannot override those owners or authorize extra work.
- Model recovery from the smallest underlying authority and connection state.
Restart, crash, timeout, and network loss do not justify parallel states or
case-specific fallbacks when their required action is the same.
@@ -21,9 +34,20 @@
stage the requested files. Use the full integration/release path only for an
explicitly requested release or a material contract, route/security,
infrastructure, persistence, or irreversible change.
-- Until a public release is explicitly declared, keep one current internal
- contract. Delete replaced wire/config/API surfaces; do not add compatibility
- aliases, dual readers/writers, migrations, or tests for stale private clients.
+
+## Required Skills
+
+Read each applicable skill completely before using it. Reuse that understanding
+until the task or instructions change; adherence does not require reloading or
+reciting every rule each turn. Use the repo-linked versions below when a global
+skill has the same name. Other skills apply only to matching tasks or explicit
+invocation; follow their relevant guidance without importing unrelated workflows.
+
+| When | Skill and responsibility |
+| --- | --- |
+| Coding, code review, or implementation design | [Ponytail](./.agents/skills/ponytail/SKILL.md): smallest coherent implementation and reuse |
+| Implementation, debugging, or review | [Stop That Shit](./.agents/skills/stop-that-shit/SKILL.md): proportionate investigation, verification and complete delivery |
+| Cross-surface consistency, recurring sibling-path defects, or standardization audits | [Context consistency](./.agents/skills/context-consistency/SKILL.md): trace shared meanings and ownership; ordinary changes check only their affected family |
## Product Contract
@@ -89,8 +113,6 @@
one owned [contextual contract](./docs/standards/engineering.md#contextual-consistency).
Check related producers and consumers before adding another local rule;
preserve differences justified by authority, scope or user intent.
- Use the [consistency review skill](./.agents/skills/context-consistency/SKILL.md)
- for cross-cutting consistency work; ordinary changes check the affected family.
- UI changes must follow the shared [visual language](./docs/standards/visual-language.md):
cast, semantic colours, result panels and motion have one owner. Extend the
existing preview when adding a new meaning; do not invent scene-local rules.
@@ -100,7 +122,8 @@
does not need; total complexity matters more than marginal performance gains.
- [Versioning](./docs/standards/versioning.md) separates build identity, wire,
storage and live generations, and owns the public compatibility design.
- The declared public release is the compatibility baseline for subsequent work.
+ Preserve published compatibility promises; remove replaced private experiments
+ without aliases, dual readers/writers or migrations for stale private clients.
- Use primary sources for non-trivial design and bugs. Add focused tests in
proportion to risk; batch full browser/network/endurance checks at acceptance.
- Keep scripts deterministic, fast, cross-platform and CI-runnable.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c2c785f8..62c1a150 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -35,7 +35,7 @@ accurately, without attributing independently written code to a PR author.
This is the default for an ordinary scoped implementation or bug fix.
-1. Start from the canonical repository root on a clean, current `main`; preserve unrelated user work.
+1. Start a new phase from clean, current canonical `main`; continue scoped work in that phase's existing worktree. Preserve unrelated user work.
2. Inspect the affected code, current owner, and reachable evidence. Research primary sources only when the issue is non-trivial or component behavior is uncertain.
3. Make the smallest coherent change under the repo-tracked [`ponytail` skill](./.agents/skills/ponytail/SKILL.md).
4. Run the focused tests or checks that exercise the changed behavior, inspect the pending diff, stage requested files, and report the result and evidence.
diff --git a/README.md b/README.md
index fb865ebe..0c200409 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,7 @@ on your own server.
- **Direct connections first.** Media travels between participants where possible (P2P). A self-hosted server can provide automatic media forwarding (SFU) as a fallback.
- **Rooms you control.** Invitations, room codes and optional room passwords, for one host and up to 20 viewers.
- **Chat while watching.** Send messages and reactions to friends, with optional on-screen chat.
+- **Hand control to a friend.** When sharing through Piik App, optionally let one viewer use your keyboard and mouse, and take control back at any time.
- **Flexible viewing.** Light and dark themes, playback controls, picture-in-picture and a connection topology view.
- **One program to host a site.** Web UI, room management and optional media forwarding are packaged together.
@@ -59,7 +60,6 @@ you can also create a room in the online version.
| --- | --- |
| [Use Piik online](https://demo.piik.tv) | Share from a desktop browser, or choose Camera on a phone with browser camera support. |
| [Download Piik App](https://piik.tv/#download) | Extract and open the App, choose **Public invite**, then **Open Piik** to create a temporary room. |
-| [Host your own site](./docs/operations/self-hosting.md) | Advanced: deploy Piik Server on a Linux x64 or ARM64 server with your own domain, then connect through Piik App or a browser. |
<p align="center"><img src="./docs/assets/quickstart.svg" width="640" alt="Choose a screen, send an invitation, watch together."></p>
@@ -94,6 +94,11 @@ link and the online version, may not connect on restrictive networks.
## Self-hosting
+To run a site for your group, deploy Piik Server. App users can start with
+public invitations without a server of their own.
+
+<p><a href="./docs/operations/self-hosting.md#docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&amp;logo=docker&amp;logoColor=white" alt="Deploy Piik with Docker Compose"></a></p>
+
Piik Server is a standalone binary with the web interface built in.
Download the Server package for Linux x64 (`piik-<revision>-runtime.tar.gz`)
or ARM64 (`piik-<revision>-linux-arm64-runtime.tar.gz`),
@@ -120,3 +125,17 @@ See [ways to contribute](./CONTRIBUTING.md#ways-to-help) or
Piik-owned code is [MIT licensed](./LICENSE). Dependencies retain their own
[licenses and notices](./licenses/README.md).
+
+## Project activity
+
+<p align="center">
+ <a href="https://trendshift.io/repositories/236065"><img src="https://trendshift.io/api/badge/trendshift/repositories/236065/daily?language=TypeScript" width="250" alt="Piik on Trendshift"></a>
+</p>
+<p align="center">
+ <a href="https://www.star-history.com/#TNTcraftHIM/Piik&amp;Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=TNTcraftHIM/Piik&amp;type=Date&amp;theme=dark">
+ <img src="https://api.star-history.com/svg?repos=TNTcraftHIM/Piik&amp;type=Date" width="760" alt="Piik GitHub star history">
+ </picture>
+ </a>
+</p>
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 35226e5d..a80c5de4 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -34,6 +34,7 @@ Piik 是一个免费开源的私密屏幕共享工具,适合游戏直播、一
- **优先直接连接。** 画面优先在设备之间传输(P2P),自建站点可启用媒体转发(SFU)自动兜底。
- **房间由你管理。** 支持邀请链接、房间号和可选的房间密码,一位房主、最多 20 位观众。
- **边看边聊。** 发送文字、和朋友互送表情,也可开启弹幕。
+- **让朋友接手操作。** 通过 Piik App 分享时,可选择让一位观众操作键鼠,随时结束控制。
- **灵活的观看方式。** 支持深浅主题、播放控制、画中画和连接拓扑查看。
- **一个程序就能建站。** 网页、房间管理和可选的媒体转发打包在同一服务端程序中。
@@ -55,7 +56,6 @@ Piik 是一个免费开源的私密屏幕共享工具,适合游戏直播、一
| --- | --- |
| [使用在线版](https://demo.piik.tv) | 用电脑浏览器分享画面;手机浏览器支持摄像头访问时,也可选择摄像头分享。 |
| [下载 Piik App](https://piik.tv/?lang=zh-CN#download) | 解压并启动 Piik App,选择**公网邀请**,点击**进入 Piik**,创建临时房间。 |
-| [部署自己的站点](./docs/operations/self-hosting.zh-CN.md) | 进阶使用:在 Linux x64 或 ARM64 服务器上部署 Piik Server、配置自己的域名,再用 Piik App 或浏览器连接。 |
<p align="center"><img src="./docs/assets/quickstart.svg" width="640" alt="选择画面,发送邀请,一起观看。"></p>
@@ -87,6 +87,10 @@ Piik App 的公网邀请和在线版使用纯 P2P 连接,
## 自行部署
+想为朋友搭建站点时,再部署 Piik Server。使用 App 的公网邀请,无须自行部署服务器。
+
+<p><a href="./docs/operations/self-hosting.zh-CN.md#使用-docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&amp;logo=docker&amp;logoColor=white" alt="使用 Docker Compose 部署 Piik"></a></p>
+
Piik Server 是一个内置网页界面的独立程序。
根据服务器架构下载 Linux x64 的 `piik-<revision>-runtime.tar.gz` 或 ARM64 的
`piik-<revision>-linux-arm64-runtime.tar.gz`,解压后运行:
@@ -111,3 +115,17 @@ Piik Server 是一个内置网页界面的独立程序。
## 许可
Piik 自有代码采用 [MIT 许可](./LICENSE),依赖保留各自的[许可与声明](./licenses/README.md)。
+
+## 项目动态
+
+<p align="center">
+ <a href="https://trendshift.io/repositories/236065"><img src="https://trendshift.io/api/badge/trendshift/repositories/236065/daily?language=TypeScript" width="250" alt="Piik 的 Trendshift 趋势"></a>
+</p>
+<p align="center">
+ <a href="https://www.star-history.com/#TNTcraftHIM/Piik&amp;Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=TNTcraftHIM/Piik&amp;type=Date&amp;theme=dark">
+ <img src="https://api.star-history.com/svg?repos=TNTcraftHIM/Piik&amp;type=Date" width="760" alt="Piik GitHub 星标增长趋势">
+ </picture>
+ </a>
+</p>
diff --git a/cmd/piik-app/README.md b/cmd/piik-app/README.md
index 7634d81f..fd816db2 100644
--- a/cmd/piik-app/README.md
+++ b/cmd/piik-app/README.md
@@ -7,9 +7,10 @@ interface in your system Browser.
## Run A Package
-Extract the matching platform bundle in full and keep `runtime` beside the
-App executable. Run `piik-app.exe` on Windows, `./piik-app` on
-Linux, or `Piik App.app` on macOS. The launcher opens in the system Browser.
+Extract the matching platform bundle in full. On Windows and Linux, keep
+`runtime` beside the App executable and run `piik-app.exe` or `./piik-app`.
+On macOS, open `Piik App.app`; you can move the whole `.app` to Applications.
+The launcher opens in the system Browser.
Linux native capture uses the system dependencies described
in the [Linux capture guide](../../native/capture/linux/README.md).
@@ -215,7 +216,8 @@ The result is a ZIP bundle and SHA-256 file. Manual sidecar assembly,
explicit CI packaging, Release publication and updates are documented in
[deployment](../../docs/deployment.md); creating a candidate does not publish it.
-The extracted bundle contains:
+The App runtime contains the following files. On macOS they live inside
+`Piik App.app/Contents/MacOS`; move the whole `.app` when installing it.
```text
piik-app[.exe]
@@ -241,8 +243,9 @@ The Windows App embeds the shared Piik mark through the
`cmd/piik-app/piik_windows_amd64.syso` resource; the platform
suffix keeps that Windows resource out of Linux and macOS builds.
Linux packages include the standard `share/applications` desktop entry and
-hicolor icon. macOS packages include a thin `Piik App.app` launcher
-with an ICNS resource; the raw Go executable remains available beside it.
+hicolor icon. macOS packages include `Piik App.app` with an ICNS resource,
+the App executable and its helpers. For terminal use, the executable is
+`"Piik App.app/Contents/MacOS/piik-app"`.
The editable badge is [public/favicon.svg](../../public/favicon.svg).
Export it at 16/24/32/48/64/128/256 px as PNG entries in `cmd/piik-app/piik.ico`;
diff --git a/cmd/piik-app/README.zh-CN.md b/cmd/piik-app/README.zh-CN.md
index d9abcc55..d6e9a064 100644
--- a/cmd/piik-app/README.zh-CN.md
+++ b/cmd/piik-app/README.zh-CN.md
@@ -6,8 +6,9 @@ Piik App 通过系统浏览器中的 Piik 网页界面,提供本地房间与
## 运行程序包
-完整解压对应平台的程序包,保留 App 程序旁的 `runtime` 目录。
-Windows 运行 `piik-app.exe`,Linux 运行 `./piik-app`,macOS 打开 `Piik App.app`。
+完整解压对应平台的程序包。Windows 和 Linux 保留 App 程序旁的 `runtime` 目录,
+分别运行 `piik-app.exe` 或 `./piik-app`。
+macOS 打开 `Piik App.app`,也可以将整个 `.app` 移到「应用程序」。
启动页会在系统浏览器中打开。Linux 原生采集所需的系统依赖见
[Linux 采集指南](../../native/capture/linux/README.md)。
@@ -172,7 +173,8 @@ Darwin 组装需要原生 macOS runner 与 SDK,并启用 cgo;Windows 与 Lin
结果是 ZIP 程序包和 SHA-256 文件。手动组装辅助程序、显式 CI 打包、Release 发布与更新,
见[部署与发布](../../docs/deployment.md);创建候选包不会将它发布。
-解压后的目录包含:
+App 运行目录包含以下文件。macOS 下它们位于
+`Piik App.app/Contents/MacOS`,安装时移动整个 `.app` 即可。
```text
piik-app[.exe]
@@ -194,7 +196,8 @@ App 与站点之间的互操作遵循[公开兼容规则](../../docs/standards/v
Windows App 通过 `cmd/piik-app/piik_windows_amd64.syso` 资源内嵌共享的 Piik 标识;
平台后缀使该 Windows 资源不参与 Linux 和 macOS 构建。
Linux 程序包包含标准的 `share/applications` 桌面入口与 hicolor 图标。
-macOS 程序包包含一个带 ICNS 资源的轻量 `Piik App.app` 启动器,原始 Go 程序仍保留在它旁边。
+macOS 的 `Piik App.app` 包含 ICNS 图标、App 程序及其辅助程序。
+需要从终端运行时,入口为 `"Piik App.app/Contents/MacOS/piik-app"`。
图标源文件为 [public/favicon.svg](../../public/favicon.svg)。
将它按 16/24/32/48/64/128/256 px 导出为 PNG 图层,写入 `cmd/piik-app/piik.ico`;
diff --git a/cmd/piik-app/piik.ico b/cmd/piik-app/piik.ico
index 1a92ce56..cef7ad44 100644
Binary files a/cmd/piik-app/piik.ico and b/cmd/piik-app/piik.ico differ
diff --git a/cmd/piik-app/piik_windows_amd64.syso b/cmd/piik-app/piik_windows_amd64.syso
index f3fedd72..5e87bb15 100644
Binary files a/cmd/piik-app/piik_windows_amd64.syso and b/cmd/piik-app/piik_windows_amd64.syso differ
diff --git a/docs/assets/room-en-dark.png b/docs/assets/room-en-dark.png
index 6512a779..8587f75d 100644
Binary files a/docs/assets/room-en-dark.png and b/docs/assets/room-en-dark.png differ
diff --git a/docs/assets/room-en-light.png b/docs/assets/room-en-light.png
index a674d138..07dc73c6 100644
Binary files a/docs/assets/room-en-light.png and b/docs/assets/room-en-light.png differ
diff --git a/docs/assets/room-zh-dark.png b/docs/assets/room-zh-dark.png
index 0ea23b1f..4b0adb45 100644
Binary files a/docs/assets/room-zh-dark.png and b/docs/assets/room-zh-dark.png differ
diff --git a/docs/assets/room-zh-light.png b/docs/assets/room-zh-light.png
index 20dce42a..bf333277 100644
Binary files a/docs/assets/room-zh-light.png and b/docs/assets/room-zh-light.png differ
diff --git a/docs/deployment.md b/docs/deployment.md
index 9d523c9d..4e45ff1e 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -85,9 +85,14 @@ native runner. Server builds for both Linux architectures remain cgo-free.
The platform package also carries its native presentation metadata: Windows
embeds the icon in the Go executable, Linux emits a freedesktop desktop entry
-under `share/`, and macOS emits a thin `.app` launcher with an ICNS resource.
-The latter two are packaging metadata only and do not duplicate the App
-executable.
+under `share/`, and macOS emits a self-contained `.app` with an ICNS resource.
+The macOS `CFBundleExecutable` names the real Mach-O App binary in
+`Contents/MacOS`; its relative `runtime/`, license notices and `REVISION` live
+beside it. Moving the `.app` must retain every runtime dependency. This follows
+[Apple's bundle relocation guidance](https://developer.apple.com/forums/thread/724969)
+and avoids a shell entry that reaches outside the bundle. Package checks execute
+the extracted entry and helpers; Finder/Gatekeeper and desktop permissions still
+need macOS acceptance.
CI and local release-candidate builds use the same wrapper on the target's
native operating system:
diff --git a/docs/guide/README.md b/docs/guide/README.md
index 7fb1cec6..2ac042ab 100644
--- a/docs/guide/README.md
+++ b/docs/guide/README.md
@@ -30,6 +30,8 @@ with your version, system, browser and reproduction steps. The
## Run a site for your group
+<p><a href="../operations/self-hosting.md#docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&amp;logo=docker&amp;logoColor=white" alt="Deploy Piik Server with Docker Compose"></a></p>
+
Self-hosting is an advanced option requiring a server, domain and network configuration.
- [Deploy Piik Server](../operations/self-hosting.md) with Docker Compose or the server package.
diff --git a/docs/guide/README.zh-CN.md b/docs/guide/README.zh-CN.md
index 8063179b..14221972 100644
--- a/docs/guide/README.zh-CN.md
+++ b/docs/guide/README.zh-CN.md
@@ -30,6 +30,8 @@
## 为朋友搭建站点
+<p><a href="../operations/self-hosting.zh-CN.md#使用-docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&amp;logo=docker&amp;logoColor=white" alt="使用 Docker Compose 部署 Piik Server"></a></p>
+
自部署属于进阶操作,需要服务器、域名和网络配置。
- [部署 Piik Server](../operations/self-hosting.zh-CN.md):使用 Docker Compose 或服务端程序包。
diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md
index 54bf109b..a976d643 100644
--- a/docs/guide/getting-started.md
+++ b/docs/guide/getting-started.md
@@ -7,7 +7,7 @@ watching, using Piik online, using Piik App and sharing through an existing site
[Join a room](#join-a-friends-room) · [Use online](#use-piik-online) ·
[Piik App](#share-with-piik-app) · [Existing site](#share-from-an-existing-site) ·
-[Chat and reactions](#chat-and-reactions) ·
+[Remote control](#let-a-friend-control-your-shared-screen) · [Chat and reactions](#chat-and-reactions) ·
[Troubleshooting](#when-something-gets-in-the-way)
Viewers need a browser and an invitation. To start sharing, download Piik App
@@ -21,7 +21,7 @@ and choose **Public invite**. To share without installing, open
3. Move the pointer over the picture or tap it to show the playback bar.
The playback bar controls only your own picture and sound.
-On a computer, click the picture to pause or resume; double-click to enter or
+Use the playback button to pause or resume; on a computer, double-click the picture to enter or
leave fullscreen where supported. On a phone, tap the picture to show the bar
and use its buttons. Safari may show system controls in video fullscreen.
@@ -31,9 +31,10 @@ and use its buttons. Safari may show system controls in video fullscreen.
| Control | What it does |
| --- | --- |
| **Theater mode** | Expands the picture inside the browser tab. |
-| **Fullscreen** | Uses the full screen while keeping the picture's proportions; black bars can remain when they differ from your screen. |
+| **Fullscreen** | Expands the picture to the full screen. |
| **Picture in picture** | Opens a floating video where supported. |
| **Volume** | Goes up to 200% with audio boost, or 100% otherwise. Lower it if the sound distorts. |
+| **Playback settings** | **Fit** keeps the whole picture visible; **Fill** crops its edges; **Stretch** fills the area by changing its proportions. Connection settings default to **Auto**; available alternatives depend on the host and site. |
</details>
@@ -76,9 +77,10 @@ restrictive networks may load the page but block video.
**Screens** as available. Pick the actual source and sound option.
5. Copy and send the room invitation. Keep both the App and sharing tab open.
-When the launcher offers an update, **Release notes** opens its details on GitHub
-or Gitee. A new major version includes a compatibility warning; read the upgrade
-instructions before replacing your App.
+Click the launcher's update button to download the new App. **Gitee mirror**
+provides an alternative if the download is slow or unavailable. A new major
+version includes a compatibility warning that links to the upgrade instructions;
+read them before replacing your App.
| Filename contains | Platform |
| --- | --- |
@@ -109,10 +111,16 @@ also keeps an **App launcher** address. To change between Local room and Public
invite, close and reopen the App, then choose again. This ends the previous room
and generates a new public-invitation address.
-**Already have a Piik site?** Keep the App running, open the site and click
-**App** at the top. Check the address on the local confirmation page, then choose
-**Allow access**. Enter any site passphrase on the site itself. Allow local-network
-access if the browser asks. No room mode needs to be selected in the launcher.
+### Use App with an existing site
+
+1. Keep Piik App running and open the Piik site in your browser. Enter its site
+ passphrase if asked; [Piik online](https://demo.piik.tv) needs no site passphrase.
+ No room mode needs to be selected in the App launcher.
+2. Click **App** at the top. Allow local-network access if the browser asks.
+3. Check the site address on the local confirmation page, then choose **Allow access**.
+4. Return to the site, choose **Start sharing**, then **Apps / Windows** or **Screens**.
+ Select a source and send the new room invitation to your friends.
+
You can also choose **Connect Piik App** inside the **Start sharing** source
selector; its list updates as soon as the connection completes.
If connection fails, the App button offers **Retry** and **Download App**.
@@ -139,8 +147,10 @@ The [App guide](../../cmd/piik-app/README.md#modes) explains the connection setu
### Upgrading
-**Piik 2.0 and 1.x cannot be used together.** The App and the site it connects to
-need the same major version. Read the release notes on
+**Piik 2.x and 1.x cannot be used together.** The App and the site it connects to
+need the same major version. Different 2.x versions preserve established sharing
+and viewing; new features require support from the relevant App and site.
+Read the release notes on
[GitHub](https://github.com/TNTcraftHIM/Piik/releases/latest) or
[Gitee](https://gitee.com/TNTcraftHIM/Piik/releases) before upgrading.
@@ -173,16 +183,17 @@ Screen capture requires an HTTPS site or `localhost`. The sources and audio
offered by the picker depend on your browser and operating system.
Invitation links grant access to that room; share them with the people you want there.
-To use App capture on that same site, follow [Connect to Site](#choose-an-app-mode).
+To use App capture on that same site, follow [Use App with an existing site](#use-app-with-an-existing-site).
The site manages rooms and invitations; the App supplies native capture.
If its operator has enabled SFU forwarding, turn off **Privacy mode** before
sharing to allow that fallback. The project's online site uses P2P only.
## Picture and sound settings
-Open **Sharing settings** below the picture to adjust picture and audio quality.
+Open **Sharing settings** below the picture. Picture presets are directly available;
+expand **Fine-tune picture** for resolution, frame-rate, bitrate, picture preference and video codec.
-- Choose a picture preset, or enter width and height under **Resolution limit**.
+- In **Fine-tune picture**, enter width and height under **Resolution limit**.
Piik preserves the source's proportions within that ceiling, including portrait
and ultrawide pictures.
- Sliders cover 15–60 fps in steps of 5 and 2–12 Mbps in steps of 0.5. You can also enter an
@@ -191,7 +202,9 @@ Open **Sharing settings** below the picture to adjust picture and audio quality.
selects the nearest available slider value.
The frame-rate limit depends
on picture size: for example, 1080p240, 1440p144 and 4K60 are accepted requests.
-- Choose an audio preset, or enter an **Audio bitrate limit** from 6 to 320 kbps.
+- Under **Sound**, adjust source audio and microphone input. **Audio quality**
+ controls the shared audio output: choose a preset or enter an **Audio bitrate limit**
+ from 6 to 320 kbps.
The selectable range depends on picture size and the connected App. Picture and sound
still adapt to the source, device and available bandwidth.
@@ -203,7 +216,7 @@ when your public-invite address changes.
## Add your voice
While sharing, select **Microphone** below the picture and
-allow microphone access. Select it again to mute. Open **Settings → Sound** below the picture
+allow microphone access. Select it again to mute. Open **Sharing settings → Sound** below the picture
to choose a microphone and adjust its input volume.
The default volume is 100%, with up to 200% available.
Source audio and your voice reach viewers together. The Host preview stays muted.
@@ -227,6 +240,10 @@ then select the virtual audio input in Piik's microphone list and turn on the mi
### Exclude a voice app from screen audio
+On Windows, this control applies to system sound from **Screens**. **Apps / Windows**
+captures only the selected application's process tree; **Camera** uses the separately
+selected microphone or audio input.
+
On supported Windows Apps, open the **Screens** tab and enable **System sound**.
Under **Exclude application audio**, select a window belonging to the voice app,
then choose the screen to share. Open the app's window and refresh if it is absent.
@@ -250,22 +267,66 @@ Windows 10 support depends on system updates and the actual capability check.
If the option is absent, share a single application window or route the voice
app to a different playback device.
+## Let a friend control your shared screen
+
+1. Share through Piik App using **Apps / Windows** or **Screens**.
+2. Open **Remote control** below the picture and turn it on. It starts with
+ **Ask each time**.
+3. Your friend selects **Request control** in their playback bar. Choose
+ **Allow control** on your sharing page when their request arrives.
+
+When sharing a window, switch back to that window after allowing control. Input
+pauses while another window is active and resumes when you return.
+
+One viewer can control at a time, using a desktop or mobile browser. Update the
+host's App and the room's site, then refresh the viewing page. The control button
+appears when the host enables control and the connection supports it. Browser
+and camera capture cannot receive remote input.
+
+Either person can choose **End control**. On the host's computer, **Ctrl+Alt+F10**
+on Windows or **Control+Option+F10** on macOS also stops control. Changing the
+shared source or stopping sharing turns remote control off. After a connection
+interruption, the viewer requests control again.
+
+On a phone, swipe to move the pointer, tap to click and hold to drag. Two-finger
+tap is right-click; two-finger swipe scrolls. Pinch to zoom, then use two fingers
+to move around the enlarged picture. **Remote keyboard** provides keys,
+shortcuts and text input. On a computer, **Game mouse** captures continuous
+mouse movement; press **Esc** to release it.
+
+<details>
+<summary>Permissions and platform support</summary>
+
+**Room Viewers** allows a room member to take idle control without asking each
+time; **Password** requires a separate control password. These choices apply
+only to the current shared source. Control gives access to the computer's mouse
+and keyboard, so allow people you trust. It is not limited to what is visible
+inside the video.
+
+macOS asks for Accessibility permission. Linux needs a supported desktop Portal
+and currently controls a selected screen, not an application window. Windows
+is the primary physically tested host; macOS/Linux device acceptance is still
+limited. System-protected shortcuts and some games may not accept remote input.
+
+</details>
+
## Chat and reactions
-Once the host starts the first share, participants can select **Chat** below the
+Once the host starts the first share, participants can select **Interact** below the
sofa to send messages. Select a person on the sofa to open their reaction menu:
your own reactions appear above you; reactions sent to a friend fly towards them.
-The chat window can be moved and resized without rearranging the page.
+The interaction window can be moved and resized without rearranging the page.
-Supported desktop browsers show **Always-on-top chat** in the window's top-right
-corner, so you can read messages while playing. Keep the Piik page open; closing
-the small window returns chat to the page. Use a windowed or borderless game;
-exclusive fullscreen may cover the chat. The window cannot show the game through
-its background or let mouse clicks pass through.
+Supported desktop browsers show **Open in always-on-top window** in its top-right
+corner. You can read messages, see reactions and select someone to interact with
+while playing. Keep the Piik page open; closing the small window returns it to the page.
+Use a windowed or borderless game; exclusive fullscreen may cover the window.
+The window cannot show the game through its background or let mouse clicks pass through.
**On screen**, beside the message box or in the viewer's playback bar, shows new
messages over the picture. It is off by default and only changes your own view.
-Open **Chat settings** in the chat window to adjust text size and opacity.
+Adjust text size and opacity in **Playback settings → On-screen chat**, or in
+the chat window's **Chat settings**. Both use the same local preferences.
System video fullscreen and picture in picture cannot show these overlays.
Stopping a share keeps the room's chat available. App Local and Public invite
diff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.md
index 375d58cf..fa289aa8 100644
--- a/docs/guide/getting-started.zh-CN.md
+++ b/docs/guide/getting-started.zh-CN.md
@@ -7,7 +7,7 @@ Piik 支持一位房主分享屏幕,最多 20 位受邀观众通过浏览器
[加入房间](#加入朋友的房间) · [在线版](#使用在线版) ·
[Piik App](#用-piik-app-分享) · [已有站点](#使用已有站点分享) ·
-[聊天与表情](#聊天与表情) · [问题排查](#遇到问题了)
+[远程控制](#让朋友操作共享的电脑) · [聊天与表情](#聊天与表情) · [问题排查](#遇到问题了)
观众只需要浏览器和邀请链接。
分享画面推荐下载 Piik App,选择 **公网邀请**。
@@ -20,7 +20,7 @@ Piik 支持一位房主分享屏幕,最多 20 位受邀观众通过浏览器
3. 将鼠标移到画面上,或轻点画面,显示播放控制栏。
播放控制栏只改变你自己看到的画面和听到的声音。
-电脑上单击画面可暂停或继续,双击可进入或退出全屏(浏览器支持时)。
+点击播控栏的按钮可暂停或继续;电脑上双击画面可进入或退出全屏(浏览器支持时)。
手机上轻点画面唤出控制栏,再使用其中的按钮。Safari 的视频全屏可能使用系统播控。
<details>
@@ -29,9 +29,10 @@ Piik 支持一位房主分享屏幕,最多 20 位受邀观众通过浏览器
| 按钮 | 作用 |
| --- | --- |
| **剧场模式** | 在浏览器标签页内展开画面。 |
-| **全屏观看** | 全屏显示并保持原始比例;画面与屏幕比例不同时会留边。 |
+| **全屏观看** | 将画面展开至全屏。 |
| **悬浮小窗** | 浏览器支持时,把视频放进独立小窗。 |
| **音量** | 支持增强时最高 200%,否则最高 100%;声音失真时调低一些。 |
+| **播放设置** | **完整显示** 保留全部画面;**等比铺满** 会裁掉边缘;**拉伸铺满** 会改变比例。连接设置默认为 **自动**,可选线路取决于房主和站点。 |
</details>
@@ -69,8 +70,8 @@ App 的本地房间和临时公网邀请会随本次 App 退出而结束。
然后选定要分享的画面与声音。
5. 复制房间邀请发给朋友。分享期间保持 App 和分享标签页打开。
-启动页提示更新时,可点击 **版本说明** 查看 GitHub 或 Gitee 上的详情。
-跨大版本更新会显示兼容性提醒;替换 App 前,请先阅读升级说明。
+点击启动页的更新按钮即可下载新版 App;下载慢或无法下载时,可使用下方的 **Gitee 备用下载**。
+跨大版本更新会显示兼容性提醒,点击提醒可查看升级说明;替换 App 前,请先阅读。
| 文件名包含 | 适用平台 |
| --- | --- |
@@ -97,9 +98,15 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)
App 终端也保留 **App 启动页** 地址。更换本地房间/公网邀请模式时,关闭并重新打开 App 后选择。
这会结束原有房间,公网邀请地址也会重新生成。
-**已经有 Piik 站点?** 保持 App 运行,打开站点,点击顶部的 **App**。
-在本机确认页核对网址,点击 **允许使用**。如果站点要求口令,在站点页面输入。
-浏览器询问本地网络权限时,请允许访问。启动页无需选择房间模式。
+### 通过已有站点使用 App
+
+1. 保持 Piik App 运行,在浏览器打开 Piik 站点。如果站点要求口令,先输入口令;
+ 项目提供的[在线版](https://demo.piik.tv)无需站点口令。App 启动页无需选择房间模式。
+2. 点击站点顶部的 **App**。浏览器询问本地网络权限时,请允许访问。
+3. 在本机确认页核对站点网址,点击 **允许使用**。
+4. 返回站点,点击 **开始分享**,选择 **程序 / 窗口** 或 **屏幕**,
+ 选好来源后,将新房间的邀请链接发给朋友。
+
也可以在 **开始分享** 的选源窗口里点击 **连接 Piik App**,连接后列表会直接显示 App 来源。
连接失败时,App 按钮旁会提供 **重试** 和 **下载 App**;仍可继续使用浏览器分享和观看。
@@ -119,7 +126,8 @@ App 终端也保留 **App 启动页** 地址。更换本地房间/公网邀请
### 版本升级
-**Piik 2.0 与 1.x 不能混用。** App 与连接的站点需要使用同一大版本。
+**Piik 2.x 与 1.x 不能混用。** App 与连接的站点需要使用同一大版本。
+不同 2.x 版本保留已有的分享和观看功能;新功能需要相关 App 与站点支持。
升级前,请先查看 [GitHub](https://github.com/TNTcraftHIM/Piik/releases/latest) 或
[Gitee](https://gitee.com/TNTcraftHIM/Piik/releases) 上的版本说明。
@@ -146,22 +154,24 @@ App 终端也保留 **App 启动页** 地址。更换本地房间/公网邀请
弹窗里有哪些画面和声音可选,取决于浏览器与操作系统。
拿到邀请链接的人可以进入这个房间,请把它发给你想邀请的人。
-想在同一站点使用 App 采集,可按[连接站点](#选择-app-模式)的步骤操作。
+想在同一站点使用 App 采集,可按[通过已有站点使用 App](#通过已有站点使用-app)的步骤操作。
站点负责房间与邀请,App 提供原生采集。
如果管理员已启用 SFU 转发,房主可在开始分享前关闭 **隐私模式**,允许使用这条兜底线路。
项目提供的在线版仅使用 P2P。
## 画面与声音设置
-在画面下方打开 **分享设置**,调整画质和音频质量。
+在画面下方打开 **分享设置**,可直接选择画质预设;
+展开 **画面细调**,再调整分辨率、帧率、码率、画面偏好和视频编码。
-- 可选画质预设,也可在 **分辨率上限** 中填写宽和高。画面在上限内保留来源比例,
+- 在 **画面细调** 的 **分辨率上限** 中填写宽和高。画面在上限内保留来源比例,
包括竖屏和超宽屏。
- 滑块覆盖 15–60 帧(每步 5 帧)、2–12 Mbps(每步 0.5 Mbps)的常用范围;也可直接填写 1–240 帧的 **帧率上限**
和 0.1–240 Mbps 的 **视频码率上限**。
不在滑块档位上的数值显示为 **自定义**;点击 **返回常用范围**,使用最近的可用档位。
帧率范围随画幅变化,例如可以请求 1080p240、1440p144 或 4K60。
-- 音频保留三档预设,也可填写 6–320 kbps 的 **音频码率上限**。
+- **声音** 下可调整来源声音和麦克风输入;**音频质量** 调整分享输出,
+ 可选择预设,也可填写 6–320 kbps 的 **音频码率上限**。
可选范围会随画幅和连接的 App 变化。实际画质和声音仍会根据来源、设备与可用带宽调整。
@@ -171,7 +181,7 @@ Piik 会记住已应用的设置,供下次使用。仅用浏览器时,设置
## 加上自己的声音
分享时,点击画面下方的 **麦克风**,并允许访问。
-再次点击即可静音。在画面下方的 **设置 → 声音** 中可以选择麦克风和调节输入音量,默认 100%,最高可调至 200%。
+再次点击即可静音。在画面下方的 **分享设置 → 声音** 中可以选择麦克风和调节输入音量,默认 100%,最高可调至 200%。
观众会同时听到来源声音和你的解说;房主本机预览保持静音。
摄像头分享不会自动开启麦克风。App 的 **程序 / 窗口** 和 **屏幕** 采集也使用同一组控件,
@@ -189,6 +199,9 @@ Piik 会记住已应用的设置,供下次使用。仅用浏览器时,设置
### 分享屏幕时排除语音软件的声音
+在 Windows 上,此控件用于 **屏幕** 分享的系统声音。**程序 / 窗口** 只采集所选应用及其子进程的声音;
+**摄像头** 的声音来自单独选择的麦克风或音频输入。
+
在支持此功能的 Windows App 中,打开 **屏幕** 页签并开启 **系统声音**,
在 **排除应用声音** 中选择语音软件的窗口,再选择要分享的屏幕。
未列出的应用请先打开窗口,再刷新。此功能排除所选进程及其子进程,
@@ -205,18 +218,51 @@ Piik 会记住已应用的设置,供下次使用。仅用浏览器时,设置
此控件需要新版页面和通过进程排除能力检测的 Windows App,不适用于浏览器自带的分享选择器。
Windows 10 是否支持取决于系统更新与实际检测;未显示此选项时,可改为分享单个应用窗口,或将语音软件输出到另一播放设备。
+## 让朋友操作共享的电脑
+
+1. 通过 Piik App 的 **程序 / 窗口** 或 **屏幕** 开始分享。
+2. 打开画面下方的 **远程控制** 并开启开关,默认使用 **每次询问**。
+3. 朋友在播放控制栏中点击 **请求控制**。收到请求后,在自己的分享页面选择 **允许控制**。
+
+分享窗口时,允许控制后请切回该窗口。其他窗口处于前台时,远程输入会暂停;切回即可继续。
+
+同一时间只能有一位观众控制,可使用电脑或手机浏览器。更新房主的 App 和房间所在站点后,
+观众刷新页面即可。房主开启远控、连接支持后,观众才会看到控制按钮。
+浏览器和摄像头采集不支持接收远程操作。
+
+双方都可以点击 **结束控制**。房主还可以在本机按 **Ctrl+Alt+F10**(Windows)
+或 **Control+Option+F10**(macOS)立即结束。切换来源或停止分享会关闭远控;
+连接中断后,观众需要重新请求。
+
+手机上滑动可移动鼠标,轻点点击、长按拖动;双指轻点右击、滑动滚动。
+捏合可以放大画面,放大后用双指移动查看位置。**远程键盘** 提供按键、组合键和文字输入。
+电脑上可开启 **游戏鼠标** 连续转动视角,按 **Esc** 释放鼠标。
+
+<details>
+<summary>授权与平台支持</summary>
+
+**房间观众** 允许房间内的观众直接取得空闲控制权;**控制密码** 要求输入单独设置的控制密码。
+这些设置只对当前分享来源有效。允许控制后,对方可以操作这台电脑的鼠标和键盘,
+请只授权给信任的人;操作范围不受视频画面边界限制。
+
+macOS 需要允许「辅助功能」权限。Linux 需要桌面环境支持 Portal,目前只支持控制所选屏幕,
+不支持单个应用窗口。Windows 是主要经过实机验证的房主平台,macOS/Linux 的设备验收仍有限。
+受系统保护的快捷键和部分游戏可能无法接收远程输入。
+
+</details>
+
## 聊天与表情
-房主首次开始分享、创建房间后,参与者可以点击沙发下方的 **聊天** 发送消息。
+房主首次开始分享、创建房间后,参与者可以点击沙发下方的 **互动** 发送消息。
点击沙发上的人物可打开表情菜单:给自己发的表情出现在头顶,送给朋友的表情会飞向对方。
-聊天窗口可以移动和缩放,不会挤动页面。
+互动窗口可以移动和缩放,不会挤动页面。
-支持的桌面浏览器会在窗口右上角显示 **置顶聊天窗口**,方便切到游戏时看消息。
-保持 Piik 页面打开;关闭小窗会把聊天收回页面。建议游戏使用窗口或无边框模式,
+支持的桌面浏览器会在窗口右上角显示 **在置顶窗口中打开**,方便玩游戏时看消息、接收表情,
+也可以在小窗中选人互动。保持 Piik 页面打开;关闭小窗会将它收回页面。建议游戏使用窗口或无边框模式,
独占全屏不保证显示置顶窗。小窗目前不支持透出游戏画面或鼠标穿透。
输入框旁和观众播放控制栏中的 **弹幕** 可以把新消息显示在画面上,默认关闭,只影响自己的观看。
-打开聊天窗口中的 **聊天设置**,可以调整弹幕字号和不透明度。
+通过 **播放设置 → 弹幕** 或聊天窗口中的 **聊天设置** 调整字号和不透明度,两处共用本机设置。
系统视频全屏和画中画无法显示弹幕。
停止分享后仍可继续聊天;App 的本地房间和公网邀请需要保持 App 运行。
diff --git a/docs/guide/translating.md b/docs/guide/translating.md
index a19e7b70..cb9f97e3 100644
--- a/docs/guide/translating.md
+++ b/docs/guide/translating.md
@@ -73,6 +73,10 @@ claims. A cultural reference should still make sense to someone unfamiliar with
Machine-assisted drafts need proofreading by someone who understands the language
and the screen; raise unclear source text in the PR instead of guessing.
+App startup failures share reason codes between the launcher and console. Translate
+their user-facing explanations in both catalogs; keep error codes and raw technical
+details unchanged so reports remain useful for diagnosis.
+
Locale files are TypeScript objects. These are existing examples:
```ts
diff --git a/docs/guide/translating.zh-CN.md b/docs/guide/translating.zh-CN.md
index 08552a5d..52c77809 100644
--- a/docs/guide/translating.zh-CN.md
+++ b/docs/guide/translating.zh-CN.md
@@ -54,6 +54,9 @@ App 连接远程站点时使用站点提供的界面,因此该站点的网页
性能、平台、连接条件等限制应保留原意。梗和彩蛋应让不懂出处的人也能理解。
机器辅助翻译需要由理解目标语言和使用场景的人校对;原文本身有歧义时,在 PR 中说明。
+App 启动错误在网页和终端之间共用原因代码。请在两处词库中翻译用户说明;错误码和
+原始技术详情保持不变,方便根据报告定位问题。
+
语言文件使用 TypeScript 对象。下面是现有的一组内容:
```ts
diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md
index 280a9dad..020e04f3 100644
--- a/docs/guide/troubleshooting.md
+++ b/docs/guide/troubleshooting.md
@@ -23,14 +23,14 @@ collect a diagnostic report if the problem persists.
| HDR picture looks too bright or washed out | On Windows, try App capture or temporarily turn off HDR; see [HDR capture](#hdr-picture-looks-too-bright-or-washed-out). |
| Yellow outline around the shared window or screen | This is Windows' capture indicator. See [capture borders](#yellow-capture-border-on-windows) for Windows 11 controls and an optional Windows 10 workaround. |
| Picture but no source sound | Unmute the video. The host should choose a source with shareable audio and enable sound in the source picker. Camera video and audio inputs are selected separately; see [audio settings](./getting-started.md#add-your-voice). |
-| Cannot hear the host's voice | The host can enable **Microphone** below the picture, then check the selected input and its volume in **Settings → Sound**. Check the device connection and microphone permission. If the control is unavailable, update the App and refresh the page. |
+| Cannot hear the host's voice | The host can enable **Microphone** below the picture, then check the selected input and its volume in **Sharing settings → Sound**. Check the device connection and microphone permission. If the control is unavailable, update the App and refresh the page. |
| Screen sharing includes a voice app's audio | Windows App screen capture can [exclude application audio](./getting-started.md#exclude-a-voice-app-from-screen-audio). This does not remove echo from speakers picked up by a microphone. |
| Virtual microphone has echo, or remains audible when muted in Piik | Temporarily turn off **System sound** to compare. A mixer's playback can enter source audio separately from Piik's microphone; check its [audio routing](./getting-started.md#exclude-a-voice-app-from-screen-audio). |
| Page opens but video will not connect | Use **Reconnect** if available, or refresh the viewing page. See [connection troubleshooting](#when-video-will-not-connect) if it still fails. |
| WebRTC or IP-leak protection is enabled | Check whether it blocks media connections using [browser WebRTC settings](#browser-webrtc-restrictions). |
| Connection fails on a campus or restricted network | Compare with a phone hotspot, then consider a [site with SFU forwarding](#campus-networks-and-strict-nat). |
| Picture repeatedly blurs, stutters or stops | Identify who is affected, then follow [picture quality and interruption checks](#picture-blurs-stutters-or-stops). |
-| Phone fullscreen has black bars, or the button does not work | Video keeps its proportions; try landscape orientation and the playback bar's **Fullscreen** button. System video fullscreen depends on the browser. See [viewing controls](./getting-started.md#join-a-friends-room). |
+| Phone fullscreen has black bars, or the button does not work | Video keeps its proportions by default. Try landscape orientation, or choose **Fill** or **Stretch** in the page's **Playback settings**. Use the playback bar's **Fullscreen** button; system video fullscreen depends on the browser. See [viewing controls](./getting-started.md#join-a-friends-room). |
| Sharing stops after sleep or suspension | Wake the device and return to the sharing tab; start sharing again if needed. Browser and OS suspension can interrupt capture or playback. |
For a bug report, include the version, OS/browser, what you expected, and how
@@ -110,7 +110,7 @@ If selecting a window or screen returns you to the start screen, or reports a
sharing failure, it may involve capture, encoding or the Browser-to-App media
connection. The message alone does not identify a graphics-driver problem.
-1. **Compare codecs on the same source.** In **Settings → Connection & encoding**, change the
+1. **Compare codecs on the same source.** In **Sharing settings → Picture → Fine-tune picture**, change the
video codec from **H264** to **Auto** or **VP8**, then start sharing again.
If VP8 works, you can keep using it while checking the H264 path.
2. **Update and restart.** Update Piik App and Chrome, and install the appropriate
@@ -237,11 +237,14 @@ loading ordinary websites does not establish that this port is accessible.
See [Cloudflare's connection troubleshooting](https://developers.cloudflare.com/tunnel/troubleshooting/)
for the requirements. You do not need to open an inbound port on your router.
-**To continue sharing:** keep the App running, open a reachable
-[online site or existing site](./getting-started.md#share-from-an-existing-site),
-and click **App** at the top to authorize it. You can then use App window/screen
-capture without creating a temporary public invitation. The online site still
-uses P2P; if the page opens but video does not connect, follow
+**To continue without a public invite:** keep the App running and open
+[Piik online](https://demo.piik.tv) or another reachable Piik site. Follow
+[Use App with an existing site](./getting-started.md#use-app-with-an-existing-site)
+to authorize App window/screen capture, then send your friends the new site's
+room invitation. The old public-invitation link does not lead to this new room.
+Piik online needs no site passphrase. This bypasses the temporary Cloudflare web
+address; the online site remains P2P-only, with no SFU fallback.
+If the page opens but video does not connect, follow
[media connection troubleshooting](#when-video-will-not-connect).
Include the App version, failure time and [App diagnostic report](../../cmd/piik-app/README.md#diagnostics)
in feedback. If the unavailable address is a self-hosted site rather than the App's
@@ -256,7 +259,7 @@ If it recurs or never recovers, compare the following:
one viewer? Note the time and whether it recovers on its own. A clear host
preview does not establish that viewers' connections are healthy.
2. **Change one thing at a time.** The host can try a lower resolution or frame
- rate under **Settings → Picture**, and check CPU/GPU load while the game runs.
+ rate under **Sharing settings → Picture**, and check CPU/GPU load while the game runs.
An affected viewer can compare another browser or a phone hotspot. Increasing
bitrate does not necessarily help.
3. **Check the actual codec.** Open the host's **Show connection details** and
diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.md
index e265fb16..04c8f6c5 100644
--- a/docs/guide/troubleshooting.zh-CN.md
+++ b/docs/guide/troubleshooting.zh-CN.md
@@ -23,14 +23,14 @@
| HDR 画面过亮或颜色发白 | Windows 上可改用 App 选源,或暂时关闭 HDR;查看 [HDR 说明](#hdr-画面过亮或颜色发白)。 |
| 分享的窗口或屏幕周围出现黄框 | 这是 Windows 的采集提示。查看[采集边框说明](#windows-分享时出现黄框),了解 Windows 11 的开关和 Windows 10 的可选处理方法。 |
| 有画面,没来源声音 | 先取消视频静音。房主应选择支持分享声音的来源,并在选源器中打开声音。摄像头画面与音频输入分别选择,见[声音设置](./getting-started.zh-CN.md#加上自己的声音)。 |
-| 听不到房主说话 | 房主可在画面下方开启 **麦克风**,在 **设置 → 声音** 中检查输入设备和音量,并确认设备连接与麦克风权限。如控件不可用,请更新 App 并刷新页面。 |
+| 听不到房主说话 | 房主可在画面下方开启 **麦克风**,在 **分享设置 → 声音** 中检查输入设备和音量,并确认设备连接与麦克风权限。如控件不可用,请更新 App 并刷新页面。 |
| 分享时把语音软件的声音也传出去了 | Windows App 屏幕采集可选择[排除应用声音](./getting-started.zh-CN.md#分享屏幕时排除语音软件的声音);该功能不消除扬声器被麦克风收音产生的回声。 |
| 虚拟麦克风有回声,或在 Piik 闭麦后仍能听到 | 暂时关闭 **系统声音** 对照。混音软件的播放输出可能通过来源音频进入分享,请检查[音频路由](./getting-started.zh-CN.md#分享屏幕时排除语音软件的声音)。 |
| 网页能打开,画面连不上 | **重新连接** 按钮可用时先点击,否则刷新观看页。仍然失败时,查看 [画面连接排查](#画面连接不上)。 |
| 开启了 WebRTC 或 IP 泄露保护 | 按[浏览器 WebRTC 设置](#浏览器限制了-webrtc)检查是否阻止了媒体连接。 |
| 校园网或受限网络连不上 | 先用手机热点对照,再考虑[启用 SFU 的自建站点](#校园网或严格-nat)。 |
| 画面反复模糊、卡顿或中断 | 先分清哪些观众受影响,再按[画质与中断排查](#画面模糊卡顿或中断)操作。 |
-| 手机全屏仍有黑边,或全屏按钮无效 | 画面会保持原始比例,可尝试横屏;使用播放栏的 **全屏观看** 按钮,系统视频全屏由浏览器提供。详见[观看操作](./getting-started.zh-CN.md#加入朋友的房间)。 |
+| 手机全屏仍有黑边,或全屏按钮无效 | 画面默认保持原始比例,可尝试横屏,或在页面内的 **播放设置** 中选择 **等比铺满** 或 **拉伸铺满**。使用播放栏的 **全屏观看** 按钮;系统视频全屏由浏览器提供。详见[观看操作](./getting-started.zh-CN.md#加入朋友的房间)。 |
| 休眠或挂起后分享中断 | 唤醒设备,回到分享标签页,必要时重新开始分享。浏览器或系统挂起可能中断采集和播放。 |
反馈问题时,请附上版本、系统与浏览器、预期结果和复现步骤。
@@ -95,7 +95,7 @@
选中窗口或屏幕后回到未分享状态,或出现「启动分享失败」,可能涉及采集、编码或网页与 App
之间的媒体连接,不能仅凭提示确定是显卡驱动问题。
-1. **用同一来源对比编码。** 在 **设置 → 连接与编码** 中,将视频编码从 **H264** 改为 **自动** 或
+1. **用同一来源对比编码。** 在 **分享设置 → 画面 → 画面细调** 中,将视频编码从 **H264** 改为 **自动** 或
**VP8**,重新开始分享。如果 VP8 正常,可以先用它,再排查 H264 路径。
2. **更新后重启。** 更新 Piik App 和 Chrome,并从电脑或显卡厂商的官方网站安装适合本机的
显卡驱动。双显卡笔记本应检查两块显卡的驱动,安装后重启电脑。
@@ -202,9 +202,11 @@ Piik 已启用 QUIC(UDP)失败后尝试 HTTP/2(TCP),两者都使用出
具体要求见 [Cloudflare 连接排查](https://developers.cloudflare.com/tunnel/troubleshooting/)(英文),
无需在路由器上开放入站端口。
-**需要继续分享时:** 保持 App 运行,打开可访问的[在线版或已有站点](./getting-started.zh-CN.md#使用已有站点分享),
-点击顶部的 **App** 完成授权,即可继续使用 App 的窗口/屏幕采集,无需创建临时公网邀请。
-在线版仍使用 P2P;网页能打开但画面连不上时,转到[画面连接排查](#画面连接不上)。
+**暂时绕过公网邀请:** 保持 App 运行,打开[在线版](https://demo.piik.tv)或其他可访问的 Piik 站点,
+按[通过已有站点使用 App](./getting-started.zh-CN.md#通过已有站点使用-app)完成授权并使用窗口/屏幕采集,
+再将新站点的房间邀请发给朋友。原公网邀请链接不会转到这个新房间。
+在线版无需站点口令。这绕过的是 Cloudflare 临时网页入口;在线版仍仅使用 P2P,不提供 SFU 兜底。
+网页能打开但画面连不上时,转到[画面连接排查](#画面连接不上)。
反馈中请附上 App 版本、失败时间和 [App 诊断报告](../../cmd/piik-app/README.zh-CN.md#诊断)。
如果打不开的是自建站点而非 App 的临时地址,请联系该站点管理员检查服务。
@@ -214,7 +216,7 @@ Piik 已启用 QUIC(UDP)失败后尝试 HTTP/2(TCP),两者都使用出
1. **确认影响范围。** 是房主预览、所有观众,还是只有某位观众?记录大致时间,
以及能否自行恢复。房主预览清楚并不保证观众的连接也正常。
-2. **一次调整一项。** 房主可在 **设置 → 画面** 中先试较低的分辨率或帧率,
+2. **一次调整一项。** 房主可在 **分享设置 → 画面** 中先试较低的分辨率或帧率,
检查游戏运行时 CPU/GPU 是否接近满载;受影响的观众可用另一浏览器或手机热点对照。
将码率调高不一定有帮助。
3. **查看实际编码。** 展开房主的 **显示连接详情**,查看 **视频编码**。Windows 上,
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 9fb42293..4d8656f9 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -1,6 +1,6 @@
# Project Memory
-Last updated: 2026-10-16
+Last updated: 2026-10-19
Piik is private, low-latency screen sharing for one Host and up to 20
authenticated friends. The current product surface is Web Host, Web Viewer, and
@@ -102,6 +102,12 @@ implementation and routine UI detail.
## Current Snapshot
+Optional attended keyboard/mouse control follows the committed media route back
+to the native Host. One source-scoped grant admits one controller; source change,
+stop and revocation retire it. It adds no separate connection planner or listener.
+Viewer playback preferences and the combined interaction window remain local
+presentation owners under the existing 2.x compatibility boundary.
+
The current contract tuple is owned by [status](./status.md#accepted-release-contract).
Embedded SFU SDP/ICE and demand travel over the
authenticated room WebSocket, without an external room service or media token.
diff --git a/docs/research/agent-context-governance.md b/docs/research/agent-context-governance.md
index 8ad3310a..4b973750 100644
--- a/docs/research/agent-context-governance.md
+++ b/docs/research/agent-context-governance.md
@@ -3,7 +3,7 @@
- Reviewed: 2026-08-27
- Scope: repository context, durable memory, documentation types, and decisions
- Status: evidence; repository policy is owned by
- [maintenance](../standards/documentation.md)
+ [documentation ownership](../standards/documentation.md)
## Findings
@@ -65,6 +65,49 @@ Sources:
- [Martin Fowler: Architecture Decision Record](https://martinfowler.com/bliki/ArchitectureDecisionRecord.html)
- [GitHub Flow](https://docs.github.com/en/get-started/using-github/github-flow)
+### Instructions And Skills
+
+Reviewed: 2026-10-17. These are source-derived design considerations, not a
+benchmark of agent reliability or another set of mandatory instructions.
+
+OpenAI's current guidance favors task-scoped references, short skill descriptions
+and explicit completion boundaries. Its documented OSS workflow separates
+repository policy from reusable skill methods. The Agent Skills community
+guidance likewise recommends coherent purposes, detail proportional to task
+fragility, and refinement against real execution. A skill need not carry its
+own scripts, reference tree or elaborate procedure to be useful.
+
+Codex loads an instruction chain from global scope through the working directory;
+more specific project instructions follow broader ones. Skill descriptions
+select workflows whose bodies load on use. Same-named skills are not merged, so
+Piik links its repo adaptations explicitly. This loading behavior is distinct
+from project authority: a skill cannot grant a release, change an accepted
+product contract or weaken a user's task boundary.
+
+The community Ponytail and Stop That Shit approaches support reuse and completion
+with less speculative work. Piik keeps those principles but evaluates total
+ownership and the complete experience, rather than line count or the first
+working implementation. Its Ponytail adaptation removes forced persistence,
+fixed response length and per-branch test prescriptions; upstream attribution
+remains in the skill's [provenance](../../.agents/skills/ponytail/UPSTREAM.md).
+New mechanisms still need relevant end-to-end evidence. Required design thinking
+does not imply a separate design document, review agent or approval for each edit.
+
+Sources:
+
+- [OpenAI: Rethinking skills and prompts](https://developers.openai.com/blog/rethinking-skills-and-prompts-for-gpt-6-astra)
+- [OpenAI: Using skills for OSS maintenance](https://developers.openai.com/blog/skills-agents-sdk)
+- [Codex instruction discovery](https://learn.chatgpt.com/docs/agent-configuration/agents-md) and [skill loading](https://learn.chatgpt.com/docs/build-skills)
+- [Agent Skills best practices](https://agentskills.io/skill-creation/best-practices) and [specification](https://agentskills.io/specification)
+- [Stop That Shit](https://github.com/lennney/stop-that-shit/blob/0.2.4/skills/stop-that-shit/SKILL.md) and [STSS](https://github.com/lennney/stop-that-shit/blob/0.2.4/skills/stss/SKILL.md): complete the responsibility and omit unnecessary work or self-justifying prose.
+- [Avoid Over-Defensive Programming](https://github.com/aravelo7/codex-agent-skills/blob/main/skills/avoid-overdefensive-programming/SKILL.md): fix the producing owner; Piik does not adopt a per-branch reporting procedure.
+
+The earlier community reports about
+[small-task expansion](https://www.reddit.com/r/codex/comments/1vf5elq/how_do_you_stop_codexclaude_from_overengineering/)
+and [ignored context](https://www.reddit.com/r/codex/comments/1ujnwxb/codex_quality_issues_in_realworld_coding_ignored/)
+motivate inspecting useful output and execution cost; they are anecdotes, not
+statistical evidence about a model.
+
## Applicability
Piik is small enough that a vector database, memory provider, generated code
@@ -72,4 +115,4 @@ map, parallel agent-context format, or separate RFC repository would add more
ownership than it removes. The useful practices are bounded always-on context,
one owner per fact, domain-shaped reference, evidence on demand, short ADRs,
link checks, and Git-backed history. Exact repository policy remains in
-[maintenance](../standards/documentation.md), not in this research note.
+[documentation ownership](../standards/documentation.md), not in this research note.
diff --git a/docs/research/cross-platform-client-runtime.md b/docs/research/cross-platform-client-runtime.md
index 6e91a8c6..f18a8baf 100644
--- a/docs/research/cross-platform-client-runtime.md
+++ b/docs/research/cross-platform-client-runtime.md
@@ -18,16 +18,10 @@
These are architecture references only. No implementation or copyleft source is
copied.
-A read-only inventory of locally installed streaming clients adds one practical
-constraint. GameViewer separates its UI, supervised media service, codec
-capability detector, streamer, health process, and updater. Discord keeps its
-Chromium UI separate from a native voice/media module and updater. Oopz ships
-Flutter, a second WebView, FFmpeg, Agora RTC, and Tencent LiteAV together; that
-stack is substantially larger and duplicates media ownership. Piik follows
-the first two products' process separation but not their UI runtimes, and avoids
-Oopz's parallel RTC stacks: one Go process, one Pion media core, and one thin
-system capture sidecar per platform remain sufficient. No binary code or private
-application data was copied or inspected.
+Piik separates the Browser UI from native capture and media ownership. One Go
+process, one Pion media core, and one thin system capture sidecar per platform
+remain sufficient; additional UI runtimes or parallel RTC stacks need an actual
+consumer and a distinct responsibility.
## Current Control Boundary
@@ -324,11 +318,9 @@ Its [feature-upgrade guidance](https://sparkle-project.org/documentation/publish
also requires capable readers or a separate feed; metadata alone cannot teach
older readers a new rule.
-[CC Switch's About panel](https://github.com/farion1231/cc-switch/blob/243cd9a93b67f56efac173f32505b4085fb40cae/src/components/settings/AboutSection.tsx)
-separates its update action from opening the target version's release notes.
-The installed edition downloads, installs and restarts. Reading release notes
-is optional. This supports Piik's action hierarchy, not adoption of CC Switch's
-installer or update infrastructure; no implementation code was copied.
+Piik's primary action opens the download for the target version; release notes
+are optional context. This action hierarchy does not require another installer
+or update infrastructure.
The evidence supports direct manual downloads with an optional release-note
link and inline major-upgrade guidance. The accepted behavior belongs to
@@ -370,8 +362,6 @@ undecided.
- [LocalSend protocol](https://github.com/localsend/protocol/blob/main/README.md)
- [Sunshine](https://docs.lizardbyte.dev/projects/sunshine/latest/)
- [Syncthing GUI configuration](https://docs.syncthing.net/users/config.html)
-- [GameViewer product](https://uuyc.163.com/)
-- [Discord desktop architecture](https://discord.com/blog/how-discord-maintains-performance-while-adding-features)
- [WebView2 Evergreen runtime](https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/evergreen-vs-fixed-version)
- [WebView2 screen capture](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2screencapturestartingeventargs)
- [WebKitGTK multimedia](https://docs.webkit.org/Ports/WebKitGTK%20and%20WPE%20WebKit/Multimedia.html)
diff --git a/docs/research/nat-traversal.md b/docs/research/nat-traversal.md
index 1f44db5b..7f8cd998 100644
--- a/docs/research/nat-traversal.md
+++ b/docs/research/nat-traversal.md
@@ -26,28 +26,16 @@ configured, Chromium emitted one deduplicated srflx candidate. No raw address or
port was retained. This proves endpoint reachability and candidate
deduplication; it does not classify the NAT or prove another direct path.
-### TeamSpeak ICE Comparison
-
-TeamSpeak's [engineer explanation](https://community.teamspeak.com/t/how-does-share-screen-technically-work/56850)
-identifies ordinary WebRTC ICE and two operator-hosted STUN services. Their
-`turn.teamspeak.com` / `turn2.teamspeak.com` names do not establish TURN relay;
-the engineer explicitly describes them as STUN-only. This supplies no measured
-connection-success advantage or evidence for proprietary hole punching.
-
-Static inspection of TeamSpeak 6 beta5 on 2026-10-16 found explicit negotiation
-ownership, stale-connection and old-ICE-generation rejection, an ICE-restart
-recovery tier followed by complete connection reset, and a check that skips a
-duplicate restart already performed since the reported failure. Its
-[release notes](https://community.teamspeak.com/t/teamspeak-6-0-0-beta5-foundation-iii-update/65513)
-also identify lost large offers after restart and overly strict timeouts as
-repaired connection failures. These findings support generation-aware recovery
-and complete signaling delivery, not simply raising retry counts. Piik already
-owns these concerns in [ordinary recovery](#ordinary-ice-and-media-recovery);
-no second restart controller or borrowed public STUN service is introduced.
-The installed package's `StreamSFU` class name alone does not prove an enabled
-server relay or automatic P2P/SFU switching. No live TeamSpeak NAT comparison
-was performed. [Encoding and rate-control findings](./realtime-quality-adaptation.md#teamspeak-native-comparison)
-are separate from reachability evidence.
+### ICE Recovery Boundaries
+
+Connection recovery needs explicit negotiation ownership, stale-connection and
+old-ICE-generation rejection, and complete signaling delivery. A duplicate
+restart already performed since a reported failure should not create another
+operation. Piik owns these concerns in
+[ordinary recovery](#ordinary-ice-and-media-recovery); increasing retry counts
+or adding another restart controller does not repair those boundaries.
+Endpoint names and packaged class names alone do not establish active relay
+behavior or a measured connection-success advantage.
### Public-Link Discovery Redundancy
@@ -523,6 +511,16 @@ Blocked initial/retransmission writes and unused stable-socket retirement have
regression coverage. The shared wire decoder requires an explicit zero step;
missing/null fields cannot silently select this behavior.
+A focused in-memory preparation check on 2026-10-17 retained the existing
+sequential-NAT fixture and three ordered destinations. Losing the first request
+to one destination recovered through Pion retransmission in 300 ms; delaying
+one response by 250 ms completed preparation in 250 ms. A silent destination
+returned no prediction at the existing 1.5-second survey deadline. The Browser
+caller supplies exactly three destinations, so skipping a failed destination
+cannot supply the three successful observations required by this preparation.
+Keep the current failure-to-ordinary-ICE behavior; these controls establish
+bounded recovery and failure, not a physical-network success-rate benefit.
+
The Windows Browser-to-App fanout gate also exercises the actual room retry,
both Native control preparations and ordinary ICE continuation when the mapping
is ineligible. Two Viewers decode about 30 fps; live quality, pause/resume, source
@@ -595,12 +593,18 @@ against that same endpoint pair and relay policy.
#### Stable Pion Interoperability
-The candidate uses Pion WebRTC v4.2.23 / ICE v4.4.7. The
+The candidate uses Pion WebRTC v4.2.24 / ICE v4.4.7. The
[upstream changes](https://github.com/pion/ice/compare/v4.4.0...v4.4.7) include
STUN retransmission, gathering-generation ownership, Chromium mDNS compatibility
and pre-created mux lifetime corrections. This updates the shared Native/SFU
composition; ordinary Browser-to-Browser ICE remains Browser-owned.
+WebRTC's DTLS v3.1.13 dependency also includes
+[queued-buffer ownership and handshake-retransmission corrections](https://github.com/pion/dtls/compare/v3.1.10...v3.1.13).
+They address loss/reordering during transport establishment and strengthen
+handshake validation; they do not add reachable NAT paths or another Piik retry
+owner.
+
A controlled Chrome 152 check reproduced the
[mDNS query incompatibility](https://github.com/pion/mdns/commit/5b0a717e4ff6e81300d54ce2fef53e635b95fe3c):
after the Browser's initial announcement, a fresh v2.1.0 resolver could not resolve
diff --git a/docs/research/native-client-media.md b/docs/research/native-client-media.md
index 82c694bc..9172a065 100644
--- a/docs/research/native-client-media.md
+++ b/docs/research/native-client-media.md
@@ -361,7 +361,7 @@ bottleneck.
On 2026-10-07, the local Native H.264 SFU gate initially passed its two-room
check, then missed its unchanged 300-frame/30-second requirement. The repeat
-environment exposed only a GameViewer virtual display. Current main reproduced
+environment exposed only a third-party virtual display. Current main reproduced
the failure with its own App and capture binary: video/audio arrived, but video
was roughly 4–7 fps without receiver loss or decode drops. A source-window draw
counter advanced about 133 times per second; that counts drawing attempts, not
diff --git a/docs/research/native-sender.md b/docs/research/native-sender.md
index 10cee9bb..5947a775 100644
--- a/docs/research/native-sender.md
+++ b/docs/research/native-sender.md
@@ -139,7 +139,7 @@ Pion is MIT and coder/websocket is ISC. The Windows APIs use installed hardware
MFTs; vendor codec binaries are not redistributed. Direct NVENC would require a
separate NVIDIA Video Codec SDK and redistribution review. H.264 patent and
project licensing remain unresolved before executable distribution. No
-proprietary Oopz/Agora or GPL/AGPL code was copied.
+proprietary or GPL/AGPL implementation code was copied.
## Primary Sources
diff --git a/docs/research/network-lab.md b/docs/research/network-lab.md
index eaee6bc9..8fdeb7ff 100644
--- a/docs/research/network-lab.md
+++ b/docs/research/network-lab.md
@@ -267,6 +267,19 @@ intended reasons and cleaned up. The route regression separately covers a connec
Peer reaching its operation deadline before a first frame: untried fallback must
survive that deadline, while each attempted route retains its finite budget.
+### Route-Handoff Measurement
+
+An additional continuous `requestVideoFrameCallback` inspection loop can change
+the behavior being measured. On Chromium 152.0.7977.82, it reproduced a receiver
+stall during a P2P/SFU switch while RTP reception continued. Removing only that
+extra observer, retaining pixel readback, decoded-frame counters and Piik's own
+first-frame observer, passed six Auto/P2P/SFU transitions against the same current
+Server: the moving VP8 picture sustained about 30 fps. Installed Chrome
+155.0.8059.84 also passed with the continuous observer. This establishes a
+probe-dependent browser interaction, not a Piik route failure or a particular
+upstream fix. Recheck a failed probe with passive frame counters and changing
+pixels before adding playback resets or transport workarounds.
+
## Sustained Quality Recovery
P2P stage comparisons also use the existing
diff --git a/docs/research/node-local-media-design.md b/docs/research/node-local-media-design.md
index 926671b8..c5684875 100644
--- a/docs/research/node-local-media-design.md
+++ b/docs/research/node-local-media-design.md
@@ -150,6 +150,18 @@ by projection while outbound sequence continuity remains intact. Incoming sender
reports retain their source-clock relation; local codec outputs correlate to one
input anchor, not independently to each encoder's completion time.
+Outgoing video sender reports and RR/RTT accounting share the DownTrack owner.
+Pion supplies the loop at LiveKit's three-second cadence; audio retains Pion
+reports. RTX therefore cannot corrupt the primary clock, and feedback matches
+the owner that sent the report. Real RTCP checks cover probing, pause/resume
+and RTT; constrained checks also cover source replacement. Field logs confirmed
+that a corrupted upstream RTP/NTP reference can block layer changes despite
+restored capacity. A failed downgrade can stop forwarding while the input still
+advances; resuming that input then exposes sequence gaps and RR rollover
+adjustments. Sender-feed gaps and receiver-reported loss are distinct from
+physical network loss. ICE reconnect retains the source reference; update App
+and Server.
+
Local capture replacement keeps its RTP source and cumulative counters while
rebasing only the input packetizers. It must not also restart the RTP projector.
Unconnected edges reserve child slots without asking for output. Video capacity
@@ -596,6 +608,88 @@ configured demand never substitutes for measured source bitrate. This verifies
the shared forwarding adapter used by SFU subscribers, not a complete hosted
Browser/SFU session or a field-report diagnosis.
+### Persistent Loss With Low Source Utilization
+
+A 2026-10-18 Native-to-Browser P2P trace retained healthy local 1080p output
+while the remote connection's video budget fell from 5 Mbps to about 8 kbps.
+Remote feedback reported roughly 320 ms RTT and sustained loss, commonly
+10–25%. Congestion began on loss, followed by repeated CTR-trend reductions
+based on progressively lower acknowledged throughput. Probes were sent, but
+their loss prevented promotion. This establishes the reduction path, not the
+physical path's capacity or the origin of its loss. A local TUN was active;
+it was left unchanged, so proxy causation is unproven.
+
+A virtual-network comparison reused the production forwarding gate with a
+12 Mbps link, 320 ms round-trip delay and 15% random packet loss for 30 seconds,
+then removed loss. Full-budget synthetic video bottomed out near 1.16 Mbps;
+video using one quarter of its budget fell to about 13 kbps. Both restored a
+5 Mbps budget after loss ended. These are generated RTP payloads, not decoded
+picture-quality measurements, and the fixed random seed does not pair packets
+across different send rates.
+
+Two measurement defects were already present in v1.9.2's LiveKit v1.13.6 dependency:
+CTR group rollover discarded its boundary packet, and overlapping TWCC reports
+recounted received/lost packets and moved the receive-time baseline. A real Pion
+recorder with four sent packets and two late arrivals produced six ACKs and one
+remaining loss. Packet-state transitions now retain the late ACK repairs while
+ignoring repeated observations; ordinary, probe and CTR measurements receive the
+same facts. Rollover likewise retains its boundary packet. Both controls fail
+without their respective fixes.
+
+The same feedback-boundary review found that replayed observations could advance
+the congestion state without any new measurement. Long runs of delayed packets
+also exceeded the group's ACK-count-sized loss bitmap: all 172 packets could be
+received with 43 losses still counted. Group membership now covers the tracker's
+live history, while late ACKs repair only losses observed by that group. A reused
+bitmap slot cannot erase an expired packet's loss.
+
+Delay measurements now advance in send order with a receive-time watermark;
+historical ACKs repair counts without rewinding that baseline. Actual packet
+timestamps remain available. Reset reseeds delay measurement while preserving
+delivery history. This replaces a scope-local negative-delta clamp that could
+leave 100 ms of phantom queue after one reordered packet, even after hundreds of clean
+packets. A Pion TWCC control verifies queue drainage, steady acknowledged bitrate
+and packet counts; a sustained-delay control still retains congestion.
+
+Inconclusive completed probes also use the existing regulator's failure backoff
+from completion. Previously they entered its successful-probe branch, growing
+the next duration and allowing immediate retries after a long feedback wait.
+The reported result remains inconclusive and cannot raise capacity.
+
+The earlier low-utilization comparison still fell to about 13 kbps after the
+accounting repairs, then restored its 5 Mbps budget about seven seconds after loss
+ended. These results do not establish a repair for persistent-loss collapse.
+Further CTR-reference and measurement-window experiments are not accepted
+production changes. Requiring
+new ratio deterioration held about 1.19 Mbps under the same persistent loss and
+still reduced the budget after a real 120 kbps bottleneck. However, retaining
+that reference can mask later deterioration within one congestion episode;
+refreshing it on improvement re-arms false reductions from random variation.
+Accumulating observations without resetting avoided those reductions but made
+the reaction to a later bottleneck depend on the length of the preceding run.
+These controls reject a reference guard or longer averaging window as a complete
+repair. The lab's final-recovery assertion alone does not detect intervening
+unjustified cuts; inspect the budget timeline against each imposed link change.
+
+Reduced source traffic and network capacity must remain distinct. Google WebRTC's
+[loss-based estimator](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc)
+models inherent loss separately and can exclude the low-ACK capacity candidate
+under its application-limited policy. Its application-limited input comes from sending
+activity relative to the target, not received throughput: a real bottleneck
+also lowers ACK throughput. The retained LiveKit detector has no such input;
+neither freezing loss response nor swapping to Pion's older loss controller
+establishes the same behavior. Pion's
+[underutilized-source discussion](https://github.com/pion/interceptor/issues/156)
+likewise distinguishes unoffered traffic from capacity and points to
+application-limited detection and probing. This is guidance, not a drop-in repair
+for Piik's retained detector.
+
+On 2026-10-18 the owner deferred replacing the loss estimator: sustained high
+loss may reduce quality, and a custom model is not justified by the present
+tradeoff. Retain this limitation without claiming that the severe low-utilization
+case is fixed, or that every upstream implementation has the same behavior.
+Concrete feedback and recovery defects remain separate from that policy choice.
+
### Capture Boundary
Output construction follows the [media-quality owner](../standards/media-quality.md):
diff --git a/docs/research/peer-assisted-media.md b/docs/research/peer-assisted-media.md
index febf757b..5facfc6e 100644
--- a/docs/research/peer-assisted-media.md
+++ b/docs/research/peer-assisted-media.md
@@ -158,8 +158,8 @@ configuration checks and media evidence would still be required.
## License Boundary
This research uses W3C/IETF specifications, BSD-licensed libwebrtc source,
-public browser-compatibility data, and an official TeamSpeak technical
-statement. No GPL/AGPL implementation code was copied. GPL/AGPL projects remain
+and public browser-compatibility data. No GPL/AGPL implementation code was copied.
+GPL/AGPL projects remain
study-only unless a separate distribution decision accepts their obligations;
the repository's own [MIT license](../../LICENSE) does not replace theirs.
@@ -177,7 +177,6 @@ the repository's own [MIT license](../../LICENSE) does not replace theirs.
- [libwebrtc `VideoEncoderFactory`](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder_factory.h)
- [libwebrtc `VideoEncoder`](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video_codecs/video_encoder.h)
- [libwebrtc license](https://webrtc.googlesource.com/src/+/refs/heads/main/LICENSE)
-- [TeamSpeak single-encoding explanation](https://community.teamspeak.com/t/ts6-beta-community-update-insights/58116/208)
- [Encoded Transform compatibility data](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/RTCRtpScriptTransform.json)
- [WebCodecs `VideoDecoder` compatibility data](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/VideoDecoder.json)
- [`MediaStreamTrackProcessor` compatibility data](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/MediaStreamTrackProcessor.json)
diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.md
index 451e257a..50b608a9 100644
--- a/docs/research/realtime-quality-adaptation.md
+++ b/docs/research/realtime-quality-adaptation.md
@@ -537,55 +537,14 @@ The [Native encoder control](./webrtc-encoder-pool.md#budget-restoration) also
separates restored allocation from later resolution recovery; that delay is not
specific to Browser capture or proof that a network estimate is still low.
-### Mature Product Boundaries
-
-Discord documents a multi-process capture/encode/transport/decode pipeline,
-OS-specific capture fallback, hardware codec selection, WebRTC bandwidth
-estimation, and joint monitoring of cadence, latency, visual quality, network,
-CPU and memory. Its desktop client uses native capture and codec integration;
-that result is evidence for native pipeline boundaries, not a Browser API recipe.
-Discord also reported a real frame-drop ratchet where reconfiguring an encoder
-to its already-reduced cadence increased bits per frame and compounded drops.
-
-Signed local NetEase UU Remote installations separate UI, service, streamer,
-codec detector, virtual-display and audio components. The inspected capability
-caches key encoder/decoder support by codec, adapter/device, dimensions, frame
-rate, implementation, chroma sampling and bit depth. This supports profile-scoped
-capability caching and process isolation; the detector was not executed.
-
-A static review of 4.40.1 also found WebRTC congestion-control, quality-scaling
-and probing components. Three encoder-adapter constructors supply the same
-cadence-controller defaults: five downshift samples, a 4,000 ms observation
-window, 10% headroom and a 25% rapid-upshift threshold. Local control-flow and
-log-argument references establish that sample count and elapsed time both gate
-a downshift, with a separate rapid cadence-increase branch. These are encoder
-cadence settings, not packet-loss thresholds or verified live-session policy.
-The binary also contains ALR and rapid-recovery probing configuration; static
-presence does not establish runtime activation or equivalence to current WebRTC.
-
-The [unofficial UU Linux host](https://github.com/VallierDev/uu-remote-linux/tree/15bb35573d8b71d6fe0943d8daa46f0bdc5bc2cb)
-is a different implementation. Its inspected `capture_setting.rs`, `video.rs`
-and `webrtc.rs` use viewer-selected quality/FPS, constant-quality encoding with
-a bitrate cap, a four-frame queue and dependency-aware dropping until an IDR.
-The default subprocess path relies on a short GOP; the optional in-process
-encoder can answer PLI/FIR directly. Receiver reports feed diagnostics, with no
-sender network-estimate-to-encoder-rate loop found in this source. Its preset
-values therefore do not establish NetEase's adaptation or recovery algorithm.
-
-KOOK's official 1080p60 guidance requires substantial CPU/GPU headroom and its
-troubleshooting explicitly notes that hardware acceleration can worsen some
-systems. Oopz treats VPN/accelerator changes as an independent network-path
-diagnostic. Its inspected 0.88.41 package includes Agora and TRTC libraries;
-the packaged screen-share player entry configures Agora RTC/H264 playback with
-HLS fallback available. Bundled SDK code is not evidence that every feature is
-active, or that the publisher uses a particular QoS setting. Agora and TRTC's
-public APIs explicitly distinguish clarity from cadence preferences; TRTC also
-warns that equating minimum and target bitrate disables bitrate adaptation.
-These sources support explicit media intent and stage-specific diagnosis,
-not a universal hardware switch or a forced quality floor.
-
-The useful shared lesson is to separate congestion response, encoder cadence
-and recovery demand. WebRTC's pinned [probe controller](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/modules/congestion_controller/goog_cc/probe_controller.cc)
+### Media Adaptation Boundaries
+
+Capability checks must cover the actual codec, adapter/device, dimensions,
+frame rate, implementation, chroma sampling and bit depth. Native capture and
+codec work should retain clear process and resource owners. Encoder cadence,
+network congestion response and recovery demand are separate responsibilities.
+
+WebRTC's pinned [probe controller](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/modules/congestion_controller/goog_cc/probe_controller.cc)
already distinguishes a large bandwidth drop, a bounded recovery-probe window,
ALR and maximum allocation. Its [quality scaler](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/modules/video_coding/utility/quality_scaler.cc)
separately requires samples and smoothed QP evidence. Piik's Native encoder uses
@@ -607,18 +566,13 @@ track settings remained 30 fps, and Viewer freeze intervals followed those
lows. The event therefore contained both native BWE degradation and source
cadence loss; topology churn and CSS presentation were not required causes.
-### TeamSpeak Native Comparison
-
-The 2026-10-16 review inspected the installed TeamSpeak 6 beta5 package
-(`TeamSpeak.dll` SHA-256 prefix `b4888a71b8e7a029`) and its
-[Foundation III release](https://community.teamspeak.com/t/teamspeak-6-0-0-beta5-foundation-iii-update/65513).
-The UI uses CEF; screen sharing crosses a native bridge into libwebrtc and
-FFmpeg 8.1 encoders. CEF's Chromium version does not identify the separately
-linked native WebRTC revision. This was static inspection plus experiments
-in Piik's pipeline, not a measured TeamSpeak call or a product ranking.
+### Native Encoder Policy Experiments
-Stream initialization supplies three concrete field trials, established from
-their construction and environment call sites rather than string presence:
+Piik evaluated the encoder controls below in its existing Native pipeline.
+The congestion-window setting illustrates a separate transport boundary; it
+cannot configure Piik's Pion/LiveKit transport through encoder configuration.
+The dropper and bitrate-adjuster experiments below measure the current Piik
+pipeline, not another application's complete implementation.
| Native setting | Meaning and transfer boundary |
| --- | --- |
@@ -628,43 +582,24 @@ their construction and environment call sites rather than string presence:
The [upstream parser](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/rtc_base/experiments/rate_control_settings.cc)
and [encoder contract](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/api/video_codecs/video_encoder.h)
-explain these independent controls. TeamSpeak also configures FFmpeg backends
-directly: the inspected NVENC defaults include P6, low-latency tuning, CBR,
-zero reordering delay and zero lookahead; QSV uses low-delay BRC, asynchronous
-depth one and zero lookahead. Values were checked against the
-[FFmpeg NVENC definitions](https://github.com/FFmpeg/FFmpeg/blob/n8.1/libavcodec/nvenc_h264.c).
-They are backend defaults, not proof of a user's selected encoder or settings
-that can be applied to Piik's Media Foundation backend by renaming options.
-
-The same NVENC constructor enables spatial and temporal AQ, with spatial
-strength 9 and quarter-resolution multipass. These are meaningful quality/cost
-choices: [NVIDIA documents](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.1/nvenc-video-encoder-api-prog-guide/index.html#adaptive-quantization-aq)
-better perceptual allocation, but also extra GPU work and greater frame-size
-variation with temporal AQ. Media Foundation does not expose this same named
-control set. Piik's existing backend avoids a second GPU integration but gives
-up those explicit tuning choices; neither its parameter trials nor its limited
+explain these independent controls. Encoder backend options are not portable
+merely because they have similar names. Media Foundation does not expose every
+NVENC quality/cost control; Piik's limited
[profile comparison](./native-client-media.md#native-h264-motion-quality)
-establish equal quality to TeamSpeak's native pipeline.
-
-Shared encoding has its own per-receiver rate and dependency state. Once
-initialized, the inspected rate aggregate suppresses an update unless its bitrate changes by
-more than 10% or 200 kbps, or its frame rate changes by at least 1 fps. These
-are reconfiguration thresholds, not loss tolerance, a recovery timer or an
-instruction to ignore real congestion. The fanout path tracks lost dependency
-chains per receiver. The beta5 release separately confirms a repair for one
-stalled viewer freezing the shared encoder. Piik already separates incompatible
-consumer budgets into [output groups](./webrtc-encoder-pool.md#compatible-output-groups)
-and uses LiveKit's per-output forwarding state; copying another aggregation
-controller would replace those semantics rather than merely improve encoding.
-
-The keyframe recovery path distinguishes ignored requests from silent output
-and retains encoder-local recovery before reinitialization. Its broader watchdog
-and software-fallback state machine is not transplanted. The useful boundary is
+does not establish parity with another native pipeline.
+
+Shared encoding needs independent per-receiver rate and dependency state.
+Piik separates incompatible consumer budgets into
+[output groups](./webrtc-encoder-pool.md#compatible-output-groups) and uses
+LiveKit's per-output forwarding state. Replacing that partition with one rate
+aggregate changes its semantics.
+
+The useful boundary is
request versus actual output: [Chromium's Media Foundation adapter](https://chromium.googlesource.com/chromium/src/+/d5070a6099ade2fe3c953d3b3677843e1a43e87e/media/gpu/windows/media_foundation_video_encode_accelerator_win.cc)
records whether a keyframe request was fulfilled and delivers the actual frame
type rather than failing solely because it was not fulfilled.
-This comparison exposed a Windows inconsistency in Piik: every forced live
+A Windows inconsistency in Piik required a repair: every forced live
request required immediate SPS/PPS/IDR output or failed that codec output.
Windows now retains recovery intent until actual independent output, matching
the existing macOS/Linux behavior. First-output admission, bitstream validation
@@ -678,10 +613,9 @@ frame and decoded its remaining 45 frames. This establishes controlled behavior,
not a diagnosis of an untraced user's driver failure.
Color conversion already has an explicit matrix/range owner and fidelity checks;
-TeamSpeak's BT.709 fix is not a reason to override Piik's tagged BT.601 WebRTC SDR
-contract. Likewise, Opus FEC driven by individual talker loss belongs to a different
-audio-feedback model than Piik's shared screen-audio output. Neither comparison
-justifies another color heuristic or per-viewer audio encoder.
+Piik retains its tagged BT.601 WebRTC SDR contract. Individual talker loss also
+belongs to a different audio-feedback model than Piik's shared screen-audio
+output; it does not justify a per-viewer audio encoder.
The two encoder field trials were applied, together and separately, to the
existing Windows NV12/MFT H264 lab. The control retained Piik's selected
@@ -695,7 +629,7 @@ AU delivery, not decoded pictures or Browser-rendered freezes.
| Encoder experiment | Three one-second limits: recovery / longest receive gap | Fifteen-second limit: recovery / longest receive gap |
| --- | --- | --- |
| Current Piik settings | 1.9 s / 1.48 s | 22.2 s / 6.43 s |
-| Both TeamSpeak encoder trials | 17.3 s / 2.84 s | 16.2 s / 14.96 s |
+| Both encoder trials | 17.3 s / 2.84 s | 16.2 s / 14.96 s |
| Only disable frame dropper | 8.1 s / 2.83 s | Not run |
| Only disable bitrate adjuster | 15.2 s / 1.97 s | Not run |
@@ -704,11 +638,11 @@ through brief pulses and shortened sustained-limit recovery from 11 to 9 seconds
However, sustained 400 kbps output averaged about 746 kbps instead of 380 kbps
over the settled low-budget interval. Coupling actual transport feedback exposed
the delivery tradeoff above. These single runs reject a blanket transplant;
-they do not estimate TeamSpeak's performance or the probability of a field issue.
+they do not estimate another application's performance or field failure rates.
Production retains the existing dropper and adjuster. No new controller,
FFmpeg dependency or periodic connection reset follows from this comparison.
-A separate control applied the inspected bitrate-update thresholds at Piik's
+A separate control applied bitrate-update thresholds at Piik's
existing Native encoder demand input, without changing the transport estimator.
At fixed 30 fps, updates passed only when their difference exceeded 10% or
200 kbps. Four 120-second runs used the same link impairments above. Recovery
@@ -725,11 +659,11 @@ respectively, but delayed recovery and delivered fewer picture AUs overall.
The shorter worst gaps are a tradeoff, not an established overall improvement;
no filter is retained. The control also varies from the earlier runs, so their
1.9-second recovery is not a guaranteed recovery time. These remain Piik
-experiments, not measurements of TeamSpeak's complete pipeline.
+experiments with the current Piik pipeline.
A follow-up tested whether tighter native rate control could make the two
trials useful together. NVIDIA recommends small VBV for low-latency encoding;
-this does not establish TeamSpeak's selected buffer. Piik's lab set the MFT
+Piik's lab set the MFT
[H264 HRD buffer in bytes](https://learn.microsoft.com/en-us/windows/win32/codecapi/avenccommonbuffersize-property)
to one or four frames at each rate change. On the RTX 4070 SUPER / driver 617.42,
initial values read back correctly, but live writes returned success while
@@ -743,8 +677,8 @@ gap counts exclude parameter-set-only units but are not rendered-frame timings.
The buffer variant therefore remains lab-only; no encoder recreation on bitrate
updates is added to force this property to work.
-The [ICE comparison](./nat-traversal.md#teamspeak-ice-comparison) owns its
-separate connection-establishment findings.
+[ICE recovery boundaries](./nat-traversal.md#ice-recovery-boundaries) own
+connection establishment separately.
## Quality Shadow
@@ -887,11 +821,6 @@ percentages, and tuning loops are not adopted for this Browser product.
- [Picture-in-Picture](https://www.w3.org/TR/picture-in-picture/)
- [Chrome timer throttling](https://developer.chrome.com/blog/timer-throttling-in-chrome-88)
- [Chrome Page Lifecycle](https://developer.chrome.com/docs/web-platform/page-lifecycle-api)
-- [Discord Go Live pipeline](https://discord.com/blog/how-it-all-goes-live-an-overview-of-discords-streaming-technology)
-- [Discord AMD encoder ratchet](https://discord.com/blog/from-blocky-to-brilliant-improving-video-quality-on-discord-go-live-on-amd-gpus)
-- [KOOK screen-share requirements](https://support.kookapp.cn/7ff3/b671)
-- [KOOK resource troubleshooting](https://help.kookapp.cn/6a2f/8525)
-- [Oopz network-path troubleshooting](https://help.oopz.cn/fa71/694b)
- [Agora degradation preferences](https://api-ref.agora.io/en/video-sdk/android/4.x/API/enum_degradationpreference.html)
- [TRTC encoding and QoS parameters](https://trtc.io/document/50775)
- [LiveKit server forwarder](https://github.com/livekit/livekit/blob/v1.13.5/pkg/sfu/forwarder.go)
diff --git a/docs/research/room-interactions.md b/docs/research/room-interactions.md
index fe92a54f..39f4741f 100644
--- a/docs/research/room-interactions.md
+++ b/docs/research/room-interactions.md
@@ -2,7 +2,7 @@
The owner accepted the text/reaction UI and model with bounded local acceptance.
[Status](../status.md#accepted-interaction-phase) owns release readiness and
-[TODO](../todo.md#now) owns remaining work. Reviewed 2026-10-02.
+[TODO](../todo.md#now) owns remaining work.
This document records the implementation design and its tradeoffs;
[rooms and access](../standards/rooms-access.md#room-interactions) owns authority
and retention, while [presentation and lifecycle](../standards/presentation-lifecycle.md#product-surface)
@@ -54,10 +54,9 @@ ends that service; merely leaving the Host page does not.
`hostRoomSession`; absence means the corresponding behavior is unavailable.
The page explicitly subscribes after authentication. Only subscribed current
sessions receive interaction events. The Host room-session behavior also
- requires the `roomSession: true` authentication opt-in; older clients retain
- the original stop-and-leave contract. Existing v23 media messages remain
- valid, and publication start/result messages are sent only to an opted-in
- session.
+ requires the `roomSession: true` authentication opt-in; sessions without it
+ retain the stop-and-leave contract. The [public compatibility boundary](../standards/versioning.md#public-compatibility-promise)
+ still applies; publication start/result messages go only to an opted-in session.
- The viewer discovers this optional capability independently of first-picture
startup. Late capability discovery enables data on the existing connection.
- A strict command payload union admits plain chat text or a registered reaction. Chat is
@@ -94,14 +93,13 @@ ends that service; merely leaving the Host page does not.
## Interaction Design
-Chat uses the shared `FloatingPanel` shell for its nonmodal window. The shell
+Chat and reactions use an interaction window in the shared `FloatingPanel` shell. The shell
owns native visibility, placement, movement, resizing and focus return; the
conversation retains its session, draft, reading position and unread state.
It opens initially at the lower right, without
-resizing the picture or moving the couch. Drag its title bar, use arrow keys on
-the focused bar, or explicitly choose a corner under Position. Its summary also
-allows dragging; a drag never activates the menu. Resize from either diagonal
-corner, use arrow keys on a resize handle, or choose a preset under Position.
+resizing the picture or moving the couch. Drag its title bar or use arrow keys on
+the focused bar. Resize from either diagonal corner or use arrow keys on a resize
+handle. These direct controls also work with touch; there is no separate placement menu.
Resizing holds the opposite corner steady. Size and position belong to this room
UI only; viewport and keyboard changes bound them without erasing preferences.
The native manual
@@ -128,12 +126,28 @@ target even after moving the window. Selecting a different participant keeps its
placement and any manually chosen size; selecting the same person toggles it.
The default palette height follows its content, bounded by the visible viewport.
One's own palette expresses a reaction above oneself and holds the local effects switch; other
-people's palettes offer targeted expressions and two labelled throwing props.
+people's palettes offer targeted expressions and two throwing props. The props form
+a compact pair of named action buttons beneath the expression grid, using the
+shared button motion. The same palette serves both the couch and conversation.
Connection details remain secondary when that participant has inspectable data.
Close or Escape dismisses the palette; it also closes if its participant leaves.
Sending keeps it open for repeated interaction, with the existing short cooldown.
Confirmation never changes menu visibility; failure stays visible in the card.
Opening or closing a reaction card preserves the chat draft and unread state.
+The interaction window keeps one composer with an on-demand reaction tray.
+Its recipient strip uses the same room identities and the couch's shared palette.
+The tray shortens the scrollable message list rather than covering messages;
+the input and reading position stay in place. Its composer button or a current
+participant's message avatar opens it and focuses the selected person; Escape
+returns to that opener. Avatars of departed participants remain non-interactive.
+Typing or pressing Escape dismisses the tray; sending a reaction keeps it open.
+While it is closed, the newest live reaction briefly shows its sender and recipient
+with the same animation renderer.
+It adds neither a message history entry nor an independent expiry timer. Member
+controls and reactions open on demand within the small companion window. Only
+unobscured chat following the latest messages consumes
+unread messages. The detached window uses the same room session, event expiry and
+sending controls as the couch shortcut.
Self expressions follow the sender's head, including idle and interaction motion.
Only that sender's newest self expression replaces their earlier one. A targeted
emoji is a delivery: it travels from sender to recipient, retains a compact
@@ -148,12 +162,14 @@ use short gestures and sparse accents. All decorative descendants share the
event's remaining phase and expiry; event ID and sender identity seed their
variation. No particles, stains or animation timers outlive the event.
A departed participant is never silently replaced as target.
-Everyone sees the same server-issued event; placement follows their own couch
-layout. Effects have a couch-only coordinate owner, independent of panel layout,
-and never become a video overlay or a media status. Impact transforms leave the
+Everyone sees the same server-issued event; placement follows the people in each
+visible surface. Each roster owns its local coordinates and uses the same renderer.
+Effects never become a video overlay or a media status. Impact transforms leave the
UUID-owned idle animation, names and status indicators alone. Hiding effects or
retiring the event cancels its own animation; showing a still-live event uses its
-remaining lifetime. Users can hide effects; reduced motion uses a static stamp.
+remaining lifetime. Animation scheduling and visibility follow the document
+displaying the surface, so a hidden main page does not freeze its detached window.
+Users can hide effects; reduced motion uses a static stamp.
Theater mode hides the couch and retains a chat entry, using the same floating
panel and draft without changing the picture's size. HTML player fullscreen
keeps the existing danmaku control; it does not include the conversation panel.
@@ -236,11 +252,11 @@ Bidirectional room voice is not part of the product plan.
Text, reactions and danmaku introduce no microphone capture, voice
admission or additional media peers.
-## Detached Chat Window
+## Detached Interaction Window
[Document Picture-in-Picture](https://developer.chrome.com/docs/web-platform/document-picture-in-picture)
-places the current chat panel in an always-on-top window without installing a
-PWA or implementing an App window. The candidate adopts one stable React portal:
+places the current interaction panel in an always-on-top window without installing a
+PWA or implementing an App window. Piik uses one stable React portal:
the same session, DOM, draft, reading position and controls remain in use.
Visibility, focus, tooltip placement and dismissal follow the displaying document.
Theme and language follow the opener. The browser owns window movement and sizing;
@@ -249,7 +265,7 @@ including a window request that completes after retirement.
The [specification](https://wicg.github.io/document-picture-in-picture/) requires
a secure context and user activation; closing or navigating the opener closes
-the PiP window. It is useful for reading chat beside a windowed or borderless game;
+the PiP window. It supports chat and reactions beside a windowed or borderless game;
placement above exclusive fullscreen is not guaranteed. Transparent desktop
backgrounds and mouse passthrough remain an
[upstream request](https://github.com/WICG/document-picture-in-picture/issues/99),
@@ -259,10 +275,27 @@ is incomplete, so unsupported pages retain the in-page panel. Video PiP and chat
PiP may replace each other under the browser's single-window policy; no media
or room owner changes. This needs no new room protocol or major version.
-## Remote Control Assessment (Not Implemented)
+## Multiple Sharers Assessment (Not Implemented)
-Reviewed 2026-10-15. Cross-platform control is a candidate, not an accepted
-product expansion. A Browser on a computer or phone could control a desktop App;
+The requested party mode lets several participants share their own screens while
+each Viewer chooses one picture to watch. Publishing and watching would be
+independent, with room administration separate from publication ownership.
+The existing one-Host workflow would remain the default.
+
+This is a model change: the current route controller owns one Host and one
+publication. Each new publication would need its own source generation and
+subscription lifecycle, while endpoint upload limits remain shared across all
+publications. Creating a controller per source must not multiply that endpoint's
+outbound allowance. Switching pictures should replace the selected subscription,
+preserving room membership and chat. One selected picture is the initial scope;
+camera conferencing and room voice are separate features. No implementation or
+protocol change is accepted by this assessment.
+
+## Attended Remote-Control Prototype
+
+Reviewed 2026-10-19. Remote control is included in the accepted release scope.
+Desktop and mobile Browsers are controllers; Windows App
+input has local physical evidence, while macOS/Linux backends remain under platform acceptance;
controlling Android/iOS themselves is a separate platform problem. The
[Captured Surface Control draft](https://w3c.github.io/mediacapture-surface-control/)
only provides limited wheel/zoom operations, not general OS keyboard/mouse input.
@@ -274,29 +307,335 @@ needs a separate grant, and Linux needs desktop-specific integration such as the
[RemoteDesktop Portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.RemoteDesktop.html).
Mobile controllers also need touch and text-input behavior, not just mouse-event reuse.
-The inspected [uu-remote-linux implementation](https://github.com/VallierDev/uu-remote-linux/tree/b44a639d9f94a249e511b210ac9c7f9b457fda38)
-implements the Linux controlled endpoint; its controllers, account and signaling
-service remain in the official UU ecosystem. It is not an independent
-cross-platform remote-control SDK. Its GPL implementation remains study-only
-under the repository's contribution rules. No matched measurement establishes
-a Go/Rust performance advantage or a need to replace Piik's media pipeline.
-
-A bounded candidate would be attended desktop assistance: one explicitly
-approved controller, with a local revoke action and no unattended access.
-App input authority would have to be process-wide because its two native
-sessions share the same OS keyboard and pointer. Site capture approval cannot
-silently grant a Viewer input rights. Source/session retirement and disconnect
-would end the grant, discard queued input and release pressed keys; reconnect
-would require fresh approval. Whole-window capture is not input isolation.
-
-Transport remains undecided. Existing authenticated signaling could carry
-bounded, directed assistance input independently of the media tree, but adds
-server latency and exposes input to that service. A WebRTC data channel could
-reduce that dependency only with a reachable control path: Viewers may receive
-media from another Viewer or the SFU instead of the Host. Piik has no application
-data channel today. Neither choice is equivalent to reusing chat's 800 ms
-limiter. Scope, input privacy, retirement, latency and real platform acceptance
-must justify the added owner before implementation; current sharing is unchanged.
+The native input backend is included by the existing platform build constraints;
+App checks and packaging use the same implementation without an experimental
+feature tag. App discovery advertises the optional input capability;
+a supporting page opts in when starting its native share. An older page emits
+no opt-in, so it receives neither new input events nor input channels. The
+prototype shares a display or window with one desktop or mobile Browser controller.
+Ordered WebRTC data channels carry small input messages back along the existing
+committed media route: direct, Browser relay, App relay or embedded SFU. The
+same Go forwarding module serves App playback/relay and SFU; the Browser adapter
+follows its active media input and child edges. No new listener, PeerConnection,
+route planner or dependency is introduced. The control button appears only
+after the Host enables remote control and the complete input path reports readiness. Updated forwarding peers are
+required along that path; an older peer can still carry the picture.
+Independent virtual gamepads are deferred by the owner; this phase adds no
+input driver.
+
+The logical owners are App coordination/authority, native capture/encoding, and
+native input. These are module boundaries, not three required executables.
+`internal/app/remoteinput` owns permission, grants and release; its platform
+adapter only resolves the target and executes input. Windows uses `SendInput`;
+macOS uses public Quartz events and requests Accessibility permission only when
+the Host enables control. macOS window input also verifies the process incarnation
+and actual focused AX window, rather than treating stacking order as focus.
+
+Linux uses the existing capture helper's RemoteDesktop Portal session for both
+the selected monitor and input permission. Ordinary sharing still requests only
+ScreenCast. Enabling control opens the system's combined screen/input selector;
+cancelling leaves the previous share intact. Support requires keyboard/pointer
+capabilities and libportal's restore-capable API; missing support leaves ordinary
+capture available. The inherited capture pipe carries input, with no new listener
+or privileged device access. Replacing that Portal session, including a quality
+change, revokes its input grant and resets policy before binding the replacement.
+This first Linux backend supports a monitor, not window-scoped input.
+Linux compilation, synthetic Portal input/release checks and shared Go lifecycle
+tests pass in an isolated VM. Apple SDK builds and package checks pass on both
+Intel and Apple silicon CI. A real Linux desktop/compositor and physical macOS
+permission/Retina/focus checks remain unverified.
+
+Opted-in room signaling binds an ephemeral key and endpoint ID to each
+authenticated Viewer, then sends that binding only to the owning Host. The
+Host passes the snapshot through its existing authorized native session.
+Viewer and native Host use platform AES-GCM to protect input and grant replies;
+intermediate Viewers and the SFU forward ciphertext, not keyboard events or
+authority. The Site remains trusted because it distributes those keys.
+Keys are scoped to the authenticated connection, excluded from diagnostics and
+never persisted. Direction, sequence and input-channel incarnation bind packets
+to their current owner; a delayed closure from a replaced branch cannot revoke
+a newly approved channel. The Browser requires Web Crypto in a secure context
+(HTTPS or localhost); ordinary HTTP viewing remains available without remote input.
+This uses [WebRTC data channels](https://www.rfc-editor.org/rfc/rfc8831.html)
+and the platform [AES-GCM API](https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams).
+
+`internal/app/remoteinput` owns one process-wide grant because the App's native
+sessions share the same physical keyboard and pointer. Remote control starts
+off. The Browser remembers the last successfully applied authorization mode;
+the Host must still enable it manually for each new shared source. Ask each time
+is the default. A remembered password mode asks for a new password before
+applying; the password itself is never remembered. Automatic modes accept only
+authenticated room Viewers and never displace an active controller. Permission
+belongs to the current shared source; changing sources or stopping turns it off.
+Turning it off also clears pending requests and releases held input, including
+while sharing is paused or another capture operation is pending. One input-owner
+intent covers dispatch, OS permission and capture preparation. Off, pause and
+source retirement invalidate it before a late result can enable control. A
+capture already accepted for installation remains owned by the share; cancelling
+input permission cannot kill that picture. The password verifier is kept only in App memory, with one
+attempt per second shared across that source's endpoints. The verifier is never saved in
+configuration, diagnostic reports or links. Host approval, decline and end-control
+actions stay on the same sharing page. The existing authorized native-control connection carries these commands;
+only the session that owns the share can decide its requests. Request identity
+comes from the authenticated room binding, never a relay-supplied participant
+name. The grant is bound to that input channel and source, with a fresh nonce for each approval.
+Each request has its own identity: a late Host decision cannot approve a newer
+request, and a late approval cannot revive the Viewer's cancelled intent.
+Source unavailability ends every pending intent, including one not yet received
+by the Host; it is not a response scoped to an older request.
+Site capture approval never grants input rights. Input may operate the whole
+computer; a shared picture is not an OS input sandbox.
+
+Revocation, pause, source replacement/retirement and connection loss release
+held keys and buttons. The channel belongs to the sharing session; permission
+and pointer coordinates belong to its current source. The Host can change
+windows/displays through the existing source picker without starting another
+share, with fresh permission for the replacement. Audio-only changes retain the
+current grant. Brief ICE loss and media-route replacement revoke permission;
+the recovered path carries a fresh request. App playback and relay descendants
+follow the same rule; interruption releases the upstream grant.
+A closed control channel needs a new media
+connection; neither path silently restores a grant. Either side can end control
+from its page. Windows also supplies a local Ctrl+Alt+F10 stop shortcut; macOS
+uses Control+Option+F10. Linux retains the desktop's sharing controls instead
+of registering a second global key grab. A Host stop (including that local shortcut) also resets automatic
+permission to Ask each time. A Viewer ending their own control leaves the Host's
+policy in place. This adds no service, automatic sharing or control across App
+restart. Escape releases game mouse capture without ending the grant.
+Window blur releases held input. Control ends when no input surface is visible,
+or when video is locally paused or enters native PiP/fullscreen. New requests
+require the picture to be playing in the page; returning never restores a grant.
+DOM fullscreen keeps the page's input surface and retains control. Pointer motion retains the
+latest absolute sample or accumulated relative movement within a short timer,
+flushing before button/key transitions so a drag ends at its final position.
+Input batching does not wait for rendering. Motion batching stays independent
+and bounded.
+Normal pointer-capture release after mouse-up preserves held keyboard keys;
+actual cancellation, blur and grant retirement release them.
+Host settings reuse the shared floating panel beside their entry. An unapplied
+enable request shows a cancel action without displaying permission as granted;
+older completions cannot replace newer form feedback. Viewer request, failure and
+focus feedback stays beside the remote-control action, separate from media health.
+Desktop control uses the normal pointer, game mouse capture hides it, and touch
+control retains its visible arrow.
+Control actions use the existing playback bar. While controlling, a drawer handle
+on the television frame reveals the bar, keeping picture pixels available for
+input. Remote key input does not count as keyboard navigation of playback controls.
+Host management and the Viewer's virtual keyboard can use the browser's
+always-on-top document window, reusing the same portal and state as chat.
+Closing that window returns its content to the page. Keyboard migration, blur
+and retirement release held input; its visible detached document keeps the
+existing grant while the main tab is hidden. Physical key capture and game
+mouse lock stay with the picture, while the detached keyboard sends virtual
+keys and committed text through the same input session. Grant retirement
+closes the keyboard window. Browsers without this API retain the in-page UI.
+A stalled send queue closes the input channel
+without replacing the media connection. No input history is persisted.
+
+Local acceptance exercised real Windows display capture, Browser and App-assisted viewing,
+native mouse click, keyboard text, wheel, held-key release and the local stop
+shortcut. The consent owner was also checked over real SCTP channels for
+unapproved/stale input, controller replacement, pause, disconnect and source
+retirement. Display → window → display switching retained the channel and
+required fresh approval; the App-assisted path delivered actual mouse/keyboard
+input and released a held key on revocation. Request snapshots and decisions
+are scoped to the owning native share; another session cannot inspect, approve
+or decline them. Real Browser-relay, App-relay and SFU chains also delivered
+video and native key input, released held input on Host revocation, and retired
+control on share stop. Both relay chains recovered viewing and accepted a fresh
+request after their intermediate participant left. These checks do not
+establish remote-network latency, game compatibility, mixed-DPI behavior or
+antivirus classification. The experiment build and disposable UI/input probes
+remain under ignored `build/remote-control-prototype/`.
+
+Touch input uses a relative touchpad over the contained picture: one finger
+moves the cursor, a tap clicks, holding starts a drag, and two fingers scroll
+or tap for a right-click. Pinching magnifies the local picture up to 4×; while
+magnified, a two-finger drag pans the view instead of scrolling the remote page.
+A 1× button restores the whole picture. One gesture owner distinguishes pinch
+from scrolling after both contacts update, and retains that choice until release.
+The input geometry uses the transformed picture; local panning keeps its touch
+cursor visible without sending input. Zoom is cleared with the grant and does
+not change capture resolution or the media route. Pointer events select this
+behavior without OS or browser-name checks. The gesture owner is scoped to the current grant;
+cancellation, blur and grant retirement release held input. Temporary loss of
+Host window focus retains the grant's touchpad position while suspending input.
+The keyboard panel reserves space below the picture, or beside it in a short
+landscape fullscreen/theater view. Letters, numbers/symbols and function/navigation
+keys use separate compact sections; text input retains the local IME. Opening
+the key panel does not summon the phone's software keyboard. Keys follow physical
+press/release by default. Optional combination mode lets a tap select each
+modifier; completing the next ordinary key releases the selected modifiers.
+Tapping a selected modifier again cancels it; turning the mode off releases all keys.
+Held contacts repeat and release independently, including
+on cancellation, panel closure and window blur. No pressed state survives grant
+retirement. Common text shortcuts remain beside the text field.
+Its buttons follow the controlled App's platform, including Windows Win+Space
+and macOS Command shortcuts, without depending
+on the local OS delivering that combination to the page. Physical system-key
+capture remains subject to the local OS and Browser; even the
+[Keyboard Lock API](https://developer.chrome.com/docs/capabilities/web-apis/keyboard-lock)
+only receives keys the OS permits. Piik does not install a global keyboard hook
+or simulate the protected Ctrl+Alt+Delete sequence. Closing the keyboard returns
+focus to the control surface.
+The multiline text field owns IME composition and preserves a pasted draft;
+Enter edits that draft and the explicit button submits it. One submission is
+bounded to 2 KiB of UTF-8 so it fits the existing input queue without a bulk
+transfer channel; an oversized draft stays editable rather than being truncated.
+The shared input owner releases held keys and maps line endings/tabs to their
+physical keys before passing ordinary text through the platform adapter, including Windows
+[Unicode input](https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput),
+Quartz Unicode events and Portal keysyms.
+There is no clipboard synchronization. This follows the touchpad conventions in
+[Moonlight's input guide](https://github.com/moonlight-stream/moonlight-docs/wiki/Setup-Guide#keyboardmousegamepad-input-options).
+No game-specific touch layout is added.
+Chromium touch emulation delivered native clicks, scrolling, drag/cancel,
+Chinese/emoji text and shortcuts over the existing P2P route. Narrow layouts,
+DOM fullscreen, zoom/pan coordinate alignment and Host revocation passed;
+physical Android/iOS soft keyboards and Safari's native fullscreen remain device
+checks, not established by emulation.
+
+Remote control can target an additive 2.x release under the
+[compatibility contract](../standards/versioning.md#extending-interfaces): advertise
+an optional capability, and exchange new commands/events only between supported,
+opted-in sessions. Existing sharing and old command/event shapes remain intact.
+Site capability and App discovery readers already tolerate unknown descriptions;
+this is an extension point, not proof of end-to-end compatibility. Local crossed
+builds of the published 2.1.0 page/App and this prototype completed native window
+sharing and Viewer decoding in both directions, without input opt-in, new input
+events or a remote-control button when either side lacked support. This covers
+those two combinations, not every published Site/App version. Multiple publishers
+are not a prerequisite, and neither feature size nor an internal refactor alone
+requires a major release.
+
+### Distribution Risk
+
+[Microsoft's software criteria](https://learn.microsoft.com/en-us/defender-xdr/criteria)
+distinguish malicious behavior, unwanted software and user choice/control.
+Attended remote control is a legitimate feature, but input injection and its
+potential misuse can invite additional security review or enterprise blocking.
+No source establishes a numerical false-positive increase for Piik.
+[SmartScreen reputation](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/smartscreen-reputation)
+and [Chrome download warnings](https://support.google.com/chrome/answer/6261569?hl=en)
+are also distinct from a confirmed malware detection; signing does not guarantee
+that a new binary avoids a warning. This prototype adds no unattended access,
+startup persistence, elevation, driver, keyboard hook or security-product bypass.
+Do not recommend antivirus exclusions as its deployment model.
+
+### Remote Co-play
+
+[Steam Remote Play Together](https://partner.steamgames.com/doc/features/remoteplay)
+lets remote participants act as local players in the Host's game. For Piik, this
+retains one shared picture. Games that support a shared keyboard can use separate
+key bindings for the Host and remote player without an input driver. Independent
+gamepads instead need per-player virtual controller slots. The first phase has
+one approved remote keyboard/mouse controller; multiple concurrent controllers
+would need per-controller held-key ownership so one player's key-up does not
+release another's key. The mouse remains one shared pointer.
+
+Game player count is separate from input-device support. Team17 documents
+[four local players but two sharing one keyboard in Overcooked! 2](https://www.team17.com/news/overcooked-2-faq).
+[Pummel Party's developer](https://steamcommunity.com/app/880940/discussions/0/1742226629869609303/)
+describes assigning a physical controller separately from keyboard/mouse; its
+local-player count does not establish split-keyboard support. A Host using a
+physical controller and one remote keyboard player can therefore be another
+driver-free use case when the game supports that combination. Piik's first
+phase limits remote input to one approved Viewer, not the game's local players.
+Keep the UI named remote control; co-play is a use case of the same input grant.
+
+Simulating keys is different from creating independent devices. Windows
+`SendInput` writes to the existing input stream; it does not create a second
+keyboard or pointer. Microsoft's [Virtual HID Framework](https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/virtual-hid-framework--vhf-)
+still requires a HID source driver. Device identity also needs support in the
+game. Windows also exposes [gamepad injection](https://learn.microsoft.com/en-us/uwp/api/windows.ui.input.preview.injection.inputinjector.injectgamepadinput),
+but it requires the restricted `inputInjectionBrokered` package capability;
+that API alone does not establish a portable-App backend or independent slots
+accepted by desktop games. Linux can create devices through its existing
+[uinput module](https://docs.kernel.org/input/uinput.html), subject to device
+permissions. Dependencies therefore follow the platform and supported games.
+Per-player virtual keyboards, mice and gamepads remain deferred; keep
+that future integration at the platform input boundary without prebuilding a
+device registry, driver installer or alternate transport.
+
+[Moonlight's input implementation](https://github.com/moonlight-stream/moonlight-common-c/blob/aeba988e0a302145eff2e70fa3e11cd98ec01f5d/src/InputStream.c)
+accumulates relative movement and sends the latest absolute pointer position;
+input event semantics determine batching and delivery, rather than treating
+every sample as chat. [Sunshine's input owner](https://github.com/LizardByte/Sunshine/blob/5b2a4cfdfa643b5307906c68eb122e5a34855263/src/input.cpp)
+tracks pressed keys/buttons and resets input state. These are useful reference
+patterns for bounded queues and grant retirement. Their GameStream transport
+is not a Browser WebRTC input component; both implementations remain study-only
+under the project's license policy.
+
+Virtual gamepads are a separate platform cost. [Sunshine's input configuration](https://docs.lizardbyte.dev/projects/sunshine/master/md_docs_2configuration.html#gamepad_driver)
+documents Windows/macOS driver or broker dependencies; its Windows ViGEmBus
+fallback is end-of-life. Independent gamepads were deferred by the owner on
+2026-10-17; there is no driver integration in this phase. A future gamepad
+prototype needs an accepted backend and supported-game checks. This does not
+require multiple screen publishers or a replacement media transport.
+
+### Window Capture And Game Input
+
+Reviewed 2026-10-17. The prototype now passes the existing native capture target
+to the input owner for both windows and displays. Capture selection, input
+capability and Host permission remain distinct facts; this adds no media path
+or input driver. Virtual gamepad eligibility must follow its input backend and
+grant, rather than desktop pointer coordinates.
+
+For window keyboard/mouse control, the captured region must map to the current
+native window geometry, including movement, resizing and DPI. The input owner
+reads the current geometry and process identity. It suspends input and releases
+held state when the target loses focus, and revokes control if the source
+disappears. Both pages display that same suspension; the Host is asked to focus
+the shared window to resume. This reduces
+accidental input after switching away; it is not an OS window sandbox.
+`SendInput` has no target-window parameter, and shortcuts can change focus.
+Window selection must never imply that remote input is confined to that window.
+
+The Windows sink uses physical-key mapping through
+[scan codes](https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput),
+and supports relative mouse movement through browser
+[Pointer Lock](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API),
+with an exit interaction that leaves Escape available to games in ordinary
+pointer mode. Mouse button transitions use `mousedown/up`: unlike
+[`pointerdown/up`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerdown_event),
+they retain chords such as holding right while clicking left. Pointer capture
+keeps drags attached to the picture; release is observed across the Viewer
+window so leaving the picture cannot leave a button pressed. Scroll handling
+retains magnitude and fractions across Browser wheel units; the default
+conversion follows [Chromium's wheel mapping](https://github.com/chromium/chromium/blob/main/ui/events/blink/web_input_event_builders_win.cc)
+and [Windows wheel/button semantics](https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-mouseinput).
+The Browser input session owns request/grant lifetime separately
+from the React controls and DOM capture. Real SCTP checks cover permission,
+focus suspension, updated geometry and retirement; Browser checks cover window
+capture, consent and pointer lock. Local window move/resize checks matched the
+input owner's live bounds to the decoded WGC aspect ratio, including even-pixel
+encoder rounding. A visible isolated Windows target received native clicks
+before and after movement/resizing, physical-key and relative-mouse input;
+focus suspension/resume and Host revocation also passed. These checks do not
+establish commercial-game compatibility or mixed-DPI behavior.
+
+A local Pion/SCTP probe with 40 ms RTT delivered ordered input in about 20 ms
+without loss and about 94 ms at the 95th percentile when every twentieth
+outgoing data packet was dropped. A lost final event, without subsequent input,
+instead waited about 683 ms for retransmission. This synthetic transport probe
+does not establish Browser or game latency. Reliable delivery prevents lost
+key-up events from permanently holding a key, but does not promise immediate
+release during loss. Keep the first prototype on the existing ordered channel;
+desktop acceptance must not be presented as competitive-game readiness. These
+are input semantics and acceptance work, not reasons to replace the media pipeline.
+
+The reviewed implementation uses WGC capture and the documented Windows input
+API, without game-memory access, injected game code or an input driver.
+[SendInput](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput)
+remains subject to process-integrity restrictions, and a successful call only
+proves insertion into the system input stream, not acceptance by a game.
+[Windows marks injected keyboard events](https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-kbdllhookstruct).
+[BattlEye distinguishes blocking/kicks from bans](https://www.battleye.com/support/faq/);
+its policy does not certify Piik or another game's anti-cheat. No current evidence
+establishes Piik game compatibility or a ban probability. Virtual controller
+drivers are likewise not an anti-cheat exemption. Keep integration on supported
+platform APIs and maintained input backends; do not add process injection,
+protection bypasses or forced background input to make a rejected game work.
## Primary References And Rationale
diff --git a/docs/research/webrtc-encoder-pool.md b/docs/research/webrtc-encoder-pool.md
index ee8ae801..ac59a42c 100644
--- a/docs/research/webrtc-encoder-pool.md
+++ b/docs/research/webrtc-encoder-pool.md
@@ -562,10 +562,10 @@ and timestamp. This proves spatial isolation and valid delivery, not weak-path
cadence parity. Budgets in these grouping fixtures are explicit transport
inputs; the separate shaped-network gate owns automatic estimator evidence.
-A subsequent [TeamSpeak comparison](./realtime-quality-adaptation.md#teamspeak-native-comparison)
+A subsequent [native encoder experiment](./realtime-quality-adaptation.md#native-encoder-policy-experiments)
tested replacing this partition with one common output: either the maximum or
the harmonic mean of the active requests. These are policy ablations, not a
-reproduction of TeamSpeak's receiver eligibility and dependency controller.
+a replacement for independent receiver eligibility and dependency ownership.
The real Native VP8 fixture supplied 1280x720 motion, with requests of
80 kbps and 1.25 Mbps for twenty seconds, then equal requests and retirement.
The independent groups retained the healthy receiver's 640x360 output at
@@ -576,7 +576,7 @@ derived encoder count but lost independent budget ownership. All variants
kept the decoder process while demand changed, then retired it after the last
consumer left. Chrome WebCodecs decoded every exported picture. This bounded,
forced-demand comparison does not measure real link capacity, perceptual
-quality or TeamSpeak's runtime performance; it supports retaining the current
+quality or another application's runtime performance; it supports retaining the current
partition rather than replacing it with one aggregate rate.
The full H264 Windows Host/Viewer gate also passes live and paused profile
diff --git a/docs/standards/documentation.md b/docs/standards/documentation.md
index 23b74e17..a0672814 100644
--- a/docs/standards/documentation.md
+++ b/docs/standards/documentation.md
@@ -11,6 +11,7 @@ verification procedures stay in [CONTRIBUTING.md](../../CONTRIBUTING.md).
| Topic | Owner | Keep here |
| --- | --- | --- |
| Universal constraints and navigation | `AGENTS.md` | Short mandatory boundaries and links; no procedure manual |
+| Reusable agent methods | `.agents/skills/*/SKILL.md` | Task triggers and methods under project constraints; link to domain rules and delivery rather than repeat them |
| Branches, review, validation, PRs, releases and cleanup | `CONTRIBUTING.md` | Executable workflow |
| Module boundaries, interface discipline and ablation | [Engineering](./engineering.md) | Current responsibility map and shared coding rules |
| Names, terminology and voice | [Naming and copy](./naming.md) | Product/tool names, role labels and Chinese/English writing conventions |
@@ -66,8 +67,14 @@ audit-summary directories or replacement archives of completed work.
Published copy describes Piik's behavior and design directly. Remove discarded
design labels, private operational details and conversational comparisons to
-other products. Retain primary technical evidence and required attribution or
-license notices; rewriting prose must not obscure the origin of reused work.
+other products. Describe visual choices in Piik's own design vocabulary.
+Retain relevant public technical references beside the claims they support,
+using accurate names and direct links without implying affiliation or endorsement.
+Local research inventories do not belong in product copy; keep source provenance
+accurate rather than relabel private observations as public documentation.
+Credit reused code and assets through their existing license and notice owners;
+a reference or thank-you does not replace permission or required attribution.
+Preserve accepted contributors' authorship under [CONTRIBUTING](../../CONTRIBUTING.md).
## Consolidation And Ablation
@@ -89,6 +96,31 @@ the external rationale; the existing hygiene scripts own executable limits.
Their gardening warnings invite review, not arbitrary compression; hard failures
for broken links, required owners and instruction-loading limits remain binding.
+## Agent Instructions And Skills
+
+Keep broadly applicable project constraints near the top of `AGENTS.md`, with
+explicit task triggers for required skills. Domain standards define accepted
+behavior; skills explain how to do a recurring kind of work. Neither research
+examples nor skill defaults can expand user authorization or replace a domain
+decision. Use repo-linked adaptations when a global skill has the same name;
+names alone do not establish which instructions were loaded.
+
+Give each skill one recognizable purpose and a short description stating when
+it applies. Keep useful, non-obvious decisions in its body. Link to existing
+owners for details; add supporting files only when a real workflow needs them.
+Do not create nested instruction files merely to split a short document, copy
+the same rules into multiple tool formats, or require every installed skill on
+every turn. Relevant instructions remain applicable without repeated loading.
+
+When changing instructions, check actual task behavior: would a scoped layout
+fix trigger unrelated network gates, a review silently authorize edits, or a
+simplicity rule permit incomplete UX? Check intended triggers and nearby tasks
+that should not trigger the workflow. Preserve necessary safety and compatibility
+while removing conflicting or redundant procedures. Use metadata/link checks
+for structure and representative work for behavior; passing a schema validator
+does not establish that a skill is effective. Add no permanent prompt test suite
+or hooks without a demonstrated recurring need.
+
## Checks
For documentation work use the existing link, whitespace and repository-hygiene
diff --git a/docs/standards/engineering.md b/docs/standards/engineering.md
index ffd8c06e..1dbc47bb 100644
--- a/docs/standards/engineering.md
+++ b/docs/standards/engineering.md
@@ -61,6 +61,12 @@ boundaries exist: [shared core](../adr/0012-shared-go-backend-core.md),
[Browser pooling](../adr/0014-browser-node-local-encoding-pool.md).
Directory names are a map, not a requirement to introduce another layer.
+The official website and public Demo are optional entry points, not runtime
+dependencies of App or self-hosted rooms. Ship the Web assets with the binaries.
+Help and download navigation may prefer the reachable website, with direct
+GitHub destinations while its bounded, page-scoped check is pending or fails.
+Keep this check outside room startup, authorization and media lifecycles.
+
## Contract Map
| Boundary | Schema/validation owners |
@@ -267,6 +273,9 @@ force different authorities into a universal state manager.
The [consistency skill](../../.agents/skills/context-consistency/SKILL.md) owns the
review method; ordinary changes check their affected consumers.
+UI control and surface selection belongs to the
+[visual language](./visual-language.md#control-selection), including when tools
+remain attached, float or detach. Reuse that contract before adding local UI rules.
These boundaries align with [W3C consistent identification](https://www.w3.org/WAI/WCAG21/Understanding/consistent-identification.html),
[GOV.UK contribution criteria](https://design-system.service.gov.uk/community/contribution-criteria/)
diff --git a/docs/standards/media-quality.md b/docs/standards/media-quality.md
index 529c69f6..c7277344 100644
--- a/docs/standards/media-quality.md
+++ b/docs/standards/media-quality.md
@@ -33,6 +33,13 @@ contract. [Status](../status.md) indexes delivery and remaining acceptance.
through mute, pause and source replacement. A capable App/page pair opts into
this output at startup; source sound and microphone state remain independent
facts. Browser preview audio never becomes the native mixing source.
+- Audio input availability belongs to the Host capture/mixer owner: a live source
+ audio input or an enabled, live Host microphone makes audio available. A retained
+ mixed output track alone does not. This describes input presence, not measured
+ loudness; quiet content, share pause and Viewer-local mute remain separate facts.
+ Source replacement and microphone changes update this fact without rebuilding
+ the output or media route. An opted-in room session carries it for the current
+ publication, including late joins and signaling reconnects.
- An audio-only update with the same capture video preserves the Browser video
sender, encoding state and startup evidence on both direct and SFU paths.
A new video source owns a new startup baseline; audio changes do not.
diff --git a/docs/standards/presentation-lifecycle.md b/docs/standards/presentation-lifecycle.md
index af1df106..e1aca925 100644
--- a/docs/standards/presentation-lifecycle.md
+++ b/docs/standards/presentation-lifecycle.md
@@ -24,6 +24,12 @@ room identity, current state, roster, and one manual media-reconnect action.
Controls and text must remain usable without overlap or horizontal overflow on
desktop and mobile viewports.
+Personal room-tool presentation and incoming-route preferences are remembered
+within the same Browser origin across rooms and reloads. Their existing domain
+owners still apply capability and room-policy constraints. Restoring preferences
+never restores room admission, control grants, actual held input, passwords or
+message drafts, and never starts capture or remote control.
+
A capable, opted-in authenticated room session
outlives its current publication. Stopping capture retires media, not chat;
restoring an existing room joins it without starting capture. Entering the page
@@ -34,10 +40,10 @@ is absent, provided the room service and their admitted sessions remain availabl
[Rooms and access](./rooms-access.md#room-interactions) owns interaction authority
and retention; [status](../status.md#accepted-interaction-phase) owns release readiness.
-On capable desktop browsers, chat can move to a Document Picture-in-Picture
-window. It remains one presentation of the admitted room session, with the same
-draft and history. Read visibility and guidance follow its current document.
-Closing the window returns chat to the page; room retirement or opener teardown
+On capable desktop browsers, the interaction window can move to a Document
+Picture-in-Picture window. It retains the admitted room session's messages,
+reactions and draft. Read visibility and guidance follow its current document.
+Closing the window returns it to the page; room retirement or opener teardown
closes it, including a late asynchronous open. Browser window support does not
promise game-overlay transparency, click-through or exclusive-fullscreen coverage.
@@ -151,6 +157,19 @@ or disconnected. Theater and fullscreen are separate modes. Page-element
fullscreen includes the playback bar; Safari's video-only fullscreen uses
system controls and native video events to reflect playback and exit.
Identity, connection details and topology stay in the deck.
+Room tools outside the fullscreen player close when it enters fullscreen.
+Returning a detached tool during fullscreen keeps it closed in the page; leaving
+fullscreen allows reopening it with its session and draft intact. The fullscreen
+bar retains the danmaku toggle, not an interaction-window entry.
+
+Viewer playback settings reuse shared controls in an anchored popover;
+placement follows the [visual language](./visual-language.md) without resizing video. Local picture
+fit defaults to contain; cover preserves proportions and may crop edges, while
+stretch fills the player by changing proportions. These choices do not change
+capture or encoding. Remote input and magnification use the same rendered
+picture geometry. Incoming-route choice follows the
+[routing contract](./routing-transport.md#viewer-route-choice); its selected value
+is server-acknowledged intent, not evidence of the currently playing route.
Replacement video bindings do not consult Viewer-local pause: when the Host is
playing, they attempt playback subject to browser autoplay permission. There is
@@ -162,22 +181,32 @@ audio consumer; it preserves current-frame proof and Viewer-local playback.
A pending `play()` canceled by pause or rebinding is not a media failure;
cancellation alone must not invalidate frame proof or disable local playback.
-The bar spans the screen's lower edge, preferring one row. Narrow screens shorten
-the volume slider and compact horizontal spacing and button widths, retaining
-44px control height and all actions; the percentage readout hides on narrow
-screens. If the control groups cannot fit, they wrap without overlapping.
+The bar floats at the picture's lower edge. Narrow screens shorten the volume
+slider and move secondary display actions into settings, preserving one row and
+44px control height; the percentage readout hides on narrow screens.
Playing video hides the bar
after two idle seconds, following [Media Chrome's default](https://github.com/muxinc/media-chrome/blob/main/docs/src/pages/docs/en/components/media-controller.md#autohide).
Pause or unavailable playback keeps it visible. Control hover, keyboard focus,
-dragging and an open tooltip hold it open; mouse movement reveals it, and a
-touch tap on the picture toggles only visibility. One presentation-only idle
-timer owns visibility; it never changes playback or route state. Controls
+dragging and an open tooltip hold it open. Mouse movement reveals it;
+a touch tap on the picture toggles only visibility. Remote input owns picture
+clicks and movement, so use the bezel pull during control; pointer-locked input
+also never reveals the toolbar through mouse movement.
+One presentation hook owns visibility for the current player, using one idle
+timer; it never changes playback or route state. Controls
follow the shared [motion grammar](./visual-language.md#motion-grammar).
-A desktop primary click on the picture toggles local playback after a brief
-double-click window; double-click toggles the available fullscreen action without
-first toggling playback. Controls, overlays and keyboard actions keep their own
-immediate behavior.
+A picture click does not pause playback; the playback button and focused-video
+keyboard shortcut own that action. Desktop double-click toggles the available
+fullscreen action. Remote-control input consumes its own clicks and key presses;
+controls and overlays keep their own immediate behavior.
+
+Host source-audio feedback describes the selected source independently of Host
+microphone commentary. Viewer sound controls require a received audio track and,
+when the Host supplies input availability, an available source or microphone
+input. With no input, sound controls are disabled with the no-audio explanation;
+the Viewer's volume and mute preferences remain intact for audio returning.
+Older Hosts without this fact retain received-track feedback. These controls do
+not infer input presence from silence or change capture, transport or relay audio.
Volume starts on native audio output. An explicit setting away from 100% activates
a local Web Audio stream source and gain, from silence to 200% amplitude. This also
diff --git a/docs/standards/rooms-access.md b/docs/standards/rooms-access.md
index 2431119f..42500c5c 100644
--- a/docs/standards/rooms-access.md
+++ b/docs/standards/rooms-access.md
@@ -132,8 +132,16 @@ for participants still connected to the same room. Interaction subscriptions
inherit existing membership, replacement and revocation checks; they grant no
additional authority and do not modify media routes.
-Sending a reaction requires a registered identifier. Received reaction events
-validate their envelope, identity, target and bounded identifier, then the page
+The reaction palette is curated, with no free-form input. Additions preserve
+existing choices.
+
+Sending a reaction requires a registered identifier. The Server advertises its
+command registry through the optional `roomReactionIds` runtime capability.
+The palette and send owner use its intersection with effects the page knows;
+an absent registry retains the published 2.1 reaction set. Interaction-ready
+events keep their existing shape.
+Received reaction events validate their envelope, identity, target and bounded
+identifier, then the page
skips effects it cannot display. An unknown effect does not terminate signaling,
enter history, clear a draft or confirm a pending send. Unknown message kinds,
extra fields and malformed identities remain invalid; this presentation rule
diff --git a/docs/standards/routing-transport.md b/docs/standards/routing-transport.md
index 2c8e948a..0c81fb5f 100644
--- a/docs/standards/routing-transport.md
+++ b/docs/standards/routing-transport.md
@@ -7,8 +7,8 @@ owns ports and [self-hosting](../operations/self-hosting.md) owns service setup.
## Topology
-- Media is automatic and defaults to P2P-first. Users do not select parents, route types, or
- network transports.
+- Media defaults to automatic P2P-first routing. Viewers may constrain their own
+ incoming hop; parent selection, transport and adaptation remain automatic.
- The Host is the only source. Every Viewer has at most one active upstream, and
the committed media graph is acyclic and source-reachable.
- A Viewer may relay its received Browser track to bounded peer children. This
@@ -27,7 +27,7 @@ background P2P convergence. The Host still publishes once, and every Viewer
uses the existing SFU subscription ledger and first-frame commit. Capacity or
connection failure never permits a Peer route. An explicitly peer-only share
is rejected before acquiring media authority; it is never silently forwarded.
-The page advertises this site policy and hides inapplicable P2P preferences.
+The page advertises this site policy and prevents inapplicable P2P choices.
## Per-Share Route Policy
@@ -69,6 +69,27 @@ sharing. The server-validated route policy remains fixed for that share generati
These are route-policy gates, not new routing algorithms. Changing any
policy requires stopping the current share and starting another generation.
+## Viewer Route Choice
+
+A capable Site offers `auto | p2p | sfu` for the current viewing session.
+Auto keeps ordinary P2P-first routing; the other choices allow only that kind of
+incoming hop. Host peer-only and site SFU-only policy take precedence. A choice
+does not change room privacy: a P2P parent may itself receive through SFU.
+The server acknowledges the choice and reuses the same bounded serial operation,
+capacity ledger and first-frame commit. Existing media remains during permitted
+preparation; exhaustion retires a disallowed route and reports normal failure.
+Returning to Auto restores eligible direct opportunities. A relay's children
+repair through normal availability routing if its ingress is finally retired.
+Restricting the incoming kind does not remove a Viewer from the graph: eligible
+P2P quality repair and service to downstream children keep their existing owners.
+
+The applied choice survives signaling reconnect and source/share replacement.
+The Viewer's explicit preference is remembered within the Browser origin and
+requested again on capable Sites. An incompatible site or share policy applies
+Auto without overwriting that personal preference. Discovery gates
+the optional command, and replies go only to opted-in Viewers; existing 2.x
+participants retain their established protocol and automatic behavior.
+
## Endpoint And Server Capacity
Every non-server endpoint has one server-authoritative steady outbound media-
@@ -104,6 +125,11 @@ without discarding its subtree; departure and capacity changes move only affecte
children. ADR-0005 owns filtering, ordering, cursor, revision, reservation, and
rollback mechanics.
+Reauthentication rebinds retained media and restores eligible direct opportunities
+behind healthy SFU edges through that same continuation owner. The existing
+session-scoped ledger bounds these attempts; a repeated update of the same
+session does not reopen them.
+
Five seconds is a scheduling window only while another bounded candidate or SFU
fallback remains. It advances a silent Peer candidate instead of delaying the
next available route; it is not interpreted as terminal ICE failure. The final
diff --git a/docs/standards/versioning.md b/docs/standards/versioning.md
index d4026329..caa9af36 100644
--- a/docs/standards/versioning.md
+++ b/docs/standards/versioning.md
@@ -26,6 +26,7 @@ authorization counters for visual consistency can invalidate data or stale-work
fences. A room number is a user-facing address, not a software version.
The private tooling-only npm package carries no independent product version.
The App launcher displays its installed version from the existing launcher state;
+the Web footer displays its bundled build version without a network lookup.
Server startup logs retain the running version and revision. The website may
display GitHub's latest stable tag and `published_at` as optional metadata, never
a manually maintained version or the installed App's identity. Publication time
@@ -141,17 +142,18 @@ identity separately. Stable update notices ignore prereleases.
### Major-Upgrade Guidance
-The App update notice keeps a separate link to the selected provider's exact
-release page. A newer major adds a short, visible breaking-change notice; the
-Server logs the same distinction while preserving its checker JSON and exit
-codes. This is release guidance, not a replacement for actual wire checks.
+The App update notice keeps direct download as its primary action, with a small
+Gitee mirror link below it. A newer major adds a short, visible breaking-change
+notice linking to the selected provider's exact release page; ordinary updates
+do not add a separate release-notes control. The Server logs the same distinction
+while preserving its checker JSON and exit codes. This is release guidance,
+not a replacement for actual wire checks.
Updates remain a manual action. Release prose stays on GitHub/Gitee; the App
does not fetch or render remote Markdown or add a second changelog store.
-Direct download remains the primary action; reading notes is optional. Keep the
-major warning inline, without a confirmation dialog or mandatory website detour.
-The same notice offers the official website's download section as a manual
-alternative, including the verified Gitee mirror. API response time does not
-measure package-download throughput; do not add speed probes or automatic
+Keep the major warning inline, without a confirmation dialog or mandatory
+website detour. The mirror link opens Gitee releases without depending on the
+website. API response time does not measure package-download throughput;
+do not add speed probes or automatic
provider switching to an otherwise valid update check.
Older installed Apps cannot acquire new warning UI from release metadata.
@@ -288,10 +290,7 @@ preserves authored Markdown and appends identity/checksums; it does not infer an
editorial summary from a version number. Keep provenance and the full changelog
link after the user-facing explanation.
-Editorial references: [CC Switch releases](https://github.com/farion1231/cc-switch/releases)
-and [OBS Studio releases](https://github.com/obsproject/obs-studio/releases) show
-release introductions and grouped changes; Piik's exact scope and upgrade
-instructions must come from its own accepted changes.
+Piik's release scope and upgrade instructions come from its own accepted changes.
## Release Sources
diff --git a/docs/standards/visual-language.md b/docs/standards/visual-language.md
index 6ca08f92..0b7cee9f 100644
--- a/docs/standards/visual-language.md
+++ b/docs/standards/visual-language.md
@@ -1,7 +1,7 @@
# Visual Language
This is the single design requirement for Piik's shared Web/App interface:
-illustration, semantic colour, panel grammar, motion and tooltip presentation.
+control/surface selection, illustration, semantic colour, motion and guidance.
New UI work follows this file and the local `/__tooltip-preview` catalogue.
[Media status](./media-status.md) owns which facts justify each status;
[presentation lifecycle](./presentation-lifecycle.md) owns interaction
@@ -59,18 +59,82 @@ Keep existing controls in their established positions as a room becomes active.
Represent missing room identity with a passive placeholder in its own slot;
do not move unrelated controls into that space to fill an empty state.
+### Control Selection
+
+Choose by the user's task, then reuse its interaction and visual primitive.
+A sliding selection track shows a discrete choice; a range slider adjusts a
+number. Similar shapes do not make their responsibilities interchangeable.
+
+| Task | Control and existing owner |
+| --- | --- |
+| Perform an action or open a tool | `Btn`; use a stable caption and `aria-expanded` for disclosures |
+| Turn a setting on or off immediately | `SwitchItem`; compact toolbar actions such as mute use a pressed `Btn` |
+| Select independent options within a task | Native checkboxes or independent pressed `Chip`s, such as held modifier keys; a selection awaiting Apply must not look like a committed setting |
+| Choose a short, fixed mode | Shared `.lr-toggle` sliding selection; option chips/cards when individual choices need explanations, richer previews or wrapping |
+| Switch related content pages | A named tablist with one selected tab and its associated panel; use the shared sliding treatment for short labels, including capture categories, and `navigateTabs` for Arrow/Home/End navigation |
+| Pick a device or an item from a variable list | Existing named selector/menu; use source thumbnails when appearance helps identify the item |
+| Adjust a numeric value | Range slider for quick adjustment, with a visible value; reuse `QualityNumberControl` when exact entry or a wider accepted range is useful |
+| Apply several settings together | A named preset tile/chip; allow no preset to be selected when the current values are custom |
+
+Selection, expansion and pending operations describe different facts. Use the
+appropriate native/ARIA semantics even when controls share their styling.
+Button labels and drag handles are not selectable text, including on touch
+browsers. Keep message text and editors selectable. Held-input controls own
+release on pointer-up, cancellation, lost capture and surface blur; a browser
+callout must not consume that gesture.
+Tab navigation keeps focus in the tablist and preserves drafts/settings; the
+navigation key must not become a remote keystroke or start capture. Existing
+resource cleanup still applies. Value changes keep their domain owner's commit
+behavior. A `RowGroup` arranges controls; it does not own their selection.
+
+### Surface Selection
+
+Choose the smallest surface that supports the task's duration and relationship
+to the picture. Movable and detachable are separate capabilities, not upgrades
+that every popup should acquire.
+
+| Task | Surface and existing owner |
+| --- | --- |
+| Read a brief explanation | Shared `Tooltip`; no settings or required actions hidden in a hint |
+| Adjust a few contextual settings | Attached native popover with `useAnchoredPopover`; dismiss after use, no dragging or detaching |
+| Work through related settings | Inline disclosure or tabs, as in `SharingSettings`; expand into page flow rather than cover the picture |
+| Complete a bounded task before continuing | Existing modal dialog, such as source selection; contain focus and return it on close |
+| Keep a room tool available while watching or working | `FloatingPanel`, as used for interactions and Host remote permissions; retain its position without reflowing the room |
+| Use a tool outside the page | Optional `usePanelWindow` on capable browsers; reuse the same content/session, as with interactions, remote permissions and the docked remote keyboard |
+
Persistent room utilities use the shared floating panel without reflowing the
living room. The shell owns visibility, focus return, movement, resizing and
viewport/keyboard bounds; contents retain their domain state. Support title-bar
-dragging and keyboard placement. An interaction palette starts beside its chosen
+dragging, corner resizing and equivalent keyboard controls without a second
+placement menu. An interaction palette starts beside its chosen
participant, stays open after sending and keeps its position when retargeted.
-One-shot settings and guidance retain their existing disclosures. Escape closes
+One-shot settings and guidance retain their existing disclosures. Anchored
+menus use native popovers and shared viewport placement; a small parent panel
+must not clip their actions. Browsers without the Popover API use one shared
+platform polyfill installed before UI mounting; controls retain the same
+visibility, focus and dismissal contract. Escape closes
inner guidance first, then the most recently opened floating panel, then theater
mode; an IME composition must not dismiss these surfaces.
-Detached chat uses the same content in the browser's own always-on-top frame.
+The interaction window gives conversation the main space and keeps one stable
+composer. Its reaction entry or a current participant's message avatar reveals
+the same compact recipient strip and shared palette above the input. The tray
+takes space from the scrollable message list without covering it; neither a
+permanent roster nor a second target heading competes with messages. More
+recipients scroll within that strip. Keep the composer in place while picking,
+and preserve the draft and reading position.
+Live reactions can appear briefly in the conversation surface without moving its
+layout. Retention and export details belong in settings, not beside every entry.
+Detachable tools reuse the same content in the browser's own always-on-top frame.
Close, return-to-tab, movement and resizing belong to that frame; do not duplicate
-its controls in the compact chat header. Keep messages and text contrast
+its controls in the tool header. Keep messages and text contrast
primary; do not simulate transparent desktop content with a washed-out panel.
+Moving or detaching changes the surface, not the domain owner or protocol.
+Request the tool's current rendered size when detaching, within browser window
+limits. The native title bar replaces the floating panel's header; keep body
+spacing and control sizes consistent with the in-page tool.
+Reuse visibility, placement, dismissal and focus behavior through these existing
+owners; do not give each feature its own window manager. Different layouts are
+justified by task or available space, not by which feature was implemented last.
Keep the application language control's segmented Chinese, English and visual
shortcuts. When additional catalogs exist, insert one language menu
@@ -83,6 +147,8 @@ large and long lists scrollable. Locale labels belong to the shared registry.
Use a globe and chevron for the unselected picker, and each language's own full
name in the menu, following [W3C language-navigation guidance](https://www.w3.org/International/questions/qa-navigation-select).
+### Guidance
+
Help-only indicators toggle their guidance on click or tap and dismiss on a
second activation, outside tap, Escape or focus leaving. Touch long-press opens
guidance after a 500 ms hold on both help indicators and action controls,
@@ -134,10 +200,20 @@ symbols; related time measurements keep a clock with a scene identifying the
measured stage. Illustrations explain a metric, never invent its current value,
threshold or quality verdict.
-Shared buttons and chips use pill shapes, a quiet lower edge and a short lift
-on hover or keyboard focus, then compress on press. Inputs and option tiles
-share softer corners. Keep a distinct focus ring and a persistent selected
-state; disabled controls must not pretend to activate. Reduced motion keeps
+### Sharing And Playback
+
+Shared buttons and chips use pill shapes and a quiet lower edge. Standalone
+buttons, chips and option tiles lift 2 px on hover or keyboard focus, sink 2 px
+on press, and spring back over 260 ms on release. Selected and unselected states
+use the same motion; selection changes only their colour and outline.
+Inputs and option tiles share softer corners. Press feedback uses the shared
+motion values in `button.css` and releases the lower shadow. Captions inside
+sliding tracks retain a smaller 1 px lift without moving the track. Keep icon,
+text and control dimensions intact: scaling the whole button shifts off-centre contents
+sideways and changes their stroke weight. Do not add a separate icon displacement.
+Keep filled buttons' border and face in the same colour state; a bright inset
+rim must not look like a gap between them. Keep a distinct focus ring and a
+persistent selected state; disabled controls must not pretend to activate. Reduced motion keeps
the colour, outline and selected position without decorative displacement.
The shared button uses the same pressed value for `aria-pressed` and its selected
treatment; active state remains distinct from hover in both themes.
@@ -150,19 +226,28 @@ and connection details, so inspecting a route does not displace room actions.
Sharing and local playback controls use the same quiet, compact button treatment.
The Host's persistent dock stays below the picture; the Viewer's playback bar
belongs to the video. Their similar appearance does not equate broadcast pause
-with local playback pause. Waiting overlays use the space above the actual
-playback bar, including when it wraps. Keep the primary status readable on
-narrow screens; optional waiting copy yields first. Microphone mute, sharing
-pause, source replacement and stop remain direct actions; stopping stays
-visually separated from frequent actions.
-One compact dock combines direct actions and the sharing-settings entry below
-the television, above the couch. Its disclosure groups quality presets and picture
-parameters with sound and microphone settings; presets remain available before
-sharing starts. Separate the less frequent connection/codec options in a nested
-disclosure. Expand in page flow, pushing later content down instead of covering
-the picture or participants. Keep picture and sound in distinct sections; place
-related adjustments side by side where space permits and stack them on narrow
-screens. Avoid another permanent row of settings cards. Numeric quality inputs
+with local playback pause. A waiting overlay dims the complete picture, including
+behind the playback bar; its message uses the space above that bar. Keep the
+primary status readable on narrow screens; optional waiting copy yields first.
+Microphone mute, sharing pause, source replacement and stop remain direct actions; stop retains its
+danger treatment.
+Group direct sharing actions in one centred dock below the television, above
+the couch. Keep pause/resume and stop adjacent; use an internal separator for
+the settings and remote-permission entries. Preserve that order and grouping on
+narrow screens without splitting the dock into separate floating surfaces.
+Room invitations, admission and chat retain their room scope; they do not become
+sharing settings merely because they use a similar control.
+One inline settings panel uses picture and sound tabs with the shared sliding
+two-option control. Picture presets lead; a fine-tuning disclosure contains
+picture limits, preference and video encoding, keeping configured limits visible
+when closed. In sound,
+source and microphone inputs precede the mixed output's audio quality. Presets
+remain available before sharing starts. Switching tabs does not reset values
+or restart media. Keep the less frequent connection options in a shared
+disclosure below the tabs. Expand in page flow, pushing later content down
+instead of covering the picture or participants. Related fields share a row
+where space permits and stack on narrow screens. Avoid another permanent row
+of settings cards. Numeric quality inputs
retain the accepted capability range; sliders offer a labelled common range for
quick adjustment. Values outside its range or steps show a custom-value row
instead of an inaccurate slider position. Returning to the nearest available
@@ -173,6 +258,29 @@ from the existing setting/resource owners.
The microphone comic depicts Host commentary gain;
the Viewer's listening-volume comic remains a different action.
+The Viewer bar groups local play/volume/overlay, remote mouse/keyboard, then
+settings/display modes, with fullscreen at the outer edge. Quiet dividers mark
+these responsibilities at every width. Show the remote group only when the Host
+offers control; keep both entries in place and enable the keyboard on control grant.
+The capsule floats inside the picture's lower edge with a small inset. Watching
+and remote input share that geometry; granting or ending control never moves it.
+Remote input keeps its own clicks. When controls hide during remote input,
+retain a local pull on the TV bezel, away from the status lamp. Theater and
+fullscreen place it at the screen edge. Ordinary viewing reveals controls on
+mouse movement or a touch tap on the picture, without another button or setting.
+Keep the chat-overlay toggle in the bar; its appearance settings also belong in
+playback settings and reuse the interaction window's controls and local owner.
+Shorten the volume slider before moving display modes into settings; keep the
+bar on one line at supported mobile widths.
+Viewer settings use a brief anchored popover, preferring space below the picture
+without resizing it. Picture fit owns the narrow-screen overflow for display
+modes; incoming-route settings own reconnect. Use equal-width choices and stack
+these groups on narrow screens. Fit, proportional crop and stretch change local
+display only, separate from the Host's picture settings.
+Persistent interaction and remote-permission tools may use the shared floating
+window; the remote keyboard docks outside the picture and can detach on capable
+browsers. One-step actions and brief adjustments do not need movable windows.
+
Visual source choices (windows, screens and cameras) share named thumbnail cards,
including their focus, hover and refresh treatment. Thumbnails fit the whole frame
at its original aspect ratio within the card; constrain the media box itself so
@@ -190,8 +298,15 @@ The App badge and favicons derive from [one SVG](../../public/favicon.svg):
a dark navy tile, warm white television outline and small gold sparkle. The
unfilled television, antenna, feet and wink keep the proportions of `BrandMark`;
do not give the badge a filled case or a separate screen. This palette stays
-fixed across system themes. Keep the badge recognisable at 16–48 px by
-strengthening thin strokes in tiny exports. Inline brand
+fixed across system themes. Let the television fill the tile with optical
+padding so the surrounding tile does not make the mascot look undersized.
+At 16–24 px, strengthen the outline and open eye, and omit the decorative
+sparkle and tile rim. Keep the antenna, feet and wink at every size. Render
+each export at its target viewport; check actual 16/24/32/48 px on light and
+dark backgrounds rather than judging only an enlarged master. This follows
+[Microsoft's small-size silhouette guidance](https://learn.microsoft.com/en-us/windows/apps/design/iconography/app-icon-design)
+and [GNOME's detail guidance](https://developer.gnome.org/hig/guidelines/app-icons.html#detail).
+Inline brand
marks keep the same wink identity with their existing outline and motion.
Their stroke inherits the local surface's text colour:
dark ink on light surfaces, light ink on dark surfaces, including deliberately
@@ -211,14 +326,19 @@ changing the badge does not restyle the UI, wordmark or illustrations.
| A captured window or display | Window title bar or display stand, with the shared media metaphor kept distinct |
| A camera source or Host commentary | `camera` identifies the alternative picture source; `microphone` identifies the enabled Host voice input and `microphoneOff` its muted state. Neither replaces the speaker metaphor for source/playback sound. |
| Room text and reactions | `chat` opens the conversation, `danmaku` controls its optional picture overlay, `smile` identifies reactions and `send` submits the chosen content. These do not represent media transport or voice. |
-| Floating utility placement | `grip` marks a draggable title bar; `move` opens placement controls. Closing a panel hides its presentation, not its room session. |
+| Experimental attended desktop control | `mouse` identifies keyboard/mouse control, distinct from sharing or playback. Permission copy stays literal; an active control marker describes the grant, not media connectivity. |
+| Floating utility placement | `grip` marks a draggable title bar; corner handles resize the window. Closing a panel hides its presentation, not its room session. |
| Server forwarding media | A server on the media path; opening a Site alone does not imply SFU |
These are **identity/object colours**, not status. A green pawn remains green
in a failed scene; a successful scene does not turn other people green. Real
-roster identities retain the shared UUID colour function, not the illustrative
-"you versus others" palette. Actor positions and identities remain stable from
-the first panel to the result.
+roster identities use the shared UUID colour function to generate stable hues,
+lightness and chroma outside the upholstery/crown's amber range, not a fixed
+list or the illustrative "you versus others" palette. The same identity keeps
+its colour across surfaces, themes and roster changes, without colour-assignment
+messages. Similar colours remain possible; names and self/Host marks identify
+people. Actor positions and identities remain stable from the first panel to
+the result.
Room pawns, tooltip/status comics and introduction participants use
a round head, half-oval body and two restrained eyes. Reuse the shared
@@ -247,8 +367,9 @@ spacing, then use a vertical outline when depth exceeds the available width.
Couch upholstery uses the fixed warm orange/yellow `--couch` / `--couch-dark`
palette. Never draw upholstery from the participant palette or randomize it by
room. Keep automatic participant colours outside the upholstery's amber/orange
-range and the crown's gold; check all eight tokens against both objects in light
-and dark themes. The crown retains a bright gold fill with a dark gold edge.
+range and the crown's gold; check the generated range against both objects in
+light and dark themes. Fixed illustration colours remain illustration tokens.
+The crown retains a bright gold fill with a dark gold edge.
Figures and exterior upholstery use flat fills without outline strokes.
Use differences in tone, spacing and name tags to keep people readable; retain
only the few interior seams that clarify cushions. Apply this convention to
@@ -285,7 +406,7 @@ type checking rather than silently render a warning triangle.
| Connections / 连接 | `network`, `branch`, `signal`, `wifiOff`, `server` | Topology, branching, signaling, disconnected signaling and the named server. A server on a media path means forwarding; a Site backend or control-link server alone does not imply SFU. An invitation chain does not represent signaling. |
| Playback / 播放 | `play`, `pause`, `stop` | Play/resume, pause, end. The control label states whether it affects local viewing or the Host's share. Stop is distinct from a paused or idle room. |
| Audio / 声音 | `speaker`, `speakerOff` | Audio and mute/no audio, qualified by the source or local playback label. A source track's presence does not establish delivered sound. |
-| Size and viewing mode / 尺寸与观看模式 | `expand`, `contract`, `pip`, `pipExit`, `theater`, `theaterExit` | Expand/restore, enter/leave picture in picture, enter/leave theatre mode. The same size symbol can accompany a resolution measurement. |
+| Size and viewing mode / 尺寸与观看模式 | `expand`, `contract`, `pip`, `pipExit`, `theater`, `theaterExit`, `fitContain`, `fitCover`, `fitStretch` | Expand/restore, enter/leave picture in picture or theatre mode; contain, proportional crop and stretch change only local picture fit. The same size symbol can accompany a resolution measurement. |
| Local actions / 本地操作 | `copy`, `save`, `pencil`, `eye`, `eyeOff` | Copy, save, edit, reveal and conceal the named object. An action icon does not prove completion. |
| Text appearance / 文字外观 | `textSize`, `opacity` | Relative text size and opacity. These are local display preferences, not message delivery states. |
| Repeat and disclosure / 重试与展开 | `refresh`, `chevron`, `arrowRight` | Repeat/refresh, expand/collapse, proceed/enter. Direction follows the control's action; no arrow alone establishes delivery. |
@@ -430,7 +551,29 @@ explained clearly in two; do not invent stages to fill extra panels.
## Semantic Colour And Shape
-Use the existing theme tokens in `src/client/styles.css`. The shared
+App, website and documentation use the shared surface palette in
+`src/client/ui/palette.css`: a fresh pale canvas, warm white paper, blue-grey dark
+surfaces and clear text contrast. Source selection follows the same theme.
+Reserve green for cast identity and semantic state, not the general canvas or
+hover fill. Light mode uses blue for actions, focus and selected controls;
+dark mode keeps navy surfaces with soft-white selection highlights and navy text.
+Primary actions such as starting a share, joining and confirming retain their
+blue fill and white foreground in both themes; theme selection must not erase
+their identity. The active remote-input outline uses that same fixed blue;
+suspended input uses the muted state. Use the shared foreground/background pairs
+for both themes.
+Selected choices use the shared face and inset outline; sliding segments use
+inverse ink/paper with the same accent outline. Subtle surface highlights
+and shadows add depth without changing control geometry or press feedback.
+Gold upholstery, illustration and badge artwork retain their own palettes.
+
+The App terminal keeps its user's terminal background and palette. A compact
+mascot/title block identifies the App and build; state, addresses and available
+shortcut keys form separate reading levels. Use terminal-theme blue for links
+and actions, neutral rules, and the same success/wait/failure colour meanings.
+Preserve monochrome output and compact layouts without changing their behavior.
+
+Use the semantic theme tokens in `src/client/styles.css`. The shared
`comic-presentation.ts` maps meanings to those tokens for tooltip outlines,
carets, result panels and verdict marks. Do not choose independent hex colours
or animation rules inside an individual scene.
@@ -472,9 +615,9 @@ failure; lack of PiP support is a limitation.
| Presentation | Rule |
| --- | --- |
-| Action demonstration (`demo`) | Explain an action with a short gesture and a readable hold; repeat while its tooltip is displayed |
+| Action demonstration (`demo`) | Explain an action with a short gesture and a readable hold; repeat while displayed |
| Work actually continuing (`progress`) | Repeat a gentle connection/recovery beat while that state exists |
-| Settled success, failure, limitation, pause or idle (`still`) | Keep the result readable while a related character or object moves; tooltip gestures loop without re-running the actual operation or changing the verdict |
+| Settled success, failure, limitation, pause or idle (`still`) | Keep the result readable while a related character or object moves; gestures loop without re-running the actual operation or changing the verdict |
Demonstrations and progress share the existing 3.2-second comic beat. The main
action belongs in its first half, followed by a readable hold; small internal
@@ -485,11 +628,12 @@ busier. An explanatory slider describes purpose and available range, not its
live numeric value.
Decorative sparkle must support the pictured action, never fake current success.
-The shared tooltip owns repetition for hover, keyboard focus and click/tap;
-scene animations inherit its repeat count instead of hard-coding one play.
-Closing guidance pauses and unmounts its scene. The panel entrance plays once;
-its characters and objects keep moving while shown. Standalone settled scenes
-retain their brief gesture, while real progress repeats for its state's lifetime.
+The shared comic presentation owns repetition for tooltips, overlays and
+standalone results; scenes inherit its repeat count. Previews use the same
+rule, without their own animation overrides. Closing guidance pauses and
+unmounts its scene. The panel entrance plays once; its characters and objects
+keep moving while shown. Settled scenes repeat their quiet subject gesture;
+real progress repeats for its state's lifetime.
Reduced motion uses each scene's **explicit informative static pose**. Disabling
animation alone is insufficient if the base SVG hides the result or shows a
@@ -576,6 +720,25 @@ stationary and manually scrollable instead of discarding the hidden words.
## Interaction References
+[Radix colour roles](https://www.radix-ui.com/colors/docs/palette-composition/understanding-the-scale)
+separate surfaces, interaction states, borders and text instead of tinting every
+layer with the accent. Native [text selection](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select)
+and [pointer capture](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events)
+support held controls without disabling selection across the whole page.
+
+[Fluent tabs](https://fluent2.microsoft.design/components/web/react/core/tablist/usage),
+[switches](https://fluent2.microsoft.design/components/web/react/core/switch/usage)
+and [sliders](https://fluent2.microsoft.design/components/web/react/core/slider/usage)
+distinguish content navigation, immediate binary settings and numeric adjustment.
+[WAI-ARIA tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/)
+defines the shared selection, focus and keyboard contract.
+[GNOME popovers](https://developer.gnome.org/hig/patterns/containers/popovers.html)
+and [utility panes](https://developer.gnome.org/hig/patterns/containers/utility-panes.html)
+distinguish brief contextual adjustments from tools alongside the main view.
+Piik's floating/detached tool choice applies that distinction to watching and
+remote input; [Document Picture-in-Picture](https://developer.chrome.com/docs/web-platform/document-picture-in-picture)
+supplies the optional native window and its lifetime boundary.
+
[Carbon status indicators](https://v10.carbondesignsystem.com/patterns/status-indicator-pattern/)
supports combining semantic colour with shape and symbols;
[Carbon motion](https://carbondesignsystem.com/elements/motion/overview/)
diff --git a/docs/status.md b/docs/status.md
index 6a8ff7b7..03420ffc 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -1,6 +1,6 @@
# Current Status
-Last updated: 2026-10-16
+Last updated: 2026-10-19
This is the compact execution/deployment index. Product modules own behavior,
[verification status](./verification-status.md) owns unresolved physical limits,
@@ -56,12 +56,15 @@ Release artifacts and operator deployment records own delivery completion;
## Current Work
-Current source retains the existing 2.x protocol and route owners. Native media
-recovery uses the existing allocator and encoder, available NAT enhancement is
-automatic, and App startup can open a starred approved Site without starting a
-Local room. [TODO](./todo.md) owns the upstream dependency follow-up, pending field
-evidence and deferred product work. Release artifacts and operator records own
-delivery and acceptance results.
+Current source retains the existing 2.x protocol and route owners. This phase
+combines attended keyboard/mouse control, Viewer playback settings and the
+interaction window, with shared forwarding recovery repairs. Native input is
+included in App builds and remains off until the Host enables it; its
+[prototype boundary](./research/room-interactions.md#attended-remote-control-prototype)
+owns platform evidence. The owner authorized release after final automated and
+local acceptance on 2026-10-19. [TODO](./todo.md) owns upstream follow-up,
+device acceptance and deferred work. Release artifacts and operator records own
+delivery results.
2.0 separates numeric media requests from presets and bounded runtime admission,
retains successfully applied quality settings, and lets App serve an approved
diff --git a/docs/todo.md b/docs/todo.md
index 09bd9024..721dae0f 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -1,6 +1,6 @@
# Current TODO Ledger
-Last reviewed: 2026-10-16
+Last reviewed: 2026-10-19
Explicit owner holds remain in force; an investigation does not itself
accept a new feature or architecture. A missing device or reporter trace blocks
@@ -9,11 +9,19 @@ Git/PRs own completed history.
## Now
-The 2.0 maintenance line retains the published protocol and route owners.
+The 2.x maintenance line retains the published protocol and route owners.
Release artifacts and operator records own exact delivery; remaining product
work is listed below. Broader device coverage does not override the owner's
platform deferrals or establish a diagnosis for unmatched reports.
+- [ ] **macOS bundle startup acceptance (#479).** The package now contains the
+ actual Mach-O entry and helpers inside `.app`, replacing the shell launcher's
+ dependency on an external sibling executable. A moved-bundle assembly check
+ passes, and candidate CI has built and packaged both Mac architectures.
+ Verify Finder launch on macOS, including a downloaded/quarantined bundle and
+ capture permissions. The packaging defect
+ is established; its correction has not yet been matched to the reporter's Mac.
+
- [ ] **Return LiveKit to an upstream pin.** Native publication now supplies
unmet encoder demand to the existing allocator through the scoped dependency
revision submitted in [upstream #5016](https://github.com/livekit/livekit/pull/5016).
@@ -22,8 +30,55 @@ platform deferrals or establish a diagnosis for unmatched reports.
own that boundary; this local repair does not diagnose the unmatched field
reports below.
+- [ ] **Audio-exclusion explanation (#480).** At release, point the reporter to
+ the [source-audio scopes](./guide/getting-started.md#exclude-a-voice-app-from-screen-audio).
+ The missing window/camera exclusion control is intentional; investigate a
+ specific unwanted recording only if a matching source/input report establishes it.
+
+- [ ] **SFU recovery rollout.** Shared forwarding now gives DownTrack one
+ owner for video sender reports and RR/RTT accounting, with Pion scheduling.
+ Matched SFU logs established clock contamination blocking layer changes and
+ missing RTT updates. RTCP, constrained recovery and the current App/Server
+ lifecycle checks pass locally. After the approved release, verify the affected
+ deployment with both corrected App and Server; an ICE restart does not replace
+ the affected upstream clock. This does not diagnose every unmatched
+ sustained-quality report below.
+
+- [ ] **Release issue follow-up.** After owner acceptance and publication, link
+ confirmed fixes to the release PR and notes, then reply with the shipped
+ version on relevant open and previously closed issues. Close only established
+ resolutions or explicitly declined requests; retain unmatched reports as
+ awaiting evidence.
+
+- [ ] **New promotional film.** Begin after publication. Explain Piik's screen
+ sharing directly, then show sharing/invitation, interaction and single-controller
+ keyboard/mouse use with explicit Host consent. Its visual direction may differ
+ from the existing film. Local key visuals and the motion study are exploratory,
+ not a finished film.
+
## Held By Owner
+- [ ] **Remote-control latency and responsiveness.** Scheduled after this release.
+ Compare input-to-visible-response timing on the same endpoints, source and
+ network against a mature remote-control implementation. Separate input
+ delivery, Host execution, capture/encode and receive/playout; retain the
+ existing route and authorization owners. Identify the dominant delay before
+ changing budgets or buffering, and compare loss/recovery as well as steady latency.
+
+- [ ] **Persistent-loss estimator replacement.** Deferred by the owner on
+ 2026-10-18. Retain mature congestion control and accept quality reduction under
+ sustained high loss; no custom loss model or release prerequisite is added.
+ [Evidence and limits](./research/node-local-media-design.md#persistent-loss-with-low-source-utilization)
+ retain the low-utilization collapse and distinguish it from concrete feedback
+ accounting or recovery defects, which remain in scope for ordinary fixes.
+- [ ] **Multiple remote-control screens.** Deferred by the owner on 2026-10-17.
+ Keep one shared source and the existing Host source picker; Viewer-initiated
+ screen switching and simultaneous multi-screen streams are later work.
+- [ ] **Independent virtual input devices for remote co-play.** Deferred by the owner on
+ 2026-10-17. This phase uses keyboard/mouse only and adds no virtual gamepad
+ driver. Per-player virtual keyboards, mice and gamepads are later work.
+ The [input assessment](./research/room-interactions.md#remote-co-play) owns
+ platform dependencies and the distinction from shared keyboard/mouse control.
- [ ] **32-bit Windows/Linux Apps.** Deferred by the owner on 2026-10-02;
no package or website option is planned. Browser use remains available where
the OS/browser supports the required media APIs. Retain the isolated
@@ -42,6 +97,13 @@ These physical checks or reporter diagnoses remain unverified. A local repair or
successful test is not proof of a reporter's cause; research owns the completed
experiments and their limits.
+- [ ] **Remote-control device acceptance.** Verify physical Android/iOS
+ controllers, mixed-DPI displays, commercial games and an actual remote-device
+ session. macOS needs Finder/Accessibility, focus, Retina and input checks;
+ Linux needs desktop Portal permissions and capture/input checks. Existing
+ [evidence and limits](./verification-status.md#device-evidence-boundary) remain
+ distinct from build and emulated-controller acceptance.
+
- [ ] **Sustained quality loss.** Retest the affected Native Host and the
v1.9.2 self-hosted Browser setup with matched Host/Viewer/Server diagnostics,
route and codec. [Native controls](./research/node-local-media-design.md#send-queue-recovery)
@@ -92,8 +154,10 @@ experiments and their limits.
[#448](https://github.com/TNTcraftHIM/Piik/issues/448) and
[#453](https://github.com/TNTcraftHIM/Piik/issues/453) need paired transport traces;
the v1.6.3 timeout also needs share-start/SDP evidence.
- [#471](https://github.com/TNTcraftHIM/Piik/issues/471) needs ICE traces and the
- discovery URLs after STUN redundancy and override changes.
+ [#471](https://github.com/TNTcraftHIM/Piik/issues/471) reports working STUN and
+ a router mapping on v2.1.0, but no ICE check responses. Obtain the retained
+ paired reports; that summary alone does not distinguish NAT filtering,
+ upstream mapping or a blocked path.
[#468](https://github.com/TNTcraftHIM/Piik/issues/468) needs the complete join/
reauthentication trace on repaired connection-opportunity accounting.
[#464](https://github.com/TNTcraftHIM/Piik/issues/464) needs matched SFU reports
@@ -194,22 +258,12 @@ remains; do not add another retry/transport owner to bypass these limits.
identifies pairing/revocation and native decoded-input ownership beyond the
device selector. Reopen for a concrete use case that justifies this boundary
and physical latency/echo/background checks. This does not reopen room voice.
-10. **Attended remote control.** The [cross-platform assessment](./research/room-interactions.md#remote-control-assessment-not-implemented)
- distinguishes Browser controllers from desktop App input authority. Decide
- the use case and platform scope before a prototype; transport, input privacy
- and App-wide grant retirement need acceptance. No remote-control code,
- mobile controlled endpoint or language rewrite is currently planned.
-11. **Per-Viewer SFU preference (#477).** Existing `SFU_ONLY=true` is an operator
- policy for the whole site; it does not provide the requested individual
- Viewer control. Keep this proposal separate from quality-recovery fixes.
- Reopen only for an accepted policy that preserves Host privacy, bounded SFU
- capacity and the existing automatic route owner.
-12. **Multiple simultaneous sharers.** Assess a separate room mode in which
- participants publish and each Viewer selects a stream. First define room
- authority, per-publication routes and resource ownership; retain one selected
- picture per Viewer as the simplest candidate. The current one-Host contract
- is unchanged. Names and UI follow the model decision; low-level sharing and
- recovery work takes priority over this proposal.
-13. **Review the user-suggested [piik-watch-party](https://github.com/Harsh-dev3221/piik-watch-party).**
- After current maintenance, inspect its implementation for useful ideas that
- fit Piik's existing model and interaction design.
+10. **Remote co-play and mobile controlled platforms.** The [co-play assessment](./research/room-interactions.md#remote-co-play)
+ separates virtual gamepad slots from attended keyboard/mouse assistance.
+ Desktop input acceptance remains above; independent gamepads and mobile
+ controlled endpoints need a separate scope decision.
+11. **Multiple simultaneous sharers.** The [party-mode assessment](./research/room-interactions.md#multiple-sharers-assessment-not-implemented)
+ separates room administration from publication ownership, with one selected
+ picture per Viewer and shared endpoint upload limits. Define publication and
+ subscription lifecycles before a prototype. The current one-Host contract
+ remains; names and UI follow the model decision.
diff --git a/docs/verification-status.md b/docs/verification-status.md
index a3e2e18a..4f408dab 100644
--- a/docs/verification-status.md
+++ b/docs/verification-status.md
@@ -1,6 +1,6 @@
# Verification Status
-Last updated: 2026-10-15
+Last updated: 2026-10-19
This file owns physical evidence limits that change how the product may be
described. [Status](./status.md) owns the execution/deployment index.
@@ -48,6 +48,18 @@ or a measured improvement worth its implementation and maintenance cost.
## Device Evidence Boundary
+Attended keyboard/mouse control has Windows physical input and local routed
+acceptance for consent, revocation, held-key release and source geometry.
+Browser checks cover mobile touch/zoom/keyboard emulation, detached tools and
+Viewer playback preferences. Physical Android/iOS controllers, mixed-DPI displays,
+commercial games and an actual remote-device session remain unverified.
+macOS builds and packaging pass; Finder/Accessibility, focus, Retina and input
+still need a Mac. Linux compilation and synthetic input/release pass, while
+desktop Portal permissions and capture/input need physical acceptance. The
+[remote-control assessment](./research/room-interactions.md#attended-remote-control-prototype)
+owns the mechanism and game-input limits. These limits do not claim parity with
+dedicated remote-control products.
+
Windows HDR-to-SDR has synthetic FP16 conversion and decoded
H.264/VP8 Browser reception evidence. Local displays were in SDR mode; real HDR
content, SDR white on HDR displays, mixed-display movement, display-mode changes
diff --git a/go.mod b/go.mod
index a9eeeffb..53f1c2b9 100644
--- a/go.mod
+++ b/go.mod
@@ -16,8 +16,8 @@ require (
github.com/charmbracelet/x/term v0.2.2
github.com/coder/websocket v1.8.15
github.com/go-logr/logr v1.4.4
- github.com/livekit/livekit-server v1.13.11-0.20261014174133-18df6ad4b694
- github.com/livekit/mediatransportutil v0.0.0-20260821083140-f234b534b095
+ github.com/livekit/livekit-server v1.13.11-0.20261016133420-cde3991916cf
+ github.com/livekit/mediatransportutil v0.0.0-20261014192331-dd8e31a0adc0
github.com/livekit/protocol v1.52.2-0.20261012065025-9bb708cdb819
github.com/livekit/server-sdk-go/v2 v2.14.0
github.com/netbirdio/go-nat v0.0.0-20260821095157-6b2c8c5c74e8
@@ -30,7 +30,7 @@ require (
github.com/pion/stun/v4 v4.0.1
github.com/pion/transport/v5 v5.1.1
github.com/pion/turn/v5 v5.1.2
- github.com/pion/webrtc/v4 v4.2.23
+ github.com/pion/webrtc/v4 v4.2.24
github.com/thesyncim/gopus v0.2.2
go.uber.org/zap v1.28.0
golang.org/x/crypto v0.57.0
@@ -99,7 +99,7 @@ require (
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b // indirect
github.com/pion/datachannel v1.6.3 // indirect
- github.com/pion/dtls/v3 v3.1.10 // indirect
+ github.com/pion/dtls/v3 v3.1.13 // indirect
github.com/pion/mdns/v2 v2.2.2 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/sctp v1.12.0 // indirect
@@ -139,4 +139,4 @@ require (
)
// Local-encoder demand hook pending upstream #5016; see internal/thirdparty/README.md.
-replace github.com/livekit/livekit-server => github.com/TNTcraftHIM/livekit v1.13.11-0.20261015180525-f10692c6f232
+replace github.com/livekit/livekit-server => github.com/TNTcraftHIM/livekit v1.13.11-0.20261018043008-c7f56b389713
diff --git a/go.sum b/go.sum
index fcb665dc..14083105 100644
--- a/go.sum
+++ b/go.sum
@@ -22,6 +22,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/TNTcraftHIM/livekit v1.13.11-0.20261015180525-f10692c6f232 h1:SM6Ly7cYLi1Ap+UMPZYLLi5f4T1xHRF0OrB3N3e0KvU=
github.com/TNTcraftHIM/livekit v1.13.11-0.20261015180525-f10692c6f232/go.mod h1:j0XqdfycMvylbtSq2SE4UG2aGF0SADNReWrQfbpn2DE=
+github.com/TNTcraftHIM/livekit v1.13.11-0.20261018043008-c7f56b389713 h1:RrcmStTuxqbsgEai2S+wN5vBYkrMyx9GZIWKBwJgIBA=
+github.com/TNTcraftHIM/livekit v1.13.11-0.20261018043008-c7f56b389713/go.mod h1:VisDyFQKxQr0ncrV3558MBUKjlrTUqXMBQwsxEHMRgA=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
@@ -193,6 +195,8 @@ github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5AT
github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ=
github.com/livekit/mediatransportutil v0.0.0-20260821083140-f234b534b095 h1:BcliKAXoMhl/nWmzQweQ5kmh4Qqagxl4s3Z5pvM/7AY=
github.com/livekit/mediatransportutil v0.0.0-20260821083140-f234b534b095/go.mod h1:o8CFmAdrVwzJNOCsQCLUzXRjokkufNshnQHOe4fRaqU=
+github.com/livekit/mediatransportutil v0.0.0-20261014192331-dd8e31a0adc0 h1:BSLyHr3Lsl71bHGHsfiYNmbohugR2yoaf9HjAZeFJnc=
+github.com/livekit/mediatransportutil v0.0.0-20261014192331-dd8e31a0adc0/go.mod h1:o8CFmAdrVwzJNOCsQCLUzXRjokkufNshnQHOe4fRaqU=
github.com/livekit/protocol v1.50.5-0.20260821144838-17c16cf496fd h1:pGWIR9fw1eC699v2njRX/7Y+baEXB7p6k9CvDg2uVrQ=
github.com/livekit/protocol v1.50.5-0.20260821144838-17c16cf496fd/go.mod h1:h4wP4IBPkT5aew7SZSGViHSmanKAiKWsHij/5YfL4BE=
github.com/livekit/protocol v1.52.2-0.20261007103317-a935cd67c29a h1:Sa9+0Kr+MVIabmJaBFtX8Yl3NYewkv02/mMDvLEKYiQ=
@@ -272,6 +276,8 @@ github.com/pion/datachannel v1.6.3 h1:HZAYLpunVI0xi057ZiANl558d0uSpomcWw4UEPz3qX
github.com/pion/datachannel v1.6.3/go.mod h1:oRmkXVVXxkUbqa8MatgdNHW29kvtQY3HUdjJQsfv2GE=
github.com/pion/dtls/v3 v3.1.10 h1:HWC+QCZitP/ApADS/6+g7UIw2YmLgoK3CsynnjPJgMo=
github.com/pion/dtls/v3 v3.1.10/go.mod h1:iKFQNYrjsN2TiA2YKKMqB9MOZaFpjFULBI/A4sW0eyc=
+github.com/pion/dtls/v3 v3.1.13 h1:oWNjsoF3xUPDhzOuE8U42ql1BtVzWc8X4Asiz9BKwYk=
+github.com/pion/dtls/v3 v3.1.13/go.mod h1:iKFQNYrjsN2TiA2YKKMqB9MOZaFpjFULBI/A4sW0eyc=
github.com/pion/ice/v4 v4.4.7 h1:JiI6VId3XnIztxKE8RjTC0SeXrp7ppkAO0jGez3/sIE=
github.com/pion/ice/v4 v4.4.7/go.mod h1:zCRRg4Mkpdbx9B+75fd4z2APvIXeIraeUOB7IMPt8mU=
github.com/pion/interceptor v0.1.49 h1:iyBsNHRoLNNXZiJA/DdGvJgdyfS8YWDCzxIAlVjt5nY=
@@ -302,6 +308,8 @@ github.com/pion/turn/v5 v5.1.2 h1:acEOO+D5txJ52vKfcilmSMItfP23Q9K6pJ1LM5P2VV0=
github.com/pion/turn/v5 v5.1.2/go.mod h1:57Oadc8fHnac15VFyCd6nEaBTVZBxQe2POUMD4lsHRA=
github.com/pion/webrtc/v4 v4.2.23 h1:AlVixhTtQmxrheSv6lAH0w2sH5qjM7OTos5Lt811nk0=
github.com/pion/webrtc/v4 v4.2.23/go.mod h1:vzf5RQ0uMBuXAYTK2pabZUtnZyj2t3TF88eL4xzQZvI=
+github.com/pion/webrtc/v4 v4.2.24 h1:Ove9nRpDAfK39+QSw3/Ru17VDiECjbiLaM73mRG4Yms=
+github.com/pion/webrtc/v4 v4.2.24/go.mod h1:JxD/FgjMDKCWFukjknTdG5a9rR4PUxkg0yBX1/JBInM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
diff --git a/index.html b/index.html
index 96399532..b32185bf 100644
--- a/index.html
+++ b/index.html
@@ -3,8 +3,8 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="theme-color" content="#141e29" media="(prefers-color-scheme: dark)" />
- <meta name="theme-color" content="#e9f2ee" media="(prefers-color-scheme: light)" />
+ <meta name="theme-color" content="#171a20" media="(prefers-color-scheme: dark)" />
+ <meta name="theme-color" content="#f4f3ef" media="(prefers-color-scheme: light)" />
<link rel="icon" href="/favicon.ico" />
<link rel="icon" type="image/png" sizes="96x96" href="/favicon.png" />
<link rel="icon" type="image/svg+xml" sizes="any" href="/favicon.svg" />
diff --git a/internal/app/app.go b/internal/app/app.go
index 4e21587f..7396f6c1 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -18,6 +18,7 @@ import (
"time"
appconfig "github.com/TNTcraftHIM/Piik/internal/app/config"
+ "github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/app/lan"
"github.com/TNTcraftHIM/Piik/internal/app/launcher"
"github.com/TNTcraftHIM/Piik/internal/app/loopback"
@@ -25,6 +26,7 @@ import (
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
"github.com/TNTcraftHIM/Piik/internal/app/nativecontrol"
"github.com/TNTcraftHIM/Piik/internal/app/publictunnel"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
serverapp "github.com/TNTcraftHIM/Piik/internal/server/app"
serverconfig "github.com/TNTcraftHIM/Piik/internal/server/config"
@@ -93,7 +95,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
var err error
recorder, err = openDiagnostics(options.LogDir)
if err != nil {
- return fmt.Errorf("Piik App diagnostics are unavailable: %w", err)
+ return errors.Join(failure.Diagnostics, fmt.Errorf("Piik App diagnostics are unavailable: %w", err))
}
recorder.Context("build", map[string]any{"version": buildVersion(), "revision": BuildRevision})
previous, previousWriter, previousFlags := slog.Default(), log.Writer(), log.Flags()
@@ -121,7 +123,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
slog.Debug("piik-client", "event", "start", "version", buildVersion(), "revision", BuildRevision)
options.console.show(consoleView{state: "starting"})
if err := validateMode(options); err != nil {
- return err
+ return errors.Join(failure.Configuration, err)
}
if options.Port == 0 {
options.Port = DefaultLocalPort
@@ -131,24 +133,30 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
var err error
configPath, err = appconfig.DefaultPath()
if err != nil {
- return fmt.Errorf("Piik App configuration is unavailable: %w", err)
+ return errors.Join(failure.Configuration, fmt.Errorf("Piik App configuration is unavailable: %w", err))
}
}
config, err := appconfig.LoadOrCreate(configPath)
if err != nil {
- return fmt.Errorf("Piik App configuration is unavailable: %w", err)
+ return errors.Join(failure.Configuration, fmt.Errorf("Piik App configuration is unavailable: %w", err))
}
config, err = applyMode(config, options)
if err != nil {
- return err
+ return errors.Join(failure.Configuration, err)
}
slog.Debug("piik-client", "event", "configuration", "siteConfigured", config.Site != "", "localAccessProtected", config.LocalAccessPassword != "")
if options.SiteSet {
if err = appconfig.Save(configPath, config); err != nil {
- return fmt.Errorf("Piik App configuration is unavailable: %w", err)
+ return errors.Join(failure.Configuration, fmt.Errorf("Piik App configuration is unavailable: %w", err))
}
}
nativeMedia := discoverNativeMedia(ctx, options.CaptureProcess)
+ input, inputErr := remoteinput.New(ctx, nativeMedia.capture.RemoteInput)
+ if inputErr != nil {
+ slog.Warn("Remote-control prototype unavailable", "reason", inputErr)
+ }
+ defer input.Close()
+ nativeMedia.capabilities.RemoteInput = input != nil
recordContext := func(selected Options, config appconfig.Config) {
if recorder == nil {
return
@@ -171,12 +179,12 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
control, err := loopback.Start(ctx, loopback.Options{
AllowedOrigins: allowedOrigins(config.Site, options.Port),
NativeMedia: nativeMedia.capabilities,
- NewControl: nativeMedia.controlFactory(),
+ NewControl: nativeMedia.controlFactory(input),
Presentation: options.console.setLanguage,
QualityPreference: qualityPreference,
})
if err != nil {
- return fmt.Errorf("Piik App native control could not start: %w", err)
+ return errors.Join(failure.NativeControl, fmt.Errorf("Piik App native control could not start: %w", err))
}
defer func() { returnedErr = errors.Join(returnedErr, control.Close()) }()
slog.Debug("piik-client", "event", "control-ready")
@@ -185,7 +193,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {
return err
}
}
- return runLauncher(ctx, options, configPath, config, control, func(selected *Options, config appconfig.Config) error {
+ return runLauncher(ctx, options, configPath, config, control, input, func(selected *Options, config appconfig.Config) error {
diagnosticsMu.Lock()
defer diagnosticsMu.Unlock()
if ctx.Err() != nil {
@@ -233,6 +241,7 @@ func runLauncher(
configPath string,
config appconfig.Config,
control *loopback.Server,
+ input *remoteinput.Manager,
configureDiagnostics func(*Options, appconfig.Config) error,
) (returnedErr error) {
automatic := explicitMode(options)
@@ -289,7 +298,7 @@ func runLauncher(
},
)
if err != nil {
- return err
+ return errors.Join(failure.Launcher, err)
}
defer func() { returnedErr = errors.Join(returnedErr, launch.Close()) }()
control.SetConnectURL(launch.URL())
@@ -299,14 +308,14 @@ func runLauncher(
defer options.console.send(consoleLauncher(""))
launchAddress, err := url.Parse(launch.URL())
if err != nil {
- return err
+ return errors.Join(failure.Launcher, err)
}
configMu.Lock()
launcherOrigin = launchAddress.Scheme + "://" + launchAddress.Host
err = control.SetAllowedOrigins(append(allowedOrigins(config.Site, options.Port), launcherOrigin))
configMu.Unlock()
if err != nil {
- return err
+ return errors.Join(failure.NativeControl, err)
}
if !automatic && startupSite == "" {
options.console.show(consoleView{state: "setup", entry: launch.URL()})
@@ -325,7 +334,7 @@ func runLauncher(
return roomErr
}
launch.SetResult("", roomErr)
- options.console.show(consoleView{state: "setup", entry: launch.URL(), problem: diagnostics.SafeText(roomErr.Error())})
+ options.console.show(consoleView{state: "setup", entry: launch.URL(), problem: roomErr})
slog.Debug("piik-client", "event", "local-room-stopped", diagnostics.Error(roomErr))
select {
case <-ctx.Done():
@@ -353,7 +362,7 @@ func runLauncher(
return err
case err = <-launch.Done():
if err != nil {
- return fmt.Errorf("Piik App launcher stopped unexpectedly: %w", err)
+ return errors.Join(failure.Launcher, fmt.Errorf("Piik App launcher stopped unexpectedly: %w", err))
}
return nil
}
@@ -374,7 +383,7 @@ func runLauncher(
next.LocalAccessPassword = selection.LocalAccessPassword
})
if err != nil {
- err = fmt.Errorf("Piik App configuration could not be saved: %w", err)
+ err = errors.Join(failure.Configuration, fmt.Errorf("Piik App configuration could not be saved: %w", err))
return finishRoom(err)
}
if err = configureDiagnostics(&options, selectedConfig); err != nil {
@@ -490,7 +499,7 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
) (returnedErr error) {
stunURLs, natPredictionStunURLs, err := localSTUNURLs(options.Link)
if err != nil {
- return err
+ return errors.Join(failure.Configuration, err)
}
view := consoleView{mode: "local", state: "starting", protected: config.LocalAccessPassword != ""}
if options.Link {
@@ -500,7 +509,7 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
options.console.show(view)
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero, Port: options.Port})
if err != nil {
- return fmt.Errorf("local server port is unavailable: %w", err)
+ return errors.Join(failure.LocalPort, fmt.Errorf("local server port is unavailable: %w", err))
}
defer func() {
if listener != nil {
@@ -516,7 +525,7 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
// addresses as allowed local origins but never block link startup on LAN
// selection (multi-interface hosts may not have one obvious address).
if lanErr != nil && !options.Link {
- return lanErr
+ return errors.Join(failure.LocalNetwork, lanErr)
}
var tunnel *publictunnel.Process
publicOrigin := ""
@@ -549,7 +558,7 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
NATPredictionSTUNURLs: natPredictionStunURLs,
})
if err != nil {
- return err
+ return errors.Join(failure.Configuration, err)
}
logger := options.logger
if logger == nil {
@@ -562,12 +571,12 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
Logger: logger,
})
if err != nil {
- return err
+ return errors.Join(failure.LocalServer, err)
}
listener = nil // Ownership is now in the application's startup/shutdown path.
defer func() { returnedErr = errors.Join(returnedErr, endLocalServer(localServer)) }()
if _, err = localServer.Listen(ctx); err != nil {
- return err
+ return errors.Join(failure.LocalServer, err)
}
slog.Debug("piik-client", "event", "local-server-ready", "port", options.Port, "publicLink", publicOrigin != "")
@@ -610,14 +619,14 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,
return nil
case err = <-control.Done():
if err != nil {
- return fmt.Errorf("Piik App native control stopped unexpectedly: %w", err)
+ return errors.Join(failure.NativeControl, fmt.Errorf("Piik App native control stopped unexpectedly: %w", err))
}
return nil
case <-tunnelDone:
if ctx.Err() != nil {
return nil
}
- return errors.New("public invitation link stopped; reopen Piik to create a new link")
+ return errors.Join(failure.TunnelStopped, errors.New("public invitation link stopped; reopen Piik to create a new link"))
}
}
@@ -660,9 +669,9 @@ type nativeRuntime struct {
discoveryErr error
}
-func (runtime nativeRuntime) controlFactory() func() loopback.ControlSession {
+func (runtime nativeRuntime) controlFactory(input *remoteinput.Manager) func() loopback.ControlSession {
return func() loopback.ControlSession {
- return nativecontrol.New(runtime.captureProcess, runtime.capture, true)
+ return nativecontrol.New(runtime.captureProcess, runtime.capture, true, input)
}
}
diff --git a/internal/app/app_test.go b/internal/app/app_test.go
index dd98cae2..d715b19e 100644
--- a/internal/app/app_test.go
+++ b/internal/app/app_test.go
@@ -204,7 +204,7 @@ func TestLauncherRetainsItsRuntimeFailureDuringCancellation(t *testing.T) {
joined := false
go func() {
done <- runLauncher(ctx, Options{Port: listener.Addr().(*net.TCPAddr).Port, console: console},
- configPath, config, control, func(*Options, appconfig.Config) error { return nil })
+ configPath, config, control, nil, func(*Options, appconfig.Config) error { return nil })
}()
defer func() {
cancel()
@@ -342,9 +342,9 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {
if mode == "site" {
options.SiteSet = true
config.Site = "https://share.example"
- done <- runLauncher(ctx, options, configPath, config, control, func(*Options, appconfig.Config) error { return nil })
+ done <- runLauncher(ctx, options, configPath, config, control, nil, func(*Options, appconfig.Config) error { return nil })
} else {
- done <- runLauncher(ctx, options, configPath, config, control, func(*Options, appconfig.Config) error { return nil })
+ done <- runLauncher(ctx, options, configPath, config, control, nil, func(*Options, appconfig.Config) error { return nil })
}
}()
select {
@@ -424,9 +424,9 @@ func TestBrowserOpenFailureKeepsTheAppAvailable(t *testing.T) {
if mode == "site" {
options.SiteSet = true
config.Site = "https://share.example"
- done <- runLauncher(ctx, options, configPath, config, control, func(*Options, appconfig.Config) error { return nil })
+ done <- runLauncher(ctx, options, configPath, config, control, nil, func(*Options, appconfig.Config) error { return nil })
} else {
- done <- runLauncher(ctx, options, configPath, config, control,
+ done <- runLauncher(ctx, options, configPath, config, control, nil,
func(*Options, appconfig.Config) error { return nil })
}
}()
@@ -672,7 +672,7 @@ func TestMissingCaptureKeepsViewerControlAvailable(t *testing.T) {
if native.capabilities.Video || native.capabilities.HardwareH264 {
t.Fatalf("missing native capture = %+v", native)
}
- control := native.controlFactory()()
+ control := native.controlFactory(nil)()
if control == nil {
t.Fatal("missing capture disabled the native Viewer control")
}
diff --git a/internal/app/console.go b/internal/app/console.go
index 28a45899..2eab8642 100644
--- a/internal/app/console.go
+++ b/internal/app/console.go
@@ -16,6 +16,7 @@ import (
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/TNTcraftHIM/Piik/internal/app/browser"
+ "github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/x/ansi"
@@ -25,7 +26,7 @@ import (
type consoleView struct {
mode, state, entry, invite string
protected bool
- problem string
+ problem error
browserError error
}
@@ -39,6 +40,9 @@ type consoleOpenResult struct {
err error
}
type consoleDiagnostic string
+
+func (diagnostic consoleDiagnostic) Error() string { return string(diagnostic) }
+
type consoleDebug struct {
logPath string
export func() (string, error)
@@ -85,30 +89,41 @@ type console struct {
}
var consoleCopy = map[string][3]string{
- "mode": {"Mode", "模式", ""},
- "local": {"Local network", "局域网", "□"},
- "link": {"Public link", "公网链接", "↗"},
- "site": {"Piik Site", "Piik 站点", "@"},
- "setup": {"App is ready", "App 已就绪", "?"},
- "starting": {"Starting", "正在启动", "…"},
- "ready": {"Ready", "已就绪", "✓"},
- "stopping": {"Stopping", "正在退出", "→"},
- "stopped": {"Stopped", "已停止", "○"},
- "failed": {"Could not continue", "运行失败", "!"},
- "entry": {"Open in browser", "打开网页", "□"},
- "launcher": {"App launcher", "App 启动页", "☆"},
- "invite": {"Site address", "站点地址", "↗"},
- "access": {"Site access", "站点准入", ""},
- "open": {"Open", "开放", "○"},
- "password": {"Password protected", "已设置密码", "*"},
- "error": {"Details", "详情", "!"},
- "exit": {"quit", "退出", "↪"},
- "openFailed": {"Could not open the browser; use the address above.", "无法打开浏览器,请使用上方地址。", "! ↗"},
- "log": {"Log", "日志", ""},
- "export": {"Export diagnostics", "导出诊断", ""},
- "exporting": {"Saving diagnostics", "正在保存诊断", ""},
- "exported": {"Saved", "已保存", ""},
- "exportFailed": {"Could not save diagnostics", "无法保存诊断", ""},
+ "failure.tunnel-exited": {"Public invite disconnected before it was ready. Try again or use an existing Piik site.", "公网邀请尚未就绪就已断开,请重试或使用已有 Piik 站点。", "!"},
+ "failure.tunnel-timeout": {"Public invite did not connect in time. Try again or use an existing Piik site.", "公网邀请连接超时,请重试或使用已有 Piik 站点。", "!"},
+ "failure.tunnel-unavailable": {"The public-invite helper is unavailable. Extract the complete App package again.", "公网邀请辅助程序不可用,请重新完整解压 App 程序包。", "!"},
+ "failure.tunnel-start": {"Could not start public invite. Check the details or use an existing Piik site.", "无法启动公网邀请,请查看详情或使用已有 Piik 站点。", "!"},
+ "failure.tunnel-stopped": {"Public invite stopped. Reopen App for a new link or use an existing Piik site.", "公网邀请已停止,请重开 App 获取新链接,或使用已有 Piik 站点。", "!"},
+ "failure.local-port": {"The local port is unavailable. Close the other process or choose another port.", "本地端口不可用,请关闭占用程序或更换端口。", "!"},
+ "failure.local-network": {"No suitable local invitation address. Check your network and selected address.", "没有合适的局域网邀请地址,请检查网络和所选地址。", "!"},
+ "failure.configuration": {"Could not apply App settings. Check the details.", "无法应用 App 设置,请查看详情。", "!"},
+ "failure.native-control": {"App connection service is unavailable. Reopen App and try again.", "App 连接服务不可用,请重开 App 后重试。", "!"},
+ "failure.launcher": {"App launcher is unavailable. Reopen App and try again.", "App 启动页不可用,请重开 App 后重试。", "!"},
+ "failure.diagnostics": {"Could not start diagnostics. Check the save location and permissions.", "无法开启诊断,请检查保存位置与权限。", "!"},
+ "failure.local-server": {"The local room service is unavailable. Check the details.", "本地房间服务不可用,请查看详情。", "!"},
+ "local": {"Local network", "局域网", "□"},
+ "link": {"Public link", "公网链接", "↗"},
+ "site": {"Piik Site", "Piik 站点", "@"},
+ "setup": {"App is ready", "App 已就绪", "?"},
+ "starting": {"Starting", "正在启动", "…"},
+ "ready": {"Ready", "已就绪", "✓"},
+ "stopping": {"Stopping", "正在退出", "→"},
+ "stopped": {"Stopped", "已停止", "○"},
+ "failed": {"Could not continue", "运行失败", "!"},
+ "entry": {"Open in browser", "打开网页", "□"},
+ "launcher": {"App launcher", "App 启动页", "☆"},
+ "invite": {"Site address", "站点地址", "↗"},
+ "access": {"Site access", "站点准入", ""},
+ "open": {"Open", "开放", "○"},
+ "password": {"Password protected", "已设置密码", "*"},
+ "error": {"Details", "详情", "!"},
+ "exit": {"quit", "退出", "↪"},
+ "openFailed": {"Could not open the browser; use the address above.", "无法打开浏览器,请使用上方地址。", "! ↗"},
+ "log": {"Log", "日志", ""},
+ "export": {"Export diagnostics", "导出诊断", ""},
+ "exporting": {"Saving diagnostics", "正在保存诊断", ""},
+ "exported": {"Saved", "已保存", ""},
+ "exportFailed": {"Could not save diagnostics", "无法保存诊断", ""},
}
func newConsole(cancel context.CancelFunc, machine bool) *console {
@@ -230,7 +245,7 @@ func (model consoleModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {
case consoleLauncher:
model.launcher = string(value)
case consoleDiagnostic:
- model.view.problem = string(value)
+ model.view.problem = value
model.view.browserError = nil
case consoleDebug:
model.debug = value
@@ -262,9 +277,9 @@ func (model consoleModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {
model.finished = true
model.view.entry, model.view.invite, model.launcher = "", "", ""
model.view.browserError = nil
- model.view.state, model.view.problem = "stopped", ""
+ model.view.state, model.view.problem = "stopped", nil
if value.err != nil {
- model.view.state, model.view.problem = "failed", value.err.Error()
+ model.view.state, model.view.problem = "failed", value.err
}
return model, tea.Quit
case tea.KeyPressMsg:
@@ -327,29 +342,48 @@ func (model consoleModel) content(styled bool) string {
compact := model.height > 0 && model.height < 24
compactDebug := compact && model.debug.logPath != ""
visual := model.language == "vis"
- accent, muted, link := lipgloss.NewStyle(), lipgloss.NewStyle(), lipgloss.NewStyle()
+ accent, muted, link, rule := lipgloss.NewStyle(), lipgloss.NewStyle(), lipgloss.NewStyle(), lipgloss.NewStyle()
if styled {
accent = accent.Bold(true)
muted = muted.Faint(true)
link = link.Underline(true)
}
+ key, stateStyle := accent, accent
+ if styled && model.colors {
+ // Use the terminal's palette so light and dark terminal themes both work.
+ link = link.Foreground(lipgloss.Color("12"))
+ key = key.Foreground(lipgloss.Color("12"))
+ rule = rule.Foreground(lipgloss.Color("8"))
+ switch model.view.state {
+ case "ready", "setup":
+ stateStyle = stateStyle.Foreground(lipgloss.Color("10"))
+ case "starting", "stopping":
+ stateStyle = stateStyle.Foreground(lipgloss.Color("11"))
+ case "failed":
+ stateStyle = stateStyle.Foreground(lipgloss.Color("9"))
+ }
+ }
revision := BuildRevision
if len(revision) == 40 {
revision = revision[:7]
}
var out strings.Builder
version := buildVersion()
- heading := "Piik\nApp\n" + muted.Render(version)
+ heading := accent.Render("Piik App") + "\n" + muted.Render(version)
if revision != "" && revision != version {
- heading = "Piik App\n" + muted.Render(version) + "\n" + muted.Render(revision)
+ heading += "\n" + muted.Render(revision)
}
animated := styled && model.animating()
mascot := accent.Render(consoleTV(model.frame, animated, compact || width < 34))
- if styled && model.colors && width >= 36 && !compactDebug {
+ if styled && model.colors && width >= 36 && !compact {
mascot = consoleBlockTV(model.frame, animated)
}
- fmt.Fprintln(&out, lipgloss.JoinHorizontal(lipgloss.Center, mascot, heading))
- fmt.Fprintln(&out)
+ fmt.Fprintln(&out, lipgloss.JoinHorizontal(lipgloss.Center, mascot, " ", heading))
+ if styled && !compact {
+ fmt.Fprintln(&out, rule.Render(strings.Repeat("─", width-4)))
+ } else {
+ fmt.Fprintln(&out)
+ }
state := model.text(model.view.state)
if model.view.state == "starting" && !visual {
dots := 3
@@ -359,29 +393,17 @@ func (model consoleModel) content(styled bool) string {
state += strings.Repeat(".", dots)
}
if visual {
- stateStyle := accent
- if styled && model.colors {
- switch model.view.state {
- case "ready":
- stateStyle = stateStyle.Foreground(lipgloss.Color("#3fb97a"))
- case "starting", "stopping":
- stateStyle = stateStyle.Foreground(lipgloss.Color("#e8a33d"))
- case "failed":
- stateStyle = stateStyle.Foreground(lipgloss.Color("#e25a52"))
- }
- }
// Keep visual mode one line tall; multi-line scene art side by side
// collapses on narrow terminals and reads like missing characters.
fmt.Fprintln(&out, lipgloss.JoinHorizontal(lipgloss.Center,
accent.Render(consoleVisualToken(model.view.mode)), " · ",
stateStyle.Render(consoleVisualToken(model.view.state))))
- } else if compactDebug && model.view.mode != "" {
- fmt.Fprintf(&out, "%s %s\n", accent.Render(state), model.text(model.view.mode))
} else {
- fmt.Fprintln(&out, accent.Render(state))
+ statusLine := stateStyle.Render(state)
if model.view.mode != "" {
- fmt.Fprintf(&out, "%s %s\n", muted.Render(model.text("mode")), model.text(model.view.mode))
+ statusLine += muted.Render(" · ") + model.text(model.view.mode)
}
+ fmt.Fprintln(&out, ansi.Wrap(statusLine, width-4, ""))
}
for _, item := range [][2]string{{"entry", model.view.entry}, {"launcher", model.launcher}, {"invite", model.view.invite}} {
if item[1] == "" || compact && item[0] == "invite" || item[0] == "launcher" && item[1] == model.view.entry {
@@ -416,7 +438,17 @@ func (model consoleModel) content(styled bool) string {
fmt.Fprintf(&out, "\n%s %s\n", muted.Render(model.text("access")), model.text(access))
}
}
- problem := model.view.problem
+ problem := ""
+ if model.view.problem != nil {
+ problem = diagnostics.SafeText(model.view.problem.Error())
+ if _, diagnostic := model.view.problem.(consoleDiagnostic); !diagnostic {
+ if reason := failure.Of(model.view.problem); reason != "" {
+ fmt.Fprintf(&out, "\n%s\n", ansi.Hardwrap(model.text("failure."+string(reason)), width-4, true))
+ } else if model.view.state != "failed" {
+ fmt.Fprintf(&out, "\n%s\n", model.text("failed"))
+ }
+ }
+ }
if model.view.browserError != nil {
problem = model.text("openFailed") + "\n" + model.view.browserError.Error()
}
@@ -444,31 +476,27 @@ func (model consoleModel) content(styled bool) string {
}
}
if !model.finished {
- keys := "[q / Ctrl+C]"
+ keys := key.Render("[q / Ctrl+C]")
if !styled {
keys = "Ctrl+C"
}
- help := keys + " " + model.text("exit")
+ help := keys + " " + muted.Render(model.text("exit"))
if visual {
if model.view.entry != "" && styled {
- help = "[o] ↗ " + help
+ help = key.Render("[o]") + " ↗ " + help
}
help = lipgloss.JoinHorizontal(lipgloss.Center, accessPicture, help)
} else if model.view.entry != "" && styled {
separator := " "
- if compact && model.debug.export != nil {
+ if compact {
separator = "\n"
}
- help = "[o] " + model.text("entry") + separator + help
+ help = key.Render("[o]") + " " + muted.Render(model.text("entry")) + separator + help
}
if model.debug.export != nil && styled {
- help = "[d] " + model.text("export") + "\n" + help
- }
- if visual {
- fmt.Fprintf(&out, "\n%s", accent.Render(help))
- } else {
- fmt.Fprintf(&out, "\n%s", muted.Render(help))
+ help = key.Render("[d]") + " " + muted.Render(model.text("export")) + "\n" + help
}
+ fmt.Fprintf(&out, "\n%s", help)
}
content := ansi.Hardwrap(out.String(), width-4, true)
if !styled {
@@ -479,7 +507,7 @@ func (model consoleModel) content(styled bool) string {
content = strings.ReplaceAll(content, "\n\n", "\n")
padding = 0
}
- return lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).
+ return lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(rule.GetForeground()).
Padding(padding, 1).Width(width).Render(content)
}
diff --git a/internal/app/console_test.go b/internal/app/console_test.go
index 85d12d5a..a4577bc5 100644
--- a/internal/app/console_test.go
+++ b/internal/app/console_test.go
@@ -15,10 +15,38 @@ import (
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
+ "github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
"github.com/charmbracelet/x/ansi"
)
+func TestConsoleLocalizesFailureAtRenderWithoutLosingCause(t *testing.T) {
+ cause := errors.New("cloudflared exit status 7")
+ problem := errors.Join(failure.TunnelExited, cause)
+ model := consoleModel{language: "en", width: 120, view: consoleView{state: "setup", problem: problem}}
+ for _, language := range []string{"en", "zh", "vis"} {
+ updated, _ := model.Update(consoleLanguage(language))
+ model = updated.(consoleModel)
+ content := model.content(false)
+ if !strings.Contains(strings.Join(strings.Fields(content), ""), strings.Join(strings.Fields(model.text("failure.tunnel-exited")), "")) || !strings.Contains(content, cause.Error()) {
+ t.Fatalf("%s failure presentation: %s", language, content)
+ }
+ if !errors.Is(model.view.problem, cause) {
+ t.Fatal("console lost original cause")
+ }
+ }
+ model.language = "en"
+ model.view.problem = errors.New("unclassified technical failure")
+ if content := model.content(false); !strings.Contains(content, "Could not continue") || !strings.Contains(content, "unclassified technical failure") {
+ t.Fatalf("unknown failure presentation: %s", content)
+ }
+ updated, _ := model.Update(consoleDiagnostic("raw diagnostic line"))
+ content := updated.(consoleModel).content(false)
+ if !strings.Contains(content, "raw diagnostic line") || strings.Contains(content, "Could not continue") {
+ t.Fatalf("diagnostic changed: %s", content)
+ }
+}
+
func TestConsoleRetainsTheSavedDiagnosticPathAfterRestoration(t *testing.T) {
for _, scenario := range []string{"normal", "terminal-ended-before-export", "terminal-read-failed", "manual-result-after-terminal", "failed-export", "failed-export-keeps-path"} {
t.Run(scenario, func(t *testing.T) {
diff --git a/internal/app/failure/failure.go b/internal/app/failure/failure.go
new file mode 100644
index 00000000..630fb145
--- /dev/null
+++ b/internal/app/failure/failure.go
@@ -0,0 +1,31 @@
+// Package failure identifies user-facing App failures without replacing their causes.
+package failure
+
+import "errors"
+
+type Reason string
+
+func (reason Reason) Error() string { return string(reason) }
+
+const (
+ TunnelExited Reason = "tunnel-exited"
+ TunnelTimeout Reason = "tunnel-timeout"
+ TunnelUnavailable Reason = "tunnel-unavailable"
+ TunnelStart Reason = "tunnel-start"
+ TunnelStopped Reason = "tunnel-stopped"
+ LocalPort Reason = "local-port"
+ LocalNetwork Reason = "local-network"
+ Configuration Reason = "configuration"
+ NativeControl Reason = "native-control"
+ Launcher Reason = "launcher"
+ Diagnostics Reason = "diagnostics"
+ LocalServer Reason = "local-server"
+)
+
+func Of(err error) Reason {
+ var reason Reason
+ if errors.As(err, &reason) {
+ return reason
+ }
+ return ""
+}
diff --git a/internal/app/launcher/server.go b/internal/app/launcher/server.go
index 32a08c2e..2f5ee2be 100644
--- a/internal/app/launcher/server.go
+++ b/internal/app/launcher/server.go
@@ -18,6 +18,7 @@ import (
"time"
appconfig "github.com/TNTcraftHIM/Piik/internal/app/config"
+ "github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/app/lan"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
)
@@ -266,6 +267,7 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Re
"target": server.target,
"starting": server.selected && !server.resultSet,
"detail": errorDetail(server.resultErr),
+ "reason": failure.Of(server.resultErr),
"lan": map[string]any{"addresses": addresses, "selected": selected},
"defaultMode": func() Mode {
if server.defaultMode == ModeLocal || server.defaultMode == ModeLink {
@@ -403,7 +405,7 @@ func (server *Server) handleLaunch(response http.ResponseWriter, request *http.R
server.mu.Unlock()
if !resultSet || resultErr != nil {
writeJSON(response, http.StatusServiceUnavailable, map[string]string{
- "error": "Piik App could not start", "detail": errorDetail(resultErr),
+ "error": "Piik App could not start", "detail": errorDetail(resultErr), "reason": string(failure.Of(resultErr)),
})
return
}
diff --git a/internal/app/launcher/server_test.go b/internal/app/launcher/server_test.go
index 96cb227e..6a2024cc 100644
--- a/internal/app/launcher/server_test.go
+++ b/internal/app/launcher/server_test.go
@@ -16,6 +16,7 @@ import (
"testing/fstest"
"time"
+ appfailure "github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/app/lan"
)
@@ -373,21 +374,34 @@ func TestLauncherReportsSafeBoundedFailureDetails(t *testing.T) {
t.Fatalf("CLI debug was not advertised: %+v, %v", state, err)
}
_ = response.Body.Close()
- server.SetResult("", errors.New("public tunnel failed: token=private-secret "+strings.Repeat("network unavailable ", 200)))
+ cause := errors.New("public tunnel failed: token=private-secret " + strings.Repeat("network unavailable ", 200))
+ server.SetResult("", errors.Join(appfailure.TunnelExited, cause))
response, err = localPost(origin+"/api/client-launcher/launch", "application/json",
strings.NewReader(`{"mode":"link","language":"en"}`))
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
- var failure struct{ Error, Detail string }
+ var failure struct{ Error, Detail, Reason string }
if err := json.NewDecoder(response.Body).Decode(&failure); err != nil || response.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("failure response = %d, %v", response.StatusCode, err)
}
- if failure.Error != "Piik App could not start" || !strings.Contains(failure.Detail, "public tunnel failed") ||
+ if failure.Reason != string(appfailure.TunnelExited) || failure.Error != "Piik App could not start" || !strings.Contains(failure.Detail, "public tunnel failed") ||
strings.Contains(failure.Detail, "private-secret") || len([]rune(failure.Detail)) > 2051 {
t.Fatalf("unsafe or missing failure detail: %+v", failure)
}
+ response, err = http.Get(origin + "/api/client-launcher")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ var restored struct{ Reason, Detail string }
+ if err := json.NewDecoder(response.Body).Decode(&restored); err != nil || restored.Reason != failure.Reason || restored.Detail != failure.Detail {
+ t.Fatalf("restored failure = %+v, %v", restored, err)
+ }
+ if !errors.Is(server.resultErr, cause) {
+ t.Fatal("launcher lost original cause")
+ }
}
func TestLauncherAcceptsLocalhostAlias(t *testing.T) {
diff --git a/internal/app/loopback/server.go b/internal/app/loopback/server.go
index 20f48e0f..55b16768 100644
--- a/internal/app/loopback/server.go
+++ b/internal/app/loopback/server.go
@@ -83,6 +83,7 @@ type NativeMediaCapabilities struct {
MaxVideoBitrate int `json:"maxVideoBitrate,omitempty"`
MaxAudioBitrate int `json:"maxAudioBitrate,omitempty"`
ReceiverReuse bool `json:"receiverReuse,omitempty"`
+ RemoteInput bool `json:"remoteInput,omitempty"`
Video bool `json:"video"`
CaptureBorderControl bool `json:"captureBorderControl,omitempty"`
Microphone bool `json:"microphone,omitempty"`
diff --git a/internal/app/mediaedge/edge.go b/internal/app/mediaedge/edge.go
index 657c452b..54179dab 100644
--- a/internal/app/mediaedge/edge.go
+++ b/internal/app/mediaedge/edge.go
@@ -254,6 +254,12 @@ func (edge *Edge) CreateOffer() (webrtc.SessionDescription, error) {
return offer, nil
}
+// OpenDataChannel adds an optional channel before the initial offer. The edge's
+// PeerConnection owns its transport and closes it with the media connection.
+func (edge *Edge) OpenDataChannel(label string) (*webrtc.DataChannel, error) {
+ return edge.connection.CreateDataChannel(label, nil)
+}
+
// Local bridges have no STUN or gateway discovery. Complete SDP keeps their
// candidates and answer in one bounded negotiation, including ICE restarts.
func (edge *Edge) CreateLocalOffer(ctx context.Context, offerID string, restart bool) (webrtc.SessionDescription, error) {
diff --git a/internal/app/mediaedge/publication.go b/internal/app/mediaedge/publication.go
index 39613630..a0d0cbfd 100644
--- a/internal/app/mediaedge/publication.go
+++ b/internal/app/mediaedge/publication.go
@@ -37,6 +37,10 @@ type Publication struct {
qualityCounters forwarding.PublicationCounters
}
+func (publication *Publication) OpenDataChannel(label string) (*webrtc.DataChannel, error) {
+ return publication.signaling.OpenDataChannel(label)
+}
+
func (engine *Engine) NewPublication(source *Source, options EdgeOptions) (*Publication, error) {
if source == nil || source.engine != engine || options.Local || options.ConnectionID == "" ||
len(options.ConnectionID) > 256 || options.Audio != nil && options.Audio.engine != engine {
diff --git a/internal/app/mediaedge/receiver.go b/internal/app/mediaedge/receiver.go
index 5ca83581..ec5d63eb 100644
--- a/internal/app/mediaedge/receiver.go
+++ b/internal/app/mediaedge/receiver.go
@@ -21,6 +21,7 @@ type ReceiverEvents struct {
// The final consumer must check current again after any event queues.
LocalCandidate func(candidate *webrtc.ICECandidateInit, current func() bool)
ConnectionState func(state webrtc.PeerConnectionState, pair *SelectedPair, current func() bool)
+ DataChannel func(*webrtc.DataChannel)
}
type ReceiverOptions struct {
@@ -166,6 +167,9 @@ func (engine *Engine) NewReceiver(options ReceiverOptions) (_ *Receiver, _ webrt
go receiver.readRTCP(track, rtpReceiver)
receiver.consumeTrack(track, rtpReceiver)
})
+ if options.Events.DataChannel != nil {
+ connection.OnDataChannel(options.Events.DataChannel)
+ }
answer, err := receiver.createAnswer()
if err != nil {
_ = receiver.Close()
diff --git a/internal/app/nativecapture/probe.go b/internal/app/nativecapture/probe.go
index 8f4a0a1b..290458ec 100644
--- a/internal/app/nativecapture/probe.go
+++ b/internal/app/nativecapture/probe.go
@@ -46,6 +46,7 @@ type Capabilities struct {
Platform string `json:"platform"`
PlatformBuild string `json:"platformBuild"`
VideoCapture bool `json:"videoCapture"`
+ RemoteInput bool `json:"remoteInput,omitempty"`
CaptureBorderControl bool `json:"captureBorderControl,omitempty"`
Microphone bool `json:"microphone,omitempty"`
ProcessAudio bool `json:"processAudio"`
diff --git a/internal/app/nativecapture/stream.go b/internal/app/nativecapture/stream.go
index 38e96de5..16ee8889 100644
--- a/internal/app/nativecapture/stream.go
+++ b/internal/app/nativecapture/stream.go
@@ -53,6 +53,7 @@ type CaptureTarget struct {
}
type VideoOptions struct {
+ RemoteInput bool
Target CaptureTarget
Codec string
AdapterIndex uint32
@@ -120,10 +121,11 @@ func validVideoPreference(preference string) bool {
}
type Stream struct {
- cancel context.CancelFunc
- input io.ReadCloser
- key io.WriteCloser
- done chan error
+ remoteInput bool
+ cancel context.CancelFunc
+ input io.ReadCloser
+ key io.WriteCloser
+ done chan error
outputs []OutputProfile
active [maxOutputs]bool
@@ -251,6 +253,9 @@ func StartVideo(parent context.Context, executable string, options VideoOptions)
if options.RestoreToken != "" {
environment = []string{"PIIK_XDP_RESTORE_TOKEN=" + options.RestoreToken}
}
+ if options.RemoteInput {
+ environment = append(environment, "PIIK_CAPTURE_REMOTE_INPUT=1")
+ }
arguments := []string{
"--capture-video",
options.Target.Kind,
@@ -291,6 +296,7 @@ func StartVideo(parent context.Context, executable string, options VideoOptions)
return nil, err
}
stream.outputs = outputs
+ stream.remoteInput = options.RemoteInput
stream.active[0], stream.active[1] = true, true
return stream, nil
}
@@ -643,6 +649,32 @@ func (stream *Stream) writeControl(command string) error {
return stream.writeControlLocked(command)
}
+// Remote input uses the selected Portal capture's inherited control pipe; it
+// never opens a separate OS session, listener or network route.
+func (stream *Stream) RemoteInput() bool {
+ // Availability cannot wait behind a blocked media-control write: the input
+ // owner must remain able to reach its bounded write/retirement path.
+ return stream != nil && stream.remoteInput && stream.ctx.Err() == nil
+}
+
+func (stream *Stream) SendRemoteInput(command string) error {
+ if stream == nil {
+ return errors.New("capture input is unavailable")
+ }
+ // A stalled helper must not hold the input grant lock indefinitely. Retire
+ // that same capture if even a small control command cannot make progress.
+ timer := time.AfterFunc(captureStopTimeout, stream.cancel)
+ defer timer.Stop()
+ if !stream.RemoteInput() {
+ return errors.New("capture input is unavailable")
+ }
+ err := stream.writeControl("I " + command)
+ if err != nil {
+ stream.cancel()
+ }
+ return err
+}
+
func (stream *Stream) writeControlLocked(command string) error {
if stream.closed {
return io.ErrClosedPipe
diff --git a/internal/app/nativecapture/stream_test.go b/internal/app/nativecapture/stream_test.go
index 3aa8f23a..d56ae361 100644
--- a/internal/app/nativecapture/stream_test.go
+++ b/internal/app/nativecapture/stream_test.go
@@ -203,6 +203,41 @@ func TestCaptureStopPreservesAnInFlightFrame(t *testing.T) {
<-closed
}
+func TestRemoteInputDoesNotBlockOnAStalledCapture(t *testing.T) {
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ stream, err := startStreamWithEnvironment(t.Context(), executable,
+ []string{"-test.run=^TestCaptureStopHelper$"}, []string{"PIIK_CAPTURE_STOP_FIXTURE=unresponsive"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer stream.Close()
+ if _, err := stream.Read(); err != nil {
+ t.Fatal(err)
+ }
+ stream.remoteInput = true
+ result := make(chan error, 1)
+ go func() {
+ for range 8192 {
+ if err := stream.SendRemoteInput("M 0.500000000 0.500000000"); err != nil {
+ result <- err
+ return
+ }
+ }
+ result <- nil
+ }()
+ select {
+ case err := <-result:
+ if err == nil {
+ t.Fatal("unresponsive helper accepted input after its pipe filled")
+ }
+ case <-time.After(captureStopTimeout + 3*time.Second):
+ t.Fatal("input held its grant lock beyond the capture stop budget")
+ }
+}
+
func TestDiagnosticStderrOverflowDoesNotStopTheChildReader(t *testing.T) {
for _, discard := range []bool{false, true} {
buffer := &boundedBuffer{limit: 4, discardOverflow: discard}
diff --git a/internal/app/nativecontrol/operation_failure_test.go b/internal/app/nativecontrol/operation_failure_test.go
index e4f2b3b1..1c4e2bfb 100644
--- a/internal/app/nativecontrol/operation_failure_test.go
+++ b/internal/app/nativecontrol/operation_failure_test.go
@@ -13,6 +13,7 @@ import (
"github.com/TNTcraftHIM/Piik/internal/app/loopback"
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
@@ -48,7 +49,7 @@ func TestSourceProbesRetireWithTheirControlConnection(t *testing.T) {
const origin = "https://site.example"
server, err := loopback.Start(ctx, loopback.Options{AllowedOrigins: []string{origin},
NewControl: func() loopback.ControlSession {
- return &observedProbeSession{Session: New(executable, nativecapture.Capabilities{}, false), closed: closed}
+ return &observedProbeSession{Session: New(executable, nativecapture.Capabilities{}, false, nil), closed: closed}
}})
if err != nil {
t.Fatal(err)
@@ -123,7 +124,9 @@ func TestOperationalFailureAndIdempotentStopKeepTheRealControlConnection(t *test
defer cancel()
const origin = "https://site.example"
server, err := loopback.Start(ctx, loopback.Options{AllowedOrigins: []string{origin},
- NewControl: func() loopback.ControlSession { return New("missing-capture", nativecapture.Capabilities{}, false) }})
+ NewControl: func() loopback.ControlSession {
+ return New("missing-capture", nativecapture.Capabilities{}, false, nil)
+ }})
if err != nil {
t.Fatal(err)
}
@@ -143,6 +146,7 @@ func TestOperationalFailureAndIdempotentStopKeepTheRealControlConnection(t *test
{"edge-answer", `,"shareId":"missing_share","connectionId":"edge_123456","sdp":"v=0"`, "request-failed"},
{"receive-candidate", `,"shareId":"missing_share","connectionId":"edge_123456","candidate":null`, "request-failed"},
{"pause-share", `,"shareId":"missing_share","paused":true`, "request-failed"},
+ {"set-remote-control", `,"shareId":"missing_share","requestId":"input_request","allow":true`, "request-failed"},
{"publication-media", `,"shareId":"missing_share","publicationGeneration":"publication_123","connectionId":"edge_123456"`, "request-failed"},
{"stop-share", `,"shareId":"missing_share"`, "share-stopped"},
{"stop-share", `,"shareId":"missing_share"`, "share-stopped"},
@@ -178,7 +182,7 @@ func TestFailedEdgeAndLateStopDoNotRetireAnotherShare(t *testing.T) {
t.Fatal(err)
}
t.Setenv("PIIK_QUIET_CAPTURE_FIXTURE", t.TempDir())
- session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false)
+ session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false, nil)
defer session.Close()
const start = `{"version":10,"id":"request_start","type":"start-share","shareId":"share_123456","source":{"kind":"display","sourceId":"1","title":"Fixture"},"audio":false,"edgeCapacity":1,"codec":"vp8","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced"}}`
if value, err := awaitControlResponse(t, session, []byte(start)); err != nil {
@@ -272,9 +276,10 @@ func TestCaptureStartupAndReplacementRemainCancellable(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false)
+ // No input sink is needed to turn permission off.
+ session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false, &remoteinput.Manager{})
defer session.Close()
- start := `{"version":10,"id":"request_start","type":"start-share","shareId":"share_123456","source":{"kind":"display","sourceId":"1","title":"Fixture"},"edgeCapacity":1,"codec":"vp8","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced"}}`
+ start := `{"version":10,"id":"request_start","type":"start-share","shareId":"share_123456","source":{"kind":"display","sourceId":"1","title":"Fixture"},"remoteInput":true,"edgeCapacity":1,"codec":"vp8","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced"}}`
payload := strings.Replace(start, `"width":1920,"height":1080`, `"width":1280,"height":720`, 1)
if kind == "replace-share-source" {
if value, err := awaitControlResponse(t, session, []byte(start)); err != nil {
@@ -300,6 +305,12 @@ func TestCaptureStartupAndReplacementRemainCancellable(t *testing.T) {
}
// No unbounded parallel initialization while the first is still waiting.
assertOperationFailure(t, session, payload)
+ if kind == "replace-share-source" {
+ value, err := session.Handle(t.Context(), []byte(`{"version":10,"id":"request_input_off","type":"set-remote-control-policy","shareId":"share_123456","mode":"off"}`))
+ if err != nil || value != response(requestEnvelope{Version: 10, ID: "request_input_off"}, "remote-control-set") {
+ t.Fatalf("capture preparation blocked permission shutdown: %#v, %v", value, err)
+ }
+ }
if _, err := session.Handle(t.Context(), []byte(`{"version":10,"id":"request_ice","type":"edge-candidate","shareId":"share_123456","connectionId":"missing_edge","candidate":null}`)); err != nil {
t.Fatalf("capture initialization blocked independent control: %v", err)
}
diff --git a/internal/app/nativecontrol/punch_test.go b/internal/app/nativecontrol/punch_test.go
index 57c90654..f772c4b5 100644
--- a/internal/app/nativecontrol/punch_test.go
+++ b/internal/app/nativecontrol/punch_test.go
@@ -11,7 +11,7 @@ import (
)
func TestPunchResponseBackpressureBoundsWorkers(t *testing.T) {
- session := New("", nativecapture.Capabilities{}, false)
+ session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
viewer, err := session.ensureViewer("review_share", 1)
if err != nil {
@@ -73,7 +73,7 @@ func TestPunchResponseBackpressureBoundsWorkers(t *testing.T) {
func TestPunchPreparationPreservesMediaRole(t *testing.T) {
for _, sourceID := range []string{"", "retired_receiver"} {
t.Run("sender/"+sourceID, func(t *testing.T) {
- session := New("", nativecapture.Capabilities{}, false)
+ session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
request := preparePunchRequest{
requestEnvelope: requestEnvelope{Version: 10, ID: "prepare_request", Type: "prepare-punch"},
@@ -91,7 +91,7 @@ func TestPunchPreparationPreservesMediaRole(t *testing.T) {
})
}
t.Run("receiver", func(t *testing.T) {
- session := New("", nativecapture.Capabilities{}, false)
+ session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
capacity := 2
request := preparePunchRequest{
@@ -112,7 +112,7 @@ func TestPunchPreparationPreservesMediaRole(t *testing.T) {
func TestPunchRequiresExplicitMappingStep(t *testing.T) {
for _, step := range []string{"", `,"step":null`, `,"step":0`} {
t.Run(step, func(t *testing.T) {
- session := New("", nativecapture.Capabilities{}, false)
+ session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
payload := []byte(`{"version":10,"id":"run_request","type":"run-punch","shareId":"share_id",` +
`"connectionId":"connection","prediction":{"address":"198.51.100.1","port":5000` + step + `}}`)
diff --git a/internal/app/nativecontrol/session.go b/internal/app/nativecontrol/session.go
index 76bfa6c9..67e275fd 100644
--- a/internal/app/nativecontrol/session.go
+++ b/internal/app/nativecontrol/session.go
@@ -22,6 +22,7 @@ import (
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
"github.com/TNTcraftHIM/Piik/internal/app/nativehost"
"github.com/TNTcraftHIM/Piik/internal/app/nativeviewer"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/pion/webrtc/v4"
@@ -42,6 +43,7 @@ type Session struct {
captureProcess string
capabilities nativecapture.Capabilities
portMapping bool
+ remoteInput *remoteinput.Manager
ctx context.Context
cancel context.CancelFunc
events chan any
@@ -69,12 +71,14 @@ func New(
captureProcess string,
capabilities nativecapture.Capabilities,
portMapping bool,
+ remoteInput *remoteinput.Manager,
) *Session {
ctx, cancel := context.WithCancel(context.Background())
session := &Session{
captureProcess: captureProcess,
capabilities: capabilities,
portMapping: portMapping,
+ remoteInput: remoteInput,
ctx: ctx,
cancel: cancel,
events: make(chan any, 256),
@@ -203,6 +207,61 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,
result = session.beginShare(ctx, envelope, request, complete)
asynchronous = result == nil
return result, nil
+ case "set-remote-input-peers":
+ var request remoteInputPeersRequest
+ if err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) || len(request.Peers) > 20 {
+ return nil, protocolViolation("native input endpoints are invalid")
+ }
+ host := session.current(request.ShareID)
+ if host == nil {
+ return nil, errors.New("native share does not exist")
+ }
+ if err := host.SetRemoteInputPeers(request.Peers); err != nil {
+ return nil, err
+ }
+ return response(envelope, "remote-control-set"), nil
+ case "set-remote-control-policy":
+ var request remoteControlPolicyRequest
+ if err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) {
+ return nil, protocolViolation("native remote-control policy is invalid")
+ }
+ host := session.current(request.ShareID)
+ if host == nil {
+ return nil, errors.New("native share does not exist")
+ }
+ // Revocation is independent of capture preparation and its operation slot.
+ if request.Mode == "off" {
+ apply, err := host.PrepareRemoteInputPolicy(request.Mode, request.Password)
+ if err != nil {
+ return nil, err
+ }
+ return response(envelope, "remote-control-set"), apply()
+ }
+ var apply func() error
+ result = session.runHostOperation(host, envelope, func() error {
+ var err error
+ apply, err = host.PrepareRemoteInputPolicy(request.Mode, request.Password)
+ return err
+ }, func() (any, error) {
+ err := apply()
+ return response(envelope, "remote-control-set"), err
+ }, complete)
+ asynchronous = result == nil
+ return result, nil
+ case "set-remote-control":
+ var request remoteControlRequest
+ if err := decodeStrict(payload, &request); err != nil ||
+ !validIdentities(request.ShareID, request.RequestID) || request.Allow == nil {
+ return nil, protocolViolation("native remote-control decision is invalid")
+ }
+ host := session.current(request.ShareID)
+ if host == nil {
+ return nil, errors.New("native share does not exist")
+ }
+ if err := host.DecideRemoteInput(request.RequestID, *request.Allow); err != nil {
+ return nil, err
+ }
+ return response(envelope, "remote-control-set"), nil
case "set-microphone":
var request microphoneRequest
if err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) ||
@@ -225,7 +284,7 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,
if request.Enabled == nil && request.DeviceID == nil {
return response(envelope, "microphone-set"), nil
}
- result = session.runHostOperation(host, envelope, func() (any, error) {
+ result = session.runHostOperation(host, envelope, nil, func() (any, error) {
err := host.SetMicrophone(request.Enabled, nil, request.DeviceID)
return response(envelope, "microphone-set"), err
}, complete)
@@ -275,7 +334,7 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,
slog.Debug("piik-client", "event", "native-source-requested", "requestId", envelope.ID,
"share", diagnostics.ID(request.ShareID), "sourceKind", request.Source.Kind, "audio", audio,
"adapterIndex", request.AdapterIndex, "encoderIndex", request.EncoderIndex)
- result = session.runHostOperation(host, envelope, func() (any, error) {
+ result = session.runHostOperation(host, envelope, nil, func() (any, error) {
err := host.ReplaceSource(nativecapture.VideoOptions{
Target: request.Source,
ShowCaptureBorder: request.ShowCaptureBorder && session.capabilities.CaptureBorderControl,
@@ -472,7 +531,7 @@ func (session *Session) Close() error {
}
func (session *Session) updateHost(host *nativehost.Session, request requestEnvelope, shareID string, profile nativehost.QualityProfile, complete func(any, error)) any {
- return session.runHostOperation(host, request, func() (any, error) {
+ return session.runHostOperation(host, request, nil, func() (any, error) {
err := host.UpdateProfile(profile)
return session.shareUpdateResult(request, shareID, profile, err), err
}, complete)
@@ -480,12 +539,20 @@ func (session *Session) updateHost(host *nativehost.Session, request requestEnve
// Capture mutations share one bounded operation slot. Stop remains
// synchronous and cancels the owning share before joining this completion.
-func (session *Session) runHostOperation(host *nativehost.Session, request requestEnvelope, operation func() (any, error), complete func(any, error)) any {
+func (session *Session) runHostOperation(host *nativehost.Session, request requestEnvelope, prepare func() error, operation func() (any, error), complete func(any, error)) any {
session.mu.Lock()
if session.closed || session.host != host || session.updateDone != nil || session.startCancel != nil {
session.mu.Unlock()
return operationFailure(request, errors.New("native share operation is unavailable or already active"))
}
+ // Register an authority-changing intent before asynchronous work can be
+ // overtaken by off/pause. This step never waits for an OS permission dialog.
+ if prepare != nil {
+ if err := prepare(); err != nil {
+ session.mu.Unlock()
+ return operationFailure(request, err)
+ }
+ }
done := make(chan struct{})
session.updateDone = done
session.mu.Unlock()
@@ -588,7 +655,14 @@ func (session *Session) startShare(
return nil, errors.New("native share is already active")
}
session.mu.Unlock()
+ // Old pages reject unknown events. Only an opted-in page can own input
+ // requests; this advertises support, not permission for any Viewer.
+ var input *remoteinput.Manager
+ if request.RemoteInput {
+ input = session.remoteInput
+ }
host, err := nativehost.Start(ctx, nativehost.Options{
+ RemoteInput: input,
ShareID: request.ShareID,
CaptureProcess: session.captureProcess,
Video: nativecapture.VideoOptions{
@@ -871,19 +945,32 @@ func (session *Session) stopViewer(shareID string) {
}
func (session *Session) watchHost(host *nativehost.Session) {
- err, open := <-host.Done()
- session.mu.Lock()
- if session.host == host {
- session.host = nil
- }
- session.mu.Unlock()
- if open {
- session.emit(shareEndedEvent{
- Version: loopback.ProtocolVersion,
- Type: "share-ended",
- ShareID: host.ShareID(),
- Failed: err != nil,
- })
+ for {
+ select {
+ case <-host.RemoteInputChanges():
+ session.emit(loopback.ControlEvent{
+ Value: remoteControlStateEvent{
+ eventEnvelope: eventEnvelope{Version: loopback.ProtocolVersion, Type: "remote-control-state", ShareID: host.ShareID()},
+ State: host.RemoteInputState(),
+ },
+ Current: func() bool { return session.current(host.ShareID()) == host },
+ })
+ case err, open := <-host.Done():
+ session.mu.Lock()
+ if session.host == host {
+ session.host = nil
+ }
+ session.mu.Unlock()
+ if open {
+ session.emit(shareEndedEvent{
+ Version: loopback.ProtocolVersion,
+ Type: "share-ended",
+ ShareID: host.ShareID(),
+ Failed: err != nil,
+ })
+ }
+ return
+ }
}
}
diff --git a/internal/app/nativecontrol/session_test.go b/internal/app/nativecontrol/session_test.go
index 222a304b..7a601c9f 100644
--- a/internal/app/nativecontrol/session_test.go
+++ b/internal/app/nativecontrol/session_test.go
@@ -18,6 +18,7 @@ import (
"github.com/TNTcraftHIM/Piik/internal/app/loopback"
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
"github.com/TNTcraftHIM/Piik/internal/app/nativehost"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/pion/webrtc/v4"
)
@@ -79,7 +80,7 @@ func TestReceiveOfferReusePreservesLegacyResponseShape(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- session := New("", nativecapture.Capabilities{}, false)
+ session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
for _, reuse := range []bool{false, true} {
request := receiveOfferRequest{Version: 10, ID: "request_offer", Type: "receive-offer", ShareID: "viewer_session",
@@ -159,7 +160,7 @@ func TestSourceListFitsTheControlEnvelope(t *testing.T) {
t.Fatal(err)
}
t.Setenv("PIIK_SOURCE_LIST_FIXTURE", path)
- session := New(executable, nativecapture.Capabilities{}, false)
+ session := New(executable, nativecapture.Capabilities{}, false, nil)
defer session.Close()
value, err := awaitControlResponse(t, session,
[]byte(`{"version":10,"id":"request_sources","type":"list-sources"}`))
@@ -268,7 +269,7 @@ func TestMicrophoneOptInPreservesLegacyAndOrdersStateBeforeCompletion(t *testing
if err != nil {
t.Fatal(err)
}
- session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true, Microphone: true}, false)
+ session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true, Microphone: true}, false, nil)
defer session.Close()
request := startShareRequest{Version: 10, ID: "request_start", Type: "start-share", ShareID: "share_123456",
Source: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"},
@@ -320,6 +321,41 @@ func TestMicrophoneOptInPreservesLegacyAndOrdersStateBeforeCompletion(t *testing
}
}
+func TestRemoteInputRequiresPageOptIn(t *testing.T) {
+ for _, optIn := range []bool{false, true} {
+ t.Run(strconv.FormatBool(optIn), func(t *testing.T) {
+ t.Setenv("PIIK_QUIET_CAPTURE_FIXTURE", t.TempDir())
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // No OS sink or approved controller: only exercise event ownership.
+ session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true}, false, &remoteinput.Manager{})
+ defer session.Close()
+ request := startShareRequest{Version: 10, ID: "request_start", Type: "start-share", ShareID: "share_123456",
+ Source: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"},
+ RemoteInput: optIn, EdgeCapacity: 1, Codec: "vp8",
+ Profile: qualitySettings{Resolution: protocol.QualityResolution{Width: 1920, Height: 1080}, MaxFramerate: 30, MaxBitrate: 5_000_000, DegradationPreference: "balanced"}}
+ payload, _ := json.Marshal(request)
+ result, err := awaitControlResponse(t, session, payload)
+ if _, ok := result.(shareStartedResponse); err != nil || !ok {
+ t.Fatalf("start failed: %v %#v", err, result)
+ }
+ if (session.current(request.ShareID).RemoteInputChanges() != nil) != optIn {
+ t.Fatal("input events did not respect page opt-in")
+ }
+ // Browser quality candidates relay through this same preview bridge.
+ offer, err := session.current(request.ShareID).PrepareLocalEdge("preview_input", "preview_offer", false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(offer.SDP, "m=application ") != optIn {
+ t.Fatal("preview bridge did not preserve the opted-in input channel")
+ }
+ })
+ }
+}
+
func TestCaptureBorderPreferenceFollowsSourceAndProfile(t *testing.T) {
for _, supported := range []bool{false, true} {
t.Run(strconv.FormatBool(supported), func(t *testing.T) {
@@ -329,7 +365,7 @@ func TestCaptureBorderPreferenceFollowsSourceAndProfile(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true, CaptureBorderControl: supported}, false)
+ session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true, CaptureBorderControl: supported}, false, nil)
t.Cleanup(func() { _ = session.Close() })
handle := func(request any) {
t.Helper()
@@ -398,7 +434,7 @@ func TestQuietHostUpdatePreservesControlAndCancelsCleanly(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false)
+ session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false, nil)
t.Cleanup(func() { _ = session.Close() })
handle := func(payload string) any {
t.Helper()
@@ -596,7 +632,7 @@ func TestSTUNURLsUseTheCurrentBoundedWire(t *testing.T) {
}
func TestControlMessagesRejectUnknownFieldsAndStaleVersions(t *testing.T) {
- session := New("missing-capture-process", nativecapture.Capabilities{}, false)
+ session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
for _, payload := range []string{
`{"version":10,"id":"request_sources","type":"list-sources","extra":true}`,
@@ -629,7 +665,7 @@ func TestResponseKeepsTheRequestIdentity(t *testing.T) {
}
func TestPrepareLocalEdgeOwnsOneStrictRequestShape(t *testing.T) {
- session := New("missing-capture-process", nativecapture.Capabilities{}, false)
+ session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
valid := `{"version":10,"id":"request_local_edge","type":"prepare-local-edge","shareId":"share_123456","connectionId":"edge_1234567"}`
assertOperationFailure(t, session, valid)
@@ -640,7 +676,7 @@ func TestPrepareLocalEdgeOwnsOneStrictRequestShape(t *testing.T) {
}
func TestPreviewFailureReturnsAnAdvisoryResponse(t *testing.T) {
- session := New("missing-capture-process", nativecapture.Capabilities{}, false)
+ session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
value, err := session.Handle(t.Context(), []byte(
`{"version":10,"id":"request_preview","type":"source-preview","source":{"kind":"display","sourceId":"65537","title":"Display 1"}}`,
@@ -655,7 +691,7 @@ func TestPreviewFailureReturnsAnAdvisoryResponse(t *testing.T) {
}
func TestSourceEnumerationFailureDoesNotCloseControl(t *testing.T) {
- session := New("missing-capture-process", nativecapture.Capabilities{}, false)
+ session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
value, err := session.Handle(t.Context(), []byte(
`{"version":10,"id":"request_sources","type":"list-sources"}`,
@@ -707,7 +743,7 @@ func TestQualitySettingsMapOnceIntoNativeMedia(t *testing.T) {
}
func TestUpdateShareRequiresTheCurrentStrictProfile(t *testing.T) {
- session := New("missing-capture-process", nativecapture.Capabilities{}, false)
+ session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
valid := `{"version":10,"id":"request_update","type":"update-share","shareId":"share_123456","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced","maxAudioBitrate":128000}}`
assertOperationFailure(t, session, valid)
@@ -736,7 +772,7 @@ func TestUpdateShareRequiresTheCurrentStrictProfile(t *testing.T) {
}
func TestReplaceShareSourceKeepsOneStrictTargetShape(t *testing.T) {
- session := New("missing-capture-process", nativecapture.Capabilities{}, false)
+ session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
valid := `{"version":10,"id":"request_source","type":"replace-share-source","shareId":"share_123456","source":{"kind":"picker","sourceId":"1","title":"Portal"},"audio":false,"adapterIndex":0,"encoderIndex":0}`
assertOperationFailure(t, session, valid)
diff --git a/internal/app/nativecontrol/wire.go b/internal/app/nativecontrol/wire.go
index 6efd759f..2ec6ea6d 100644
--- a/internal/app/nativecontrol/wire.go
+++ b/internal/app/nativecontrol/wire.go
@@ -3,6 +3,7 @@ package nativecontrol
import (
"github.com/TNTcraftHIM/Piik/internal/app/mediaedge"
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/pion/webrtc/v4"
)
@@ -44,6 +45,7 @@ type startShareRequest struct {
Source nativecapture.CaptureTarget `json:"source"`
Audio bool `json:"audio"`
MicrophoneMixing bool `json:"microphoneMixing,omitempty"`
+ RemoteInput bool `json:"remoteInput,omitempty"`
ExcludeAudio *nativecapture.CaptureTarget `json:"excludeAudio,omitempty"`
ShowCaptureBorder bool `json:"showCaptureBorder,omitempty"`
AdapterIndex uint32 `json:"adapterIndex"`
@@ -61,6 +63,31 @@ type microphoneRequest struct {
DeviceID *string `json:"deviceId,omitempty"`
}
+type remoteControlRequest struct {
+ requestEnvelope
+ ShareID string `json:"shareId"`
+ RequestID string `json:"requestId"`
+ Allow *bool `json:"allow"`
+}
+
+type remoteInputPeersRequest struct {
+ requestEnvelope
+ ShareID string `json:"shareId"`
+ Peers []protocol.RemoteInputPeer `json:"peers"`
+}
+
+type remoteControlPolicyRequest struct {
+ requestEnvelope
+ ShareID string `json:"shareId"`
+ Mode string `json:"mode"`
+ Password string `json:"password,omitempty"`
+}
+
+type remoteControlStateEvent struct {
+ eventEnvelope
+ remoteinput.State
+}
+
type audioStateEvent struct {
eventEnvelope
SourceAudio bool `json:"sourceAudio"`
diff --git a/internal/app/nativehost/publication.go b/internal/app/nativehost/publication.go
index c41bd260..bb29b6ab 100644
--- a/internal/app/nativehost/publication.go
+++ b/internal/app/nativehost/publication.go
@@ -4,6 +4,7 @@ import (
"errors"
"github.com/TNTcraftHIM/Piik/internal/app/mediaedge"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/pion/webrtc/v4"
)
@@ -35,6 +36,9 @@ func (session *Session) PreparePublication(generation, connectionID string, serv
PublicationGeneration: generation, ConnectionID: connectionID, Candidate: candidate})
},
ConnectionState: func(state webrtc.PeerConnectionState, _ *mediaedge.SelectedPair) {
+ if state == webrtc.PeerConnectionStateDisconnected || state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed {
+ session.remoteInput.RevokeEdge(connectionID)
+ }
session.emit(Event{Type: "publication-state", ShareID: session.shareID,
Current: current,
PublicationGeneration: generation, ConnectionID: connectionID, State: state.String()})
@@ -56,6 +60,12 @@ func (session *Session) PreparePublication(generation, connectionID string, serv
publication = created
session.publications[key] = publication
session.mu.Unlock()
+ if session.remoteInput != nil {
+ channel, channelErr := publication.OpenDataChannel(remoteinput.ChannelLabel)
+ if channelErr == nil {
+ session.remoteInput.Attach(connectionID, channel)
+ }
+ }
offer, err := publication.CreateOffer()
if err != nil {
session.ClosePublication(generation, connectionID)
diff --git a/internal/app/nativehost/session.go b/internal/app/nativehost/session.go
index 60694a36..5e4edfb4 100644
--- a/internal/app/nativehost/session.go
+++ b/internal/app/nativehost/session.go
@@ -15,8 +15,10 @@ import (
"github.com/TNTcraftHIM/Piik/internal/app/mediaedge"
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
"github.com/TNTcraftHIM/Piik/internal/media/encoded"
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/pion/webrtc/v4"
)
@@ -38,6 +40,7 @@ type CaptureState struct {
Height uint32 `json:"height,omitempty"`
FPS uint32 `json:"fps,omitempty"`
RestoreToken string `json:"restoreToken,omitempty"`
+ RemoteInput bool `json:"remoteInput,omitempty"`
Outputs []nativecapture.OutputProfile `json:"outputs"`
unavailableLayers []int
@@ -72,6 +75,7 @@ type Options struct {
EdgeCapacity int
BindAddress string
PortMapping bool
+ RemoteInput *remoteinput.Manager
Events func(context.Context, Event)
}
@@ -105,6 +109,7 @@ type Session struct {
audioChanged chan struct{}
paused bool
closed bool
+ remoteInput *remoteinput.Session
}
func Start(parent context.Context, options Options) (*Session, error) {
@@ -162,7 +167,9 @@ func Start(parent context.Context, options Options) (*Session, error) {
ready: make(chan error, 1),
edges: make(map[string]*mediaedge.Edge),
audioChanged: make(chan struct{}, 1),
+ remoteInput: options.RemoteInput.NewSession(),
}
+ session.syncRemoteInputSource(nil)
if audioStream != nil || options.MicrophoneMixing {
audioSource, audioErr := engine.NewAudioSource(
options.EdgeCapacity, options.Profile.AudioBitrate,
@@ -279,6 +286,9 @@ func (session *Session) prepareEdge(
})
},
ConnectionState: func(state webrtc.PeerConnectionState, pair *mediaedge.SelectedPair) {
+ if state == webrtc.PeerConnectionStateDisconnected || state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed {
+ session.remoteInput.RevokeEdge(connectionID)
+ }
session.emit(Event{
Type: "edge-state", ShareID: session.shareID,
ConnectionID: connectionID, State: state.String(),
@@ -308,6 +318,12 @@ func (session *Session) prepareEdge(
session.edges[connectionID] = edge
session.mu.Unlock()
var offer webrtc.SessionDescription
+ if session.remoteInput != nil {
+ channel, channelErr := edge.OpenDataChannel(remoteinput.ChannelLabel)
+ if channelErr == nil {
+ session.remoteInput.Attach(connectionID, channel)
+ }
+ }
if localOfferID != "" {
offer, err = edge.CreateLocalOffer(session.ctx, localOfferID, false)
} else {
@@ -342,6 +358,7 @@ func (session *Session) AddCandidate(
}
func (session *Session) SetPaused(paused bool) {
+ session.remoteInput.Pause(paused)
session.mu.Lock()
if session.closed {
session.mu.Unlock()
@@ -413,6 +430,7 @@ func (session *Session) UpdateProfile(profile QualityProfile) error {
state,
nil,
false,
+ nil,
)
}
@@ -423,7 +441,6 @@ func (session *Session) ReplaceSource(
) error {
session.updateMu.Lock()
defer session.updateMu.Unlock()
-
session.mu.Lock()
if session.closed {
session.mu.Unlock()
@@ -444,6 +461,12 @@ func (session *Session) ReplaceSource(
if session.mixer == nil && audioEnabled != hasAudio {
return errors.New("native source audio availability cannot change while sharing")
}
+ if !audioOnly {
+ // Suspend input while changing capture. On success bind the committed
+ // target; on failure the previous picture remains eligible for a new grant.
+ session.remoteInput.SetTarget(nativecapture.CaptureTarget{}, nil)
+ defer session.syncRemoteInputSource(nil)
+ }
if excludeAudio != nil {
if session.mixer == nil {
return errors.New("native audio exclusion requires mixed audio")
@@ -492,9 +515,77 @@ func (session *Session) ReplaceSource(
state,
replacementAudio,
true,
+ nil,
)
}
+func (session *Session) RemoteInputChanges() <-chan struct{} {
+ return session.remoteInput.Changes()
+}
+
+func (session *Session) RemoteInputState() remoteinput.State {
+ return session.remoteInput.State()
+}
+
+// Reserve the intent synchronously, before dispatch starts asynchronous OS work.
+func (session *Session) PrepareRemoteInputPolicy(mode, password string) (func() error, error) {
+ change, err := session.remoteInput.BeginPolicy(session.ctx, mode, password)
+ if err != nil {
+ return nil, err
+ }
+ return func() error {
+ defer change.Close()
+ if session.remoteInput.UsesCaptureInput() && mode != "off" {
+ session.updateMu.Lock()
+ defer session.updateMu.Unlock()
+ session.mu.Lock()
+ options, profile := session.videoOptions, session.profile
+ closed := session.closed
+ session.mu.Unlock()
+ if closed {
+ return errors.New("native share is unavailable")
+ }
+ if !options.RemoteInput {
+ // Only enabling control requests the combined screen/input permission.
+ // The pending intent can retire without ending the current picture.
+ options.RemoteInput, options.RestoreToken = true, ""
+ replacement, state, err := session.prepareVideo(change.Context(), options, true, false)
+ if err != nil {
+ return err
+ }
+ if err := change.Context().Err(); err != nil {
+ _ = replacement.Close()
+ return err
+ }
+ if err = session.commitCapture(options, profile, replacement, state, nil, false, change); err != nil {
+ return err
+ }
+ }
+ }
+ return change.Apply()
+ }, nil
+}
+
+func (session *Session) SetRemoteInputPeers(peers []protocol.RemoteInputPeer) error {
+ return session.remoteInput.SetPeers(peers)
+}
+
+func (session *Session) DecideRemoteInput(id string, allow bool) error {
+ return session.remoteInput.Decide(id, allow)
+}
+
+func (session *Session) syncRemoteInputSource(change *remoteinput.PolicyChange) {
+ session.mu.Lock()
+ target := session.videoOptions.Target
+ capture := session.stream
+ session.mu.Unlock()
+ if change != nil {
+ change.SetTarget(target, capture)
+ } else {
+ session.remoteInput.SetTarget(target, capture)
+ }
+}
+
func startAudioCapture(
ctx context.Context,
captureProcess string,
@@ -516,9 +607,14 @@ func (session *Session) prepareVideo(
interactive bool,
allowQuiet bool,
) (*nativecapture.Stream, CaptureState, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, CaptureState{}, err
+ }
options.OutputGroups = session.edgeCapacity
+ // Preparation can be cancelled independently. Installed capture always lives
+ // with the share; cancelling a permission request must not kill its process.
replacement, err := nativecapture.StartVideo(
- ctx,
+ session.ctx,
session.captureProcess,
options,
)
@@ -538,6 +634,10 @@ func (session *Session) prepareVideo(
_ = replacement.Close()
return nil, CaptureState{}, err
}
+ if options.RemoteInput && !state.RemoteInput {
+ _ = replacement.Close()
+ return nil, CaptureState{}, errors.New("desktop did not grant remote input")
+ }
return replacement, state, nil
}
@@ -548,6 +648,7 @@ func (session *Session) commitCapture(
state CaptureState,
replacementAudio *nativecapture.Stream,
replaceAudio bool,
+ inputChange *remoteinput.PolicyChange,
) error {
session.mu.Lock()
if session.closed || session.ctx.Err() != nil {
@@ -594,6 +695,16 @@ func (session *Session) commitCapture(
if replacement == nil {
return nil
}
+ // A Portal stream owns input permission as well as the picture. Retire its
+ // grant before closing it, then bind the replacement through the same owner.
+ if session.remoteInput.UsesCaptureInput() {
+ if inputChange != nil {
+ inputChange.SetTarget(nativecapture.CaptureTarget{}, nil)
+ } else {
+ session.remoteInput.SetTarget(nativecapture.CaptureTarget{}, nil)
+ }
+ defer session.syncRemoteInputSource(inputChange)
+ }
_ = replacement.RequestKeyFrame(-1)
_ = previous.Close()
select {
@@ -687,6 +798,7 @@ func (session *Session) Close() error {
// Both explicit Close and source termination retire these idempotent owners.
// Do not wait for run here: Close uses this to unblock run's readers.
func (session *Session) retire() {
+ session.remoteInput.Close()
session.mu.Lock()
source, stream := session.source, session.stream
audioSource, audioStream := session.audioSource, session.audioStream
diff --git a/internal/app/nativehost/session_test.go b/internal/app/nativehost/session_test.go
index 5c7b6b7a..05802db2 100644
--- a/internal/app/nativehost/session_test.go
+++ b/internal/app/nativehost/session_test.go
@@ -90,7 +90,7 @@ func TestCaptureCommitWaitsForReaderMetadataOrTermination(t *testing.T) {
go func() {
session.updateMu.Lock()
err := session.commitCapture(options, QualityProfile{Video: options.Profile, AudioBitrate: 64_000}, replacement,
- CaptureState{AdapterIndex: &adapter, EncoderIndex: &encoder, unavailableLayers: []int{0}}, nil, false)
+ CaptureState{AdapterIndex: &adapter, EncoderIndex: &encoder, unavailableLayers: []int{0}}, nil, false, nil)
session.updateMu.Unlock()
committed <- err
}()
@@ -133,7 +133,7 @@ func TestCaptureCommitWaitsForReaderMetadataOrTermination(t *testing.T) {
check(err)
defer healthy.Close()
go func() {
- committed <- session.commitCapture(options, session.profile, healthy, CaptureState{}, nil, false)
+ committed <- session.commitCapture(options, session.profile, healthy, CaptureState{}, nil, false, nil)
}()
select {
case <-replacement.Done():
@@ -275,7 +275,7 @@ func TestCaptureFailureBelongsToSelectedStream(t *testing.T) {
committed := make(chan error, 1)
if replace {
go func() {
- committed <- session.commitCapture(options, QualityProfile{Video: options.Profile}, replacement, CaptureState{}, nil, false)
+ committed <- session.commitCapture(options, QualityProfile{Video: options.Profile}, replacement, CaptureState{}, nil, false, nil)
}()
deadline := time.Now().Add(5 * time.Second)
for session.currentStream() != replacement {
@@ -306,6 +306,42 @@ func TestCaptureFailureBelongsToSelectedStream(t *testing.T) {
}
}
+func TestPreparedCaptureOutlivesItsPermissionOperation(t *testing.T) {
+ t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "backend")
+ t.Setenv("PIIK_CAPTURE_STARTING", string(captureStatePayload(t,
+ `{"state":"starting","codec":"vp8","adapterIndex":0,"adapterName":"Fixture","adapterIdentity":"0:0","encoderName":"VP8","encoderIdentity":"vp8"}`)))
+ t.Setenv("PIIK_CAPTURE_ACTIVE", string(captureStatePayload(t, `{"state":"active","codec":"vp8","width":1280,"height":720,"fps":30}`)))
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ shareContext, stopShare := context.WithCancel(t.Context())
+ defer stopShare()
+ operationContext, finishOperation := context.WithCancel(shareContext)
+ defer finishOperation()
+ session := &Session{ctx: shareContext, captureProcess: executable, edgeCapacity: 4}
+ stream, _, err := session.prepareVideo(operationContext, nativecapture.VideoOptions{
+ Target: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"}, Codec: "vp8",
+ Profile: nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 3_000_000, Preference: "balanced"},
+ }, true, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer stream.Close()
+ finishOperation()
+ select {
+ case <-stream.Done():
+ t.Fatal("finishing permission preparation stopped its accepted picture")
+ case <-time.After(250 * time.Millisecond):
+ }
+ stopShare()
+ select {
+ case <-stream.Done():
+ case <-time.After(2 * time.Second):
+ t.Fatal("capture outlived its owning share")
+ }
+}
+
func TestCaptureProfileRetainsSelectedBackendFromStarting(t *testing.T) {
t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "backend")
t.Setenv("PIIK_CAPTURE_STARTING", string(captureStatePayload(t,
diff --git a/internal/app/nativeviewer/input_bridge_test.go b/internal/app/nativeviewer/input_bridge_test.go
new file mode 100644
index 00000000..20699470
--- /dev/null
+++ b/internal/app/nativeviewer/input_bridge_test.go
@@ -0,0 +1,148 @@
+package nativeviewer
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
+ "github.com/pion/webrtc/v4"
+)
+
+// Exercise the actual native receiver and local playback edge, not a second
+// Browser-only path. Both local playback and relay children use the media tree.
+func TestInputChannelUsesPlaybackAndRelay(t *testing.T) {
+ peer := func() *webrtc.PeerConnection {
+ t.Helper()
+ p, err := webrtc.NewPeerConnection(webrtc.Configuration{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = p.Close() })
+ return p
+ }
+ localDescription := func(p *webrtc.PeerConnection, description webrtc.SessionDescription) webrtc.SessionDescription {
+ t.Helper()
+ gathered := webrtc.GatheringCompletePromise(p)
+ if err := p.SetLocalDescription(description); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-gathered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("ICE gathering timed out")
+ }
+ return *p.LocalDescription()
+ }
+ upstream, playback := peer(), peer()
+ if _, err := upstream.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo); err != nil {
+ t.Fatal(err)
+ }
+ remote, err := upstream.CreateDataChannel(remoteinput.ChannelLabel, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ requests := make(chan string, 10)
+ remote.OnMessage(func(message webrtc.DataChannelMessage) { requests <- string(message.Data) })
+ offer, err := upstream.CreateOffer(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ offer = localDescription(upstream, offer)
+ events := make(chan Event, 32)
+ session, err := Start(t.Context(), Options{ShareID: "input-viewer", EdgeCapacity: 2, Events: events})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = session.Close() })
+ result, err := session.AcceptOffer("upstream", offer, nil, false, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = upstream.SetRemoteDescription(result.Answer); err != nil {
+ t.Fatal(err)
+ }
+ go func() {
+ for {
+ select {
+ case event := <-events:
+ if event.Type == "edge-candidate" && event.ConnectionID == "upstream" && event.Candidate != nil {
+ _ = upstream.AddICECandidate(*event.Candidate)
+ }
+ case <-t.Context().Done():
+ return
+ }
+ }
+ }()
+ opened := make(chan *webrtc.DataChannel, 1)
+ states := make(chan string, 10)
+ playback.OnDataChannel(func(channel *webrtc.DataChannel) {
+ channel.OnMessage(func(message webrtc.DataChannelMessage) { states <- string(message.Data) })
+ channel.OnOpen(func() { opened <- channel })
+ })
+ localOffer, err := session.PrepareLocalEdge("upstream", "playback", "local-offer", false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = playback.SetRemoteDescription(localOffer); err != nil {
+ t.Fatal(err)
+ }
+ answer, err := playback.CreateAnswer(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = session.SetAnswer("playback", localDescription(playback, answer), "local-offer"); err != nil {
+ t.Fatal(err)
+ }
+ var local *webrtc.DataChannel
+ select {
+ case local = <-opened:
+ case <-time.After(5 * time.Second):
+ t.Fatal("local input channel did not open")
+ }
+ waitMessage := func(messages <-chan string, want string) {
+ t.Helper()
+ timer := time.NewTimer(5 * time.Second)
+ defer timer.Stop()
+ for {
+ select {
+ case message := <-messages:
+ if message == want {
+ return
+ }
+ case <-timer.C:
+ t.Fatalf("missing forwarded message %s", want)
+ }
+ }
+ }
+ waitMessage(requests, `{"ready":true}`)
+ if err = remote.SendText(`{"ready":true}`); err != nil {
+ t.Fatal(err)
+ }
+ waitMessage(states, `{"ready":true}`)
+ const packet = `{"id":"0123456789abcdef0123456789abcdef","epoch":"0123456789abcdef0123456789abcdef","data":"encrypted"}`
+ const closed = `{"id":"0123456789abcdef0123456789abcdef","epoch":"0123456789abcdef0123456789abcdef","closed":true}`
+ if err = local.SendText(packet); err != nil {
+ t.Fatal(err)
+ }
+ waitMessage(requests, packet)
+ if err = session.UpdateProfile(nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 2_000_000, Preference: "balanced"}); err != nil {
+ t.Fatal(err)
+ }
+ relay, err := session.PrepareEdge("upstream", "relay-child", nil, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(relay.SDP, "\nm=application ") {
+ t.Fatal("relay child has no input return path")
+ }
+ session.receiver("upstream").input.LoseDown("playback", nil)
+ waitMessage(requests, closed)
+ if err = local.SendText(packet); err != nil {
+ t.Fatal(err)
+ }
+ waitMessage(requests, packet)
+ session.CloseEdge("playback")
+ waitMessage(requests, closed)
+}
diff --git a/internal/app/nativeviewer/session.go b/internal/app/nativeviewer/session.go
index 53a9a803..d31e1bb9 100644
--- a/internal/app/nativeviewer/session.go
+++ b/internal/app/nativeviewer/session.go
@@ -3,11 +3,13 @@ package nativeviewer
import (
"context"
"errors"
+ "strings"
"sync"
"time"
"github.com/TNTcraftHIM/Piik/internal/app/mediaedge"
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/media/inputroute"
"github.com/pion/webrtc/v4"
)
@@ -37,6 +39,18 @@ type sessionEdge struct {
sourceConnectionID string
}
+type sessionReceiver struct {
+ *mediaedge.Receiver
+ input *inputroute.Relay
+}
+
+func (receiver *sessionReceiver) Close() error {
+ if receiver.input != nil {
+ receiver.input.Close()
+ }
+ return receiver.Receiver.Close()
+}
+
// One current upstream and one prepared route may overlap during a handoff.
const receiverCapacity = 2
@@ -52,7 +66,7 @@ type Session struct {
relay *mediaedge.RelayOptions
mu sync.Mutex
- receivers map[string]*mediaedge.Receiver
+ receivers map[string]*sessionReceiver
edges map[string]sessionEdge
profile *nativecapture.VideoProfile
closed bool
@@ -77,7 +91,7 @@ func Start(parent context.Context, options Options) (*Session, error) {
session := &Session{
shareID: options.ShareID, edgeCapacity: options.EdgeCapacity,
engine: engine, events: options.Events, ctx: ctx, cancel: cancel, relay: options.Relay,
- receivers: make(map[string]*mediaedge.Receiver),
+ receivers: make(map[string]*sessionReceiver),
edges: make(map[string]sessionEdge),
}
go session.runQuality()
@@ -153,13 +167,20 @@ func (session *Session) AcceptOffer(
}
}
session.CloseReceiver(connectionID)
- receiver, answer, err := session.engine.NewReceiver(mediaedge.ReceiverOptions{
+ var input *inputroute.Relay
+ var onDataChannel func(*webrtc.DataChannel)
+ if strings.Contains(offer.SDP, "\nm=application ") {
+ input = inputroute.New(nil)
+ onDataChannel = input.AttachUp
+ }
+ mediaReceiver, answer, err := session.engine.NewReceiver(mediaedge.ReceiverOptions{
Offer: offer,
ICEServers: iceServers,
EdgeCapacity: session.edgeCapacity,
Relay: session.relay,
PunchedSocket: punchedSocket,
Events: mediaedge.ReceiverEvents{
+ DataChannel: onDataChannel,
LocalCandidate: func(candidate *webrtc.ICECandidateInit, current func() bool) {
session.emit(Event{
Current: current,
@@ -168,6 +189,9 @@ func (session *Session) AcceptOffer(
})
},
ConnectionState: func(state webrtc.PeerConnectionState, pair *mediaedge.SelectedPair, current func() bool) {
+ if input != nil {
+ input.SetUpAvailable(state == webrtc.PeerConnectionStateConnected)
+ }
session.emit(Event{
Current: current,
Type: "edge-state", ShareID: session.shareID,
@@ -187,8 +211,12 @@ func (session *Session) AcceptOffer(
},
})
if err != nil {
+ if input != nil {
+ input.Close()
+ }
return OfferResult{}, err
}
+ receiver = &sessionReceiver{Receiver: mediaReceiver, input: input}
session.mu.Lock()
if session.closed || session.receivers[connectionID] != nil || len(session.receivers) >= receiverCapacity {
session.mu.Unlock()
@@ -281,6 +309,9 @@ func (session *Session) prepareEdge(
})
},
ConnectionState: func(state webrtc.PeerConnectionState, pair *mediaedge.SelectedPair) {
+ if receiver.input != nil && (state == webrtc.PeerConnectionStateDisconnected || state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed) {
+ receiver.input.LoseDown(connectionID, nil)
+ }
session.emit(Event{
Type: "edge-state", ShareID: session.shareID,
ConnectionID: connectionID, State: state.String(),
@@ -312,6 +343,14 @@ func (session *Session) prepareEdge(
}
session.mu.Unlock()
var offer webrtc.SessionDescription
+ if receiver.input != nil {
+ channel, channelErr := edge.OpenDataChannel(inputroute.Label)
+ if channelErr != nil {
+ session.CloseEdge(connectionID)
+ return webrtc.SessionDescription{}, channelErr
+ }
+ receiver.input.AttachDown(connectionID, channel)
+ }
if local {
offer, err = edge.CreateLocalOffer(session.ctx, localOfferID, false)
} else {
@@ -379,7 +418,7 @@ func (session *Session) Close() error {
return nil
}
session.closed = true
- receivers := make([]*mediaedge.Receiver, 0, len(session.receivers))
+ receivers := make([]*sessionReceiver, 0, len(session.receivers))
for _, receiver := range session.receivers {
receivers = append(receivers, receiver)
}
@@ -387,7 +426,7 @@ func (session *Session) Close() error {
for _, owned := range session.edges {
edges = append(edges, owned.edge)
}
- session.receivers = make(map[string]*mediaedge.Receiver)
+ session.receivers = make(map[string]*sessionReceiver)
session.edges = make(map[string]sessionEdge)
session.mu.Unlock()
session.cancel()
@@ -400,7 +439,7 @@ func (session *Session) Close() error {
return session.engine.Close()
}
-func (session *Session) receiver(connectionID string) *mediaedge.Receiver {
+func (session *Session) receiver(connectionID string) *sessionReceiver {
session.mu.Lock()
defer session.mu.Unlock()
if session.closed {
diff --git a/internal/app/publictunnel/process.go b/internal/app/publictunnel/process.go
index 749c66ec..c7c70b5b 100644
--- a/internal/app/publictunnel/process.go
+++ b/internal/app/publictunnel/process.go
@@ -20,6 +20,7 @@ import (
"sync"
"time"
+ "github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
)
@@ -72,10 +73,10 @@ func Start(
return nil, err
}
if err := validateExecutable(executable); err != nil {
- return nil, err
+ return nil, errors.Join(failure.TunnelUnavailable, err)
}
if err := validateLocalOrigin(localOrigin); err != nil {
- return nil, err
+ return nil, errors.Join(failure.TunnelStart, err)
}
startup, cancel := context.WithTimeout(parent, startupTimeout)
defer cancel()
@@ -109,8 +110,15 @@ func Start(
err = errors.Join(startup.Err(), err)
}
if parent.Err() == nil {
- err = errors.Join(errors.New("public invitation service did not connect within 30 seconds; check your Internet connection and reopen Piik to try again"), err)
+ err = errors.Join(failure.TunnelTimeout, errors.New("public invitation service did not connect within 30 seconds; check your Internet connection and reopen Piik to try again"), err)
+ }
+ }
+ if err != nil && err != parent.Err() && failure.Of(err) == "" {
+ reason := failure.TunnelStart
+ if errors.Is(err, errStartupExited) {
+ reason = failure.TunnelExited
}
+ err = errors.Join(reason, err)
}
return nil, err
}
diff --git a/internal/app/publictunnel/process_test.go b/internal/app/publictunnel/process_test.go
index 23322c9a..ce307796 100644
--- a/internal/app/publictunnel/process_test.go
+++ b/internal/app/publictunnel/process_test.go
@@ -15,6 +15,8 @@ import (
"sync"
"testing"
"time"
+
+ appfailure "github.com/TNTcraftHIM/Piik/internal/app/failure"
)
func TestMain(tests *testing.M) {
@@ -137,7 +139,7 @@ func TestStartupRetriesOnlyRetiredPreReadyChildren(t *testing.T) {
t.Fatal(err)
}
} else {
- if process != nil || !errors.Is(err, errStartupExited) {
+ if process != nil || !errors.Is(err, errStartupExited) || appfailure.Of(err) != appfailure.TunnelExited {
t.Fatalf("exhausted startup: %v, %v", process, err)
}
if sample.exitCode != 0 {
@@ -409,7 +411,7 @@ func TestStartupCancellationStillRetiresTheTunnel(t *testing.T) {
func TestMissingTunnelExplainsHowToRestoreThePackage(t *testing.T) {
_, err := Start(t.Context(), filepath.Join(t.TempDir(), "missing-tunnel"), "http://127.0.0.1:8787")
var cause *os.PathError
- if !errors.As(err, &cause) || !strings.Contains(err.Error(), "extract the complete Piik archive") {
+ if !errors.As(err, &cause) || appfailure.Of(err) != appfailure.TunnelUnavailable || !strings.Contains(err.Error(), "extract the complete Piik archive") {
t.Fatalf("missing tunnel lost its cause or recovery instruction: %v", err)
}
}
diff --git a/internal/app/remoteinput/cipher.go b/internal/app/remoteinput/cipher.go
new file mode 100644
index 00000000..f25a3fc1
--- /dev/null
+++ b/internal/app/remoteinput/cipher.go
@@ -0,0 +1,63 @@
+package remoteinput
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+)
+
+// Each authenticated room endpoint gets a fresh key through room signaling,
+// never through a media relay. Random nonces survive native-session replacement;
+// authenticated direction and sequence reject reflected or delayed packets.
+type inputCipher struct {
+ aead cipher.AEAD
+ sent, received uint64
+}
+
+func newInputCipher(key string) (*inputCipher, error) {
+ bytes, err := hex.DecodeString(key)
+ if err != nil || len(bytes) != 32 {
+ return nil, errors.New("invalid input key")
+ }
+ block, err := aes.NewCipher(bytes)
+ if err != nil {
+ return nil, err
+ }
+ aead, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, err
+ }
+ return &inputCipher{aead: aead}, nil
+}
+
+func (c *inputCipher) open(data, epoch string) ([]byte, error) {
+ bytes, err := base64.StdEncoding.DecodeString(data)
+ if err != nil || len(bytes) < 20+c.aead.Overhead() || len(bytes) > maxInputBytes+20+c.aead.Overhead() {
+ return nil, errors.New("invalid input packet")
+ }
+ seq := binary.BigEndian.Uint64(bytes[:8])
+ if seq <= c.received {
+ return nil, errors.New("stale input packet")
+ }
+ plain, err := c.aead.Open(nil, bytes[8:20], bytes[20:], inputAAD(0, bytes[:8], epoch))
+ if err == nil {
+ c.received = seq
+ }
+ return plain, err
+}
+
+func (c *inputCipher) seal(data []byte, epoch string) string {
+ c.sent++
+ header := make([]byte, 20)
+ binary.BigEndian.PutUint64(header, c.sent)
+ _, _ = rand.Read(header[8:])
+ return base64.StdEncoding.EncodeToString(c.aead.Seal(header, header[8:], data, inputAAD(1, header[:8], epoch)))
+}
+
+func inputAAD(direction byte, sequence []byte, epoch string) []byte {
+ return append(append([]byte{direction}, sequence...), []byte(epoch)...)
+}
diff --git a/internal/app/remoteinput/cipher_test.go b/internal/app/remoteinput/cipher_test.go
new file mode 100644
index 00000000..64ed8ce0
--- /dev/null
+++ b/internal/app/remoteinput/cipher_test.go
@@ -0,0 +1,46 @@
+package remoteinput
+
+import (
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/TNTcraftHIM/Piik/internal/media/inputroute"
+)
+
+func TestRoutedInputRejectsForgeryReflectionAndReplay(t *testing.T) {
+ host, _ := newInputCipher(strings.Repeat("ab", 32))
+ epoch := strings.Repeat("cd", 16)
+ header := make([]byte, 20)
+ binary.BigEndian.PutUint64(header, 1)
+ _, _ = rand.Read(header[8:])
+ // Escaped quotes/backslashes at the text limit must survive the same relay
+ // envelope as keys, with no alternate channel or widened queue budget.
+ plain, _ := json.Marshal(inputEvent{Type: "text", Text: strings.Repeat("\\\"", maxTextBytes/2), Grant: strings.Repeat("a", 64)})
+ bytes := host.aead.Seal(header, header[8:], plain, inputAAD(0, header[:8], epoch))
+ packet := base64.StdEncoding.EncodeToString(bytes)
+ envelope, _ := json.Marshal(inputroute.Packet{ID: strings.Repeat("b", 32), Epoch: epoch, Data: packet})
+ if len(plain) > maxInputBytes || len(envelope) > inputroute.MaxPacket {
+ t.Fatal("valid text does not fit the input transport")
+ }
+ forged := append([]byte{}, bytes...)
+ forged[len(forged)-1] ^= 1
+ if _, err := host.open(base64.StdEncoding.EncodeToString(forged), epoch); err == nil {
+ t.Fatal("relay modification accepted")
+ }
+ if _, err := host.open(host.seal(plain, epoch), epoch); err == nil {
+ t.Fatal("Host reply reflected as input")
+ }
+ if _, err := host.open(packet, strings.Repeat("ef", 16)); err == nil {
+ t.Fatal("relay replaced the input channel epoch")
+ }
+ if decoded, err := host.open(packet, epoch); err != nil || string(decoded) != string(plain) {
+ t.Fatal("valid endpoint input rejected", err)
+ }
+ if _, err := host.open(packet, epoch); err == nil {
+ t.Fatal("delayed input replay accepted")
+ }
+}
diff --git a/internal/app/remoteinput/keyboard.go b/internal/app/remoteinput/keyboard.go
new file mode 100644
index 00000000..95011db4
--- /dev/null
+++ b/internal/app/remoteinput/keyboard.go
@@ -0,0 +1,35 @@
+//go:build windows || linux
+
+package remoteinput
+
+// Browser KeyboardEvent.code identifies a physical key. Windows SendInput uses
+// set-1 scan codes; E0 prefixes distinguish navigation/right-hand modifiers.
+// Text/IME input is a separate operation, not a different interpretation of keys.
+var scanCodes = map[string]uint16{
+ "Escape": 0x01, "Digit1": 0x02, "Digit2": 0x03, "Digit3": 0x04, "Digit4": 0x05,
+ "Digit5": 0x06, "Digit6": 0x07, "Digit7": 0x08, "Digit8": 0x09, "Digit9": 0x0a,
+ "Digit0": 0x0b, "Minus": 0x0c, "Equal": 0x0d, "Backspace": 0x0e, "Tab": 0x0f,
+ "KeyQ": 0x10, "KeyW": 0x11, "KeyE": 0x12, "KeyR": 0x13, "KeyT": 0x14,
+ "KeyY": 0x15, "KeyU": 0x16, "KeyI": 0x17, "KeyO": 0x18, "KeyP": 0x19,
+ "BracketLeft": 0x1a, "BracketRight": 0x1b, "Enter": 0x1c, "ControlLeft": 0x1d,
+ "KeyA": 0x1e, "KeyS": 0x1f, "KeyD": 0x20, "KeyF": 0x21, "KeyG": 0x22,
+ "KeyH": 0x23, "KeyJ": 0x24, "KeyK": 0x25, "KeyL": 0x26, "Semicolon": 0x27,
+ "Quote": 0x28, "Backquote": 0x29, "ShiftLeft": 0x2a, "Backslash": 0x2b,
+ "KeyZ": 0x2c, "KeyX": 0x2d, "KeyC": 0x2e, "KeyV": 0x2f, "KeyB": 0x30,
+ "KeyN": 0x31, "KeyM": 0x32, "Comma": 0x33, "Period": 0x34, "Slash": 0x35,
+ "ShiftRight": 0x36, "NumpadMultiply": 0x37, "AltLeft": 0x38, "Space": 0x39,
+ "CapsLock": 0x3a, "F1": 0x3b, "F2": 0x3c, "F3": 0x3d, "F4": 0x3e,
+ "F5": 0x3f, "F6": 0x40, "F7": 0x41, "F8": 0x42, "F9": 0x43, "F10": 0x44,
+ "NumLock": 0x45, "ScrollLock": 0x46, "Numpad7": 0x47, "Numpad8": 0x48,
+ "Numpad9": 0x49, "NumpadSubtract": 0x4a, "Numpad4": 0x4b, "Numpad5": 0x4c,
+ "Numpad6": 0x4d, "NumpadAdd": 0x4e, "Numpad1": 0x4f, "Numpad2": 0x50,
+ "Numpad3": 0x51, "Numpad0": 0x52, "NumpadDecimal": 0x53, "IntlBackslash": 0x56,
+ "F11": 0x57, "F12": 0x58, "F13": 0x64, "F14": 0x65, "F15": 0x66,
+ "F16": 0x67, "F17": 0x68, "F18": 0x69, "F19": 0x6a, "F20": 0x6b,
+ "F21": 0x6c, "F22": 0x6d, "F23": 0x6e, "F24": 0x76,
+ "NumpadEnter": 0xe01c, "ControlRight": 0xe01d, "NumpadDivide": 0xe035,
+ "PrintScreen": 0xe037, "AltRight": 0xe038, "Home": 0xe047, "ArrowUp": 0xe048,
+ "PageUp": 0xe049, "ArrowLeft": 0xe04b, "ArrowRight": 0xe04d, "End": 0xe04f,
+ "ArrowDown": 0xe050, "PageDown": 0xe051, "Insert": 0xe052, "Delete": 0xe053,
+ "MetaLeft": 0xe05b, "MetaRight": 0xe05c, "ContextMenu": 0xe05d,
+}
diff --git a/internal/app/remoteinput/manager.go b/internal/app/remoteinput/manager.go
new file mode 100644
index 00000000..71ffbd2f
--- /dev/null
+++ b/internal/app/remoteinput/manager.go
@@ -0,0 +1,609 @@
+// Package remoteinput owns the source-scoped desktop input grant.
+// Only the owning Host control session can choose its authorization policy. Media routing remains
+// outside this package; closing its exact source or connection releases input.
+package remoteinput
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "runtime"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/media/inputroute"
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+ "github.com/pion/webrtc/v4"
+)
+
+const ChannelLabel = inputroute.Label
+
+type bounds struct{ left, top, width, height int32 }
+
+type inputEvent struct {
+ Type string `json:"type"`
+ Grant string `json:"grant,omitempty"`
+ Intent string `json:"intent,omitempty"`
+ Password string `json:"password,omitempty"`
+ X float64 `json:"x,omitempty"`
+ Y float64 `json:"y,omitempty"`
+ Button int `json:"button,omitempty"`
+ Down bool `json:"down,omitempty"`
+ Code string `json:"code,omitempty"`
+ Text string `json:"text,omitempty"`
+ Delta int `json:"delta,omitempty"`
+ DX int32 `json:"dx,omitempty"`
+ DY int32 `json:"dy,omitempty"`
+}
+
+type inputSink interface {
+ Authorize() error
+ Target(nativecapture.CaptureTarget, *nativecapture.Stream) (bounds, bool, error)
+ Apply(bounds, inputEvent) error
+ Reset() error
+}
+
+type View struct {
+ ID string `json:"id"`
+ PeerID string `json:"peerId"`
+ State string `json:"state"`
+}
+
+// One manager covers both native sessions: they operate the same physical desktop.
+type Manager struct {
+ mu sync.Mutex
+ sink inputSink
+ connections map[endpointKey]*connection
+ active *connection
+ closed bool
+ stop context.CancelFunc
+}
+
+type Session struct {
+ manager *Manager
+ target nativecapture.CaptureTarget
+ capture *nativecapture.Stream
+ paused bool
+ closed bool
+ changed chan struct{}
+ route *inputroute.Relay
+ mode string
+ policyChange *PolicyChange
+ password [32]byte
+ passwordRetry time.Time
+}
+
+type connection struct {
+ owner *Session
+ edgeID string
+ epoch string
+ id string
+ requested bool
+ requestID string
+ intent string
+ grant string
+ suspended bool
+ peerID string
+ secret string
+ cipher *inputCipher
+}
+
+type endpointKey struct {
+ owner *Session
+ id string
+}
+
+// New prepares the platform backend. Input remains disabled until the sharing
+// session enables it; no service, driver or startup entry is installed.
+func New(ctx context.Context, captureInput bool) (*Manager, error) {
+ sink, err := newPlatformSink(captureInput)
+ if err != nil || sink == nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithCancel(ctx)
+ m := &Manager{sink: sink, connections: make(map[endpointKey]*connection), stop: cancel}
+ if err := watchStopShortcut(ctx, func() { m.Revoke() }); err != nil {
+ cancel()
+ if closer, ok := sink.(io.Closer); ok {
+ _ = closer.Close()
+ }
+ return nil, err
+ }
+ // Foreground changes must release held input even when the remote player
+ // is holding a key without sending more events. Only an active grant polls.
+ go func() {
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ m.mu.Lock()
+ m.refreshActive()
+ m.mu.Unlock()
+ }
+ }
+ }()
+ return m, nil
+}
+
+func (m *Manager) NewSession() *Session {
+ if m == nil {
+ return nil
+ }
+ s := &Session{manager: m, changed: make(chan struct{}, 1), mode: "off"}
+ s.route = inputroute.New(s.receivePacket)
+ return s
+}
+
+// Changes coalesces notifications; State reads the current permission and grant owner. Input
+// packets do not generate UI updates, and no callback runs under the input lock.
+func (s *Session) Changes() <-chan struct{} {
+ if s == nil {
+ return nil
+ }
+ return s.changed
+}
+
+func (s *Session) notify() {
+ select {
+ case s.changed <- struct{}{}:
+ default:
+ }
+}
+
+// The channel belongs to the sharing session; input permission belongs to its
+// current source. Replacing a picture revokes the grant without losing the
+// channel needed to request control of the next source.
+func (s *Session) SetTarget(target nativecapture.CaptureTarget, capture *nativecapture.Stream) {
+ s.setTarget(target, capture, nil)
+}
+
+// A Portal permission change replaces its capture as part of that same intent.
+// Always bind the installed picture, including after cancellation; only a still
+// current change may survive this binding and subsequently enable input.
+func (change *PolicyChange) SetTarget(target nativecapture.CaptureTarget, capture *nativecapture.Stream) {
+ change.session.setTarget(target, capture, change)
+}
+
+func (s *Session) setTarget(target nativecapture.CaptureTarget, capture *nativecapture.Stream, change *PolicyChange) {
+ if s == nil {
+ return
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.closed || s.closed {
+ return
+ }
+ if target.Kind != "display" && target.Kind != "window" && !(s.UsesCaptureInput() && target.Kind == "picker") {
+ target = nativecapture.CaptureTarget{}
+ }
+ s.target = target
+ s.capture = capture
+ if change == nil || s.policyChange != change {
+ s.cancelPolicy()
+ }
+ s.applyPolicy("off", [32]byte{})
+}
+
+// The Linux Portal owns input and screen selection in the same OS session.
+func (s *Session) UsesCaptureInput() bool { return s != nil && runtime.GOOS == "linux" }
+
+func (s *Session) Attach(edgeID string, channel *webrtc.DataChannel) {
+ s.route.AttachDown(edgeID, channel)
+}
+
+// Bindings come only from the owning Host's authenticated room connection.
+// Receiving a packet from a relay never creates or names an input identity.
+func (s *Session) SetPeers(peers []protocol.RemoteInputPeer) error {
+ if s == nil {
+ return errors.New("remote input is unavailable")
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.closed || s.closed {
+ return errors.New("remote input is closed")
+ }
+ retained := make(map[string]bool, len(peers))
+ for _, peer := range peers {
+ if !protocol.ValidInputKey(peer.EndpointID, peer.Secret) || !protocol.ValidOpaqueID(peer.PeerID) || retained[peer.EndpointID] {
+ return errors.New("invalid input endpoint")
+ }
+ retained[peer.EndpointID] = true
+ }
+ for _, peer := range peers {
+ previous := m.connections[endpointKey{s, peer.EndpointID}]
+ if previous != nil && previous.secret == peer.Secret && previous.peerID == peer.PeerID {
+ continue
+ }
+ if previous == m.active && previous != nil {
+ m.release()
+ }
+ cipher, _ := newInputCipher(peer.Secret)
+ c := &connection{owner: s, id: peer.EndpointID, peerID: peer.PeerID, secret: peer.Secret, cipher: cipher}
+ m.connections[endpointKey{s, c.id}] = c
+ // Signaling and the media return path can arrive in either order.
+ // Ask this endpoint to sync only after its authenticated key is installed.
+ ready := true
+ s.route.Reply(inputroute.Packet{ID: c.id, Ready: &ready})
+ }
+ for id, c := range m.connections {
+ if c.owner == s && !retained[id.id] {
+ if m.active == c {
+ m.release()
+ }
+ delete(m.connections, id)
+ }
+ }
+ s.notify()
+ return nil
+}
+
+func (s *Session) receivePacket(edgeID string, packet inputroute.Packet) {
+ m := s.manager
+ m.mu.Lock()
+ c := m.connections[endpointKey{s, packet.ID}]
+ if c == nil || m.closed || s.closed {
+ m.mu.Unlock()
+ return
+ }
+ if packet.Closed {
+ if c.edgeID == edgeID && c.epoch == packet.Epoch {
+ m.revoke(c)
+ c.edgeID = ""
+ }
+ m.mu.Unlock()
+ return
+ }
+ plain, err := c.cipher.open(packet.Data, packet.Epoch)
+ if err != nil {
+ m.mu.Unlock()
+ return
+ }
+ if c.edgeID != "" && (c.edgeID != edgeID || c.epoch != packet.Epoch) {
+ m.revoke(c)
+ }
+ c.edgeID, c.epoch = edgeID, packet.Epoch
+ m.mu.Unlock()
+ m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: plain}, packet.Epoch)
+}
+
+func (m *Manager) send(c *connection, state string) {
+ m.reply(c, state, "")
+}
+
+func (m *Manager) reply(c *connection, state, reason string) {
+ if c.epoch == "" {
+ return
+ }
+ if state == "ready" && (!c.owner.available() || c.owner.mode == "off") {
+ state = "unavailable"
+ }
+ data, _ := json.Marshal(struct {
+ Platform string `json:"platform"`
+ State string `json:"state"`
+ Grant string `json:"grant,omitempty"`
+ Intent string `json:"intent,omitempty"`
+ Mode string `json:"mode"`
+ Reason string `json:"reason,omitempty"`
+ }{runtime.GOOS, state, c.grant, c.intent, c.owner.mode, reason})
+ c.owner.route.Reply(inputroute.Packet{ID: c.id, Epoch: c.epoch, Data: c.cipher.seal(data, c.epoch)})
+}
+
+func (s *Session) available() bool {
+ return !s.closed && !s.paused && s.target.SourceID != ""
+}
+
+func (m *Manager) state(c *connection) string {
+ if m.active == c {
+ if c.suspended {
+ return "suspended"
+ }
+ return "active"
+ }
+ if c.requested {
+ return "pending"
+ }
+ return "ready"
+}
+
+// Caller holds mu. Source identity, geometry and focus are checked at the
+// input owner, never inferred from a Browser's last displayed video frame.
+func (m *Manager) refreshActive() (bounds, bool) {
+ c := m.active
+ if c == nil {
+ return bounds{}, false
+ }
+ b, focused, err := m.sink.Target(c.owner.target, c.owner.capture)
+ if err != nil {
+ m.release()
+ m.send(c, "failed")
+ return bounds{}, false
+ }
+ suspended := !focused
+ if c.suspended != suspended {
+ c.suspended = suspended
+ if !focused {
+ _ = m.sink.Reset()
+ }
+ m.send(c, m.state(c))
+ c.owner.notify()
+ }
+ return b, focused
+}
+
+func (m *Manager) release() {
+ if c := m.active; c != nil {
+ m.active = nil
+ c.grant = ""
+ c.suspended = false
+ _ = m.sink.Reset()
+ m.send(c, "ready")
+ c.owner.notify()
+ }
+}
+
+func (m *Manager) receive(c *connection, message webrtc.DataChannelMessage, epoch string) {
+ if !message.IsString || len(message.Data) > maxInputBytes {
+ return
+ }
+ var event inputEvent
+ decoder := json.NewDecoder(bytes.NewReader(message.Data))
+ decoder.DisallowUnknownFields()
+ if decoder.Decode(&event) != nil || decoder.Decode(&struct{}{}) != io.EOF {
+ return
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.closed || c.owner.closed || m.connections[endpointKey{c.owner, c.id}] != c || c.epoch != epoch {
+ return
+ }
+ switch event.Type {
+ case "sync":
+ m.send(c, m.state(c))
+ case "request":
+ if !c.owner.available() || c.owner.mode == "off" || c.requested || c == m.active {
+ return
+ }
+ if intent, err := hex.DecodeString(event.Intent); err != nil || len(intent) != 16 {
+ return
+ }
+ id := make([]byte, 16)
+ _, _ = rand.Read(id)
+ c.requestID, c.intent = hex.EncodeToString(id), event.Intent
+ if c.owner.mode != "ask" {
+ if reason := c.owner.authorize(event.Password); reason != "" {
+ m.reply(c, "ready", reason)
+ return
+ }
+ // Automatic permission never displaces another controller, including
+ // a controller of the App's other native session.
+ if m.active != nil {
+ m.reply(c, "ready", "busy")
+ return
+ }
+ m.grant(c)
+ return
+ }
+ c.requested = true
+ m.send(c, "pending")
+ c.owner.notify()
+ case "release":
+ if event.Intent != c.intent || (!c.requested && m.active != c) {
+ return
+ }
+ c.requested = false
+ if m.active == c {
+ m.release()
+ } else {
+ m.send(c, "ready")
+ }
+ c.owner.notify()
+ default:
+ if m.active != c || c.grant == "" || event.Grant != c.grant || !c.owner.available() {
+ return
+ }
+ if event.Type == "reset" {
+ _ = m.sink.Reset()
+ return
+ }
+ b, focused := m.refreshActive()
+ if !focused {
+ return
+ }
+ var err error
+ if event.Type == "text" {
+ err = applyText(m.sink, b, event.Text)
+ } else {
+ err = m.sink.Apply(b, event)
+ }
+ if err != nil {
+ m.release()
+ m.send(c, "failed")
+ }
+ }
+}
+
+func (m *Manager) revoke(c *connection) {
+ c.requested = false
+ if m.active == c {
+ m.release()
+ } else {
+ m.send(c, "ready")
+ }
+ c.owner.notify()
+}
+
+func (s *Session) Pause(paused bool) {
+ if s == nil {
+ return
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ s.paused = paused
+ if paused {
+ s.cancelPolicy()
+ }
+ if paused && m.active != nil && m.active.owner == s {
+ m.release()
+ }
+ for _, c := range m.connections {
+ if c.owner == s {
+ if paused {
+ c.requested = false
+ }
+ m.send(c, m.state(c))
+ }
+ }
+ s.notify()
+}
+
+// Transport loss retires permission, not the media-owned channel. A recovered
+// ICE connection can carry a new request, but never restore the previous grant.
+func (s *Session) RevokeEdge(edgeID string) {
+ if s == nil {
+ return
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, c := range m.connections {
+ if c.owner == s && c.edgeID == edgeID {
+ m.revoke(c)
+ }
+ }
+}
+
+func (s *Session) Close() {
+ if s == nil {
+ return
+ }
+ m := s.manager
+ m.mu.Lock()
+ s.closed = true
+ s.cancelPolicy()
+ if m.active != nil && m.active.owner == s {
+ m.release()
+ }
+ for id, c := range m.connections {
+ if c.owner == s {
+ delete(m.connections, id)
+ }
+ }
+ s.notify()
+ m.mu.Unlock()
+ s.route.Close()
+}
+
+func (m *Manager) Revoke() {
+ if m == nil {
+ return
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.active != nil {
+ m.active.owner.setPolicy("ask", [32]byte{})
+ }
+}
+
+func (m *Manager) Close() {
+ if m == nil {
+ return
+ }
+ m.mu.Lock()
+ if m.closed {
+ m.mu.Unlock()
+ return
+ }
+ m.closed = true
+ m.release()
+ if closer, ok := m.sink.(io.Closer); ok {
+ _ = closer.Close()
+ }
+ m.mu.Unlock()
+ if m.stop != nil {
+ m.stop()
+ }
+}
+
+type State struct {
+ Platform string `json:"platform"`
+ Mode string `json:"mode"`
+ Requests []View `json:"requests"`
+}
+
+func (s *Session) State() State {
+ state := State{Platform: runtime.GOOS, Mode: "off", Requests: []View{}}
+ if s == nil {
+ return state
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ state.Mode = s.mode
+ for _, c := range m.connections {
+ if c.owner == s && (c.requested || m.active == c) {
+ state.Requests = append(state.Requests, View{c.requestID, c.peerID, m.state(c)})
+ }
+ }
+ sort.Slice(state.Requests, func(i, j int) bool { return state.Requests[i].ID < state.Requests[j].ID })
+ return state
+}
+
+func (s *Session) Decide(id string, allow bool) error {
+ if s == nil {
+ return errors.New("remote input is unavailable")
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var c *connection
+ for _, candidate := range m.connections {
+ if candidate.owner == s && candidate.requestID == id {
+ c = candidate
+ break
+ }
+ }
+ if m.closed || c == nil || !s.available() || c.edgeID == "" || (!c.requested && m.active != c) {
+ return errors.New("request is no longer available")
+ }
+ defer s.notify()
+ if !allow {
+ if s.mode != "ask" {
+ s.setPolicy("ask", [32]byte{})
+ return nil
+ }
+ c.requested = false
+ if m.active == c {
+ m.release()
+ } else {
+ m.send(c, "ready")
+ }
+ return nil
+ }
+ m.grant(c)
+ return nil
+}
+
+func (m *Manager) grant(c *connection) {
+ m.release()
+ token := make([]byte, 32)
+ _, _ = rand.Read(token)
+ c.grant, c.requested = hex.EncodeToString(token), false
+ m.active = c
+ m.refreshActive()
+ if m.active == c {
+ m.send(c, m.state(c))
+ }
+ c.owner.notify()
+}
diff --git a/internal/app/remoteinput/manager_test.go b/internal/app/remoteinput/manager_test.go
new file mode 100644
index 00000000..7975e3e3
--- /dev/null
+++ b/internal/app/remoteinput/manager_test.go
@@ -0,0 +1,636 @@
+package remoteinput
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/hex"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "github.com/TNTcraftHIM/Piik/internal/media/inputroute"
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+ "github.com/pion/webrtc/v4"
+)
+
+type recordedInput struct {
+ authorize func() error
+ events chan inputEvent
+ resets chan struct{}
+ target bounds
+ geometry bounds
+ focused bool
+}
+
+func setTestPolicy(s *Session, mode, password string) error {
+ change, err := s.BeginPolicy(context.Background(), mode, password)
+ if err != nil {
+ return err
+ }
+ defer change.Close()
+ return change.Apply()
+}
+
+func TestSourceAuthorizationPolicy(t *testing.T) {
+ sink := &recordedInput{events: make(chan inputEvent, 20), resets: make(chan struct{}, 20), focused: true}
+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}
+ s := m.NewSession()
+ t.Cleanup(s.Close)
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)
+ peers := []protocol.RemoteInputPeer{
+ {PeerID: "first-viewer", EndpointID: strings.Repeat("a", 32), Secret: strings.Repeat("b", 64)},
+ {PeerID: "second-viewer", EndpointID: strings.Repeat("c", 32), Secret: strings.Repeat("d", 64)},
+ }
+ if err := s.SetPeers(peers); err != nil {
+ t.Fatal(err)
+ }
+ first, second := m.connections[endpointKey{s, peers[0].EndpointID}], m.connections[endpointKey{s, peers[1].EndpointID}]
+ for _, c := range []*connection{first, second} {
+ c.edgeID, c.epoch = "root-edge", strings.Repeat("e", 32)
+ }
+ request := func(c *connection, password string) {
+ t.Helper()
+ data, _ := json.Marshal(inputEvent{Type: "request", Intent: strings.Repeat("f", 32), Password: password})
+ m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: data}, c.epoch)
+ }
+ request(first, "")
+ if s.State().Mode != "off" || first.requested || m.active != nil {
+ t.Fatal("ordinary sharing accepted a control request before opt-in")
+ }
+ if err := setTestPolicy(s, "ask", ""); err != nil {
+ t.Fatal(err)
+ }
+ request(first, "")
+ oldRequest := first.requestID
+ if !first.requested || m.active != nil {
+ t.Fatal("Ask each time did not require Host approval")
+ }
+ if err := setTestPolicy(s, "room", ""); err != nil {
+ t.Fatal(err)
+ }
+ if m.active != nil || first.requested || s.Decide(oldRequest, true) == nil {
+ t.Fatal("policy change inherited an old request")
+ }
+ request(first, "")
+ if m.active != first {
+ t.Fatal("explicit room policy did not grant control")
+ }
+ request(second, "")
+ if m.active != first || second.requested {
+ t.Fatal("automatic request displaced an active controller")
+ }
+ m.Revoke()
+ if m.active != nil || s.State().Mode != "ask" {
+ t.Fatal("local stop did not disable automatic access")
+ }
+ request(second, "")
+ if !second.requested || m.active != nil {
+ t.Fatal("local stop allowed automatic re-entry")
+ }
+ if setTestPolicy(s, "password", "") == nil {
+ t.Fatal("password mode accepted an empty credential")
+ }
+ if err := setTestPolicy(s, "password", "shared-secret"); err != nil {
+ t.Fatal(err)
+ }
+ request(first, "wrong")
+ if m.active != nil || first.requested {
+ t.Fatal("incorrect password acquired control")
+ }
+ request(second, "shared-secret")
+ if m.active != nil {
+ t.Fatal("changing endpoints bypassed password attempt pacing")
+ }
+ s.passwordRetry = time.Time{}
+ request(first, "shared-secret")
+ if m.active != first {
+ t.Fatal("correct password did not authorize control")
+ }
+ if err := s.Decide(first.requestID, false); err != nil {
+ t.Fatal(err)
+ }
+ if m.active != nil || s.State().Mode != "ask" {
+ t.Fatal("Host stop left automatic access enabled")
+ }
+ if err := setTestPolicy(s, "room", ""); err != nil {
+ t.Fatal(err)
+ }
+ request(first, "")
+ s.RevokeEdge("root-edge")
+ if m.active != nil {
+ t.Fatal("route loss retained input")
+ }
+ request(first, "")
+ if m.active != first {
+ t.Fatal("room policy could not authorize a fresh request")
+ }
+ oldGrant := first.grant
+ s.Pause(true)
+ if err := setTestPolicy(s, "off", ""); err != nil {
+ t.Fatal(err)
+ }
+ s.Pause(false)
+ m.receive(first, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"key","code":"KeyA","down":true,"grant":"` + oldGrant + `"}`)}, first.epoch)
+ request(second, "")
+ if m.active != nil || second.requested || len(sink.events) != 0 {
+ t.Fatal("disabled remote control retained input or accepted a new request")
+ }
+ if err := setTestPolicy(s, "room", ""); err != nil {
+ t.Fatal(err)
+ }
+ request(first, "")
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)
+ if m.active != nil || s.State().Mode != "off" {
+ t.Fatal("source replacement inherited permission")
+ }
+ request(second, "")
+ if second.requested || m.active != nil {
+ t.Fatal("replacement source accepted input without opt-in")
+ }
+}
+
+func TestRouteReplacementRequiresApprovalAndIgnoresOldClosure(t *testing.T) {
+ sink := &recordedInput{events: make(chan inputEvent, 8), resets: make(chan struct{}, 8), focused: true}
+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}
+ s := m.NewSession()
+ t.Cleanup(s.Close)
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)
+ if err := setTestPolicy(s, "ask", ""); err != nil {
+ t.Fatal(err)
+ }
+ peer := protocol.RemoteInputPeer{PeerID: "viewer-route-test", EndpointID: strings.Repeat("a", 32), Secret: strings.Repeat("b", 64)}
+ if err := s.SetPeers([]protocol.RemoteInputPeer{peer}); err != nil {
+ t.Fatal(err)
+ }
+ cipher, _ := newInputCipher(peer.Secret)
+ request := func(epoch string) string {
+ t.Helper()
+ cipher.sent++
+ header := make([]byte, 20)
+ binary.BigEndian.PutUint64(header, cipher.sent)
+ _, _ = rand.Read(header[8:])
+ plain := []byte(`{"type":"request","intent":"` + epoch + `"}`)
+ data := cipher.aead.Seal(header, header[8:], plain, inputAAD(0, header[:8], epoch))
+ s.receivePacket("same-root-relay", inputroute.Packet{ID: peer.EndpointID, Epoch: epoch, Data: base64.StdEncoding.EncodeToString(data)})
+ views := s.State().Requests
+ if len(views) != 1 || views[0].State != "pending" {
+ t.Fatal("new channel did not require fresh approval")
+ }
+ if err := s.Decide(views[0].ID, true); err != nil {
+ t.Fatal(err)
+ }
+ return m.active.grant
+ }
+ oldEpoch, newEpoch := strings.Repeat("c", 32), strings.Repeat("d", 32)
+ oldGrant := request(oldEpoch)
+ newGrant := request(newEpoch)
+ if oldGrant == newGrant || len(sink.resets) != 1 {
+ t.Fatal("replacement retained old input")
+ }
+ s.receivePacket("same-root-relay", inputroute.Packet{ID: peer.EndpointID, Epoch: oldEpoch, Closed: true})
+ m.receive(m.active, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"release","intent":"` + newEpoch + `"}`)}, oldEpoch)
+ if m.active == nil || m.active.grant != newGrant {
+ t.Fatal("old descendant closure retired the new grant")
+ }
+ s.receivePacket("same-root-relay", inputroute.Packet{ID: peer.EndpointID, Epoch: newEpoch, Closed: true})
+ if m.active != nil || len(sink.resets) != 2 {
+ t.Fatal("current route loss did not release input")
+ }
+}
+
+func (s *recordedInput) Authorize() error {
+ if s.authorize != nil {
+ return s.authorize()
+ }
+ return nil
+}
+
+func TestOSPermissionCannotAuthorizeAReplacementSource(t *testing.T) {
+ sink := &recordedInput{}
+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}
+ s := m.NewSession()
+ t.Cleanup(s.Close)
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)
+ sink.authorize = func() error {
+ // Closing/replacing the share must remain possible while an OS dialog is open.
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)
+ return nil
+ }
+ if setTestPolicy(s, "room", "") == nil || s.State().Mode != "off" {
+ t.Fatal("late OS permission enabled input on a replacement source")
+ }
+ sink.authorize = func() error { return setTestPolicy(s, "off", "") }
+ if setTestPolicy(s, "room", "") == nil || s.State().Mode != "off" {
+ t.Fatal("late OS permission undid Host revocation")
+ }
+}
+
+func TestPreparedPolicyFollowsTheCommittedSourceAndHostIntent(t *testing.T) {
+ for _, action := range []string{"complete", "off-before-work", "off-during-prepare", "pause-and-resume", "replace-source"} {
+ t.Run(action, func(t *testing.T) {
+ sink := &recordedInput{}
+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}
+ s := m.NewSession()
+ t.Cleanup(s.Close)
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)
+ change, err := s.BeginPolicy(t.Context(), "room", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer change.Close()
+ if action == "off-before-work" {
+ if err := setTestPolicy(s, "off", ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Portal capture replacement must retire input while preserving only
+ // the same current Host intent through its own two source bindings.
+ change.SetTarget(nativecapture.CaptureTarget{}, nil)
+ switch action {
+ case "off-during-prepare":
+ if err := setTestPolicy(s, "off", ""); err != nil {
+ t.Fatal(err)
+ }
+ case "pause-and-resume":
+ s.Pause(true)
+ s.Pause(false)
+ case "replace-source":
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)
+ }
+ installed := nativecapture.CaptureTarget{Kind: "display", SourceID: "3"}
+ change.SetTarget(installed, nil)
+ cancelled := action != "complete"
+ if (change.Context().Err() != nil) != cancelled {
+ t.Fatal("preparation cancellation did not follow the Host intent")
+ }
+ if (change.Apply() != nil) != cancelled {
+ t.Fatal("late preparation changed a retired permission")
+ }
+ expected := "room"
+ if cancelled {
+ expected = "off"
+ }
+ if s.State().Mode != expected || s.target != installed {
+ t.Fatal("policy or actual source binding diverged after preparation")
+ }
+ if err := setTestPolicy(s, "ask", ""); err != nil {
+ t.Fatalf("new authorization could not use the committed source: %v", err)
+ }
+ })
+ }
+}
+
+func (s *recordedInput) Target(nativecapture.CaptureTarget, *nativecapture.Stream) (bounds, bool, error) {
+ return s.geometry, s.focused, nil
+}
+
+func (s *recordedInput) Apply(target bounds, event inputEvent) error {
+ s.target = target
+ s.events <- event
+ return nil
+}
+func (s *recordedInput) Reset() error { s.resets <- struct{}{}; return nil }
+
+func TestCommittedMultilineText(t *testing.T) {
+ sink := &recordedInput{events: make(chan inputEvent, 16), resets: make(chan struct{}, 8)}
+ longLine := strings.Repeat("\\\"", maxTextBytes/2)
+ for _, text := range []string{longLine, "if (ready) {\r\n\tprint(\"中文 😀\");\n}"} {
+ if err := applyText(sink, bounds{}, text); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := []inputEvent{
+ {Type: "text", Text: longLine},
+ {Type: "text", Text: "if (ready) {"},
+ {Type: "key", Code: "Enter", Down: true}, {Type: "key", Code: "Enter"},
+ {Type: "key", Code: "Tab", Down: true}, {Type: "key", Code: "Tab"},
+ {Type: "text", Text: "print(\"中文 😀\");"},
+ {Type: "key", Code: "Enter", Down: true}, {Type: "key", Code: "Enter"},
+ {Type: "text", Text: "}"},
+ }
+ if len(sink.events) != len(want) {
+ t.Fatalf("input events: %d, want %d", len(sink.events), len(want))
+ }
+ for _, event := range want {
+ if actual := <-sink.events; actual != event {
+ t.Fatalf("input: %+v, want %+v", actual, event)
+ }
+ }
+ for _, text := range []string{"", strings.Repeat("x", maxTextBytes+1), "a\x00b", "a\x7fb", string([]byte{0xff})} {
+ if err := applyText(sink, bounds{}, text); err == nil {
+ t.Fatal("invalid text accepted")
+ }
+ }
+ if len(sink.events) != 0 || len(sink.resets) != 2 {
+ t.Fatal("invalid text applied partial input or reset held keys")
+ }
+}
+
+// Exercise the consent/retirement owner over real SCTP channels. No OS input
+// is injected by this test; the platform acceptance uses a dedicated window.
+func TestAttendedGrantLifecycle(t *testing.T) {
+ sink := &recordedInput{events: make(chan inputEvent, 20), resets: make(chan struct{}, 20), geometry: bounds{width: 1920, height: 1080}, focused: true}
+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}
+ s := m.NewSession()
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)
+ if err := setTestPolicy(s, "ask", ""); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(m.Close)
+ host, err := webrtc.NewPeerConnection(webrtc.Configuration{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = host.Close() })
+ viewer, err := webrtc.NewPeerConnection(webrtc.Configuration{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = viewer.Close() })
+ channels := make(chan *webrtc.DataChannel, 2)
+ type observedState struct{ peer, state string }
+ states := make(chan observedState, 128)
+ bindings := map[string]protocol.RemoteInputPeer{}
+ ciphers := map[string]*inputCipher{}
+ for _, name := range []string{"first", "second"} {
+ id, key := make([]byte, 16), make([]byte, 32)
+ _, _ = rand.Read(id)
+ _, _ = rand.Read(key)
+ bindings[name] = protocol.RemoteInputPeer{PeerID: name + "-viewer", EndpointID: hex.EncodeToString(id), Secret: hex.EncodeToString(key)}
+ ciphers[name], _ = newInputCipher(bindings[name].Secret)
+ }
+ if err := s.SetPeers([]protocol.RemoteInputPeer{bindings["first"], bindings["second"]}); err != nil {
+ t.Fatal(err)
+ }
+ viewer.OnDataChannel(func(c *webrtc.DataChannel) {
+ c.OnMessage(func(message webrtc.DataChannelMessage) {
+ var packet inputroute.Packet
+ if json.Unmarshal(message.Data, &packet) != nil || packet.ID != bindings[c.Label()].EndpointID {
+ return
+ }
+ bytes, err := base64.StdEncoding.DecodeString(packet.Data)
+ if err != nil || len(bytes) < 36 {
+ return
+ }
+ plain, err := ciphers[c.Label()].aead.Open(nil, bytes[8:20], bytes[20:], inputAAD(1, bytes[:8], packet.Epoch))
+ if err != nil {
+ return
+ }
+ var value struct {
+ State string `json:"state"`
+ }
+ if json.Unmarshal(plain, &value) == nil {
+ states <- observedState{c.Label(), value.State}
+ }
+ })
+ c.OnOpen(func() { channels <- c })
+ })
+ for _, id := range []string{"first", "second"} {
+ c, err := host.CreateDataChannel(id, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.Attach(id, c)
+ }
+ offer, err := host.CreateOffer(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gathered := webrtc.GatheringCompletePromise(host)
+ if err = host.SetLocalDescription(offer); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-gathered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("offer gathering timed out")
+ }
+ if err = viewer.SetRemoteDescription(*host.LocalDescription()); err != nil {
+ t.Fatal(err)
+ }
+ answer, err := viewer.CreateAnswer(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gathered = webrtc.GatheringCompletePromise(viewer)
+ if err = viewer.SetLocalDescription(answer); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-gathered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("answer gathering timed out")
+ }
+ if err = host.SetRemoteDescription(*viewer.LocalDescription()); err != nil {
+ t.Fatal(err)
+ }
+ peers := map[string]*webrtc.DataChannel{}
+ for range 2 {
+ select {
+ case c := <-channels:
+ peers[c.Label()] = c
+ case <-time.After(5 * time.Second):
+ t.Fatal("channel did not open")
+ }
+ }
+ wait := func(check func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(deadline) {
+ m.mu.Lock()
+ ok := check()
+ m.mu.Unlock()
+ if ok {
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ t.Fatal("grant state did not settle")
+ }
+ request := func(peer string) *connection {
+ t.Helper()
+ intent := make([]byte, 16)
+ _, _ = rand.Read(intent)
+ cipher := ciphers[peer]
+ cipher.sent++
+ header := make([]byte, 20)
+ binary.BigEndian.PutUint64(header, cipher.sent)
+ _, _ = rand.Read(header[8:])
+ plain := []byte(`{"type":"request","intent":"` + hex.EncodeToString(intent) + `"}`)
+ epoch := bindings[peer].EndpointID
+ data := cipher.aead.Seal(header, header[8:], plain, inputAAD(0, header[:8], epoch))
+ packet, _ := json.Marshal(inputroute.Packet{ID: bindings[peer].EndpointID, Epoch: epoch, Data: base64.StdEncoding.EncodeToString(data)})
+ if err := peers[peer].SendText(string(packet)); err != nil {
+ t.Fatal(err)
+ }
+ var found *connection
+ wait(func() bool {
+ for _, c := range m.connections {
+ if c.edgeID == peer && c.requested {
+ found = c
+ return true
+ }
+ }
+ return false
+ })
+ return found
+ }
+ decide := func(c *connection, allow bool) string {
+ t.Helper()
+ if err := s.Decide(c.requestID, allow); err != nil {
+ t.Fatal(err)
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return c.grant
+ }
+ key := func(c *connection, grant string) {
+ m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"key","code":"KeyA","down":true,"grant":"` + grant + `"}`)}, c.epoch)
+ }
+ <-s.Changes() // Drain display setup; the next notification must be a request.
+ first := request("first")
+ other := m.NewSession()
+ other.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)
+ if err := other.SetPeers([]protocol.RemoteInputPeer{bindings["first"]}); err != nil {
+ t.Fatal("endpoint identity leaked across independent rooms", err)
+ }
+ if len(other.State().Requests) != 0 || other.Decide(first.requestID, true) == nil || other.Decide(first.requestID, false) == nil {
+ t.Fatal("another Host session can view or decide this share's request")
+ }
+ select {
+ case <-s.Changes():
+ views := s.State().Requests
+ if len(views) != 1 || views[0].PeerID != "first-viewer" || views[0].State != "pending" {
+ t.Fatal("request not reflected in its Host snapshot")
+ }
+ default:
+ t.Fatal("request did not notify its Host")
+ }
+ key(first, "")
+ if len(sink.events) != 0 {
+ t.Fatal("unapproved input accepted")
+ }
+ grant := decide(first, true)
+ if s.State().Requests[0].State != "active" {
+ t.Fatal("approval not reflected in Host snapshot")
+ }
+ if grant == "" {
+ t.Fatal("missing grant")
+ }
+ key(first, grant)
+ if len(sink.events) != 1 {
+ t.Fatal("approved input missing")
+ }
+ second := request("second")
+ grant2 := decide(second, true)
+ key(first, grant)
+ if len(sink.events) != 1 || len(sink.resets) != 1 {
+ t.Fatal("takeover did not retire old input")
+ }
+ key(second, grant2)
+ s.Pause(true)
+ key(second, grant2)
+ if len(sink.events) != 2 || len(sink.resets) != 2 {
+ t.Fatal("pause did not release input")
+ }
+ // Wait for the paused status before resuming; a ready message from the
+ // initial connection must not stand in for the actual resume notification.
+ stateDeadline := time.After(3 * time.Second)
+ waitState := func(want string) {
+ t.Helper()
+ for {
+ select {
+ case state := <-states:
+ if state.peer == "second" && state.state == want {
+ return
+ }
+ case <-stateDeadline:
+ t.Fatalf("missing viewer state %q", want)
+ }
+ }
+ }
+ waitState("unavailable")
+ s.Pause(false)
+ waitState("ready")
+ second = request("second")
+ grant2 = decide(second, true)
+ s.RevokeEdge("second")
+ key(second, grant2)
+ if len(sink.events) != 2 || len(sink.resets) != 3 {
+ t.Fatal("disconnect kept a grant")
+ }
+ // ICE may recover on the same channel. It must accept a fresh request,
+ // without reviving the old grant or a pending approval from before loss.
+ second = request("second")
+ staleRequest := second.requestID
+ s.RevokeEdge("second")
+ if s.Decide(staleRequest, true) == nil || len(s.State().Requests) != 0 {
+ t.Fatal("transport loss kept a pending approval")
+ }
+ second = request("second")
+ key(second, grant2)
+ if len(sink.events) != 2 {
+ t.Fatal("new request restored the disconnected grant")
+ }
+ decide(second, false)
+ first = request("first")
+ grant = decide(first, true)
+ m.Revoke()
+ key(first, grant)
+ if len(sink.events) != 2 || len(sink.resets) != 4 {
+ t.Fatal("local stop kept a grant")
+ }
+ first = request("first")
+ grant = decide(first, true)
+ s.SetTarget(nativecapture.CaptureTarget{}, nil)
+ key(first, grant)
+ if len(sink.events) != 2 || len(sink.resets) != 5 || s.available() {
+ t.Fatal("source replacement kept input authority")
+ }
+ nextDisplay := bounds{left: 1920, width: 1280, height: 720}
+ sink.geometry = nextDisplay
+ s.SetTarget(nativecapture.CaptureTarget{Kind: "window", SourceID: "3"}, nil)
+ if err := setTestPolicy(s, "ask", ""); err != nil {
+ t.Fatal(err)
+ }
+ first = request("first")
+ oldRequest, oldIntent := first.requestID, first.intent
+ m.receive(first, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"release","intent":"` + oldIntent + `"}`)}, first.epoch)
+ first = request("first")
+ if s.Decide(oldRequest, true) == nil {
+ t.Fatal("late approval authorized a replacement request")
+ }
+ nextGrant := decide(first, true)
+ m.receive(first, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"release","intent":"` + oldIntent + `"}`)}, first.epoch)
+ key(first, grant)
+ key(first, nextGrant)
+ if len(sink.events) != 3 || nextGrant == grant || sink.target != nextDisplay {
+ t.Fatal("replacement did not require fresh approval on the existing channel")
+ }
+ // A held key must be released when the Host leaves the shared window,
+ // even when the Viewer sends nothing. Focus recovery retains the grant.
+ m.mu.Lock()
+ sink.focused = false
+ m.refreshActive()
+ m.refreshActive()
+ m.mu.Unlock()
+ key(first, nextGrant)
+ if !first.suspended || s.State().Requests[0].State != "suspended" || len(sink.events) != 3 || len(sink.resets) != 6 {
+ t.Fatal("window focus loss did not suspend and release held input once")
+ }
+ sink.focused = true
+ sink.geometry = bounds{left: 100, top: 200, width: 640, height: 480}
+ key(first, nextGrant)
+ if first.suspended || len(sink.events) != 4 || sink.target != sink.geometry {
+ t.Fatal("window movement/focus recovery did not use the current target")
+ }
+ s.Close()
+ key(first, nextGrant)
+ if len(sink.events) != 4 || len(sink.resets) != 7 || len(s.State().Requests) != 0 || s.Decide(first.requestID, true) == nil {
+ t.Fatal("source retirement kept a grant")
+ }
+}
diff --git a/internal/app/remoteinput/platform_darwin.go b/internal/app/remoteinput/platform_darwin.go
new file mode 100644
index 00000000..523aa86a
--- /dev/null
+++ b/internal/app/remoteinput/platform_darwin.go
@@ -0,0 +1,226 @@
+//go:build darwin && cgo
+
+package remoteinput
+
+/*
+#cgo LDFLAGS: -framework ApplicationServices -framework AppKit
+#include "platform_darwin.h"
+*/
+import "C"
+
+import (
+ "context"
+ "errors"
+ "strconv"
+ "time"
+ "unicode/utf16"
+ "unsafe"
+
+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+)
+
+type macSink struct {
+ source C.CGEventSourceRef
+ keys map[uint16]bool
+ buttons map[int]bool
+ clicks [5]C.PiikInputClick
+ caps bool
+}
+
+func newPlatformSink(bool) (inputSink, error) {
+ source := C.CGEventSourceCreate(C.kCGEventSourceStatePrivate)
+ if source == 0 {
+ return nil, errors.New("macOS input is unavailable")
+ }
+ return &macSink{source: source, keys: map[uint16]bool{}, buttons: map[int]bool{},
+ caps: C.CGEventSourceFlagsState(C.kCGEventSourceStateCombinedSessionState)&C.kCGEventFlagMaskAlphaShift != 0}, nil
+}
+
+func (*macSink) Authorize() error {
+ if !bool(C.CGPreflightPostEventAccess()) && !bool(C.CGRequestPostEventAccess()) {
+ return errors.New("remote input requires macOS Accessibility permission")
+ }
+ return nil
+}
+
+func (*macSink) Target(target nativecapture.CaptureTarget, _ *nativecapture.Stream) (bounds, bool, error) {
+ if !bool(C.CGPreflightPostEventAccess()) {
+ return bounds{}, false, errors.New("macOS input permission was revoked")
+ }
+ id, err := strconv.ParseUint(target.SourceID, 10, 32)
+ if err != nil || id == 0 || (target.Kind != "display" && target.Kind != "window") {
+ return bounds{}, false, errors.New("shared source is unavailable")
+ }
+ created, _ := strconv.ParseUint(target.CreationTime, 10, 64)
+ var b C.PiikInputBounds
+ if !bool(C.piik_input_target(C.bool(target.Kind == "window"), C.uint32_t(id), C.uint32_t(target.PID), C.uint64_t(created), &b)) {
+ return bounds{}, false, errors.New("shared source is unavailable")
+ }
+ return bounds{int32(b.left), int32(b.top), int32(b.width), int32(b.height)}, bool(b.focused), nil
+}
+
+func (s *macSink) flags() C.uint64_t {
+ var flags uint64
+ if s.caps {
+ flags |= 1 << 16
+ }
+ for key := range s.keys {
+ switch key {
+ case 56, 60:
+ flags |= 1 << 17
+ case 59, 62:
+ flags |= 1 << 18
+ case 58, 61:
+ flags |= 1 << 19
+ case 54, 55:
+ flags |= 1 << 20
+ }
+ }
+ return C.uint64_t(flags)
+}
+
+func (s *macSink) Apply(b bounds, e inputEvent) error {
+ ok := true
+ switch e.Type {
+ case "move", "relative":
+ x, y := float64(b.left)+e.X*float64(b.width-1), float64(b.top)+e.Y*float64(b.height-1)
+ if e.Type == "relative" {
+ if e.DX < -32767 || e.DX > 32767 || e.DY < -32767 || e.DY > 32767 {
+ return errors.New("invalid pointer delta")
+ }
+ x, y = float64(e.DX), float64(e.DY)
+ } else if e.X < 0 || e.X > 1 || e.Y < 0 || e.Y > 1 {
+ return errors.New("invalid pointer position")
+ }
+ drag := -1
+ for button := 0; button < 5; button++ {
+ if s.buttons[button] {
+ drag = button
+ break
+ }
+ }
+ ok = bool(C.piik_input_pointer(s.source, C.double(x), C.double(y), -1, false, C.int(drag), C.bool(e.Type == "relative"), s.flags(), nil))
+ case "button":
+ if e.Button < 0 || e.Button > 4 {
+ return errors.New("invalid pointer button")
+ }
+ button := [...]int{0, 2, 1, 3, 4}[e.Button]
+ if !e.Down && !s.buttons[button] {
+ return nil
+ }
+ ok = bool(C.piik_input_pointer(s.source, 0, 0, C.int(button), C.bool(e.Down), -1, false, s.flags(), &s.clicks[button]))
+ if ok {
+ if e.Down {
+ s.buttons[button] = true
+ } else {
+ delete(s.buttons, button)
+ }
+ }
+ case "wheel":
+ if e.Delta < -1200 || e.Delta > 1200 {
+ return errors.New("invalid scroll delta")
+ }
+ ok = bool(C.piik_input_scroll(s.source, C.int32_t(e.Delta), s.flags()))
+ case "key":
+ code, known := macKeyCodes[e.Code]
+ if !known {
+ return nil
+ }
+ held := s.keys[code]
+ if !e.Down && !held {
+ return nil
+ }
+ caps := s.caps
+ if code == 57 && e.Down && !held {
+ s.caps = !s.caps
+ }
+ if e.Down {
+ s.keys[code] = true
+ } else {
+ delete(s.keys, code)
+ }
+ ok = bool(C.piik_input_key(s.source, C.uint16_t(code), C.bool(e.Down), s.flags(), C.bool(held && e.Down)))
+ if !ok {
+ s.caps = caps
+ if held {
+ s.keys[code] = true
+ } else {
+ delete(s.keys, code)
+ }
+ }
+ case "text":
+ text := utf16.Encode([]rune(e.Text))
+ ok = bool(C.piik_input_text(s.source, (*C.uint16_t)(unsafe.Pointer(&text[0])), C.size_t(len(text))))
+ default:
+ return errors.New("unsupported input")
+ }
+ if !ok {
+ return errors.New("macOS could not create the input event")
+ }
+ return nil
+}
+
+func (s *macSink) Reset() error {
+ var result error
+ for code := range s.keys {
+ delete(s.keys, code)
+ if !bool(C.piik_input_key(s.source, C.uint16_t(code), false, s.flags(), false)) {
+ s.keys[code] = true
+ result = errors.New("macOS could not release held input")
+ }
+ }
+ for button := range s.buttons {
+ if bool(C.piik_input_pointer(s.source, 0, 0, C.int(button), false, -1, false, s.flags(), &s.clicks[button])) {
+ delete(s.buttons, button)
+ } else {
+ result = errors.New("macOS could not release held input")
+ }
+ }
+ s.clicks = [5]C.PiikInputClick{}
+ return result
+}
+
+func (s *macSink) Close() error {
+ _ = s.Reset()
+ C.CFRelease(C.CFTypeRef(s.source))
+ return nil
+}
+
+func watchStopShortcut(ctx context.Context, stop func()) error {
+ go func() {
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ held := false
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ pressed := bool(C.piik_input_stop_pressed())
+ if pressed && !held {
+ stop()
+ }
+ held = pressed
+ }
+ }
+ }()
+ return nil
+}
+
+// Physical KeyboardEvent.code -> macOS virtual key, independent of text/IME.
+var macKeyCodes = map[string]uint16{
+ "KeyA": 0, "KeyS": 1, "KeyD": 2, "KeyF": 3, "KeyH": 4, "KeyG": 5, "KeyZ": 6, "KeyX": 7, "KeyC": 8, "KeyV": 9,
+ "IntlBackslash": 10, "KeyB": 11, "KeyQ": 12, "KeyW": 13, "KeyE": 14, "KeyR": 15, "KeyY": 16, "KeyT": 17,
+ "Digit1": 18, "Digit2": 19, "Digit3": 20, "Digit4": 21, "Digit6": 22, "Digit5": 23, "Equal": 24, "Digit9": 25,
+ "Digit7": 26, "Minus": 27, "Digit8": 28, "Digit0": 29, "BracketRight": 30, "KeyO": 31, "KeyU": 32, "BracketLeft": 33,
+ "KeyI": 34, "KeyP": 35, "Enter": 36, "KeyL": 37, "KeyJ": 38, "Quote": 39, "KeyK": 40, "Semicolon": 41, "Backslash": 42,
+ "Comma": 43, "Slash": 44, "KeyN": 45, "KeyM": 46, "Period": 47, "Tab": 48, "Space": 49, "Backquote": 50, "Backspace": 51,
+ "Escape": 53, "MetaRight": 54, "MetaLeft": 55, "ShiftLeft": 56, "CapsLock": 57, "AltLeft": 58, "ControlLeft": 59,
+ "ShiftRight": 60, "AltRight": 61, "ControlRight": 62, "NumpadDecimal": 65, "NumpadMultiply": 67, "NumpadAdd": 69,
+ "NumLock": 71, "NumpadDivide": 75, "NumpadEnter": 76, "NumpadSubtract": 78, "NumpadEqual": 81, "Numpad0": 82,
+ "Numpad1": 83, "Numpad2": 84, "Numpad3": 85, "Numpad4": 86, "Numpad5": 87, "Numpad6": 88, "Numpad7": 89,
+ "Numpad8": 91, "Numpad9": 92, "F5": 96, "F6": 97, "F7": 98, "F3": 99, "F8": 100, "F9": 101, "F11": 103,
+ "F13": 105, "F16": 106, "F14": 107, "F10": 109, "F12": 111, "F15": 113, "Insert": 114, "Home": 115, "PageUp": 116,
+ "Delete": 117, "F4": 118, "End": 119, "F2": 120, "PageDown": 121, "F1": 122, "ArrowLeft": 123, "ArrowRight": 124,
+ "ArrowDown": 125, "ArrowUp": 126, "F17": 64, "F18": 79, "F19": 80, "F20": 90,
+}
diff --git a/internal/app/remoteinput/platform_darwin.h b/internal/app/remoteinput/platform_darwin.h
new file mode 100644
index 00000000..95e4edec
--- /dev/null
+++ b/internal/app/remoteinput/platform_darwin.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include <CoreGraphics/CoreGraphics.h>
+#include <stdint.h>
+
+// Geometry is in Quartz display points, not Retina capture pixels.
+typedef struct {
+ int32_t left, top, width, height;
+ bool focused;
+} PiikInputBounds;
+
+typedef struct {
+ double time, x, y;
+ int64_t count;
+} PiikInputClick;
+
+bool piik_input_target(bool window, uint32_t id, uint32_t pid, uint64_t created,
+ PiikInputBounds *bounds);
+bool piik_input_key(CGEventSourceRef source, uint16_t code, bool down,
+ uint64_t flags, bool repeat);
+bool piik_input_pointer(CGEventSourceRef source, double x, double y,
+ int button, bool down, int drag, bool relative,
+ uint64_t flags, PiikInputClick *click);
+bool piik_input_scroll(CGEventSourceRef source, int32_t delta, uint64_t flags);
+bool piik_input_text(CGEventSourceRef source, const uint16_t *text, size_t length);
+bool piik_input_stop_pressed(void);
diff --git a/internal/app/remoteinput/platform_darwin.m b/internal/app/remoteinput/platform_darwin.m
new file mode 100644
index 00000000..69e23664
--- /dev/null
+++ b/internal/app/remoteinput/platform_darwin.m
@@ -0,0 +1,164 @@
+//go:build darwin && cgo
+
+#include "platform_darwin.h"
+#include <ApplicationServices/ApplicationServices.h>
+#import <AppKit/NSEvent.h>
+#include <libproc.h>
+#include <math.h>
+#include <string.h>
+#include <time.h>
+
+static bool number(CFDictionaryRef value, CFStringRef key, int64_t *out) {
+ CFTypeRef field = CFDictionaryGetValue(value, key);
+ return field && CFGetTypeID(field) == CFNumberGetTypeID() &&
+ CFNumberGetValue(field, kCFNumberSInt64Type, out);
+}
+
+static bool focused_window(uint32_t pid, CGRect rect) {
+ AXUIElementRef system = AXUIElementCreateSystemWide();
+ if (!system) return false;
+ AXUIElementSetMessagingTimeout(system, 0.1f);
+ CFTypeRef app = NULL, window = NULL, position = NULL, size = NULL;
+ pid_t owner = 0;
+ CGPoint origin = CGPointZero;
+ CGSize extent = CGSizeZero;
+ bool focused = AXUIElementCopyAttributeValue(system, kAXFocusedApplicationAttribute, &app) == kAXErrorSuccess &&
+ CFGetTypeID(app) == AXUIElementGetTypeID() &&
+ AXUIElementGetPid((AXUIElementRef)app, &owner) == kAXErrorSuccess && owner == pid &&
+ AXUIElementCopyAttributeValue((AXUIElementRef)app, kAXFocusedWindowAttribute, &window) == kAXErrorSuccess &&
+ CFGetTypeID(window) == AXUIElementGetTypeID() &&
+ AXUIElementCopyAttributeValue((AXUIElementRef)window, kAXPositionAttribute, &position) == kAXErrorSuccess &&
+ CFGetTypeID(position) == AXValueGetTypeID() && AXValueGetValue(position, kAXValueCGPointType, &origin) &&
+ AXUIElementCopyAttributeValue((AXUIElementRef)window, kAXSizeAttribute, &size) == kAXErrorSuccess &&
+ CFGetTypeID(size) == AXValueGetTypeID() && AXValueGetValue(size, kAXValueCGSizeType, &extent) &&
+ CGRectEqualToRect(rect, (CGRect){origin, extent});
+ if (size) CFRelease(size);
+ if (position) CFRelease(position);
+ if (window) CFRelease(window);
+ if (app) CFRelease(app);
+ CFRelease(system);
+ return focused;
+}
+
+bool piik_input_target(bool window, uint32_t id, uint32_t pid, uint64_t created,
+ PiikInputBounds *bounds) {
+ CGRect rect = CGRectNull;
+ bool focused = true;
+ if (!window) {
+ if (!CGDisplayIsActive(id)) return false;
+ rect = CGDisplayBounds(id);
+ } else {
+ struct proc_bsdinfo process = {0};
+ if (!pid || proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &process, sizeof(process)) != sizeof(process) ||
+ process.pbi_start_tvsec * 1000000ULL + process.pbi_start_tvusec != created) return false;
+ CFArrayRef windows = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID);
+ if (!windows) return false;
+ for (CFIndex index = 0; index < CFArrayGetCount(windows); ++index) {
+ CFDictionaryRef entry = CFArrayGetValueAtIndex(windows, index);
+ int64_t current = 0, owner = 0;
+ if (!number(entry, kCGWindowNumber, &current)) continue;
+ if (current != id || !number(entry, kCGWindowOwnerPID, &owner) || owner != pid) continue;
+ CFDictionaryRef geometry = CFDictionaryGetValue(entry, kCGWindowBounds);
+ if (geometry) CGRectMakeWithDictionaryRepresentation(geometry, &rect);
+ }
+ // Public AX has no CGWindowID. Match the actual key window's geometry only
+ // when it identifies exactly one window of this process; z-order is not focus.
+ unsigned matches = 0;
+ for (CFIndex index = 0; index < CFArrayGetCount(windows); ++index) {
+ CFDictionaryRef entry = CFArrayGetValueAtIndex(windows, index);
+ int64_t owner = 0;
+ CGRect candidate = CGRectNull;
+ CFDictionaryRef geometry = CFDictionaryGetValue(entry, kCGWindowBounds);
+ if (number(entry, kCGWindowOwnerPID, &owner) && owner == pid && geometry &&
+ CGRectMakeWithDictionaryRepresentation(geometry, &candidate) && CGRectEqualToRect(candidate, rect)) ++matches;
+ }
+ focused = matches == 1 && focused_window(pid, rect);
+ CFRelease(windows);
+ }
+ if (CGRectIsNull(rect) || CGRectIsEmpty(rect)) return false;
+ *bounds = (PiikInputBounds){rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, focused};
+ return true;
+}
+
+static bool post(CGEventRef event, uint64_t flags) {
+ if (!event) return false;
+ CGEventSetFlags(event, flags);
+ CGEventPost(kCGHIDEventTap, event);
+ CFRelease(event);
+ return true;
+}
+
+bool piik_input_key(CGEventSourceRef source, uint16_t code, bool down,
+ uint64_t flags, bool repeat) {
+ CGEventRef event = CGEventCreateKeyboardEvent(source, code, down);
+ if (event) {
+ if (code >= 54 && code <= 62) CGEventSetType(event, kCGEventFlagsChanged);
+ else if (repeat) CGEventSetIntegerValueField(event, kCGKeyboardEventAutorepeat, 1);
+ }
+ return post(event, flags);
+}
+
+bool piik_input_pointer(CGEventSourceRef source, double x, double y,
+ int button, bool down, int drag, bool relative,
+ uint64_t flags, PiikInputClick *click) {
+ CGEventRef current = CGEventCreate(NULL);
+ if (!current) return false;
+ CGPoint point = CGEventGetLocation(current);
+ CFRelease(current);
+ CGEventType type;
+ if (button < 0) {
+ point = relative ? CGPointMake(point.x + x, point.y + y) : CGPointMake(x, y);
+ type = drag < 0 ? kCGEventMouseMoved : drag == 0 ? kCGEventLeftMouseDragged :
+ drag == 1 ? kCGEventRightMouseDragged : kCGEventOtherMouseDragged;
+ button = drag < 0 ? 0 : drag;
+ } else {
+ type = button == 0 ? (down ? kCGEventLeftMouseDown : kCGEventLeftMouseUp) :
+ button == 1 ? (down ? kCGEventRightMouseDown : kCGEventRightMouseUp) :
+ (down ? kCGEventOtherMouseDown : kCGEventOtherMouseUp);
+ }
+ CGEventRef event = CGEventCreateMouseEvent(source, type, point, button);
+ if (event && click) {
+ if (down) {
+ struct timespec clock;
+ clock_gettime(CLOCK_MONOTONIC, &clock);
+ double now = clock.tv_sec + clock.tv_nsec / 1e9;
+ // Quartz requires an explicit click count. Use the Host's double-click
+ // interval and keep distinct positions/buttons from becoming double-clicks.
+ click->count = now - click->time <= [NSEvent doubleClickInterval] &&
+ hypot(point.x - click->x, point.y - click->y) <= 4 ? click->count + 1 : 1;
+ click->time = now; click->x = point.x; click->y = point.y;
+ }
+ CGEventSetIntegerValueField(event, kCGMouseEventClickState, click->count);
+ }
+ if (event && relative) {
+ CGEventSetIntegerValueField(event, kCGMouseEventDeltaX, (int64_t)x);
+ CGEventSetIntegerValueField(event, kCGMouseEventDeltaY, (int64_t)y);
+ }
+ return post(event, flags);
+}
+
+bool piik_input_scroll(CGEventSourceRef source, int32_t delta, uint64_t flags) {
+ // The shared input session already normalizes wheel deltas to positive up.
+ return post(CGEventCreateScrollWheelEvent(source, kCGScrollEventUnitPixel, 1, delta), flags);
+}
+
+bool piik_input_text(CGEventSourceRef source, const uint16_t *text, size_t length) {
+ CGEventRef down = CGEventCreateKeyboardEvent(source, 0, true);
+ CGEventRef up = CGEventCreateKeyboardEvent(source, 0, false);
+ if (!down || !up) {
+ if (down) CFRelease(down);
+ if (up) CFRelease(up);
+ return false;
+ }
+ CGEventKeyboardSetUnicodeString(down, length, text);
+ CGEventKeyboardSetUnicodeString(up, length, text);
+ return post(down, 0) && post(up, 0);
+}
+
+bool piik_input_stop_pressed(void) {
+ // Inspect only the local emergency chord; no event tap or key log.
+ CGEventSourceStateID state = kCGEventSourceStateHIDSystemState;
+ return (CGEventSourceKeyState(state, 59) || CGEventSourceKeyState(state, 62)) &&
+ (CGEventSourceKeyState(state, 58) || CGEventSourceKeyState(state, 61)) &&
+ CGEventSourceKeyState(state, 109); // Control + Option + F10
+}
diff --git a/internal/app/remoteinput/platform_linux.go b/internal/app/remoteinput/platform_linux.go
new file mode 100644
index 00000000..5b5328c6
--- /dev/null
+++ b/internal/app/remoteinput/platform_linux.go
@@ -0,0 +1,105 @@
+//go:build linux
+
+package remoteinput
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strconv"
+
+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+)
+
+type portalSink struct{ capture *nativecapture.Stream }
+
+func newPlatformSink(captureInput bool) (inputSink, error) {
+ if !captureInput {
+ return nil, nil
+ }
+ return &portalSink{}, nil
+}
+
+func (*portalSink) Authorize() error { return nil } // The capture owner obtains Portal consent.
+
+func (s *portalSink) Target(_ nativecapture.CaptureTarget, capture *nativecapture.Stream) (bounds, bool, error) {
+ if !capture.RemoteInput() {
+ return bounds{}, false, errors.New("shared screen input is unavailable")
+ }
+ s.capture = capture
+ return bounds{width: 1, height: 1}, true, nil // Portal maps normalized positions to logical screen coordinates.
+}
+
+func (s *portalSink) Apply(_ bounds, e inputEvent) error {
+ var command string
+ down := 0
+ if e.Down {
+ down = 1
+ }
+ switch e.Type {
+ case "move":
+ if e.X < 0 || e.X > 1 || e.Y < 0 || e.Y > 1 {
+ return errors.New("invalid pointer position")
+ }
+ command = fmt.Sprintf("M %.9f %.9f", e.X, e.Y)
+ case "relative":
+ if e.DX < -32767 || e.DX > 32767 || e.DY < -32767 || e.DY > 32767 {
+ return errors.New("invalid pointer delta")
+ }
+ command = fmt.Sprintf("R %d %d", e.DX, e.DY)
+ case "button":
+ if e.Button < 0 || e.Button > 4 {
+ return errors.New("invalid pointer button")
+ }
+ command = fmt.Sprintf("B %d %d", e.Button, down)
+ case "key":
+ code := evdevCode(e.Code)
+ if code == 0 {
+ return nil
+ }
+ command = fmt.Sprintf("K %d %d", code, down)
+ case "wheel":
+ if e.Delta < -1200 || e.Delta > 1200 {
+ return errors.New("invalid scroll delta")
+ }
+ command = fmt.Sprintf("W %d", e.Delta)
+ case "text":
+ for _, r := range e.Text {
+ if err := s.capture.SendRemoteInput(fmt.Sprintf("U %d", r)); err != nil {
+ return err
+ }
+ }
+ return nil
+ default:
+ return errors.New("unsupported input")
+ }
+ return s.capture.SendRemoteInput(command)
+}
+
+func (s *portalSink) Reset() error {
+ if s.capture == nil {
+ return nil
+ }
+ return s.capture.SendRemoteInput("Z")
+}
+
+// The compositor owns its global stop shortcut. The page's stop action/chord
+// remains available; we do not grab global keys or request a second permission.
+func watchStopShortcut(context.Context, func()) error { return nil }
+
+func evdevCode(code string) uint16 {
+ if scan := scanCodes[code]; scan > 0 && scan <= 0x58 {
+ return scan
+ }
+ if len(code) >= 3 && code[0] == 'F' {
+ if f, err := strconv.Atoi(code[1:]); err == nil && f >= 13 && f <= 24 {
+ return uint16(183 + f - 13)
+ }
+ }
+ return map[string]uint16{
+ "NumpadEnter": 96, "ControlRight": 97, "NumpadDivide": 98, "PrintScreen": 99, "AltRight": 100,
+ "Home": 102, "ArrowUp": 103, "PageUp": 104, "ArrowLeft": 105, "ArrowRight": 106, "End": 107,
+ "ArrowDown": 108, "PageDown": 109, "Insert": 110, "Delete": 111, "Pause": 119,
+ "MetaLeft": 125, "MetaRight": 126, "ContextMenu": 127,
+ }[code]
+}
diff --git a/internal/app/remoteinput/platform_stub.go b/internal/app/remoteinput/platform_stub.go
new file mode 100644
index 00000000..a6502b7d
--- /dev/null
+++ b/internal/app/remoteinput/platform_stub.go
@@ -0,0 +1,10 @@
+//go:build (!windows && !darwin && !linux) || (darwin && !cgo)
+
+package remoteinput
+
+import (
+ "context"
+)
+
+func newPlatformSink(bool) (inputSink, error) { return nil, nil }
+func watchStopShortcut(context.Context, func()) error { return nil }
diff --git a/internal/app/remoteinput/platform_windows.go b/internal/app/remoteinput/platform_windows.go
new file mode 100644
index 00000000..bb59595f
--- /dev/null
+++ b/internal/app/remoteinput/platform_windows.go
@@ -0,0 +1,228 @@
+//go:build windows
+
+package remoteinput
+
+import (
+ "context"
+ "errors"
+ "math"
+ "runtime"
+ "unicode/utf16"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+var user32 = windows.NewLazySystemDLL("user32.dll")
+var sendInput = user32.NewProc("SendInput")
+var metrics = user32.NewProc("GetSystemMetrics")
+
+type mouseInput struct {
+ X, Y int32
+ Data, Flags, Time uint32
+ Extra uintptr
+}
+type keyboardInput struct {
+ VK, Scan uint16
+ Flags, Time uint32
+ Extra uintptr
+}
+type winInput struct {
+ Kind uint32
+ Mouse mouseInput
+}
+type windowsSink struct {
+ keys map[uint16]bool
+ buttons map[int]bool
+}
+
+func newPlatformSink(bool) (inputSink, error) {
+ if err := sendInput.Find(); err != nil {
+ return nil, err
+ }
+ // The capture helper reports physical pixels. Match that coordinate space
+ // before reading monitor bounds in this Go process (including mixed DPI).
+ user32.NewProc("SetProcessDpiAwarenessContext").Call(^uintptr(3))
+ return &windowsSink{keys: map[uint16]bool{}, buttons: map[int]bool{}}, nil
+}
+
+func (*windowsSink) Authorize() error { return nil }
+
+func inject(inputs ...winInput) error {
+ n, _, _ := sendInput.Call(uintptr(len(inputs)), uintptr(unsafe.Pointer(&inputs[0])), unsafe.Sizeof(inputs[0]))
+ if n != uintptr(len(inputs)) {
+ return errors.New("Windows did not accept input")
+ }
+ return nil
+}
+
+func keyInput(scan uint16, down bool) winInput {
+ input := winInput{Kind: 1}
+ k := (*keyboardInput)(unsafe.Pointer(&input.Mouse))
+ k.Scan, k.Flags = scan&0xff, 8 // KEYEVENTF_SCANCODE: physical key, not text.
+ if !down {
+ k.Flags |= 2
+ }
+ if scan&0xff00 == 0xe000 {
+ k.Flags |= 1
+ }
+ return input
+}
+
+// Soft keyboards and IMEs supply committed text, not physical scan codes.
+// Send complete UTF-16 pairs through Windows' standard VK_PACKET path.
+func textInputs(text string) []winInput {
+ var inputs []winInput
+ for _, unit := range utf16.Encode([]rune(text)) {
+ for _, flags := range []uint32{4, 6} { // KEYEVENTF_UNICODE, then KEYUP.
+ input := winInput{Kind: 1}
+ k := (*keyboardInput)(unsafe.Pointer(&input.Mouse))
+ k.Scan, k.Flags = unit, flags
+ inputs = append(inputs, input)
+ }
+ }
+ return inputs
+}
+
+func buttonInput(button int, down bool) (winInput, error) {
+ flags := [...]uint32{2, 0x20, 8, 0x80, 0x80} // left, middle, right, X1, X2
+ if button < 0 || button >= len(flags) {
+ return winInput{}, errors.New("invalid button")
+ }
+ input := winInput{Mouse: mouseInput{Flags: flags[button]}}
+ if button >= 3 {
+ input.Mouse.Data = 1 << (button - 3)
+ }
+ if !down {
+ input.Mouse.Flags <<= 1
+ }
+ return input, nil
+}
+
+func (s *windowsSink) Apply(b bounds, e inputEvent) error {
+ switch e.Type {
+ case "move":
+ if math.IsNaN(e.X) || math.IsNaN(e.Y) || e.X < 0 || e.X > 1 || e.Y < 0 || e.Y > 1 {
+ return errors.New("invalid pointer")
+ }
+ x, _, _ := metrics.Call(76)
+ y, _, _ := metrics.Call(77)
+ w, _, _ := metrics.Call(78)
+ h, _, _ := metrics.Call(79)
+ if int32(w) < 2 || int32(h) < 2 {
+ return errors.New("desktop is unavailable")
+ }
+ px := float64(b.left) + e.X*float64(b.width-1) - float64(int32(x))
+ py := float64(b.top) + e.Y*float64(b.height-1) - float64(int32(y))
+ return inject(winInput{Mouse: mouseInput{X: int32(px * 65535 / float64(int32(w)-1)), Y: int32(py * 65535 / float64(int32(h)-1)), Flags: 0xc001}})
+ case "relative":
+ if e.DX < -32767 || e.DX > 32767 || e.DY < -32767 || e.DY > 32767 {
+ return errors.New("invalid relative pointer")
+ }
+ return inject(winInput{Mouse: mouseInput{X: e.DX, Y: e.DY, Flags: 1}})
+ case "button":
+ input, err := buttonInput(e.Button, e.Down)
+ if err != nil {
+ return err
+ }
+ if !e.Down && !s.buttons[e.Button] {
+ return nil
+ }
+ if err := inject(input); err != nil {
+ return err
+ }
+ if e.Down {
+ s.buttons[e.Button] = true
+ } else {
+ delete(s.buttons, e.Button)
+ }
+ case "wheel":
+ if e.Delta < -1200 || e.Delta > 1200 {
+ return errors.New("invalid wheel")
+ }
+ return inject(winInput{Mouse: mouseInput{Data: uint32(int32(e.Delta)), Flags: 0x800}})
+ case "key":
+ key := scanCodes[e.Code]
+ if key == 0 {
+ return nil
+ }
+ if !e.Down && !s.keys[key] {
+ return nil
+ }
+ if err := inject(keyInput(key, e.Down)); err != nil {
+ return err
+ }
+ if e.Down {
+ s.keys[key] = true
+ } else {
+ delete(s.keys, key)
+ }
+ case "text":
+ return inject(textInputs(e.Text)...)
+ default:
+ return errors.New("unsupported input")
+ }
+ return nil
+}
+
+func (s *windowsSink) Reset() error {
+ var result error
+ for key := range s.keys {
+ if err := inject(keyInput(key, false)); err != nil {
+ result = errors.Join(result, err)
+ } else {
+ delete(s.keys, key)
+ }
+ }
+ for button := range s.buttons {
+ result = errors.Join(result, s.Apply(bounds{}, inputEvent{Type: "button", Button: button}))
+ }
+ return result
+}
+
+// A native hotkey supplies local revocation even while a Browser has focus.
+// It observes this shortcut only; no keyboard hook or key recording is installed.
+func watchStopShortcut(ctx context.Context, stop func()) error {
+ ready := make(chan error, 1)
+ go func() {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ tid := windows.GetCurrentThreadId()
+ var msg struct {
+ Window uintptr
+ Message uint32
+ WParam uintptr
+ LParam uintptr
+ Time uint32
+ X, Y int32
+ Private uint32
+ }
+ user32.NewProc("PeekMessageW").Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, 0)
+ ok, _, _ := user32.NewProc("RegisterHotKey").Call(0, 1, 0x4003, 0x79) // Ctrl+Alt+F10; no repeat.
+ if ok == 0 {
+ ready <- errors.New("Ctrl+Alt+F10 is already in use")
+ return
+ }
+ defer user32.NewProc("UnregisterHotKey").Call(0, 1)
+ ready <- nil
+ done := make(chan struct{})
+ defer close(done)
+ go func() {
+ select {
+ case <-ctx.Done():
+ user32.NewProc("PostThreadMessageW").Call(uintptr(tid), 0x12, 0, 0)
+ case <-done:
+ }
+ }()
+ for {
+ n, _, _ := user32.NewProc("GetMessageW").Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
+ if int32(n) <= 0 {
+ return
+ }
+ if msg.Message == 0x312 {
+ stop()
+ }
+ }
+ }()
+ return <-ready
+}
diff --git a/internal/app/remoteinput/platform_windows_test.go b/internal/app/remoteinput/platform_windows_test.go
new file mode 100644
index 00000000..df426c7d
--- /dev/null
+++ b/internal/app/remoteinput/platform_windows_test.go
@@ -0,0 +1,43 @@
+//go:build windows
+
+package remoteinput
+
+import (
+ "testing"
+ "unsafe"
+)
+
+func TestCommittedTextPackets(t *testing.T) {
+ inputs := textInputs("A中😀")
+ units := []uint16{0x41, 0x4e2d, 0xd83d, 0xde00}
+ if len(inputs) != 2*len(units) {
+ t.Fatalf("text packets: %d", len(inputs))
+ }
+ for i, input := range inputs {
+ key := (*keyboardInput)(unsafe.Pointer(&input.Mouse))
+ if input.Kind != 1 || key.VK != 0 || key.Scan != units[i/2] || key.Flags != uint32(4+2*(i%2)) {
+ t.Fatalf("packet %d: %+v", i, key)
+ }
+ }
+}
+
+func TestMouseButtonPackets(t *testing.T) {
+ for button, flags := range []uint32{2, 0x20, 8, 0x80, 0x80} {
+ for _, down := range []bool{true, false} {
+ input, err := buttonInput(button, down)
+ wantFlags, wantData := flags, uint32(0)
+ if !down {
+ wantFlags <<= 1
+ }
+ if button >= 3 {
+ wantData = 1 << (button - 3)
+ }
+ if err != nil || input.Kind != 0 || input.Mouse.Flags != wantFlags || input.Mouse.Data != wantData {
+ t.Fatalf("button %d down=%v: %+v, %v", button, down, input, err)
+ }
+ }
+ }
+ if _, err := buttonInput(5, true); err == nil {
+ t.Fatal("unknown button accepted")
+ }
+}
diff --git a/internal/app/remoteinput/policy.go b/internal/app/remoteinput/policy.go
new file mode 100644
index 00000000..11104b65
--- /dev/null
+++ b/internal/app/remoteinput/policy.go
@@ -0,0 +1,128 @@
+package remoteinput
+
+import (
+ "context"
+ "crypto/sha256"
+ "crypto/subtle"
+ "errors"
+ "time"
+)
+
+func validatePolicy(mode, password string) error {
+ if mode != "off" && mode != "ask" && mode != "room" && mode != "password" ||
+ len(password) > 512 || (mode == "password") != (password != "") {
+ return errors.New("invalid remote input policy")
+ }
+ return nil
+}
+
+// PolicyChange owns one Host intent from dispatch through OS/capture preparation.
+// It never owns the lifetime of an installed capture stream.
+type PolicyChange struct {
+ session *Session
+ ctx context.Context
+ cancel context.CancelFunc
+ mode string
+ password [32]byte
+}
+
+func (s *Session) BeginPolicy(ctx context.Context, mode, password string) (*PolicyChange, error) {
+ if s == nil {
+ return nil, errors.New("remote input is unavailable")
+ }
+ if err := validatePolicy(mode, password); err != nil {
+ return nil, err
+ }
+ m := s.manager
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.closed || s.closed || ctx.Err() != nil || (mode != "off" && !s.available()) {
+ return nil, errors.New("remote input is unavailable")
+ }
+ s.cancelPolicy()
+ ctx, cancel := context.WithCancel(ctx)
+ change := &PolicyChange{session: s, ctx: ctx, cancel: cancel, mode: mode}
+ if mode == "password" {
+ change.password = sha256.Sum256([]byte(password))
+ }
+ s.policyChange = change
+ return change, nil
+}
+
+func (change *PolicyChange) Context() context.Context { return change.ctx }
+
+func (change *PolicyChange) Close() {
+ s := change.session
+ s.manager.mu.Lock()
+ defer s.manager.mu.Unlock()
+ if s.policyChange == change {
+ s.cancelPolicy()
+ }
+}
+
+func (change *PolicyChange) Apply() error {
+ s := change.session
+ m := s.manager
+ if err := change.ctx.Err(); err != nil {
+ return err
+ }
+ // OS input permission is requested only by the Host enabling control, never
+ // by App startup, capture discovery or a remote Viewer's request. The dialog
+ // must not hold the grant lock; recheck the source after it returns.
+ if change.mode != "off" {
+ if err := m.sink.Authorize(); err != nil {
+ return err
+ }
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.closed || s.closed || s.policyChange != change || change.ctx.Err() != nil || (change.mode != "off" && !s.available()) {
+ return errors.New("remote input is unavailable")
+ }
+ s.setPolicy(change.mode, change.password)
+ return nil
+}
+
+// Caller holds manager.mu. Cancellation invalidates preparation before it can
+// commit a newer permission, even if an OS dialog itself cannot be dismissed.
+func (s *Session) cancelPolicy() {
+ if s.policyChange != nil {
+ s.policyChange.cancel()
+ s.policyChange = nil
+ }
+}
+
+// Caller holds manager.mu. A policy change retires all previous requests and
+// grants, so an old approval cannot acquire the newly configured permission.
+func (s *Session) setPolicy(mode string, password [32]byte) {
+ s.cancelPolicy()
+ s.applyPolicy(mode, password)
+}
+
+func (s *Session) applyPolicy(mode string, password [32]byte) {
+ s.mode, s.password = mode, password
+ for _, c := range s.manager.connections {
+ if c.owner == s {
+ s.manager.revoke(c)
+ }
+ }
+ s.notify()
+}
+
+func (s *Session) authorize(password string) string {
+ if s.mode != "password" {
+ return ""
+ }
+ // One password attempt per second for this source, shared across endpoints
+ // and route changes. The short-lived verifier is never logged or persisted.
+ now := time.Now()
+ if now.Before(s.passwordRetry) {
+ return "retry"
+ }
+ s.passwordRetry = now.Add(time.Second)
+ digest := sha256.Sum256([]byte(password))
+ if len(password) > 512 || subtle.ConstantTimeCompare(digest[:], s.password[:]) != 1 {
+ return "password"
+ }
+ return ""
+}
diff --git a/internal/app/remoteinput/target_windows.go b/internal/app/remoteinput/target_windows.go
new file mode 100644
index 00000000..1983fb27
--- /dev/null
+++ b/internal/app/remoteinput/target_windows.go
@@ -0,0 +1,73 @@
+//go:build windows
+
+package remoteinput
+
+import (
+ "errors"
+ "strconv"
+ "unsafe"
+
+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
+ "golang.org/x/sys/windows"
+)
+
+var extendedFrameBounds = windows.NewLazySystemDLL("dwmapi.dll").NewProc("DwmGetWindowAttribute")
+
+type rect struct{ left, top, right, bottom int32 }
+
+func (s *windowsSink) Target(target nativecapture.CaptureTarget, _ *nativecapture.Stream) (bounds, bool, error) {
+ id, err := strconv.ParseUint(target.SourceID, 10, 64)
+ if err != nil || id == 0 {
+ return bounds{}, false, errors.New("shared source is unavailable")
+ }
+ var area rect
+ focused := true
+ switch target.Kind {
+ case "display":
+ info := struct {
+ size uint32
+ monitor, work rect
+ flags uint32
+ }{}
+ info.size = uint32(unsafe.Sizeof(info))
+ ok, _, _ := user32.NewProc("GetMonitorInfoW").Call(uintptr(id), uintptr(unsafe.Pointer(&info)))
+ if ok == 0 {
+ return bounds{}, false, errors.New("shared display is unavailable")
+ }
+ area = info.monitor
+ case "window":
+ var pid uint32
+ user32.NewProc("GetWindowThreadProcessId").Call(uintptr(id), uintptr(unsafe.Pointer(&pid)))
+ if pid == 0 || pid != target.PID {
+ return bounds{}, false, errors.New("shared window is unavailable")
+ }
+ // Match the capture target's process incarnation, not a recycled HWND/PID.
+ process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
+ if err != nil {
+ return bounds{}, false, err
+ }
+ var created, exited, kernel, user windows.Filetime
+ err = windows.GetProcessTimes(process, &created, &exited, &kernel, &user)
+ windows.CloseHandle(process)
+ creation, parseErr := strconv.ParseUint(target.CreationTime, 10, 64)
+ if err != nil || parseErr != nil || creation != uint64(created.HighDateTime)<<32|uint64(created.LowDateTime) {
+ return bounds{}, false, errors.New("shared window was replaced")
+ }
+ if hr, _, _ := extendedFrameBounds.Call(uintptr(id), 9, uintptr(unsafe.Pointer(&area)), unsafe.Sizeof(area)); int32(hr) < 0 {
+ ok, _, _ := user32.NewProc("GetWindowRect").Call(uintptr(id), uintptr(unsafe.Pointer(&area)))
+ if ok == 0 {
+ return bounds{}, false, errors.New("shared window geometry is unavailable")
+ }
+ }
+ foreground, _, _ := user32.NewProc("GetForegroundWindow").Call()
+ root, _, _ := user32.NewProc("GetAncestor").Call(foreground, 2) // GA_ROOT
+ minimized, _, _ := user32.NewProc("IsIconic").Call(uintptr(id))
+ focused = root == uintptr(id) && minimized == 0
+ default:
+ return bounds{}, false, errors.New("source cannot accept input")
+ }
+ if area.right <= area.left || area.bottom <= area.top {
+ return bounds{}, false, errors.New("shared source has no area")
+ }
+ return bounds{area.left, area.top, area.right - area.left, area.bottom - area.top}, focused, nil
+}
diff --git a/internal/app/remoteinput/text.go b/internal/app/remoteinput/text.go
new file mode 100644
index 00000000..a7033230
--- /dev/null
+++ b/internal/app/remoteinput/text.go
@@ -0,0 +1,49 @@
+package remoteinput
+
+import (
+ "errors"
+ "strings"
+ "unicode/utf8"
+)
+
+const maxTextBytes = 2048
+const maxInputBytes = maxTextBytes*2 + 256 // JSON escaping and grant fields.
+
+// Text is one explicit submission. Newlines and tabs use real keys on every
+// platform; Unicode events handle the remaining text independently of layout.
+func applyText(sink inputSink, target bounds, text string) error {
+ if text == "" || len(text) > maxTextBytes || !utf8.ValidString(text) {
+ return errors.New("invalid input text")
+ }
+ text = strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\r", "\n")
+ for _, r := range text {
+ if r < 0x20 && r != '\n' && r != '\t' || r == 0x7f {
+ return errors.New("text contains a control character")
+ }
+ }
+ if err := sink.Reset(); err != nil {
+ return err
+ }
+ for text != "" {
+ end := strings.IndexAny(text, "\n\t")
+ if end < 0 {
+ return sink.Apply(target, inputEvent{Type: "text", Text: text})
+ }
+ if end > 0 {
+ if err := sink.Apply(target, inputEvent{Type: "text", Text: text[:end]}); err != nil {
+ return err
+ }
+ }
+ code := "Enter"
+ if text[end] == '\t' {
+ code = "Tab"
+ }
+ for _, down := range []bool{true, false} {
+ if err := sink.Apply(target, inputEvent{Type: "key", Code: code, Down: down}); err != nil {
+ return err
+ }
+ }
+ text = text[end+1:]
+ }
+ return nil
+}
diff --git a/internal/media/forwarding/publication.go b/internal/media/forwarding/publication.go
index 975cfba3..d86fdd1b 100644
--- a/internal/media/forwarding/publication.go
+++ b/internal/media/forwarding/publication.go
@@ -122,7 +122,14 @@ func NewPublication(options TransportOptions) (_ *Publication, err error) {
return input
}
registry := &interceptor.Registry{}
- if err = webrtc.ConfigureRTCPReports(registry); err != nil {
+ if err = configureRTCPReports(registry, func(ssrc uint32) *sfu.DownTrack {
+ for _, track := range publication.tracks {
+ if track.SSRC() == ssrc {
+ return track
+ }
+ }
+ return nil
+ }); err != nil {
return nil, err
}
publication.PC, err = webrtc.NewAPI(webrtc.WithMediaEngine(media), webrtc.WithInterceptorRegistry(registry),
diff --git a/internal/media/forwarding/publication_test.go b/internal/media/forwarding/publication_test.go
index 09525a62..b388c155 100644
--- a/internal/media/forwarding/publication_test.go
+++ b/internal/media/forwarding/publication_test.go
@@ -168,6 +168,10 @@ func checkPublicationProbeCapacity(t *testing.T, received bool) {
AvailableBandwidthBps: int(target), DesiredBps: 800_000,
Duration: 200 * time.Millisecond, DesiredBytes: 20_000,
}}
+ if !received {
+ // A delayed completion must back off from now, not an expired start time.
+ info.CreatedAt = start.Add(-time.Minute)
+ }
bandwidth.ProbeClusterStarting(info)
for index := range 100 {
at := start.Add(time.Duration(index) * 2 * time.Millisecond).UnixMicro()
@@ -195,6 +199,9 @@ func checkPublicationProbeCapacity(t *testing.T, received bool) {
} else if signal != ccutils.ProbeSignalInconclusive || capacity != target {
t.Fatalf("unacknowledged probe changed capacity: signal=%v committed=%d", signal, capacity)
}
+ if !received && (bandwidth.ProbeDuration() > info.Goal.Duration || bandwidth.CanProbe()) {
+ t.Fatalf("unacknowledged probe did not back off: duration=%v ready=%v", bandwidth.ProbeDuration(), bandwidth.CanProbe())
+ }
bandwidth.OnCongestionStateChange(bwe.CongestionStateNone, bwe.CongestionStateCongested, target/2)
if bandwidth.target.Load() != target/2 {
t.Fatal("finalized probe suppressed ordinary media congestion")
@@ -287,7 +294,7 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
check(mediaEngine.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: publicationRIDExtension}, webrtc.RTPCodecTypeVideo))
check(mediaEngine.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: "urn:ietf:params:rtp-hdrext:sdes:mid"}, webrtc.RTPCodecTypeVideo))
registry := &interceptor.Registry{}
- reports := &receiverReportGate{}
+ reports := &receiverReportGate{reportDelay: 20 * time.Millisecond}
registry.Add(reports)
check(webrtc.RegisterDefaultInterceptors(mediaEngine, registry))
receiver, err := webrtc.NewAPI(webrtc.WithMediaEngine(mediaEngine), webrtc.WithInterceptorRegistry(registry), webrtc.WithSettingEngine(settings)).NewPeerConnection(webrtc.Configuration{})
@@ -296,10 +303,12 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
var received [3]atomic.Uint32
var invalid atomic.Bool
var lastSequence, lowSSRC, missingSequence atomic.Uint32
+ var lowTimestamp atomic.Uint32
+ lowReports := make(chan *rtcp.SenderReport, 4)
var repaired atomic.Bool
deltaFrame := append([]byte(nil), sfu.VP8KeyFrame8x8...)
deltaFrame[0] |= 1
- receiver.OnTrack(func(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
+ receiver.OnTrack(func(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver) {
index := 2
if track.Kind() == webrtc.RTPCodecTypeVideo {
if track.RID() == "q" {
@@ -311,6 +320,24 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
return
}
}
+ if index == 0 {
+ go func() {
+ for {
+ packets, _, err := rtpReceiver.ReadSimulcastRTCP(track.RID())
+ if err != nil {
+ return
+ }
+ for _, packet := range packets {
+ if report, ok := packet.(*rtcp.SenderReport); ok && report.SSRC == uint32(track.SSRC()) {
+ select {
+ case lowReports <- report:
+ default:
+ }
+ }
+ }
+ }
+ }()
+ }
for {
packet, attributes, readErr := ReadRTP(track)
if readErr != nil {
@@ -329,6 +356,7 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
}
if index == 0 {
lastSequence.Store(uint32(packet.SequenceNumber))
+ lowTimestamp.Store(packet.Timestamp)
lowSSRC.Store(packet.SSRC)
if uint32(packet.SequenceNumber) == missingSequence.Load() && attributes.Get(webrtc.AttributeRtxPayloadType) != nil {
repaired.Store(true)
@@ -369,11 +397,10 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
if len(source.GetDownTracks()) != 2 {
t.Fatal("publication did not attach exactly one output per encoding")
}
- frame := 0
+ started := time.Now()
frameData := sfu.VP8KeyFrame8x8
write := func() {
- frame++
- pts := time.Duration(frame) * time.Second / 30
+ pts := max(time.Since(started), source.inputPTS+time.Microsecond)
check(source.BeginFrame(pts, time.Now()))
for layer := 0; layer < 2; layer++ {
check(source.WriteFrame(layer, encoded.Frame{Data: frameData, PTS: pts, Duration: time.Second / 30, Recovery: bytes.Equal(frameData, sfu.VP8KeyFrame8x8)}))
@@ -450,6 +477,16 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
t.Fatal("publication did not measure both available encodings")
}
}
+ // The sender-report owner must also receive its matching receiver feedback.
+ // Delayed real RTCP distinguishes an observed RTT from loopback's zero ms.
+ for publication.tracks[0].GetTrackStats().RttMax < 10 {
+ write()
+ select {
+ case <-time.After(time.Second / 30):
+ case <-ctx.Done():
+ t.Fatal("receiver reports never reached the publication RTT owner")
+ }
+ }
publication.bandwidth.OnCongestionStateChange(bwe.CongestionStateNone, bwe.CongestionStateCongested, 1_000)
for publication.tracks[0].BandwidthRequested()+publication.tracks[1].BandwidthRequested() > 1_000 {
select {
@@ -476,8 +513,7 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
t.Fatal("publication has no receiver-report authority for padding probes")
}
for range source.maxPackets + 8 {
- frame++
- pts := time.Duration(frame) * time.Second / 30
+ pts := max(time.Since(started), source.inputPTS+time.Microsecond)
check(source.BeginFrame(pts, time.Now()))
for layer := range 2 {
check(source.WriteFrame(layer, encoded.Frame{Data: frameData, PTS: pts, Duration: time.Second / 30}))
@@ -506,6 +542,19 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {
if publication.Counters().Limited {
t.Fatal("publication stayed limited after requested low output recovered and high was deactivated")
}
+ // The report after paused RTX probing must still match the primary clock.
+ // DownTrack omits reports while no layer is selected, then resumes normally.
+ for len(lowReports) > 0 {
+ <-lowReports
+ }
+ select {
+ case report := <-lowReports:
+ if delta := int32(report.RTPTime - lowTimestamp.Load()); delta < 0 || delta > 3*90_000 {
+ t.Fatalf("publication lost its primary clock after RTX probing: delta=%d", delta)
+ }
+ case <-ctx.Done():
+ t.Fatal("resumed publication did not report its media clock")
+ }
// A live encoder can be constrained inside its sole requested RID. The
// inactive high RID and a fitting measured rate must not hide that demand.
source.SetLowestLayerRateControlled(true)
diff --git a/internal/media/forwarding/rtcp_reports.go b/internal/media/forwarding/rtcp_reports.go
new file mode 100644
index 00000000..d2ed2e24
--- /dev/null
+++ b/internal/media/forwarding/rtcp_reports.go
@@ -0,0 +1,68 @@
+package forwarding
+
+import (
+ "time"
+
+ "github.com/livekit/livekit-server/pkg/sfu"
+ "github.com/pion/interceptor"
+ "github.com/pion/interceptor/pkg/report"
+ "github.com/pion/rtcp"
+)
+
+func configureRTCPReports(registry *interceptor.Registry, downTrack func(uint32) *sfu.DownTrack) error {
+ receiver, err := report.NewReceiverInterceptor()
+ if err != nil {
+ return err
+ }
+ // DownTrack matches RTT against its latest SR. LiveKit's three-second
+ // cadence leaves ordinary one-second RR rounds time to return that marker.
+ sender, err := report.NewSenderInterceptor(report.SenderInterval(3 * time.Second))
+ if err != nil {
+ return err
+ }
+ registry.Add(receiver)
+ registry.Add(senderReportFactory{Factory: sender, downTrack: downTrack})
+ return nil
+}
+
+type senderReportFactory struct {
+ interceptor.Factory
+ downTrack func(uint32) *sfu.DownTrack
+}
+
+func (factory senderReportFactory) NewInterceptor(id string) (interceptor.Interceptor, error) {
+ sender, err := factory.Factory.NewInterceptor(id)
+ if err != nil {
+ return nil, err
+ }
+ return &senderReports{Interceptor: sender, downTrack: factory.downTrack}, nil
+}
+
+type senderReports struct {
+ interceptor.Interceptor
+ downTrack func(uint32) *sfu.DownTrack
+}
+
+func (sender *senderReports) BindRTCPWriter(writer interceptor.RTCPWriter) interceptor.RTCPWriter {
+ return sender.Interceptor.BindRTCPWriter(interceptor.RTCPWriterFunc(func(packets []rtcp.Packet, attributes interceptor.Attributes) (int, error) {
+ reports := make([]rtcp.Packet, 0, len(packets))
+ for _, packet := range packets {
+ if report, ok := packet.(*rtcp.SenderReport); ok {
+ if track := sender.downTrack(report.SSRC); track != nil {
+ // Pion owns cadence; DownTrack owns the projected video clock and
+ // its matching RR/RTT state. Audio keeps the ordinary Pion report.
+ report = track.CreateSenderReport()
+ if report == nil {
+ continue
+ }
+ packet = report
+ }
+ }
+ reports = append(reports, packet)
+ }
+ if len(reports) == 0 {
+ return 0, nil
+ }
+ return writer.Write(reports, attributes)
+ }))
+}
diff --git a/internal/media/forwarding/transport.go b/internal/media/forwarding/transport.go
index 91737a4c..265fc6ef 100644
--- a/internal/media/forwarding/transport.go
+++ b/internal/media/forwarding/transport.go
@@ -119,8 +119,14 @@ func NewTransport(options TransportOptions) (_ *Transport, err error) {
return nil, err
}
// DownTrack owns video retransmission; registering default NACK interceptors
- // here would create a second responder. Pion still owns normal RTCP reports.
- if err = webrtc.ConfigureRTCPReports(registry); err != nil {
+ // here would create a second responder. Pion schedules reports, while the
+ // DownTrack supplies its projected video clock and matching RTT state.
+ if err = configureRTCPReports(registry, func(ssrc uint32) *sfu.DownTrack {
+ if transport.Output.SSRC() == ssrc {
+ return transport.Output.DownTrack
+ }
+ return nil
+ }); err != nil {
return nil, err
}
transport.PC, err = webrtc.NewAPI(webrtc.WithMediaEngine(media),
diff --git a/internal/media/forwarding/transport_test.go b/internal/media/forwarding/transport_test.go
index abf1dd2e..e38a1d5e 100644
--- a/internal/media/forwarding/transport_test.go
+++ b/internal/media/forwarding/transport_test.go
@@ -391,8 +391,9 @@ func testTransportVideoFeedbackAudioAndClose(t *testing.T, repair, withdrawDeman
type receiverReportGate struct {
interceptor.NoOp
- allow atomic.Bool
- allowNACK atomic.Bool
+ allow atomic.Bool
+ allowNACK atomic.Bool
+ reportDelay time.Duration
}
func (gate *receiverReportGate) NewInterceptor(string) (interceptor.Interceptor, error) {
@@ -402,6 +403,12 @@ func (gate *receiverReportGate) NewInterceptor(string) (interceptor.Interceptor,
func (gate *receiverReportGate) BindRTCPWriter(writer interceptor.RTCPWriter) interceptor.RTCPWriter {
return interceptor.RTCPWriterFunc(func(packets []rtcp.Packet, attributes interceptor.Attributes) (int, error) {
if gate.allow.Load() {
+ for _, packet := range packets {
+ if _, report := packet.(*rtcp.ReceiverReport); report {
+ time.Sleep(gate.reportDelay)
+ break
+ }
+ }
return writer.Write(packets, attributes)
}
var filtered []rtcp.Packet
diff --git a/internal/media/inputroute/relay.go b/internal/media/inputroute/relay.go
new file mode 100644
index 00000000..7637250a
--- /dev/null
+++ b/internal/media/inputroute/relay.go
@@ -0,0 +1,221 @@
+// Package inputroute carries opaque attended-input packets over the existing
+// media tree. It owns no PeerConnections, route selection or permissions.
+package inputroute
+
+import (
+ "encoding/json"
+ "sync"
+
+ "github.com/pion/webrtc/v4"
+)
+
+const Label = "piik-remote-input-prototype-v1"
+
+// 2 KiB of text, JSON escaping, authenticated encryption and the relay envelope.
+const MaxPacket = 6144
+
+// Packet data is authenticated and encrypted between the Viewer and Host App.
+// Relays only learn endpoint IDs. Small Host state replies fan out along the
+// existing tree; only the named endpoint can read them.
+type Packet struct {
+ ID string `json:"id,omitempty"`
+ Epoch string `json:"epoch,omitempty"`
+ Data string `json:"data,omitempty"`
+ Closed bool `json:"closed,omitempty"`
+ Ready *bool `json:"ready,omitempty"`
+}
+
+type leg struct {
+ channel *webrtc.DataChannel
+ endpoints map[string]string
+}
+
+type Relay struct {
+ mu sync.Mutex
+ up *webrtc.DataChannel
+ down map[string]*leg
+ ready bool
+ closed bool
+ // Root callbacks run outside mu. The root validates endpoint authority.
+ receive func(edgeID string, packet Packet)
+}
+
+func New(receive func(string, Packet)) *Relay {
+ return &Relay{down: make(map[string]*leg), receive: receive, ready: receive != nil}
+}
+
+func decode(message webrtc.DataChannelMessage) (Packet, bool) {
+ var p Packet
+ if !message.IsString || len(message.Data) > MaxPacket || json.Unmarshal(message.Data, &p) != nil {
+ return p, false
+ }
+ return p, p.Ready != nil || len(p.ID) == 32 && len(p.Epoch) == 32 && (p.Closed || p.Data != "")
+}
+
+func send(channel *webrtc.DataChannel, p Packet) {
+ if channel == nil || channel.ReadyState() != webrtc.DataChannelStateOpen {
+ return
+ }
+ if channel.BufferedAmount() > 8192 {
+ go channel.Close()
+ return
+ }
+ data, _ := json.Marshal(p)
+ _ = channel.SendText(string(data))
+}
+
+func (r *Relay) AttachUp(channel *webrtc.DataChannel) {
+ r.mu.Lock()
+ if r.closed || r.up != nil || channel.Label() != Label {
+ r.mu.Unlock()
+ _ = channel.Close()
+ return
+ }
+ r.up = channel
+ r.mu.Unlock()
+ channel.OnOpen(func() { send(channel, Packet{Ready: boolPointer(true)}) })
+ channel.OnMessage(func(message webrtc.DataChannelMessage) {
+ p, ok := decode(message)
+ if !ok {
+ return
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.closed || r.up != channel {
+ return
+ }
+ if p.Ready != nil && p.ID == "" {
+ r.ready = *p.Ready
+ }
+ for _, child := range r.down {
+ send(child.channel, p)
+ }
+ })
+ channel.OnClose(func() { r.SetUpAvailable(false) })
+}
+
+// ICE loss releases all descendant input even if SCTP has not closed yet.
+func (r *Relay) SetUpAvailable(available bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if available {
+ send(r.up, Packet{Ready: boolPointer(true)})
+ return
+ }
+ r.ready = false
+ for _, child := range r.down {
+ send(child.channel, Packet{Ready: &r.ready})
+ }
+}
+
+func (r *Relay) AttachDown(edgeID string, channel *webrtc.DataChannel) {
+ r.mu.Lock()
+ if r.closed || r.down[edgeID] != nil {
+ r.mu.Unlock()
+ _ = channel.Close()
+ return
+ }
+ child := &leg{channel: channel, endpoints: make(map[string]string)}
+ r.down[edgeID] = child
+ r.mu.Unlock()
+ channel.OnOpen(func() { r.mu.Lock(); defer r.mu.Unlock(); send(channel, Packet{Ready: &r.ready}) })
+ channel.OnMessage(func(message webrtc.DataChannelMessage) {
+ p, ok := decode(message)
+ if !ok {
+ return
+ }
+ r.mu.Lock()
+ if r.closed || r.down[edgeID] != child {
+ r.mu.Unlock()
+ return
+ }
+ if p.Ready != nil {
+ send(channel, Packet{Ready: &r.ready})
+ r.mu.Unlock()
+ return
+ }
+ if !r.ready {
+ r.mu.Unlock()
+ return
+ }
+ if p.Closed {
+ if child.endpoints[p.ID] == p.Epoch {
+ delete(child.endpoints, p.ID)
+ }
+ } else {
+ if child.endpoints[p.ID] == "" && len(child.endpoints) >= 20 {
+ r.mu.Unlock()
+ return
+ }
+ child.endpoints[p.ID] = p.Epoch
+ }
+ if r.receive == nil {
+ send(r.up, p)
+ r.mu.Unlock()
+ return
+ }
+ r.mu.Unlock()
+ r.receive(edgeID, p)
+ })
+ channel.OnClose(func() { r.LoseDown(edgeID, channel) })
+}
+
+func boolPointer(value bool) *bool { return &value }
+
+func (r *Relay) LoseDown(edgeID string, channel *webrtc.DataChannel) {
+ r.mu.Lock()
+ child := r.down[edgeID]
+ if child == nil || channel != nil && child.channel != channel {
+ r.mu.Unlock()
+ return
+ }
+ packets := make([]Packet, 0, len(child.endpoints))
+ for id, epoch := range child.endpoints {
+ packets = append(packets, Packet{ID: id, Epoch: epoch, Closed: true})
+ }
+ clear(child.endpoints)
+ if channel != nil {
+ delete(r.down, edgeID)
+ }
+ if r.receive == nil {
+ for _, p := range packets {
+ send(r.up, p)
+ }
+ }
+ r.mu.Unlock()
+ if r.receive != nil {
+ for _, p := range packets {
+ r.receive(edgeID, p)
+ }
+ }
+}
+
+func (r *Relay) Reply(p Packet) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.closed {
+ return
+ }
+ for _, child := range r.down {
+ send(child.channel, p)
+ }
+}
+
+func (r *Relay) Close() {
+ r.mu.Lock()
+ if r.closed {
+ r.mu.Unlock()
+ return
+ }
+ r.closed = true
+ channels := []*webrtc.DataChannel{r.up}
+ for _, child := range r.down {
+ channels = append(channels, child.channel)
+ }
+ r.mu.Unlock()
+ for _, channel := range channels {
+ if channel != nil {
+ _ = channel.Close()
+ }
+ }
+}
diff --git a/internal/server/app/app_test.go b/internal/server/app/app_test.go
index 8533421b..0754de36 100644
--- a/internal/server/app/app_test.go
+++ b/internal/server/app/app_test.go
@@ -366,7 +366,7 @@ func TestCapabilitiesReportServicesDisabledByDefault(t *testing.T) {
server := start(t, Options{Config: testConfig(t)})
server.do(http.MethodGet, "/api/capabilities").
- expect(http.StatusOK, `{"sfu":false,"natPrediction":false,"roomInteractions":true,"hostRoomSession":true}`)
+ expect(http.StatusOK, `{"sfu":false,"natPrediction":false,"roomInteractions":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)
}
@@ -376,7 +376,7 @@ func TestCapabilitiesReportSFUOnlyPolicy(t *testing.T) {
configuration.NATPredictionEnabled = true
server := start(t, Options{Config: configuration})
server.do(http.MethodGet, "/api/capabilities").
- expect(http.StatusOK, `{"sfu":true,"sfuOnly":true,"natPrediction":false,"roomInteractions":true,"hostRoomSession":true}`)
+ expect(http.StatusOK, `{"sfu":true,"sfuOnly":true,"natPrediction":false,"roomInteractions":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)
}
func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *testing.T) {
@@ -387,7 +387,7 @@ func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *
server := start(t, Options{Config: configuration})
server.do(http.MethodGet, "/api/capabilities").
- expect(http.StatusOK, `{"sfu":false,"natPrediction":true,"roomInteractions":true,"hostRoomSession":true}`).
+ expect(http.StatusOK, `{"sfu":false,"natPrediction":true,"roomInteractions":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`).
expectHeader("Cache-Control", "no-store").
expectHeader("X-Content-Type-Options", "nosniff")
@@ -430,7 +430,7 @@ func TestSFUListenerFollowsApplicationCloseAndEnd(t *testing.T) {
t.Fatal("missing runtime owner")
}
server.do(http.MethodGet, "/api/capabilities").
- expect(http.StatusOK, `{"sfu":true,"natPrediction":false,"roomInteractions":true,"hostRoomSession":true}`)
+ expect(http.StatusOK, `{"sfu":true,"natPrediction":false,"roomInteractions":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)
var err error
if ending {
diff --git a/internal/server/app/routes.go b/internal/server/app/routes.go
index 6d165578..44f6f4df 100644
--- a/internal/server/app/routes.go
+++ b/internal/server/app/routes.go
@@ -77,11 +77,15 @@ func (s *Server) route(
return
}
sendJSON(writer, http.StatusOK, protocol.RuntimeCapabilities{
- Sfu: s.config.SFU != nil,
- SfuOnly: s.config.SFU != nil && s.config.SFU.Only,
- NatPrediction: s.config.NATPredictionEnabled && !(s.config.SFU != nil && s.config.SFU.Only),
- RoomInteractions: true,
- HostRoomSession: true,
+ Sfu: s.config.SFU != nil,
+ SfuOnly: s.config.SFU != nil && s.config.SFU.Only,
+ NatPrediction: s.config.NATPredictionEnabled && !(s.config.SFU != nil && s.config.SFU.Only),
+ RoomInteractions: true,
+ RoomReactionIDs: protocol.RoomReactionIDs,
+ RemoteInput: true,
+ ViewerRouteSelection: true,
+ AudioPresence: true,
+ HostRoomSession: true,
})
return
}
diff --git a/internal/server/protocol/audio_presence.go b/internal/server/protocol/audio_presence.go
new file mode 100644
index 00000000..493f6655
--- /dev/null
+++ b/internal/server/protocol/audio_presence.go
@@ -0,0 +1,55 @@
+package protocol
+
+import "errors"
+
+type SubscribeAudioPresenceMessage struct {
+ Type string `json:"type"`
+}
+
+func (SubscribeAudioPresenceMessage) isClientMessage() {}
+
+type SetAudioPresenceMessage struct {
+ Type string `json:"type"`
+ ShareGeneration string `json:"shareGeneration"`
+ Available bool `json:"available"`
+}
+
+func (SetAudioPresenceMessage) isClientMessage() {}
+
+// Nil means an older Host has not supplied input availability.
+type AudioPresenceMessage struct {
+ Type string `json:"type"`
+ Available *bool `json:"available"`
+}
+
+func (AudioPresenceMessage) isServerMessage() {}
+
+func decodeSetAudioPresence(data []byte) (ClientMessage, error) {
+ var value SetAudioPresenceMessage
+ fields, err := decodeObject(data, &value)
+ if err != nil {
+ return nil, err
+ }
+ if err = fields.require("type", "shareGeneration", "available"); err != nil {
+ return nil, err
+ }
+ if !ValidOpaqueID(value.ShareGeneration) {
+ return nil, errors.New("invalid share generation")
+ }
+ return value, nil
+}
+
+func decodeAudioPresence(data []byte) (ServerMessage, error) {
+ var value AudioPresenceMessage
+ fields, err := decodeObject(data, &value)
+ if err != nil {
+ return nil, err
+ }
+ if err = fields.require("type"); err != nil {
+ return nil, err
+ }
+ if err = fields.requireNullable("available"); err != nil {
+ return nil, err
+ }
+ return value, nil
+}
diff --git a/internal/server/protocol/audio_presence_test.go b/internal/server/protocol/audio_presence_test.go
new file mode 100644
index 00000000..35094127
--- /dev/null
+++ b/internal/server/protocol/audio_presence_test.go
@@ -0,0 +1,35 @@
+package protocol
+
+import "testing"
+
+func TestAudioPresenceWire(t *testing.T) {
+ for _, raw := range []string{
+ `{"type":"audio-presence","available":null}`,
+ `{"type":"audio-presence","available":false}`,
+ `{"type":"audio-presence","available":true}`,
+ } {
+ message, err := DecodeServerMessage([]byte(raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded, err := EncodeServerMessage(message)
+ if err != nil || string(encoded) != raw {
+ t.Fatalf("round trip %s: %s, %v", raw, encoded, err)
+ }
+ }
+ for _, raw := range []string{
+ `{"type":"audio-presence"}`, `{"type":"audio-presence","available":"true"}`,
+ } {
+ if _, err := DecodeServerMessage([]byte(raw)); err == nil {
+ t.Fatalf("accepted %s", raw)
+ }
+ }
+ for _, raw := range []string{
+ `{"type":"set-audio-presence","shareGeneration":"audio_share_generation","available":null}`,
+ `{"type":"set-audio-presence","shareGeneration":"bad","available":true}`,
+ } {
+ if _, err := DecodeClientMessage([]byte(raw)); err == nil {
+ t.Fatalf("accepted %s", raw)
+ }
+ }
+}
diff --git a/internal/server/protocol/client.go b/internal/server/protocol/client.go
index ba004829..d34173be 100644
--- a/internal/server/protocol/client.go
+++ b/internal/server/protocol/client.go
@@ -31,15 +31,16 @@ type AuthenticateHostMessage struct {
// AuthenticateViewerMessage is the viewer member of authenticateMessageSchema.
type AuthenticateViewerMessage struct {
- Type string `json:"type"`
- Protocol string `json:"protocol"`
- RoomID string `json:"roomId"`
- Role Role `json:"role"`
- ClientID string `json:"clientId"`
- ViewerGrant string `json:"viewerGrant,omitempty"`
- ViewerPassword string `json:"viewerPassword,omitempty"`
- DisplayName *DisplayName `json:"displayName,omitempty"`
- ViewerPresence bool `json:"viewerPresence,omitempty"`
+ Type string `json:"type"`
+ Protocol string `json:"protocol"`
+ RoomID string `json:"roomId"`
+ Role Role `json:"role"`
+ ClientID string `json:"clientId"`
+ ViewerGrant string `json:"viewerGrant,omitempty"`
+ ViewerPassword string `json:"viewerPassword,omitempty"`
+ DisplayName *DisplayName `json:"displayName,omitempty"`
+ ViewerPresence bool `json:"viewerPresence,omitempty"`
+ RoutePreference *ViewerRoutePreference `json:"routePreference,omitempty"`
}
// SignalingChallengeMessage is { type: "signaling-challenge", sequence }.
@@ -217,6 +218,14 @@ func DecodeClientMessage(data []byte) (ClientMessage, error) {
return nil, err
}
switch messageType {
+ case "set-viewer-route-preference":
+ return decodeSetViewerRoutePreference(data)
+ case "subscribe-audio-presence":
+ return decodeEmptyClientMessage(data, SubscribeAudioPresenceMessage{Type: messageType})
+ case "set-audio-presence":
+ return decodeSetAudioPresence(data)
+ case "subscribe-remote-input":
+ return decodeSubscribeRemoteInput(data)
case "subscribe-room-interactions":
return decodeEmptyClientMessage(data, SubscribeRoomInteractionsMessage{Type: messageType})
case "send-room-interaction":
@@ -344,7 +353,7 @@ func decodeAuthenticate(data []byte) (ClientMessage, error) {
return nil, err
}
if err := present.optional(
- "viewerGrant", "viewerPassword", "displayName", "viewerPresence"); err != nil {
+ "viewerGrant", "viewerPassword", "displayName", "viewerPresence", "routePreference"); err != nil {
return nil, err
}
if message.Protocol != SignalingProtocol {
diff --git a/internal/server/protocol/contract_test.go b/internal/server/protocol/contract_test.go
index 12049279..25ad37fc 100644
--- a/internal/server/protocol/contract_test.go
+++ b/internal/server/protocol/contract_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
+ "reflect"
"strings"
"testing"
)
@@ -19,15 +20,19 @@ func TestRuntimeCapabilities(t *testing.T) {
{`{"natPrediction":true,"SFU":true}`, RuntimeCapabilities{NatPrediction: true}},
{`{"sfu":true,"natPrediction":true}`, RuntimeCapabilities{Sfu: true, NatPrediction: true}},
{`{"sfu":"ignored duplicate","sfu":true}`, RuntimeCapabilities{Sfu: true}},
+ {`{"roomReactionIds":["heart","future-effect"]}`, RuntimeCapabilities{RoomReactionIDs: []string{"heart", "future-effect"}}},
+ {`{"roomReactionIds":[]}`, RuntimeCapabilities{RoomReactionIDs: []string{}}},
} {
got := RuntimeCapabilities{Sfu: true, NatPrediction: true}
- if err := json.Unmarshal([]byte(test.data), &got); err != nil || got != test.want {
+ if err := json.Unmarshal([]byte(test.data), &got); err != nil || !reflect.DeepEqual(got, test.want) {
t.Errorf("decode %s = %+v, %v; want %+v", test.data, got, err, test.want)
}
}
for _, data := range []string{
`null`, `[]`, `true`, `{"sfu":null}`, `{"sfu":"true"}`, `{"sfuOnly":null}`, `{"sfuOnly":"true"}`,
`{"natPrediction":null}`, `{"natPrediction":1}`,
+ `{"roomReactionIds":null}`, `{"roomReactionIds":"heart"}`, `{"roomReactionIds":["bad id"]}`,
+ `{"roomReactionIds":[true]}`, `{"roomReactionIds":[""]}`,
} {
var got RuntimeCapabilities
if err := json.Unmarshal([]byte(data), &got); err == nil {
@@ -36,6 +41,15 @@ func TestRuntimeCapabilities(t *testing.T) {
}
}
+func TestAdvertisedRoomReactionsAreRegisteredCommands(t *testing.T) {
+ for _, id := range append(append([]string{}, RoomReactionIDs...), "future-effect") {
+ _, err := DecodeClientMessage([]byte(fmt.Sprintf(`{"type":"send-room-interaction","requestId":"request_1234","payload":{"kind":"reaction","reaction":%q,"targetPeerId":"target_peer_1234"}}`, id)))
+ if (err == nil) != (id != "future-effect") {
+ t.Errorf("reaction %q: %v", id, err)
+ }
+ }
+}
+
func TestStrictMemberNamesCannotPopulateForbiddenOrOptionalFields(t *testing.T) {
for _, sample := range []struct {
name string
diff --git a/internal/server/protocol/interactions.go b/internal/server/protocol/interactions.go
index 4ed2ad28..1dfafb36 100644
--- a/internal/server/protocol/interactions.go
+++ b/internal/server/protocol/interactions.go
@@ -3,6 +3,7 @@ package protocol
import (
"errors"
"regexp"
+ "slices"
"strings"
"unicode/utf8"
@@ -14,6 +15,9 @@ const InteractionIntervalMs = 800
var reactionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
+// RoomReactionIDs is the command registry advertised to pages by this Server.
+var RoomReactionIDs = []string{"thumbsup", "thumbsdown", "laugh", "clown", "eyeroll", "eyes", "wow", "wave", "heart", "clap", "party", "fire", "star", "sleep", "tomato", "poop"}
+
type InteractionPayload struct {
Kind string `json:"kind"`
Text string `json:"text,omitempty"`
@@ -96,12 +100,8 @@ func decodeSendRoomInteraction(data []byte) (ClientMessage, error) {
}
// Only received presentation events are extensible. An unregistered command
// must never acquire meaning merely because its identifier is well-formed.
- if message.Payload.Kind == "reaction" {
- switch message.Payload.Reaction {
- case "wave", "heart", "clap", "laugh", "wow", "party", "fire", "eyes", "star", "sleep", "tomato", "poop":
- default:
- return nil, errors.New("unknown reaction")
- }
+ if message.Payload.Kind == "reaction" && !slices.Contains(RoomReactionIDs, message.Payload.Reaction) {
+ return nil, errors.New("unknown reaction")
}
return message, nil
}
diff --git a/internal/server/protocol/remote_input.go b/internal/server/protocol/remote_input.go
new file mode 100644
index 00000000..b8cca4b2
--- /dev/null
+++ b/internal/server/protocol/remote_input.go
@@ -0,0 +1,71 @@
+package protocol
+
+import (
+ "encoding/hex"
+ "errors"
+)
+
+// Signaling establishes endpoint identity and the key. Input itself follows
+// the media route and never enters room chat, storage or diagnostics.
+type SubscribeRemoteInputMessage struct {
+ Type string `json:"type"`
+ EndpointID string `json:"endpointId,omitempty"`
+ Secret string `json:"secret,omitempty"`
+}
+
+func (SubscribeRemoteInputMessage) isClientMessage() {}
+
+type RemoteInputPeer struct {
+ PeerID string `json:"peerId"`
+ EndpointID string `json:"endpointId"`
+ Secret string `json:"secret"`
+}
+type RemoteInputPeersMessage struct {
+ Type string `json:"type"`
+ Peers []RemoteInputPeer `json:"peers"`
+}
+
+func (RemoteInputPeersMessage) isServerMessage() {}
+
+func ValidInputKey(endpoint, secret string) bool {
+ id, idErr := hex.DecodeString(endpoint)
+ key, keyErr := hex.DecodeString(secret)
+ return idErr == nil && keyErr == nil && len(id) == 16 && len(key) == 32 && hex.EncodeToString(id) == endpoint && hex.EncodeToString(key) == secret
+}
+
+func decodeSubscribeRemoteInput(data []byte) (ClientMessage, error) {
+ var value SubscribeRemoteInputMessage
+ fields, err := decodeObject(data, &value)
+ if err != nil {
+ return nil, err
+ }
+ if err = fields.require("type"); err != nil {
+ return nil, err
+ }
+ if fields.has("endpointId") || fields.has("secret") {
+ if !ValidInputKey(value.EndpointID, value.Secret) {
+ return nil, errors.New("invalid input endpoint")
+ }
+ }
+ return value, nil
+}
+
+func decodeRemoteInputPeers(data []byte) (ServerMessage, error) {
+ var value RemoteInputPeersMessage
+ fields, err := decodeObject(data, &value)
+ if err != nil {
+ return nil, err
+ }
+ if err = fields.require("type", "peers"); err != nil {
+ return nil, err
+ }
+ if len(value.Peers) > 20 {
+ return nil, errors.New("too many input endpoints")
+ }
+ for _, peer := range value.Peers {
+ if !ValidOpaqueID(peer.PeerID) || !ValidInputKey(peer.EndpointID, peer.Secret) {
+ return nil, errors.New("invalid input endpoint")
+ }
+ }
+ return value, nil
+}
diff --git a/internal/server/protocol/server.go b/internal/server/protocol/server.go
index 3e1f9d1d..33bd1313 100644
--- a/internal/server/protocol/server.go
+++ b/internal/server/protocol/server.go
@@ -249,6 +249,12 @@ func DecodeServerMessage(data []byte) (ServerMessage, error) {
return nil, err
}
switch messageType {
+ case "viewer-route-preference":
+ return decodeViewerRoutePreference(data)
+ case "audio-presence":
+ return decodeAudioPresence(data)
+ case "remote-input-peers":
+ return decodeRemoteInputPeers(data)
case "room-interactions-ready":
return decodeRoomInteractionsReady(data)
case "room-interaction":
diff --git a/internal/server/protocol/types.go b/internal/server/protocol/types.go
index 7efde368..3a410c93 100644
--- a/internal/server/protocol/types.go
+++ b/internal/server/protocol/types.go
@@ -185,11 +185,15 @@ func (v *RoutePolicy) UnmarshalJSON(data []byte) error {
// RuntimeCapabilities mirrors runtimeCapabilitiesSchema.
type RuntimeCapabilities struct {
- Sfu bool `json:"sfu"`
- SfuOnly bool `json:"sfuOnly,omitempty"`
- NatPrediction bool `json:"natPrediction"`
- RoomInteractions bool `json:"roomInteractions,omitempty"`
- HostRoomSession bool `json:"hostRoomSession,omitempty"`
+ Sfu bool `json:"sfu"`
+ SfuOnly bool `json:"sfuOnly,omitempty"`
+ NatPrediction bool `json:"natPrediction"`
+ RoomInteractions bool `json:"roomInteractions,omitempty"`
+ HostRoomSession bool `json:"hostRoomSession,omitempty"`
+ RemoteInput bool `json:"remoteInput,omitempty"`
+ ViewerRouteSelection bool `json:"viewerRouteSelection,omitempty"`
+ AudioPresence bool `json:"audioPresence,omitempty"`
+ RoomReactionIDs []string `json:"roomReactionIds,omitempty"`
}
// UnmarshalJSON implements json.Unmarshaler.
@@ -202,13 +206,16 @@ func (v *RuntimeCapabilities) UnmarshalJSON(data []byte) error {
if present == nil {
return errors.New("runtime capabilities must be an object")
}
- if err := present.optional("sfu", "sfuOnly", "roomInteractions", "hostRoomSession", "natPrediction"); err != nil {
+ if err := present.optional("sfu", "sfuOnly", "roomInteractions", "hostRoomSession", "natPrediction", "remoteInput", "viewerRouteSelection", "audioPresence", "roomReactionIds"); err != nil {
return err
}
for key, target := range map[string]*bool{
"sfu": &v.Sfu, "sfuOnly": &v.SfuOnly, "natPrediction": &v.NatPrediction,
"roomInteractions": &v.RoomInteractions, "hostRoomSession": &v.HostRoomSession,
+ "remoteInput": &v.RemoteInput,
+ "viewerRouteSelection": &v.ViewerRouteSelection,
+ "audioPresence": &v.AudioPresence,
} {
if value, ok := present[key]; ok {
if err := json.Unmarshal(value, target); err != nil {
@@ -216,6 +223,19 @@ func (v *RuntimeCapabilities) UnmarshalJSON(data []byte) error {
}
}
}
+ if value, ok := present["roomReactionIds"]; ok {
+ if err := json.Unmarshal(value, &v.RoomReactionIDs); err != nil {
+ return err
+ }
+ if len(v.RoomReactionIDs) > 64 {
+ return errors.New("too many room reaction identifiers")
+ }
+ for _, id := range v.RoomReactionIDs {
+ if !reactionIDPattern.MatchString(id) {
+ return errors.New("invalid room reaction identifier")
+ }
+ }
+ }
return nil
}
diff --git a/internal/server/protocol/viewer_route.go b/internal/server/protocol/viewer_route.go
new file mode 100644
index 00000000..181052a3
--- /dev/null
+++ b/internal/server/protocol/viewer_route.go
@@ -0,0 +1,63 @@
+package protocol
+
+import (
+ "encoding/json"
+ "errors"
+)
+
+// ViewerRoutePreference constrains only this Viewer's incoming media hop.
+type ViewerRoutePreference string
+
+const (
+ ViewerRouteAuto ViewerRoutePreference = "auto"
+ ViewerRoutePeer ViewerRoutePreference = "p2p"
+ ViewerRouteSfu ViewerRoutePreference = "sfu"
+)
+
+func (v *ViewerRoutePreference) UnmarshalJSON(data []byte) error {
+ var value string
+ if err := json.Unmarshal(data, &value); err != nil {
+ return err
+ }
+ switch ViewerRoutePreference(value) {
+ case ViewerRouteAuto, ViewerRoutePeer, ViewerRouteSfu:
+ *v = ViewerRoutePreference(value)
+ return nil
+ default:
+ return errors.New("invalid viewer route preference")
+ }
+}
+
+type SetViewerRoutePreferenceMessage struct {
+ Type string `json:"type"`
+ Preference ViewerRoutePreference `json:"preference"`
+}
+
+func (SetViewerRoutePreferenceMessage) isClientMessage() {}
+
+func decodeSetViewerRoutePreference(data []byte) (ClientMessage, error) {
+ var message SetViewerRoutePreferenceMessage
+ present, err := decodeObject(data, &message)
+ if err != nil {
+ return nil, err
+ }
+ return message, present.require("type", "preference")
+}
+
+// Only a Viewer that opts into route selection receives this reply.
+type ViewerRoutePreferenceMessage struct {
+ Type string `json:"type"`
+ Preference ViewerRoutePreference `json:"preference"`
+ Accepted bool `json:"accepted"`
+}
+
+func (ViewerRoutePreferenceMessage) isServerMessage() {}
+
+func decodeViewerRoutePreference(data []byte) (ServerMessage, error) {
+ var message ViewerRoutePreferenceMessage
+ present, err := decodeObject(data, &message)
+ if err != nil {
+ return nil, err
+ }
+ return message, present.require("type", "preference", "accepted")
+}
diff --git a/internal/server/route/api.go b/internal/server/route/api.go
index bb9633e8..bc210a9f 100644
--- a/internal/server/route/api.go
+++ b/internal/server/route/api.go
@@ -317,6 +317,7 @@ type ParticipantInput struct {
Role protocol.Role
SessionID string
EffectiveDownstreamCapacity int
+ RoutePreference protocol.ViewerRoutePreference
}
// EdgeGuard identifies one committed edge exactly. ParentSessionID is only
diff --git a/internal/server/route/candidates.go b/internal/server/route/candidates.go
index 78d6f39b..58668a23 100644
--- a/internal/server/route/candidates.go
+++ b/internal/server/route/candidates.go
@@ -8,6 +8,21 @@ import (
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
+// AllowsViewerRoutePreference applies site and Host policy before a Viewer choice.
+// The choice covers only its incoming hop; a Peer parent may itself use SFU.
+func (c *Controller) AllowsViewerRoutePreference(preference protocol.ViewerRoutePreference) bool {
+ return (preference != protocol.ViewerRouteSfu || c.sfuEnabled) &&
+ (preference != protocol.ViewerRoutePeer || !c.sfuOnly)
+}
+
+func (c *Controller) allowsIncoming(childPeerID string, kind UpstreamKind) bool {
+ child, _ := c.participants.Get(childPeerID)
+ if kind == UpstreamSfu {
+ return c.sfuEnabled && (child == nil || child.routePreference != protocol.ViewerRoutePeer)
+ }
+ return !c.sfuOnly && (child == nil || child.routePreference != protocol.ViewerRouteSfu)
+}
+
// buildCandidates filters the full plan list by the
// availability opportunity ledger.
func (c *Controller) buildCandidates(childPeerID string, sfuOnly bool) []CandidatePlan {
@@ -66,7 +81,7 @@ func (c *Controller) buildCandidatePlans(childPeerID string, sfuOnly, preferUntr
directCandidates = append(directCandidates, CandidateTuple{Kind: UpstreamPeer, ParentPeerID: parent.peerID, Transport: TransportDirect})
}
var sfuCandidate *CandidateTuple
- if c.sfuEnabled {
+ if c.allowsIncoming(childPeerID, UpstreamSfu) {
if c.hostPublication != nil && c.hostPublication.Usable && c.hostPublication.PhysicalActive {
sfuCandidate = &CandidateTuple{Kind: UpstreamSfu, Publication: PublicationReuse}
} else if c.hostPublication != nil || c.publicationFits(childPeerID, false) {
@@ -79,7 +94,7 @@ func (c *Controller) buildCandidatePlans(childPeerID string, sfuOnly, preferUntr
}
var candidates []CandidateTuple
switch {
- case sfuOnly || c.sfuOnly:
+ case sfuOnly || !c.allowsIncoming(childPeerID, UpstreamPeer):
if sfuCandidate != nil {
candidates = []CandidateTuple{*sfuCandidate}
}
@@ -170,6 +185,9 @@ func (c *Controller) retirementFor(childPeerID, producerPeerID string, tuple Can
// candidateValid receives att when validating a live attempt.
func (c *Controller) candidateValid(childPeerID string, plan CandidatePlan, att *attempt) bool {
tuple := plan.Tuple
+ if !c.allowsIncoming(childPeerID, tuple.Kind) {
+ return false
+ }
child, _ := c.participants.Get(childPeerID)
if child == nil || child.sessionID == "" || child.departureConfirmed || (att != nil && att.childSessionID != child.sessionID) {
return false
diff --git a/internal/server/route/controller.go b/internal/server/route/controller.go
index a180f07d..af142c9a 100644
--- a/internal/server/route/controller.go
+++ b/internal/server/route/controller.go
@@ -40,6 +40,7 @@ type participant struct {
consumedCandidateOpportunities ordered.Map[string, candidateOpportunity]
bootstrapFailureReported bool
sfuFirstAtNextRoute bool
+ routePreference protocol.ViewerRoutePreference
}
// sessionIs never matches a disconnected participant, including an empty id.
@@ -465,6 +466,17 @@ func (c *Controller) UpsertParticipant(input ParticipantInput, nowMs *int64) []*
if input.Role == protocol.RoleViewer && nowMs != nil && !c.usableRoute(input.PeerID) {
c.recordDemand(input.PeerID, *nowMs, DemandJoin)
}
+ if input.Role == protocol.RoleViewer {
+ released = append(released, c.SetViewerRoutePreference(input.PeerID, input.SessionID, input.RoutePreference, nowMs)...)
+ }
+ if previousSessionID != input.SessionID {
+ // Reauthentication opens this session's opportunities even when SFU
+ // media survived. Restore child and parent opportunities in the same
+ // bounded continuation owner, without changing healthy media.
+ for peerID := range c.upstreamByViewer.All() {
+ c.restoreDirectContinuation(peerID)
+ }
+ }
return released
}
// New participants append to the scheduling order.
@@ -473,6 +485,7 @@ func (c *Controller) UpsertParticipant(input ParticipantInput, nowMs *int64) []*
role: input.Role,
sessionID: input.SessionID,
effectiveDownstreamCapacity: capacity,
+ routePreference: input.RoutePreference,
joinOrder: c.nextJoinOrder,
})
c.nextJoinOrder++
@@ -487,6 +500,33 @@ func (c *Controller) UpsertParticipant(input ParticipantInput, nowMs *int64) []*
return released
}
+// SetViewerRoutePreference changes eligibility, not physical edge health. The
+// ordinary serial handoff keeps current media until commit or strict-policy
+// exhaustion; selecting Auto again reopens only this Viewer's opportunities.
+func (c *Controller) SetViewerRoutePreference(peerID, sessionID string, preference protocol.ViewerRoutePreference, nowMs *int64) []*Resource {
+ current, _ := c.participants.Get(peerID)
+ if current == nil || current.role != protocol.RoleViewer || !current.sessionIs(sessionID) || current.routePreference == preference {
+ return nil
+ }
+ var released []*Resource
+ if op := c.operation; op != nil && (op.childPeerID == peerID || op.demandPeerID == peerID) {
+ released = c.abortOperation(nowMs, RejectionAborted)
+ }
+ current.routePreference = preference
+ current.consumedCandidateOpportunities.Clear()
+ current.availabilityExhausted = false
+ current.bootstrapFailureReported = false
+ c.directContinuations.Delete(peerID)
+ c.clearSfuBootstrapForDemand(peerID)
+ c.touchFacts()
+ c.restoreDirectContinuation(peerID)
+ c.debug("viewer-route-preference", "participant", c.debugPeer(peerID), "preference", preference)
+ if nowMs != nil {
+ c.recordDemand(peerID, *nowMs, c.routeDemandReason(peerID))
+ }
+ return released
+}
+
// RebindHostIdentity moves the Host to a new peer ID (same ID delegates to
// UpsertParticipant), tearing down the whole graph and returning every SFU
// subscription, the publication and the aborted reservation, deduplicated.
diff --git a/internal/server/route/graph.go b/internal/server/route/graph.go
index 97b9aa50..8673ec70 100644
--- a/internal/server/route/graph.go
+++ b/internal/server/route/graph.go
@@ -113,7 +113,7 @@ func (c *Controller) retireInvalidOperationEdge(childPeerID string, released *[]
}
func (c *Controller) edgeRequiresMove(childPeerID string, edge *CommittedEdge) bool {
- if !edge.Usable || !edge.PhysicalActive {
+ if !edge.Usable || !edge.PhysicalActive || !c.allowsIncoming(childPeerID, edge.Kind) || c.parentRouteRetired(edge) {
return true
}
if edge.Kind == UpstreamSfu {
@@ -132,6 +132,16 @@ func (c *Controller) edgeRequiresMove(childPeerID string, edge *CommittedEdge) b
return false
}
+// Keep a relay's subtree while it repairs its ingress. Once that ingress is
+// actually retired, its direct children need their own availability handoff.
+func (c *Controller) parentRouteRetired(edge *CommittedEdge) bool {
+ if edge.Kind != UpstreamPeer || edge.ParentPeerID == c.hostPeerID {
+ return false
+ }
+ parentEdge, ok := c.upstreamByViewer.Get(edge.ParentPeerID)
+ return ok && !parentEdge.PhysicalActive
+}
+
// rebindCommittedSession preserves the reconnecting peer's edges and
// publication, updating them to its new session ID.
func (c *Controller) rebindCommittedSession(peerID, sessionID string) {
diff --git a/internal/server/route/operation.go b/internal/server/route/operation.go
index bb267900..f7e70603 100644
--- a/internal/server/route/operation.go
+++ b/internal/server/route/operation.go
@@ -1002,7 +1002,7 @@ func (c *Controller) commitAttempt(op *operation, att *attempt) []*Resource {
}
remainingParentPeerIDs = append(remainingParentPeerIDs, op.deferredParentPeerIDs...)
}
- if len(remainingParentPeerIDs) > 0 {
+ if len(remainingParentPeerIDs) > 0 && c.allowsIncoming(op.childPeerID, UpstreamPeer) {
// Dedupe preserving first occurrence.
c.directContinuations.Set(op.childPeerID, &directContinuation{
childSessionID: op.childSessionID,
@@ -1330,7 +1330,7 @@ func (c *Controller) selectNextChild() string {
departedParents = append(departedParents, viewer.peerID)
}
}
- if edge != nil && !edge.Usable {
+ if edge != nil && (!edge.Usable || !c.allowsIncoming(viewer.peerID, edge.Kind) || c.parentRouteRetired(edge)) {
unusable = append(unusable, viewer.peerID)
}
if edge != nil && edge.Kind == UpstreamSfu &&
@@ -1352,6 +1352,33 @@ func (c *Controller) selectNextChild() string {
return candidates[0]
}
+// Restore newly available session opportunities behind a healthy SFU edge.
+// Existing parent intents survive temporary capacity constraints; the normal
+// opportunity ledger still owns eligibility and the attempt budget.
+func (c *Controller) restoreDirectContinuation(peerID string) {
+ child, _ := c.participants.Get(peerID)
+ edge, _ := c.upstreamByViewer.Get(peerID)
+ if child == nil || child.sessionID == "" || !c.allowsIncoming(peerID, UpstreamPeer) ||
+ edge == nil || edge.Kind != UpstreamSfu || !edge.Usable || !edge.PhysicalActive || !c.usableRoute(peerID) {
+ return
+ }
+ var parents []string
+ if previous, ok := c.directContinuations.Get(peerID); ok {
+ parents = append(parents, previous.parentPeerIDs...)
+ }
+ for _, plan := range c.buildCandidates(peerID, false) {
+ if plan.Tuple.Kind == UpstreamPeer && plan.EndpointTransition.Kind != TransitionBoundedGap {
+ parents = append(parents, plan.Tuple.ParentPeerID)
+ }
+ }
+ if len(parents) > 0 {
+ c.directContinuations.Set(peerID, &directContinuation{
+ childSessionID: child.sessionID, sfuConnectionID: edge.ConnectionID,
+ publicationGeneration: edge.PublicationGeneration, parentPeerIDs: dedupeStrings(parents),
+ })
+ }
+}
+
// directContinuationPick is the selectDirectContinuation result.
type directContinuationPick struct {
childPeerID string
diff --git a/internal/server/route/session_opportunity_test.go b/internal/server/route/session_opportunity_test.go
index 4450fdc8..32826b15 100644
--- a/internal/server/route/session_opportunity_test.go
+++ b/internal/server/route/session_opportunity_test.go
@@ -1,6 +1,9 @@
package route
-import "testing"
+import (
+ "fmt"
+ "testing"
+)
func TestRetainedEdgeFailurePreservesNewSessionOpportunity(t *testing.T) {
for _, upstream := range []UpstreamKind{UpstreamPeer, UpstreamSfu} {
@@ -24,7 +27,11 @@ func TestRetainedEdgeFailurePreservesNewSessionOpportunity(t *testing.T) {
edge := edgeOf(t, routes, A)
eq(t, edge.Usable, true)
eq(t, edge.ConnectionID, "retained_connection")
- noOperation(t, routes.Reconcile(0).Operation)
+ if upstream == UpstreamSfu && changed != "none" {
+ eq(t, must(t, routes.Reconcile(0).Operation).Reason, DemandDirectConvergence)
+ } else {
+ noOperation(t, routes.Reconcile(0).Operation)
+ }
eq(t, routes.InvalidateEdge(EdgeGuard{
ChildPeerID: A, ChildSessionID: edge.ChildSessionID,
ParentSessionID: edge.ParentSessionID,
@@ -39,6 +46,56 @@ func TestRetainedEdgeFailurePreservesNewSessionOpportunity(t *testing.T) {
}
}
+func TestSessionRebindRestoresBoundedDirectAttemptsBehindSFU(t *testing.T) {
+ for _, changed := range []string{"child", "host", "parent"} {
+ t.Run(changed, func(t *testing.T) {
+ routes := newController(3, Options{SfuEnabled: true, NatPredictionEnabled: true})
+ addViewer(routes, A, 0, nil)
+ routes.hydrateHostPublication("publication", res("publication"), "publisher")
+ routes.hydrateEdge(A, sfuEdge("publication", "retained_sfu", "subscription"))
+ parent := HOST
+ rebound := hostInput("new_host_session", 3)
+ if changed == "child" {
+ rebound = viewerInput(A, "new_child_session", 0)
+ } else if changed == "parent" {
+ parent = B
+ addViewer(routes, B, 2, nil)
+ routes.hydrateEdge(B, peerEdge(HOST, "host_b"))
+ rebound = viewerInput(B, "new_parent_session", 2)
+ }
+ // The previous sessions exhausted direct opportunities, not SFU media.
+ for _, plan := range routes.buildCandidates(A, false) {
+ if plan.Tuple.Kind == UpstreamPeer {
+ routes.consumeCandidateOpportunity(A, plan)
+ }
+ }
+ noOperation(t, routes.Reconcile(0).Operation)
+ previous, _ := routes.participants.Get(rebound.PeerID)
+ routes.DisconnectSession(rebound.PeerID, previous.sessionID)
+ routes.Reconcile(1)
+ routes.UpsertParticipant(rebound, ms(2))
+ for attempt := 1; attempt <= 4; attempt++ {
+ now := int64(3 + attempt*2)
+ op := must(t, routes.Reconcile(now).Operation)
+ eq(t, op.Reason, DemandDirectConvergence)
+ eq(t, op.ChildPeerID, A)
+ eq(t, op.Candidates[0].Tuple, peerTuple(parent))
+ prepared := beginOperation(t, routes, BeginInput{NowMs: now,
+ ConnectionID: fmt.Sprintf("retry_%d", attempt), Reservation: direct()})
+ eq(t, attemptCurrent(t, prepared), attempt)
+ routes.CandidateFailed(CandidateGuard{ChildPeerID: A, ChildSessionID: prepared.ChildSessionID,
+ Revision: prepared.Current.Revision, ConnectionID: prepared.Current.ConnectionID}, now+1)
+ eq(t, edgeOf(t, routes, A).ConnectionID, "retained_sfu")
+ eq(t, edgeOf(t, routes, A).Usable, true)
+ }
+ noOperation(t, routes.Reconcile(20).Operation)
+ // Duplicate session updates cannot reopen the exhausted budget.
+ routes.UpsertParticipant(rebound, ms(21))
+ noOperation(t, routes.Reconcile(22).Operation)
+ })
+ }
+}
+
func TestRebuiltDirectConnectionConsumesCurrentSessionOpportunity(t *testing.T) {
routes := newController(2, Options{SfuEnabled: true})
addViewer(routes, A, 0, ms(0))
diff --git a/internal/server/route/sfu_bootstrap.go b/internal/server/route/sfu_bootstrap.go
index 8e836319..dd4845ae 100644
--- a/internal/server/route/sfu_bootstrap.go
+++ b/internal/server/route/sfu_bootstrap.go
@@ -92,7 +92,7 @@ func (c *Controller) bootstrapOperationOwned(op *operation) bool {
}
func (c *Controller) sfuBootstrapNeeded(demandPeerID string) bool {
- if !c.sfuBootstrapGloballyNeeded() {
+ if !c.sfuBootstrapGloballyNeeded() || !c.allowsIncoming(demandPeerID, UpstreamSfu) {
return false
}
demand, _ := c.participants.Get(demandPeerID)
@@ -134,6 +134,7 @@ func (c *Controller) sfuBootstrapCarriers() []string {
edge.Usable &&
edge.PhysicalActive &&
plan != nil &&
+ c.candidateValid(peerID, *plan, nil) &&
plan.EndpointTransition.Kind != TransitionBoundedGap &&
c.sfuBootstrapOpportunityAvailable(peerID, *plan) {
carriers = append(carriers, peerID)
diff --git a/internal/server/route/viewer_preference_test.go b/internal/server/route/viewer_preference_test.go
new file mode 100644
index 00000000..0486f313
--- /dev/null
+++ b/internal/server/route/viewer_preference_test.go
@@ -0,0 +1,178 @@
+package route
+
+import (
+ "testing"
+
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+)
+
+func TestViewerRoutePreferenceAutoRestoresDirectContinuation(t *testing.T) {
+ routes := newController(2, Options{SfuEnabled: true})
+ addViewer(routes, A, 2, nil)
+ routes.hydrateHostPublication("publication", res("publication"), "publication_connection")
+ routes.hydrateEdge(A, sfuEdge("publication", "sfu_connection", "subscription"))
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteSfu, ms(0))
+ noOperation(t, routes.Reconcile(1).Operation)
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteAuto, ms(2))
+ op := must(t, routes.Reconcile(3).Operation)
+ eq(t, op.Reason, DemandDirectConvergence)
+ eq(t, op.Candidates[0].Tuple, peerTuple(HOST))
+ eq(t, edgeOf(t, routes, A).ConnectionID, "sfu_connection")
+ prepared := beginOperation(t, routes, BeginInput{NowMs: 4, ConnectionID: "peer_connection", Reservation: direct()})
+ late := guardFor(A, prepared.Current.Revision, "peer_connection")
+ // Selecting SFU again aborts preparation without disturbing playback.
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteSfu, ms(5))
+ eq(t, routes.CandidateReady(late, 6, nil, CandidateProof{}).Accepted, false)
+ eq(t, edgeOf(t, routes, A).ConnectionID, "sfu_connection")
+ noOperation(t, routes.Reconcile(7).Operation)
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteAuto, ms(8))
+ eq(t, must(t, routes.Reconcile(9).Operation).Reason, DemandDirectConvergence)
+ commitCurrent(t, routes, 10, "restored_peer")
+ eq(t, edgeOf(t, routes, A).Kind, UpstreamPeer)
+ noOperation(t, routes.Reconcile(12).Operation)
+}
+
+func TestViewerRoutePreferenceExhaustionRepairsRelayChildren(t *testing.T) {
+ routes := newController(2, Options{SfuEnabled: true})
+ for _, peer := range []string{A, B, C} {
+ addViewer(routes, peer, 2, nil)
+ }
+ routes.hydrateEdge(A, peerEdge(HOST, "host_a"))
+ routes.hydrateEdge(B, peerEdge(A, "a_b"))
+ routes.hydrateEdge(C, peerEdge(B, "b_c"))
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteSfu, ms(0))
+ op := must(t, routes.Reconcile(1).Operation)
+ eq(t, op.ChildPeerID, A)
+ eqSlice(t, tupleKinds(op), []UpstreamKind{UpstreamSfu})
+ eq(t, routes.sourceUsable(C), true)
+ // The retained ingress and entire subtree survive candidate preparation.
+ prepared := beginOperation(t, routes, BeginInput{NowMs: 2, ConnectionID: "a_sfu",
+ PublicationGeneration: "publication", PublicationConnectionID: "publisher",
+ Reservation: sfuCreate("subscription", "publication")})
+ eq(t, routes.sourceUsable(C), true)
+ routes.CandidateFailed(guardFor(A, prepared.Current.Revision, "a_sfu"), 3)
+ eq(t, edgeOf(t, routes, A).PhysicalActive, false)
+ eq(t, edgeOf(t, routes, B).Usable, true)
+ op = must(t, routes.Reconcile(4).Operation)
+ eq(t, op.ChildPeerID, B)
+ eq(t, op.Candidates[0].Tuple, peerTuple(HOST))
+ commitCurrent(t, routes, 5, "host_b")
+ eq(t, routes.sourceUsable(C), true)
+ eq(t, edgeOf(t, routes, C).ConnectionID, "b_c")
+ // The exhausted strict choice cannot spin when another branch commits.
+ noOperation(t, routes.Reconcile(7).Operation)
+ noOperation(t, routes.Reconcile(8).Operation)
+}
+
+func TestViewerRoutePreferenceP2PAcceptsSFUFedParent(t *testing.T) {
+ routes := newController(1, Options{SfuEnabled: true, QualityConvergenceEnabled: true})
+ addViewer(routes, A, 1, nil)
+ addViewer(routes, B, 1, nil)
+ routes.hydrateHostPublication("publication", res("publication"), "publisher")
+ routes.hydrateEdge(A, sfuEdge("publication", "a_sfu", "subscription"))
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteSfu, ms(0))
+ routes.SetViewerRoutePreference(B, sessionOf(B), protocol.ViewerRoutePeer, ms(0))
+ op := must(t, routes.Reconcile(1).Operation)
+ eq(t, op.ChildPeerID, B)
+ eqSlice(t, tuples(op), []CandidateTuple{peerTuple(A)})
+ commitCurrent(t, routes, 2, "a_b")
+ eq(t, routes.sourceUsable(B), true)
+ noOperation(t, routes.Reconcile(4).Operation)
+ // A fixed incoming kind still permits quality repair of the P2P child.
+ for index, state := range []SenderQualityState{SenderQualityHealthy, SenderQualityDegraded, SenderQualityDegraded, SenderQualityDegraded} {
+ eq(t, observeSenderState(routes, senderState{parentPeerID: A, childPeerID: B,
+ connectionID: "a_b", state: state, acceptedAtMs: int64(10 + index)}).Accepted, true)
+ }
+ op = must(t, routes.Reconcile(14).Operation)
+ eq(t, op.Reason, DemandQualityConvergence)
+ eq(t, op.ChildPeerID, B)
+ eqSlice(t, tuples(op), []CandidateTuple{regenerateTuple(A)})
+ prepared := beginOperation(t, routes, BeginInput{NowMs: 15, ConnectionID: "a_b_regenerated",
+ Reservation: directOverlap("regeneration_overlap")})
+ guard := guardFor(B, prepared.Current.Revision, "a_b_regenerated")
+ eq(t, routes.CandidateReady(guard, 16, nil, CandidateProof{RelativeQualityApproved: true}).Committed, false)
+ eq(t, routes.ObserveSenderQualityEvidence(senderSample(A, B, prepared.Current.Revision,
+ "a_b_regenerated", "regenerated-rtp\x00track", SenderQualityHealthy, 17), nil).Committed, true)
+ eq(t, edgeOf(t, routes, B).ConnectionID, "a_b_regenerated")
+ eq(t, edgeOf(t, routes, A).Kind, UpstreamSfu)
+ eq(t, edgeOf(t, routes, A).ConnectionID, "a_sfu")
+ noOperation(t, routes.Reconcile(18).Operation)
+}
+
+func TestViewerRoutePreferenceSFUBootstrapDoesNotQueuePeerContinuation(t *testing.T) {
+ routes := newController(2, Options{SfuEnabled: true})
+ for _, peer := range []string{B, C} {
+ addViewer(routes, peer, 0, nil)
+ routes.hydrateEdge(peer, peerEdge(HOST, peer+"_host"))
+ }
+ addViewer(routes, A, 0, nil)
+ op := must(t, routes.Reconcile(0).Operation)
+ eq(t, op.Reason, DemandSfuBootstrap)
+ eq(t, op.ChildPeerID, C)
+ // The carrier selects SFU while its existing bootstrap is being prepared.
+ routes.SetViewerRoutePreference(C, sessionOf(C), protocol.ViewerRouteSfu, ms(1))
+ op = must(t, routes.Reconcile(2).Operation)
+ eq(t, op.Reason, DemandSfuBootstrap)
+ eq(t, op.ChildPeerID, C)
+ prepared := beginOperation(t, routes, BeginInput{NowMs: 3, ConnectionID: "carrier_sfu",
+ PublicationGeneration: "publication", PublicationConnectionID: "publisher",
+ Reservation: sfuCreateOverlap("carrier_subscription", "publication", "publication_overlap")})
+ eq(t, routes.CandidateReady(guardFor(C, prepared.Current.Revision, "carrier_sfu"),
+ 4, nil, CandidateProof{}).Committed, true)
+ eq(t, routes.directContinuations.Has(C), false)
+ op = must(t, routes.Reconcile(5).Operation)
+ eq(t, op.ChildPeerID, A)
+ eqSlice(t, tuples(op), []CandidateTuple{sfuTuple(PublicationReuse)})
+ prepared = beginOperation(t, routes, BeginInput{NowMs: 6, ConnectionID: "a_sfu", Reservation: sfuReuse("a_subscription")})
+ eq(t, routes.CandidateReady(guardFor(A, prepared.Current.Revision, "a_sfu"), 7, nil, CandidateProof{}).Committed, true)
+ noOperation(t, routes.Reconcile(8).Operation)
+ noOperation(t, routes.Reconcile(9).Operation)
+}
+
+func TestViewerRoutePreferenceExhaustionRetainsSFUAnchorForChildRepair(t *testing.T) {
+ routes := newController(1, Options{SfuEnabled: true})
+ addViewer(routes, A, 1, nil)
+ addViewer(routes, B, 1, nil)
+ routes.hydrateHostPublication("publication", res("publication"), "publisher")
+ routes.hydrateEdge(A, sfuEdge("publication", "a_sfu", "subscription"))
+ routes.hydrateEdge(B, peerEdge(A, "a_b"))
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRoutePeer, ms(0))
+ op := must(t, routes.Reconcile(1).Operation)
+ eqSlice(t, tuples(op), []CandidateTuple{peerTuple(HOST)})
+ eq(t, routes.sourceUsable(B), true)
+ routes.SkipCurrentCandidate(cursorGuard(op), 2, RejectionCandidateFailed)
+ eq(t, edgeOf(t, routes, A).PhysicalActive, false)
+ eq(t, routes.Publication() == nil, true)
+ routes.assertGraph()
+ op = must(t, routes.Reconcile(3).Operation)
+ // Retiring the last subscription frees the Host's publication copy. The
+ // existing ledger permits that less disruptive Peer opportunity once.
+ eq(t, op.ChildPeerID, A)
+ eq(t, op.Candidates[0].EndpointTransition.Kind, TransitionNone)
+ routes.SkipCurrentCandidate(cursorGuard(op), 4, RejectionCandidateFailed)
+ op = must(t, routes.Reconcile(5).Operation)
+ eq(t, op.ChildPeerID, B)
+ eq(t, op.Candidates[0].Tuple, peerTuple(HOST))
+ commitCurrent(t, routes, 6, "host_b")
+ eq(t, routes.sourceUsable(B), true)
+ routes.assertGraph()
+}
+
+func TestViewerRoutePreferenceP2PExhaustionThenAuto(t *testing.T) {
+ routes := newController(1, Options{SfuEnabled: true})
+ addViewer(routes, A, 0, nil)
+ addViewer(routes, B, 0, nil)
+ routes.hydrateHostPublication("publication", res("publication"), "publisher")
+ routes.hydrateEdge(A, sfuEdge("publication", "a_sfu", "a_subscription"))
+ routes.hydrateEdge(B, sfuEdge("publication", "b_sfu", "b_subscription"))
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRoutePeer, ms(0))
+ result := routes.Reconcile(1)
+ noOperation(t, result.Operation)
+ eqSlice(t, result.FailedPeerIDs, []string{A})
+ eq(t, hasEdge(routes, A), false)
+ noOperation(t, routes.Reconcile(2).Operation)
+ routes.SetViewerRoutePreference(A, sessionOf(A), protocol.ViewerRouteAuto, ms(3))
+ op := must(t, routes.Reconcile(4).Operation)
+ eq(t, op.ChildPeerID, A)
+ eqSlice(t, tuples(op), []CandidateTuple{sfuTuple(PublicationReuse)})
+}
diff --git a/internal/server/sfu/media.go b/internal/server/sfu/media.go
index 6c4a0184..56d3ba3a 100644
--- a/internal/server/sfu/media.go
+++ b/internal/server/sfu/media.go
@@ -9,6 +9,7 @@ import (
"sync"
"github.com/TNTcraftHIM/Piik/internal/media/forwarding"
+ "github.com/TNTcraftHIM/Piik/internal/media/inputroute"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/pion/interceptor"
"github.com/pion/rtcp"
@@ -74,6 +75,7 @@ type mediaPublication struct {
connectionID string
metadata PublicationMedia
pc *webrtc.PeerConnection
+ input *inputroute.Relay
source *forwarding.Source
audio *webrtc.TrackLocalStaticRTP
ready chan struct{}
@@ -191,6 +193,12 @@ func (media *Media) PreparePublication(fence ResourceFence, connectionID string,
publication.emit(MediaEvent{Candidate: value})
})
pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
+ publication.mu.Lock()
+ input := publication.input
+ publication.mu.Unlock()
+ if input != nil {
+ input.SetUpAvailable(state == webrtc.PeerConnectionStateConnected)
+ }
if state == webrtc.PeerConnectionStateFailed {
publication.fail(errors.New("SFU publisher transport failed"))
return
@@ -198,6 +206,16 @@ func (media *Media) PreparePublication(fence ResourceFence, connectionID string,
publication.emit(MediaEvent{State: state})
})
pc.OnTrack(publication.consumeTrack)
+ pc.OnDataChannel(func(channel *webrtc.DataChannel) {
+ publication.mu.Lock()
+ input := publication.input
+ publication.mu.Unlock()
+ if input != nil {
+ input.AttachUp(channel)
+ } else {
+ _ = channel.Close()
+ }
+ })
media.publications[fence] = publication
go publication.runDemand()
return nil
@@ -323,6 +341,15 @@ func (media *Media) AcceptPublisherOffer(fence ResourceFence, connectionID strin
if offer.Type != webrtc.SDPTypeOffer {
return webrtc.SessionDescription{}, errors.New("SFU publisher requires an offer")
}
+ publication.mu.Lock()
+ if publication.closed {
+ publication.mu.Unlock()
+ return webrtc.SessionDescription{}, errors.New("SFU publication is closed")
+ }
+ if publication.input == nil && strings.Contains(offer.SDP, "\nm=application ") {
+ publication.input = inputroute.New(nil)
+ }
+ publication.mu.Unlock()
if err = publication.pc.SetRemoteDescription(offer); err != nil {
return webrtc.SessionDescription{}, err
}
@@ -580,7 +607,15 @@ func (media *Media) PrepareSubscriber(ctx context.Context, fence SubscriptionFen
return webrtc.SessionDescription{}, errors.New("SFU subscription media is unavailable")
}
subscriber.transport = transport
+ input := publication.input
publication.mu.Unlock()
+ if input != nil {
+ channel, channelErr := transport.PC.CreateDataChannel(inputroute.Label, nil)
+ if channelErr != nil {
+ return webrtc.SessionDescription{}, channelErr
+ }
+ input.AttachDown(fence.ViewerPeerID+":"+connectionID, channel)
+ }
transport.PC.OnICECandidate(func(candidate *webrtc.ICECandidate) {
var value *webrtc.ICECandidateInit
if candidate != nil {
@@ -590,6 +625,9 @@ func (media *Media) PrepareSubscriber(ctx context.Context, fence SubscriptionFen
publication.emitSubscriber(subscriber, MediaEvent{Candidate: value})
})
transport.PC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
+ if input != nil && (state == webrtc.PeerConnectionStateDisconnected || state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed) {
+ input.LoseDown(fence.ViewerPeerID+":"+connectionID, nil)
+ }
if state == webrtc.PeerConnectionStateConnected {
if err := transport.SetConnected(); err != nil {
state = webrtc.PeerConnectionStateFailed
@@ -727,8 +765,12 @@ func (publication *mediaPublication) close() error {
}
}
source := publication.source
+ input := publication.input
publication.mu.Unlock()
publication.closeErr = publication.pc.Close()
+ if input != nil {
+ input.Close()
+ }
for _, transport := range transports {
_ = transport.PC.Close()
}
diff --git a/internal/server/signal/audio_presence.go b/internal/server/signal/audio_presence.go
new file mode 100644
index 00000000..c5cd2aff
--- /dev/null
+++ b/internal/server/signal/audio_presence.go
@@ -0,0 +1,29 @@
+package signal
+
+import "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+
+func (s *Server) setAudioPresence(sess *session, actor *authenticatedSession, message protocol.SetAudioPresenceMessage) {
+ host, ok := s.store.GetConnectedHost(actor.roomID)
+ if actor.role != protocol.RoleHost || !ok || host.SessionID != sess.sessionID ||
+ actor.shareGeneration == "" || actor.shareGeneration != message.ShareGeneration ||
+ s.shares[actor.roomID].generation != message.ShareGeneration {
+ return
+ }
+ share := s.shares[actor.roomID]
+ share.audioAvailable = &message.Available
+ s.shares[actor.roomID] = share
+ s.broadcastAudioPresence(actor.roomID)
+}
+
+func (s *Server) sendAudioPresence(sess *session, roomID string) {
+ if sess == nil || !sess.audioPresence {
+ return
+ }
+ s.send(sess, protocol.AudioPresenceMessage{Type: "audio-presence", Available: s.shares[roomID].audioAvailable})
+}
+
+func (s *Server) broadcastAudioPresence(roomID string) {
+ for _, viewer := range s.store.GetConnectedViewers(roomID) {
+ s.sendAudioPresence(s.sessionsByID[viewer.SessionID], roomID)
+ }
+}
diff --git a/internal/server/signal/audio_presence_test.go b/internal/server/signal/audio_presence_test.go
new file mode 100644
index 00000000..3804f7dc
--- /dev/null
+++ b/internal/server/signal/audio_presence_test.go
@@ -0,0 +1,63 @@
+package signal
+
+import (
+ "testing"
+ "time"
+
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+)
+
+func TestAudioPresenceSubscriptionGenerationAndReconnect(t *testing.T) {
+ h := startHarness(t, harnessOptions{})
+ host := openClient(t, h)
+ const generation = "audio_share_generation_12345678"
+ authenticate(t, host, h.room, protocol.RoleHost, "audio_host_client", 1, generation, presenceOptions{roomSession: true})
+ viewer := openClient(t, h)
+ authenticate(t, viewer, h.room, protocol.RoleViewer, "audio_viewer_client", 1, "", presenceOptions{})
+ legacy := openClient(t, h)
+ authenticate(t, legacy, h.room, protocol.RoleViewer, "legacy_audio_client", 1, "", presenceOptions{})
+ viewer.sendJSON(map[string]any{"type": "subscribe-audio-presence"})
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":null}`)
+ set := func(client *testClient, share string, available bool) {
+ client.sendJSON(map[string]any{"type": "set-audio-presence", "shareGeneration": share, "available": available})
+ }
+ set(host, generation, false)
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":false}`)
+ set(host, generation, true)
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":true}`)
+ if _, ok := legacy.tryNext("audio-presence", 30*time.Millisecond); ok {
+ t.Fatal("legacy Viewer received an unrequested event")
+ }
+ legacy.sendJSON(map[string]any{"type": "subscribe-audio-presence"})
+ expectMatch(t, legacy.next("audio-presence").raw, `{"available":true}`)
+ set(viewer, generation, false)
+ set(host, "replaced_audio_generation", false)
+ if _, ok := viewer.tryNext("audio-presence", 30*time.Millisecond); ok {
+ t.Fatal("non-Host or stale generation changed availability")
+ }
+ h.closeClient(viewer)
+ viewer = openClient(t, h)
+ authenticate(t, viewer, h.room, protocol.RoleViewer, "audio_viewer_client", 1, "", presenceOptions{})
+ viewer.sendJSON(map[string]any{"type": "subscribe-audio-presence"})
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":true}`)
+ h.closeClient(host)
+ host = openClient(t, h)
+ authenticate(t, host, h.room, protocol.RoleHost, "audio_host_client", 1, generation, presenceOptions{roomSession: true})
+ h.locked(func() {
+ available := h.server.shares[h.room.RoomID].audioAvailable
+ if available == nil || !*available {
+ t.Fatal("same-generation Host reconnect lost input availability")
+ }
+ })
+ set(host, generation, false)
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":false}`)
+ host.sendJSON(map[string]any{"type": "stop-sharing", "shareGeneration": generation})
+ // stopSharing clears the room fact before notifying publication retirement.
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":null}`)
+ viewer.next("sharing-stopped")
+ host.sendJSON(map[string]any{"type": "start-sharing", "shareGeneration": "next_audio_generation", "routePolicy": protocol.DefaultRoutePolicy})
+ host.next("sharing-started")
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":null}`)
+ set(host, "next_audio_generation", true)
+ expectMatch(t, viewer.next("audio-presence").raw, `{"available":true}`)
+}
diff --git a/internal/server/signal/presence.go b/internal/server/signal/presence.go
index 94f484a5..318df6b9 100644
--- a/internal/server/signal/presence.go
+++ b/internal/server/signal/presence.go
@@ -148,6 +148,7 @@ func (s *Server) handleDisconnect(sess *session) {
return
}
s.router.disconnectParticipant(disconnected.RoomID, disconnected.PeerID, sess.sessionID)
+ s.sendRemoteInputPeers(disconnected.RoomID)
if disconnected.Role == protocol.RoleHost {
s.broadcastHostStatus(disconnected.RoomID, false, false)
s.sendViewerPresence(disconnected.RoomID)
@@ -182,6 +183,7 @@ func (s *Server) stopSharing(roomID string) {
if current, ok := s.shares[roomID]; ok {
s.shares[roomID] = roomShare{generation: current.generation}
}
+ s.broadcastAudioPresence(roomID)
s.clearRoomViewerEvidence(roomID)
s.router.stopRoom(roomID)
for _, viewer := range s.store.GetConnectedViewers(roomID) {
diff --git a/internal/server/signal/remote_input.go b/internal/server/signal/remote_input.go
new file mode 100644
index 00000000..2757ecd3
--- /dev/null
+++ b/internal/server/signal/remote_input.go
@@ -0,0 +1,48 @@
+package signal
+
+import "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+
+func (s *Server) subscribeRemoteInput(sess *session, actor *authenticatedSession, message protocol.SubscribeRemoteInputMessage) {
+ if sess.remoteInput {
+ return
+ }
+ if actor.role == protocol.RoleViewer {
+ if !protocol.ValidInputKey(message.EndpointID, message.Secret) {
+ return
+ }
+ // One endpoint belongs to one authenticated Viewer, never an identity
+ // supplied by a relay. Keep the binding only for this room session.
+ for _, viewer := range s.store.GetConnectedViewers(actor.roomID) {
+ other := s.sessionsByID[viewer.SessionID]
+ if other != nil && other != sess && other.inputEndpoint == message.EndpointID {
+ return
+ }
+ }
+ sess.inputEndpoint, sess.inputSecret = message.EndpointID, message.Secret
+ } else if message.EndpointID != "" || message.Secret != "" {
+ return
+ }
+ sess.remoteInput = true
+ s.sendRemoteInputPeers(actor.roomID)
+}
+
+// Caller holds Server.mu. Only an opted-in Host receives the keys; observers,
+// relays and older pages cannot acquire them through this subscription.
+func (s *Server) sendRemoteInputPeers(roomID string) {
+ host, ok := s.store.GetConnectedHost(roomID)
+ if !ok {
+ return
+ }
+ target := s.sessionsByID[host.SessionID]
+ if target == nil || !target.remoteInput || !target.open() || target.revoked {
+ return
+ }
+ peers := []protocol.RemoteInputPeer{}
+ for _, viewer := range s.store.GetConnectedViewers(roomID) {
+ current := s.sessionsByID[viewer.SessionID]
+ if current != nil && current.remoteInput && current.open() && !current.revoked && current.inputEndpoint != "" {
+ peers = append(peers, protocol.RemoteInputPeer{PeerID: viewer.PeerID, EndpointID: current.inputEndpoint, Secret: current.inputSecret})
+ }
+ }
+ s.send(target, protocol.RemoteInputPeersMessage{Type: "remote-input-peers", Peers: peers})
+}
diff --git a/internal/server/signal/remote_input_test.go b/internal/server/signal/remote_input_test.go
new file mode 100644
index 00000000..397bb155
--- /dev/null
+++ b/internal/server/signal/remote_input_test.go
@@ -0,0 +1,44 @@
+package signal
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+)
+
+func TestInputKeysBelongToAuthenticatedRoomEndpoints(t *testing.T) {
+ h := startHarness(t, harnessOptions{})
+ host, viewer, other := openClient(t, h), openClient(t, h), openClient(t, h)
+ authenticate(t, host, h.room, protocol.RoleHost, "host_input_test", -1, "", presenceOptions{})
+ actor := authenticate(t, viewer, h.room, protocol.RoleViewer, "viewer_input_test", -1, "", presenceOptions{})
+ authenticate(t, other, h.room, protocol.RoleViewer, "other_input_test", -1, "", presenceOptions{})
+ key := protocol.SubscribeRemoteInputMessage{Type: "subscribe-remote-input", EndpointID: strings.Repeat("1", 32), Secret: strings.Repeat("2", 64)}
+ message := map[string]any{"type": key.Type, "endpointId": key.EndpointID, "secret": key.Secret}
+ viewer.sendJSON(message)
+ if _, ok := host.tryNext("remote-input-peers", 30*time.Millisecond); ok {
+ t.Fatal("unopted Host received a new event")
+ }
+ host.sendJSON(map[string]any{"type": "subscribe-remote-input"})
+ event, err := protocol.DecodeServerMessage(host.next("remote-input-peers").raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ peers := event.(protocol.RemoteInputPeersMessage).Peers
+ if len(peers) != 1 || peers[0].PeerID != actor.PeerID || peers[0].Secret != key.Secret {
+ t.Fatal("key is not bound to authenticated Viewer")
+ }
+ other.sendJSON(message)
+ if _, ok := other.tryNext("remote-input-peers", 30*time.Millisecond); ok {
+ t.Fatal("Viewer received another participant's keys")
+ }
+ if _, ok := host.tryNext("remote-input-peers", 30*time.Millisecond); ok {
+ t.Fatal("second Viewer replaced an occupied endpoint")
+ }
+ h.closeClient(viewer)
+ event, err = protocol.DecodeServerMessage(host.next("remote-input-peers").raw)
+ if err != nil || len(event.(protocol.RemoteInputPeersMessage).Peers) != 0 {
+ t.Fatal("departure retained input authority")
+ }
+}
diff --git a/internal/server/signal/router.go b/internal/server/signal/router.go
index 391ae525..df112db6 100644
--- a/internal/server/signal/router.go
+++ b/internal/server/signal/router.go
@@ -83,11 +83,12 @@ type routerOptions struct {
// authenticatedRouteParticipant carries admitted identity and optional Host policy.
type authenticatedRouteParticipant struct {
- roomID string
- role protocol.Role
- peerID string
- sessionID string
- routePolicy *protocol.RoutePolicy
+ roomID string
+ role protocol.Role
+ peerID string
+ sessionID string
+ routePolicy *protocol.RoutePolicy
+ routePreference *protocol.ViewerRoutePreference
}
// hybridAuthenticationState supplies the joining session's route assignment.
@@ -146,12 +147,18 @@ type peerSignalDebugInput struct {
type roomRuntime struct {
hostPeerID string
controller *route.Controller
- // Capacities survive stopRoom in insertion order.
- advertisedCapacityByViewer ordered.Map[string, int]
- requested bool
- pumping bool
- deadlineStop func() bool
- deadlineGeneration uint64
+ // Viewer choices survive signaling recovery and share replacement, not leave.
+ viewerSettings ordered.Map[string, viewerRouteSettings]
+ requested bool
+ pumping bool
+ deadlineStop func() bool
+ deadlineGeneration uint64
+}
+
+type viewerRouteSettings struct {
+ capacity int
+ // Empty means the page has not opted into route selection.
+ preference protocol.ViewerRoutePreference
}
// router applies controller decisions through room signaling and media resources.
@@ -269,19 +276,29 @@ func (r *router) connectParticipant(input authenticatedRouteParticipant) hybridA
r.createController(input.roomID, rm, input)
}
} else {
- capacity, _ := rm.advertisedCapacityByViewer.Get(input.peerID)
- rm.advertisedCapacityByViewer.Set(input.peerID, capacity)
+ settings, _ := rm.viewerSettings.Get(input.peerID)
+ settings.preference = ""
+ if input.routePreference != nil {
+ settings.preference = *input.routePreference
+ if !r.viewerRouteAllowed(input.roomID, settings.preference) {
+ settings.preference = protocol.ViewerRouteAuto
+ }
+ }
+ rm.viewerSettings.Set(input.peerID, settings)
}
if rm.controller != nil {
capacity := r.capacity
+ var preference protocol.ViewerRoutePreference
if input.role != protocol.RoleHost {
- capacity, _ = rm.advertisedCapacityByViewer.Get(input.peerID)
+ settings, _ := rm.viewerSettings.Get(input.peerID)
+ capacity, preference = settings.capacity, settings.preference
}
r.releaseResources(rm.controller.UpsertParticipant(route.ParticipantInput{
PeerID: input.peerID,
Role: input.role,
SessionID: input.sessionID,
EffectiveDownstreamCapacity: capacity,
+ RoutePreference: preference,
}, r.nowPtr()))
}
state := hybridAuthenticationState{routeAssignment: emptyAssignment()}
@@ -371,8 +388,8 @@ func (r *router) observeSenderQualityEvidence(participant authenticatedRoutePart
before := snapshot.Revision
endpointCapacity := r.capacity
if participant.role != protocol.RoleHost {
- advertised, _ := rm.advertisedCapacityByViewer.Get(participant.peerID)
- endpointCapacity = min(advertised, r.capacity)
+ settings, _ := rm.viewerSettings.Get(participant.peerID)
+ endpointCapacity = min(settings.capacity, r.capacity)
}
copyContext := r.qualityCopyContext(snapshot, rm.hostPeerID, participant.peerID, endpointCapacity, qualitySample{
kind: route.UpstreamPeer,
@@ -691,12 +708,61 @@ func (r *router) debugPeerSignal(input peerSignalDebugInput) {
"authorization", authorization)
}
+func (r *router) viewerRouteAllowed(roomID string, preference protocol.ViewerRoutePreference) bool {
+ if rm, ok := r.rooms.Get(roomID); ok && rm.controller != nil {
+ return rm.controller.AllowsViewerRoutePreference(preference)
+ }
+ return (preference != protocol.ViewerRouteSfu || r.sfu != nil) &&
+ (preference != protocol.ViewerRoutePeer || !r.sfuOnly)
+}
+
+func (r *router) setViewerRoutePreference(participant authenticatedRouteParticipant, preference protocol.ViewerRoutePreference) {
+ rm := r.room(participant.roomID)
+ settings, _ := rm.viewerSettings.Get(participant.peerID)
+ accepted := r.viewerRouteAllowed(participant.roomID, preference)
+ if accepted {
+ settings.preference = preference
+ } else if settings.preference == "" {
+ settings.preference = protocol.ViewerRouteAuto
+ }
+ rm.viewerSettings.Set(participant.peerID, settings)
+ if accepted && rm.controller != nil {
+ before := rm.controller.Revision()
+ r.releaseResources(rm.controller.SetViewerRoutePreference(participant.peerID, participant.sessionID, preference, r.nowPtr()))
+ if rm.controller.Revision() != before {
+ r.broadcastActive(participant.roomID, rm)
+ }
+ }
+ r.sendViewerRoutePreference(participant.roomID, participant.peerID, accepted)
+ if accepted {
+ r.requestPump(participant.roomID)
+ }
+}
+
+func (r *router) sendViewerRoutePreference(roomID, peerID string, accepted bool) {
+ rm, ok := r.rooms.Get(roomID)
+ if !ok {
+ return
+ }
+ settings, _ := rm.viewerSettings.Get(peerID)
+ if settings.preference == "" {
+ return // Published clients that did not opt in receive no new event.
+ }
+ if viewer, ok := r.store.GetConnectedViewer(roomID, peerID); ok {
+ r.hooks.sendToSession(viewer.SessionID, protocol.ViewerRoutePreferenceMessage{
+ Type: "viewer-route-preference", Preference: settings.preference, Accepted: accepted,
+ })
+ }
+}
+
func (r *router) setViewerRelayCapacity(participant authenticatedRouteParticipant, downstreamEdges int) {
rm := r.room(participant.roomID)
r.debug(participant.roomID, "relay-capacity-received",
"participant", r.debugPeer(participant.roomID, participant.peerID),
"downstreamEdges", downstreamEdges)
- rm.advertisedCapacityByViewer.Set(participant.peerID, downstreamEdges)
+ settings, _ := rm.viewerSettings.Get(participant.peerID)
+ settings.capacity = downstreamEdges
+ rm.viewerSettings.Set(participant.peerID, settings)
if rm.controller != nil &&
rm.controller.SetEffectiveCapacity(participant.peerID, participant.sessionID, downstreamEdges, r.nowPtr()) {
r.requestPump(participant.roomID)
@@ -954,33 +1020,24 @@ func (r *router) disconnectParticipant(roomID, peerID, sessionID string) {
func (r *router) removeViewer(roomID, peerID string) {
rm, _ := r.rooms.Get(roomID)
if rm != nil {
- rm.advertisedCapacityByViewer.Delete(peerID)
+ rm.viewerSettings.Delete(peerID)
}
if rm != nil && rm.controller != nil && rm.controller.ConfirmDeparture(peerID, r.nowPtr()) {
r.requestPump(roomID)
- } else if rm != nil && rm.controller == nil && rm.advertisedCapacityByViewer.Len() == 0 {
+ } else if rm != nil && rm.controller == nil && rm.viewerSettings.Len() == 0 {
r.rooms.Delete(roomID)
}
}
-// stopRoom preserves advertised capacities across shares.
+// stopRoom preserves Viewer settings across shares.
func (r *router) stopRoom(roomID string) {
- type capacity struct {
- peerID string
- value int
- }
- var capacities []capacity
+ var settings ordered.Map[string, viewerRouteSettings]
if rm, _ := r.rooms.Get(roomID); rm != nil {
- for peerID, value := range rm.advertisedCapacityByViewer.All() {
- capacities = append(capacities, capacity{peerID, value})
- }
+ settings = rm.viewerSettings
}
r.clearRoom(roomID)
- if len(capacities) > 0 {
- rm := r.room(roomID)
- for _, current := range capacities {
- rm.advertisedCapacityByViewer.Set(current.peerID, current.value)
- }
+ if settings.Len() > 0 {
+ r.room(roomID).viewerSettings = settings
}
}
@@ -1022,12 +1079,18 @@ func (r *router) createController(roomID string, rm *roomRuntime, host authentic
EffectiveDownstreamCapacity: r.capacity,
}, r.nowPtr())
for _, viewer := range r.store.GetConnectedViewers(roomID) {
- capacity, _ := rm.advertisedCapacityByViewer.Get(viewer.PeerID)
+ settings, _ := rm.viewerSettings.Get(viewer.PeerID)
+ if settings.preference != "" && !r.viewerRouteAllowed(roomID, settings.preference) {
+ settings.preference = protocol.ViewerRouteAuto
+ rm.viewerSettings.Set(viewer.PeerID, settings)
+ r.sendViewerRoutePreference(roomID, viewer.PeerID, true)
+ }
rm.controller.UpsertParticipant(route.ParticipantInput{
PeerID: viewer.PeerID,
Role: protocol.RoleViewer,
SessionID: viewer.SessionID,
- EffectiveDownstreamCapacity: capacity,
+ EffectiveDownstreamCapacity: settings.capacity,
+ RoutePreference: settings.preference,
}, r.nowPtr())
}
}
diff --git a/internal/server/signal/server.go b/internal/server/signal/server.go
index 34803f5a..fef5512c 100644
--- a/internal/server/signal/server.go
+++ b/internal/server/signal/server.go
@@ -130,6 +130,7 @@ type roomShare struct {
routePolicy *protocol.RoutePolicy
// pausedGeneration is the share generation the Host paused, "" if none.
pausedGeneration string
+ audioAvailable *bool
}
type senderQualityRateWindow struct {
@@ -713,6 +714,7 @@ type authRequest struct {
token string
viewerGrant string
viewerPassword string
+ routePreference *protocol.ViewerRoutePreference
shareGeneration string
sharingPaused bool
qualitySettings *protocol.QualitySettings
@@ -742,13 +744,14 @@ func authRequestOf(message protocol.ClientMessage) (authRequest, bool) {
}, true
case protocol.AuthenticateViewerMessage:
return authRequest{
- role: protocol.RoleViewer,
- roomID: m.RoomID,
- clientID: m.ClientID,
- viewerGrant: m.ViewerGrant,
- viewerPassword: m.ViewerPassword,
- viewerPresence: m.ViewerPresence,
- displayName: displayNameString(m.DisplayName),
+ role: protocol.RoleViewer,
+ roomID: m.RoomID,
+ clientID: m.ClientID,
+ viewerGrant: m.ViewerGrant,
+ viewerPassword: m.ViewerPassword,
+ routePreference: m.RoutePreference,
+ viewerPresence: m.ViewerPresence,
+ displayName: displayNameString(m.DisplayName),
}, true
}
return authRequest{}, false
@@ -916,6 +919,7 @@ func (s *Server) completeAuthentication(sess *session, request authRequest, part
mediaActive = s.activeHostShareGeneration(roomID) != ""
}
routeParticipant := routeParticipant(sess, authenticated)
+ routeParticipant.routePreference = request.routePreference
if participant.Role == protocol.RoleHost && mediaActive {
policy := s.routePolicyOf(roomID)
routeParticipant.routePolicy = &policy
@@ -1005,6 +1009,9 @@ func (s *Server) completeAuthentication(sess *session, request authRequest, part
Role: protocol.RoleViewer,
})
}
+ if participant.Role == protocol.RoleViewer && request.routePreference != nil {
+ s.router.sendViewerRoutePreference(roomID, participant.PeerID, true)
+ }
if participant.ReplacedSessionID != "" {
if replaced := s.sessionsByID[participant.ReplacedSessionID]; replaced != nil && replaced != sess {
replaced.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Session replaced")
@@ -1104,6 +1111,9 @@ func (s *Server) settleHostShare(roomID, sessionID string, request authRequest)
share.pausedGeneration = shareGeneration
}
s.shares[roomID] = share
+ if currentGeneration != shareGeneration {
+ s.broadcastAudioPresence(roomID)
+ }
return shareGeneration
}
@@ -1185,6 +1195,8 @@ func routeParticipant(sess *session, authenticated *authenticatedSession) authen
func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authenticatedSession, message protocol.ClientMessage) {
switch m := message.(type) {
+ case protocol.SubscribeRemoteInputMessage:
+ s.subscribeRemoteInput(sess, authenticated, m)
case protocol.SubscribeRoomInteractionsMessage:
// Explicit opt-in protects older v23 readers from unknown events.
sess.roomInteractions = true
@@ -1239,6 +1251,12 @@ func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authen
QualitySettings: m.QualitySettings,
})
}
+ case protocol.SetViewerRoutePreferenceMessage:
+ if authenticated.role != protocol.RoleViewer {
+ s.sendError(sess, "FORBIDDEN", "Only a viewer may select an incoming route")
+ return
+ }
+ s.router.setViewerRoutePreference(routeParticipant(sess, authenticated), m.Preference)
case protocol.RelayCapacityMessage:
if authenticated.role != protocol.RoleViewer {
s.sendError(sess, "FORBIDDEN", "Only a viewer may advertise relay capacity")
@@ -1288,6 +1306,13 @@ func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authen
name := string(m.DisplayName)
authenticated.displayName = &name
s.sendViewerPresence(authenticated.roomID)
+ case protocol.SubscribeAudioPresenceMessage:
+ if authenticated.role == protocol.RoleViewer {
+ sess.audioPresence = true
+ s.sendAudioPresence(sess, authenticated.roomID)
+ }
+ case protocol.SetAudioPresenceMessage:
+ s.setAudioPresence(sess, authenticated, m)
case protocol.SetSharingPausedMessage:
if authenticated.role != protocol.RoleHost {
s.sendError(sess, "FORBIDDEN", "只有当前房主可以暂停分享")
@@ -1381,6 +1406,7 @@ func (s *Server) startSharing(sess *session, authenticated *authenticatedSession
share := s.shares[authenticated.roomID]
share.generation = ""
share.pausedGeneration = ""
+ share.audioAvailable = nil
s.shares[authenticated.roomID] = share
request := authRequest{
role: protocol.RoleHost,
diff --git a/internal/server/signal/server_test.go b/internal/server/signal/server_test.go
index 388a8dc1..ab3efd05 100644
--- a/internal/server/signal/server_test.go
+++ b/internal/server/signal/server_test.go
@@ -1011,6 +1011,7 @@ func isMediaReady(entry presenceEntry) bool {
// ---------------------------------------------------------------------------
type presenceOptions struct {
+ routePreference *protocol.ViewerRoutePreference
displayName string
viewerPresence bool
viewerPassword string
@@ -1080,6 +1081,9 @@ func authenticate(
if presence.viewerPresence {
message["viewerPresence"] = true
}
+ if presence.routePreference != nil {
+ message["routePreference"] = *presence.routePreference
+ }
}
client.sendJSON(message)
authenticated := parseAuthenticated(t, client.next("authenticated").raw)
diff --git a/internal/server/signal/session.go b/internal/server/signal/session.go
index 1d9f2f01..c6677640 100644
--- a/internal/server/signal/session.go
+++ b/internal/server/signal/session.go
@@ -54,6 +54,10 @@ type session struct {
lastSignalingChallengeAtMs int64
authenticated *authenticatedSession
roomInteractions bool
+ audioPresence bool
+ remoteInput bool
+ inputEndpoint string
+ inputSecret string
nextInteractionAtMs int64
// authStop stops the authentication deadline; authGeneration is
diff --git a/internal/server/signal/viewer_preference_test.go b/internal/server/signal/viewer_preference_test.go
new file mode 100644
index 00000000..3f087424
--- /dev/null
+++ b/internal/server/signal/viewer_preference_test.go
@@ -0,0 +1,69 @@
+package signal
+
+import (
+ "testing"
+ "time"
+
+ "github.com/TNTcraftHIM/Piik/internal/server/protocol"
+ "github.com/TNTcraftHIM/Piik/internal/server/sfu"
+ "github.com/TNTcraftHIM/Piik/internal/server/sfu/sfutest"
+)
+
+func TestViewerRoutePreferenceOptInPolicyAndReconnect(t *testing.T) {
+ h := startHarness(t, harnessOptions{viewerDisconnectGraceMs: 500})
+ legacy := openClient(t, h)
+ authenticate(t, legacy, h.room, protocol.RoleViewer, "legacy-viewer", -1, "", presenceOptions{})
+ if _, ok := legacy.tryNext("viewer-route-preference", 30*time.Millisecond); ok {
+ t.Fatal("legacy Viewer received a new message without opting in")
+ }
+ viewer := openClient(t, h)
+ preference := protocol.ViewerRoutePeer
+ authenticate(t, viewer, h.room, protocol.RoleViewer, "choice-viewer", -1, "", presenceOptions{routePreference: &preference})
+ expectMatch(t, viewer.next("viewer-route-preference").raw, `{"preference":"p2p","accepted":true}`)
+ viewer.sendJSON(map[string]any{"type": "set-viewer-route-preference", "preference": "sfu"})
+ expectMatch(t, viewer.next("viewer-route-preference").raw, `{"preference":"p2p","accepted":false}`)
+ // The rejected choice does not terminate signaling or change the saved intent.
+ viewer.sendJSON(map[string]any{"type": "signaling-challenge", "sequence": 1})
+ viewer.next("signaling-challenge-response")
+ replacement := openClient(t, h)
+ authenticate(t, replacement, h.room, protocol.RoleViewer, "choice-viewer", -1, "", presenceOptions{routePreference: &preference})
+ expectMatch(t, replacement.next("viewer-route-preference").raw, `{"preference":"p2p","accepted":true}`)
+ if _, ok := legacy.tryNext("viewer-route-preference", 30*time.Millisecond); ok {
+ t.Fatal("Viewer preference was broadcast to legacy peers")
+ }
+ host := openClient(t, h)
+ authenticate(t, host, h.room, protocol.RoleHost, "choice-host", -1, "", presenceOptions{roomOnly: true, roomSession: true})
+ host.sendJSON(map[string]any{"type": "set-viewer-route-preference", "preference": "p2p"})
+ expectMatch(t, host.next("error").raw, `{"code":"FORBIDDEN"}`)
+}
+
+func TestViewerRoutePreferenceCannotOverrideHostOrSite(t *testing.T) {
+ for _, sfuOnly := range []bool{false, true} {
+ t.Run(map[bool]string{false: "host-private", true: "site-sfu-only"}[sfuOnly], func(t *testing.T) {
+ h := startHarness(t, harnessOptions{sfuOnly: sfuOnly, sfu: &SfuFallback{
+ Admission: sfu.NewAdmission(sfu.AdmissionOptions{IngressCapacity: 2, EgressCapacity: 20}),
+ Media: sfutest.New(), PrepareTimeoutMs: 300,
+ }})
+ viewer := openClient(t, h)
+ preference := protocol.ViewerRouteSfu
+ if sfuOnly {
+ preference = protocol.ViewerRoutePeer
+ }
+ authenticate(t, viewer, h.room, protocol.RoleViewer, "policy-viewer", -1, "", presenceOptions{routePreference: &preference})
+ if sfuOnly {
+ expectMatch(t, viewer.next("viewer-route-preference").raw, `{"preference":"auto","accepted":true}`)
+ } else {
+ expectMatch(t, viewer.next("viewer-route-preference").raw, `{"preference":"sfu","accepted":true}`)
+ }
+ host := openClient(t, h)
+ policy := protocol.DefaultRoutePolicy
+ policy.PeerOnly = !sfuOnly
+ authenticate(t, host, h.room, protocol.RoleHost, "policy-host", -1, "policy-share-generation", presenceOptions{routePolicy: &policy})
+ if !sfuOnly {
+ expectMatch(t, viewer.next("viewer-route-preference").raw, `{"preference":"auto","accepted":true}`)
+ }
+ viewer.sendJSON(map[string]any{"type": "set-viewer-route-preference", "preference": preference})
+ expectMatch(t, viewer.next("viewer-route-preference").raw, `{"preference":"auto","accepted":false}`)
+ })
+ }
+}
diff --git a/internal/thirdparty/README.md b/internal/thirdparty/README.md
index 2f387330..46f43cd6 100644
--- a/internal/thirdparty/README.md
+++ b/internal/thirdparty/README.md
@@ -33,18 +33,28 @@ with its original `LICENSE` and `NOTICE`. It uses the existing pinned LiveKit
interfaces; the rest of LiveKit comes from the pinned Go dependency, including
the temporary allocator input described below. No build-time patch is applied.
-Two measurement corrections are marked in the modified files: probe finalization
+Measurement corrections are marked in the modified files: probe finalization
returns the current acknowledged capacity and rejects invalid/empty feedback;
+inconclusive probes use existing backoff from completion without growing the
+next probe or reporting measured congestion;
probe timing begins with its first acknowledged packet, excluding pre-probe idle
-time. Piik's shared forwarding package uses this copy for both individual
-transports and publications. Its regression checks use real TWCC feedback and
-retain the no-feedback and idle-before-probe controls. The
+time; congestion statistics retain the packet that starts each new CTR group,
+including its received/lost accounting; overlapping TWCC feedback changes each
+packet's state once, retaining late ACKs without duplicating counts or moving
+the receive-time baseline. Only new observations advance congestion state.
+Group loss membership covers the packet tracker's history. Delay measurement
+advances in send order with a receive-time watermark, while older ACKs repair
+counts without rewinding it. Reset reseeds that delay baseline without discarding
+delivery history. Piik's shared
+forwarding package uses this copy for both individual transports and publications.
+Its regression checks use real TWCC feedback and retain the no-feedback and
+idle-before-probe controls. The
[media research owner](../../docs/research/node-local-media-design.md#send-queue-recovery)
records the runtime evidence and remaining limits.
The package notice collector still includes LiveKit's upstream license and
notice through the other compiled LiveKit packages. When a maintained upstream
-version covers both corrections and the same regressions pass, remove this
+version covers these corrections and the same regressions pass, remove this
directory and restore the upstream imports. Review dependency bumps against the
named baseline; do not evolve a separate congestion-control algorithm here.
@@ -56,6 +66,12 @@ Piik's former padding writer. Those repairs use the upstream dependency; no
additional LiveKit package is copied here. The local send-side measurement
corrections above remain necessary.
+The dependency also includes [upstream #5018](https://github.com/livekit/livekit/pull/5018)
+and [#5019](https://github.com/livekit/livekit/pull/5019): dummy-start timestamp
+offsets stay within the RTP clock's wrap domain and are cleared on receiver
+restart. These correct layer/source-switch continuity in the existing DownTrack;
+Piik adds no timestamp repair alongside it.
+
The retained detector also includes [upstream #4935](https://github.com/livekit/livekit/pull/4935)
and its regression from v1.13.9, adapted to standard Go assertions. Reserved
TWCC symbols carry no receive delta: skip their measurement rather than consuming
@@ -65,8 +81,8 @@ the next packet's delta or indexing past the feedback array.
Until [upstream #5016](https://github.com/livekit/livekit/pull/5016) is available,
the root module replaces LiveKit with the immutable
-[f10692c6 revision](https://github.com/TNTcraftHIM/livekit/commit/f10692c6f232790ab95a063e24220531eeda6032),
-based on upstream `18df6ad4b694`. Its only changes are an optional local encoder
+[c7f56b38 revision](https://github.com/TNTcraftHIM/livekit/commit/c7f56b38971398d077a0aa5004443eaf3c31016c),
+based on upstream `cde3991916cf`. Its only changes are an optional local encoder
demand input to `StreamAllocator` and regression tests. Native publication uses
that input; ordinary forwarding leaves it unset. The existing allocator still
owns probe timing, congestion response and allocation; encoder demand does not
diff --git a/internal/thirdparty/livekit/sendsidebwe/congestion_detector.go b/internal/thirdparty/livekit/sendsidebwe/congestion_detector.go
index c6c63a1f..9b45b1fe 100644
--- a/internal/thirdparty/livekit/sendsidebwe/congestion_detector.go
+++ b/internal/thirdparty/livekit/sendsidebwe/congestion_detector.go
@@ -13,7 +13,9 @@
// limitations under the License.
// Modified by Piik: finalize probes from valid acknowledged measurements,
-// not the detector's retained initial capacity.
+// not the detector's retained initial capacity; retain packets across CTR groups.
+// Only fresh packet observations may advance congestion state.
+// Inconclusive completed probes back off instead of growing their next duration.
// Includes upstream #4935: consume deltas only for TWCC symbols carrying one.
package sendsidebwe
@@ -576,6 +578,7 @@ func (c *congestionDetector) Reset() {
c.rtt = bwe.DefaultRTT
c.packetGroups = nil
+ c.packetTracker.ResetDelay()
c.probePacketGroup = nil
c.probeRegulator = ccutils.NewProbeRegulator(ccutils.ProbeRegulatorParams{
@@ -689,6 +692,7 @@ func (c *congestionDetector) HandleTWCCFeedback(report *rtcp.TransportLayerCC) {
sequenceNumber := report.BaseSequenceNumber
endSequenceNumberExclusive := sequenceNumber + report.PacketStatusCount
deltaIdx := 0
+ hasNewObservation := false
processSymbol := func(symbol uint16) {
recvTime := int64(0)
isLost := false
@@ -706,6 +710,7 @@ func (c *congestionDetector) HandleTWCCFeedback(report *rtcp.TransportLayerCC) {
}
pi, sendDelta, recvDelta := c.packetTracker.RecordPacketIndicationFromRemote(sequenceNumber, recvTime)
if pi.sendTime != 0 {
+ hasNewObservation = true
trackPacketGroup(&pi, sendDelta, recvDelta, isLost)
}
sequenceNumber++
@@ -736,6 +741,10 @@ func (c *congestionDetector) HandleTWCCFeedback(report *rtcp.TransportLayerCC) {
}
}
+ if !hasNewObservation {
+ c.lock.Unlock()
+ return
+ }
c.prunePacketGroups()
shouldNotify, fromState, toState, committedChannelCapacity := c.congestionDetectionStateMachine()
c.lock.Unlock()
@@ -865,7 +874,16 @@ func (c *congestionDetector) ProbeClusterFinalize() (ccutils.ProbeSignal, int64,
c.estimatedAvailableChannelCapacity = estimatedAvailableChannelCapacity
}
- c.probeRegulator.ProbeSignal(probeSignal, pci.CreatedAt)
+ // The regulator treats every non-congesting input as a successful probe.
+ // Missing or inconclusive feedback proves no headroom: retain that result
+ // for the caller, but retry with the regulator's existing backoff policy.
+ regulatorSignal := probeSignal
+ regulatorBaseTime := pci.CreatedAt
+ if regulatorSignal == ccutils.ProbeSignalInconclusive {
+ regulatorSignal = ccutils.ProbeSignalCongesting
+ regulatorBaseTime = time.Time{} // Back off after completion, including a long feedback wait.
+ }
+ c.probeRegulator.ProbeSignal(regulatorSignal, regulatorBaseTime)
c.probePacketGroup = nil
return probeSignal, estimatedAvailableChannelCapacity, true
}
@@ -1072,6 +1090,8 @@ func (c *congestionDetector) updateCTRTrend(pi *packetInfo, sendDelta, recvDelta
},
c.congestedPacketGroup.PropagatedQueuingDelay(),
)
+ // The old group rejected this packet before accounting for it.
+ _ = c.congestedPacketGroup.Add(pi, sendDelta, recvDelta, isLost)
}
}
diff --git a/internal/thirdparty/livekit/sendsidebwe/congestion_detector_test.go b/internal/thirdparty/livekit/sendsidebwe/congestion_detector_test.go
index c144bfcf..6ed2e628 100644
--- a/internal/thirdparty/livekit/sendsidebwe/congestion_detector_test.go
+++ b/internal/thirdparty/livekit/sendsidebwe/congestion_detector_test.go
@@ -17,15 +17,259 @@ package sendsidebwe
import (
"testing"
+ "time"
+ "github.com/pion/interceptor/pkg/twcc"
"github.com/pion/rtcp"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/mono"
+ "github.com/livekit/livekit-server/pkg/sfu/bwe"
"github.com/livekit/livekit-server/pkg/sfu/ccutils"
)
+func TestHandleTWCCFeedbackReorderingDrainsQueue(t *testing.T) {
+ for _, sustained := range []bool{false, true} {
+ t.Run(map[bool]string{false: "reordered-packet", true: "sustained-queue"}[sustained], func(t *testing.T) {
+ config := defaultCongestionDetectorConfig
+ config.PacketGroup.MinPackets = 2
+ c := newCongestionDetector(congestionDetectorParams{Config: config, Logger: logger.GetDiscardLogger()})
+ now := mono.UnixMicro()
+ c.RecordPacketSendAndGetSequenceNumber(now, 1200, false, 0, false)
+ var sns [400]uint16
+ for i := range sns {
+ sns[i] = c.RecordPacketSendAndGetSequenceNumber(now+int64(i+1)*10_000, 1200, false, 0, false)
+ }
+ recorder := twcc.NewRecorder(1)
+ report := func(packets []rtcp.Packet) {
+ for _, packet := range packets {
+ c.HandleTWCCFeedback(packet.(*rtcp.TransportLayerCC))
+ }
+ }
+ recorder.Record(1, sns[0], 1_100_000)
+ recorder.Record(1, sns[1], 1_210_000)
+ report(recorder.BuildFeedbackPacket())
+ if got := c.packetGroups[len(c.packetGroups)-1].PropagatedQueuingDelay(); got != 100_000 {
+ t.Fatalf("fixture queue = %d, want 100000", got)
+ }
+ c.congestionState = bwe.CongestionStateCongested
+ wantDelay, wantState := int64(0), bwe.CongestionStateNone
+ if sustained {
+ wantDelay, wantState = 100_000, bwe.CongestionStateCongested
+ }
+ for i := 2; i < len(sns); i++ {
+ recorder.Record(1, sns[i], 1_100_000+int64(i)*10_000+wantDelay)
+ if i%10 == 9 {
+ report(recorder.BuildFeedbackPacket())
+ }
+ }
+ last := c.packetGroups[len(c.packetGroups)-1]
+ if delay := last.PropagatedQueuingDelay(); delay != wantDelay || c.CongestionState() != wantState {
+ t.Fatalf("incorrect queue recovery: delay=%v state=%v, want %v/%v", time.Duration(delay)*time.Microsecond, c.CongestionState(), time.Duration(wantDelay)*time.Microsecond, wantState)
+ }
+ if rate := last.Traffic().AcknowledgedBitrate(); rate != 960_000 {
+ t.Fatalf("steady acknowledged bitrate = %d, want 960000", rate)
+ }
+ acked, lost := 0, 0
+ for _, group := range c.packetGroups {
+ acked += group.acked.numPackets()
+ lost += group.lost.numPackets()
+ }
+ if acked != len(sns) || lost != 0 {
+ t.Fatalf("reordering changed packet accounting: acked=%d lost=%d", acked, lost)
+ }
+ })
+ }
+}
+
+func TestHandleTWCCFeedbackAdvancesOnlyOnNewObservations(t *testing.T) {
+ c := newCongestionDetector(congestionDetectorParams{Config: defaultCongestionDetectorConfig, Logger: logger.GetLogger()})
+ now := mono.UnixMicro()
+ c.RecordPacketSendAndGetSequenceNumber(now, 1200, false, ccutils.ProbeClusterIdInvalid, false)
+ recorder := twcc.NewRecorder(1)
+ for i := range 420 {
+ sn := c.RecordPacketSendAndGetSequenceNumber(now+int64(i+1)*10_000, 1200, false, ccutils.ProbeClusterIdInvalid, false)
+ if i%2 == 0 || i == 419 {
+ recorder.Record(1, sn, 1_000_000+int64(i)*10_000)
+ }
+ }
+ reports := recorder.BuildFeedbackPacket()
+ for _, report := range reports {
+ c.HandleTWCCFeedback(report.(*rtcp.TransportLayerCC))
+ }
+ if c.CongestionState() != bwe.CongestionStateEarlyWarning {
+ t.Fatalf("initial loss did not produce early warning: %v", c.CongestionState())
+ }
+ for _, report := range reports {
+ c.HandleTWCCFeedback(report.(*rtcp.TransportLayerCC))
+ }
+ if c.CongestionState() != bwe.CongestionStateEarlyWarning {
+ t.Fatalf("replayed observations advanced congestion: %v", c.CongestionState())
+ }
+ // Fresh feedback must still drive the ordinary congestion response.
+ sn := c.RecordPacketSendAndGetSequenceNumber(now+4_210_000, 1200, false, ccutils.ProbeClusterIdInvalid, false)
+ recorder.Record(1, sn, 5_200_000)
+ for _, report := range recorder.BuildFeedbackPacket() {
+ c.HandleTWCCFeedback(report.(*rtcp.TransportLayerCC))
+ }
+ if c.CongestionState() != bwe.CongestionStateCongested {
+ t.Fatalf("new observations did not advance congestion: %v", c.CongestionState())
+ }
+}
+
+func TestHandleTWCCFeedbackOverlappingReports(t *testing.T) {
+ c := newCongestionDetector(congestionDetectorParams{
+ Config: defaultCongestionDetectorConfig,
+ Logger: logger.GetLogger(),
+ })
+ c.createCTRTrend()
+ c.ProbeClusterStarting(ccutils.ProbeClusterInfo{Id: 1})
+ // Keep the send-time baseline outside the reported sequence.
+ c.RecordPacketSendAndGetSequenceNumber(1_000_000, 1200, false, 1, false)
+ var sns [5]uint16
+ for i := range sns {
+ sns[i] = c.RecordPacketSendAndGetSequenceNumber(1_010_000+int64(i)*10_000, 1200, false, 1, false)
+ }
+ recorder := twcc.NewRecorder(1)
+ var initial *rtcp.TransportLayerCC
+ report := func() {
+ t.Helper()
+ for _, packet := range recorder.BuildFeedbackPacket() {
+ feedback := packet.(*rtcp.TransportLayerCC)
+ if initial == nil {
+ initial = feedback
+ }
+ c.HandleTWCCFeedback(feedback)
+ }
+ }
+ check := func(acked, lost int) {
+ t.Helper()
+ for name, group := range map[string]*packetGroup{
+ "normal": c.packetGroups[0], "probe": c.probePacketGroup.packetGroup, "congested": c.congestedPacketGroup,
+ } {
+ if group.acked.numPackets() != acked || group.lost.numPackets() != lost ||
+ group.acked.numBytes() != acked*1200 || group.lost.numBytes() != lost*1200 {
+ t.Fatalf("%s feedback: ack=%+v lost=%+v, want %d/%d packets", name, group.acked, group.lost, acked, lost)
+ }
+ }
+ }
+ // Pion repeats earlier received/lost packets when a late packet arrives.
+ recorder.Record(1, sns[0], 1_000_000)
+ recorder.Record(1, sns[3], 1_030_000)
+ report()
+ check(2, 2)
+ recorder.Record(1, sns[1], 1_040_000)
+ report()
+ check(3, 1)
+ recorder.Record(1, sns[2], 1_050_000)
+ report()
+ check(4, 0)
+ lastReceived := *c.packetTracker.piLastRecv
+ c.HandleTWCCFeedback(initial)
+ check(4, 0)
+ if *c.packetTracker.piLastRecv != lastReceived {
+ t.Fatal("repeated feedback changed the receive-time baseline")
+ }
+ recorder.Record(1, sns[4], 1_060_000)
+ report()
+ check(5, 0)
+ if got := c.packetTracker.getPacketInfoExisting(sns[4]).recvTime; got != 60_000 {
+ t.Fatalf("receive time after overlapping feedback = %d, want 60000", got)
+ }
+}
+
+func TestHandleTWCCFeedbackLateAcknowledgements(t *testing.T) {
+ for _, reset := range []bool{false, true} {
+ c := newCongestionDetector(congestionDetectorParams{Config: defaultCongestionDetectorConfig, Logger: logger.GetLogger()})
+ now := mono.UnixMicro()
+ c.RecordPacketSendAndGetSequenceNumber(now, 1200, false, 1, false)
+ sns := make([]uint16, 172)
+ for i := range sns {
+ sns[i] = c.RecordPacketSendAndGetSequenceNumber(now+int64(i+1)*1000, 1200, false, 1, false)
+ }
+ c.ProbeClusterStarting(ccutils.ProbeClusterInfo{Id: 1})
+ recorder := twcc.NewRecorder(1)
+ report := func() {
+ for _, packet := range recorder.BuildFeedbackPacket() {
+ c.HandleTWCCFeedback(packet.(*rtcp.TransportLayerCC))
+ }
+ }
+ recorder.Record(1, sns[0], 1_000_000)
+ recorder.Record(1, sns[len(sns)-1], 1_171_000)
+ report()
+ if reset {
+ c.Reset()
+ }
+ for i := 1; i < len(sns)-1; i++ {
+ recorder.Record(1, sns[i], 1_200_000+int64(i)*1000)
+ }
+ report()
+ acked, lost := 0, 0
+ for _, group := range c.packetGroups {
+ acked += group.acked.numPackets()
+ lost += group.lost.numPackets()
+ if traffic := group.Traffic(); traffic.Duration() < 0 || traffic.sendDelta < 0 || traffic.recvDelta < 0 {
+ t.Fatalf("reset=%v: late ACK used a later packet outside its measurement as the baseline: %+v", reset, traffic)
+ }
+ }
+ want := len(sns)
+ if reset {
+ want -= 2
+ }
+ if acked != want || lost != 0 {
+ t.Fatalf("reset=%v: late arrivals left ack=%d lost=%d, want %d/0", reset, acked, lost, want)
+ }
+ if !reset && (c.probePacketGroup.acked.numPackets() != want || c.probePacketGroup.lost.numPackets() != 0) {
+ t.Fatal("probe did not repair its own lost packets")
+ }
+ }
+}
+
+func TestHandleTWCCFeedbackReorderedReportsAcrossReset(t *testing.T) {
+ c := newCongestionDetector(congestionDetectorParams{Config: defaultCongestionDetectorConfig, Logger: logger.GetLogger()})
+ now := mono.UnixMicro()
+ c.RecordPacketSendAndGetSequenceNumber(now, 1200, false, 1, false)
+ a := c.RecordPacketSendAndGetSequenceNumber(now+1000, 1200, false, 1, false)
+ b := c.RecordPacketSendAndGetSequenceNumber(now+2000, 1200, false, 1, false)
+ recorder := twcc.NewRecorder(1)
+ recorder.Record(1, b, 1_000_000)
+ older := recorder.BuildFeedbackPacket()
+ // Pion splits the late arrival from the earlier report at the delta limit.
+ recorder.Record(1, a, 10_000_000)
+ newer := recorder.BuildFeedbackPacket()
+ c.HandleTWCCFeedback(newer[0].(*rtcp.TransportLayerCC))
+ c.Reset()
+ c.HandleTWCCFeedback(older[0].(*rtcp.TransportLayerCC))
+ traffic := c.packetGroups[0].Traffic()
+ if traffic.ackedPackets != 1 || traffic.sendDelta != 0 || traffic.recvDelta != 0 || traffic.Duration() != 0 {
+ t.Fatalf("new measurement inherited a later receive timestamp: %+v", traffic)
+ }
+}
+
+func TestPacketGroupExpiredLossSlot(t *testing.T) {
+ tracker := newPacketTracker(packetTrackerParams{Logger: logger.GetLogger()})
+ group := newPacketGroup(packetGroupParams{Config: defaultPacketGroupConfig}, 0)
+ tracker.RecordPacketSendAndGetSequenceNumber(1_000_000, 1200, false, 0, false)
+ sn := tracker.RecordPacketSendAndGetSequenceNumber(1_001_000, 1200, false, 0, false)
+ lost, _, _ := tracker.RecordPacketIndicationFromRemote(sn, 0)
+ if err := group.Add(&lost, 0, 0, true); err != nil {
+ t.Fatal(err)
+ }
+ // A long quiet/lost stretch can outlive both rings without closing the group.
+ // A new packet in the old bitmap slot must not cancel the expired loss.
+ for i := 1; i <= group.snBitmap.Len(); i++ {
+ sn = tracker.RecordPacketSendAndGetSequenceNumber(1_001_000+int64(i)*1000, 1200, false, 0, false)
+ }
+ acked, sendDelta, recvDelta := tracker.RecordPacketIndicationFromRemote(sn, 6_000_000)
+ if err := group.Add(&acked, sendDelta, recvDelta, false); err != nil {
+ t.Fatal(err)
+ }
+ if group.acked.numPackets() != 1 || group.lost.numPackets() != 1 {
+ t.Fatalf("fresh ACK changed expired loss: ack=%d lost=%d", group.acked.numPackets(), group.lost.numPackets())
+ }
+}
+
// the reserved symbol has no receive delta, so its packet is neither acked nor lost,
// and the next received packet uses the next delta
func TestHandleTWCCFeedbackReservedSymbol(t *testing.T) {
@@ -112,3 +356,38 @@ func TestHandleTWCCFeedbackReservedSymbol(t *testing.T) {
})
}
}
+
+// A feedback packet that closes the previous group still belongs to the next
+// measurement. Losing it biases throughput and loss, especially on sparse video.
+func TestCongestedTrafficAcrossGroupBoundaries(t *testing.T) {
+ for _, lostBoundary := range []bool{false, true} {
+ config := defaultCongestionDetectorConfig
+ config.CongestedPacketGroup.MinPackets = 2
+ c := newCongestionDetector(congestionDetectorParams{Config: config, Logger: logger.GetLogger()})
+ c.createCTRTrend()
+ lastReceived := int64(90_000)
+ for i := range 6 {
+ lost := lostBoundary && i == 2
+ packet := packetInfo{sequenceNumber: uint64(i + 1), sendTime: 100_000 + int64(i)*10_000, size: uint16(100 * (i + 1))}
+ delta := int64(0)
+ if !lost {
+ packet.recvTime = packet.sendTime + 300_000
+ delta = packet.sendTime - lastReceived
+ lastReceived = packet.sendTime
+ }
+ c.updateCTRTrend(&packet, delta, delta, lost)
+ }
+ total := newTrafficStats(trafficStatsParams{Config: config.WeightedLoss})
+ total.Merge(c.congestedTrafficStats)
+ total.Merge(c.congestedPacketGroup.Traffic())
+ ackedPackets, ackedBytes, lostPackets, lostBytes := 6, 2100, 0, 0
+ if lostBoundary {
+ ackedPackets, ackedBytes, lostPackets, lostBytes = 5, 1800, 1, 300
+ }
+ if total.ackedPackets != ackedPackets || total.ackedBytes != ackedBytes ||
+ total.lostPackets != lostPackets || total.lostBytes != lostBytes ||
+ total.Duration() != 60_000 || total.sendDelta != 60_000 || total.recvDelta != 60_000 {
+ t.Fatalf("lost boundary=%v: feedback was not conserved: %+v", lostBoundary, total)
+ }
+ }
+}
diff --git a/internal/thirdparty/livekit/sendsidebwe/packet_group.go b/internal/thirdparty/livekit/sendsidebwe/packet_group.go
index b64727fd..946b809e 100644
--- a/internal/thirdparty/livekit/sendsidebwe/packet_group.go
+++ b/internal/thirdparty/livekit/sendsidebwe/packet_group.go
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+// Modified by Piik: use feedback state; the first receive timestamp can be zero.
+// Track loss membership for the full packet history, independently of ACK count.
package sendsidebwe
import (
@@ -153,7 +155,7 @@ func newPacketGroup(params packetGroupParams, inheritedQueuingDelay int64) *pack
return &packetGroup{
params: params,
inheritedQueuingDelay: inheritedQueuingDelay,
- snBitmap: utils.NewBitmap[uint64](params.Config.MinPackets),
+ snBitmap: utils.NewBitmap[uint64](packetHistorySize),
}
}
@@ -182,17 +184,15 @@ func (p *packetGroup) Add(pi *packetInfo, sendDelta, recvDelta int64, isLost boo
p.maxRecvTime = max(p.maxRecvTime, pi.recvTime)
p.acked.add(int(pi.size), pi.isRTX, pi.isProbe)
- if int(pi.sequenceNumber-p.minSequenceNumber) < p.snBitmap.Len() && p.snBitmap.IsSet(pi.sequenceNumber-p.minSequenceNumber) {
- // an earlier packet reported as lost has been received
- p.snBitmap.Clear(pi.sequenceNumber - p.minSequenceNumber)
+ if pi.feedback == packetFeedbackReceivedAfterLoss && p.snBitmap.IsSet(pi.sequenceNumber) {
+ // Only undo a loss that this group observed. Reset/new groups may see
+ // late ACKs whose earlier loss belonged to a retired measurement.
p.lost.remove(int(pi.size), pi.isRTX, pi.isProbe)
}
+ // Absolute sequence slots cover every packet still in the tracker. A fresh
+ // ACK clears an expired slot without undoing another packet's historical loss.
+ p.snBitmap.Clear(pi.sequenceNumber)
- // note that out-of-order deliveries will amplify the queueing delay.
- // for e.g. a, b, c getting delivered as a, c, b.
- // let us say packets are delivered with interval of `x`
- // send delta aggregate will go up by x((a, c) = 2x + (c, b) -1x)
- // recv delta aggregate will go up by 3x((a, c) = 2x + (c, b) 1x)
p.aggregateSendDelta += sendDelta
p.aggregateRecvDelta += recvDelta
@@ -203,7 +203,7 @@ func (p *packetGroup) Add(pi *packetInfo, sendDelta, recvDelta int64, isLost boo
}
func (p *packetGroup) lostPacket(pi *packetInfo) error {
- if pi.recvTime != 0 {
+ if pi.feedback == packetFeedbackReceived || pi.feedback == packetFeedbackReceivedAfterLoss {
// previously received packet, so not lost
return nil
}
@@ -216,7 +216,7 @@ func (p *packetGroup) lostPacket(pi *packetInfo) error {
p.minSequenceNumber = pi.sequenceNumber
}
p.maxSequenceNumber = max(p.maxSequenceNumber, pi.sequenceNumber)
- p.snBitmap.Set(pi.sequenceNumber - p.minSequenceNumber)
+ p.snBitmap.Set(pi.sequenceNumber)
p.lost.add(int(pi.size), pi.isRTX, pi.isProbe)
return nil
diff --git a/internal/thirdparty/livekit/sendsidebwe/packet_info.go b/internal/thirdparty/livekit/sendsidebwe/packet_info.go
index 730e2a7e..e58c6a5c 100644
--- a/internal/thirdparty/livekit/sendsidebwe/packet_info.go
+++ b/internal/thirdparty/livekit/sendsidebwe/packet_info.go
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+// Modified by Piik: retain each packet's feedback state independently of time.
package sendsidebwe
import (
@@ -19,6 +20,15 @@ import (
"go.uber.org/zap/zapcore"
)
+type packetFeedback uint8
+
+const (
+ packetFeedbackUnknown packetFeedback = iota
+ packetFeedbackLost
+ packetFeedbackReceived
+ packetFeedbackReceivedAfterLoss
+)
+
type packetInfo struct {
sequenceNumber uint64
sendTime int64
@@ -27,6 +37,7 @@ type packetInfo struct {
size uint16
isRTX bool
isProbe bool
+ feedback packetFeedback
}
func (pi *packetInfo) MarshalLogObject(e zapcore.ObjectEncoder) error {
diff --git a/internal/thirdparty/livekit/sendsidebwe/packet_tracker.go b/internal/thirdparty/livekit/sendsidebwe/packet_tracker.go
index a41e50fe..e76dc154 100644
--- a/internal/thirdparty/livekit/sendsidebwe/packet_tracker.go
+++ b/internal/thirdparty/livekit/sendsidebwe/packet_tracker.go
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+// Modified by Piik: apply overlapping feedback once while retaining late ACKs.
+// Keep delay measurement monotonic without discarding packet/loss accounting.
package sendsidebwe
import (
@@ -25,6 +27,8 @@ import (
// -------------------------------------------------------------------------------
+const packetHistorySize = 2048
+
type packetTrackerParams struct {
Logger logger.Logger
}
@@ -37,10 +41,11 @@ type packetTracker struct {
sequenceNumber uint64
baseSendTime int64
- packetInfos [2048]packetInfo
+ packetInfos [packetHistorySize]packetInfo
baseRecvTime int64
piLastRecv *packetInfo
+ lastRecvTime int64
probeClusterId ccutils.ProbeClusterId
probeMaxSequenceNumber uint64
@@ -53,6 +58,15 @@ func newPacketTracker(params packetTrackerParams) *packetTracker {
}
}
+func (p *packetTracker) ResetDelay() {
+ p.lock.Lock()
+ defer p.lock.Unlock()
+
+ // Keep delivery history so overlapping reports cannot count packets twice.
+ p.piLastRecv = nil
+ p.lastRecvTime = 0
+}
+
func (p *packetTracker) RecordPacketSendAndGetSequenceNumber(
atMicro int64,
size int,
@@ -111,21 +125,43 @@ func (p *packetTracker) RecordPacketIndicationFromRemote(sn uint16, recvTime int
return
}
+ // Reports may overlap after reordering. Only new observations may change
+ // counters or the delta baseline; a late ACK must still repair earlier loss.
+ if pi.feedback == packetFeedbackReceived || pi.feedback == packetFeedbackReceivedAfterLoss {
+ return
+ }
if recvTime == 0 {
- // maybe lost OR already received but reported lost in a later report
+ if pi.feedback == packetFeedbackLost {
+ return
+ }
+ pi.feedback = packetFeedbackLost
piRecv = *pi
return
}
+ if pi.feedback == packetFeedbackLost {
+ pi.feedback = packetFeedbackReceivedAfterLoss
+ } else {
+ pi.feedback = packetFeedbackReceived
+ }
if p.baseRecvTime == 0 {
p.baseRecvTime = recvTime
- p.piLastRecv = pi
}
pi.recvTime = recvTime - p.baseRecvTime
piRecv = *pi
if p.piLastRecv != nil {
- sendDelta, recvDelta = pi.sendTime-p.piLastRecv.sendTime, pi.recvTime-p.piLastRecv.recvTime
+ // Historical ACKs repair counts, not the current delay baseline.
+ if pi.sequenceNumber < p.piLastRecv.sequenceNumber {
+ return
+ }
+ sendDelta = pi.sendTime - p.piLastRecv.sendTime
+ // TWCC is in send order, so receive times can go backwards. Retain the
+ // receive watermark while send time advances and drains the old queue.
+ recvDelta = max(0, pi.recvTime-p.lastRecvTime)
+ p.lastRecvTime = max(p.lastRecvTime, pi.recvTime)
+ } else {
+ p.lastRecvTime = pi.recvTime
}
p.piLastRecv = pi
return
diff --git a/native/capture/linux/build.sh b/native/capture/linux/build.sh
index 6601269c..54a6f10f 100644
--- a/native/capture/linux/build.sh
+++ b/native/capture/linux/build.sh
@@ -13,7 +13,7 @@ mkdir -p "$output"
build() {
cc \
-std=c11 -O2 -Wall -Wextra -Werror \
- "$source_root/$1" "$source_root/portal.c" \
+ "$source_root/$1" "$source_root/portal.c" "$source_root/input.c" \
$(pkg-config --cflags --libs \
libportal gstreamer-1.0 gstreamer-app-1.0 gstreamer-video-1.0) \
-o "$output/$2"
@@ -23,4 +23,8 @@ build main.c piik-capture
if [ "${2:-}" = "--check" ]; then
build main.test.c piik-capture-test
"$output/piik-capture-test"
+ cc -std=c11 -O2 -Wall -Wextra -Werror \
+ "$source_root/input.test.c" "$source_root/input.c" \
+ $(pkg-config --cflags --libs libportal) -o "$output/piik-input-test"
+ "$output/piik-input-test"
fi
diff --git a/native/capture/linux/input.c b/native/capture/linux/input.c
new file mode 100644
index 00000000..ac819fc2
--- /dev/null
+++ b/native/capture/linux/input.c
@@ -0,0 +1,57 @@
+#include "portal.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+static const int buttons[] = {272, 274, 273, 275, 276}; // DOM left/middle/right/back/forward
+
+void piik_portal_input_reset(PiikPortalCapture *capture) {
+ if (capture == NULL || !capture->remote_input || capture->session == NULL) return;
+ gboolean active = xdp_session_get_session_state(capture->session) == XDP_SESSION_ACTIVE;
+ for (guint key = 0; key < G_N_ELEMENTS(capture->keys); ++key) {
+ if (active && capture->keys[key]) xdp_session_keyboard_key(capture->session, FALSE, key, XDP_KEY_RELEASED);
+ capture->keys[key] = FALSE;
+ }
+ for (guint button = 0; button < G_N_ELEMENTS(buttons); ++button) {
+ if (active && capture->buttons[button]) xdp_session_pointer_button(capture->session, buttons[button], XDP_BUTTON_RELEASED);
+ capture->buttons[button] = FALSE;
+ }
+}
+
+// Only the App's grant owner writes this private pipe. The Portal session owns
+// the selected screen and OS permission; its teardown also releases held input.
+gboolean piik_portal_input(PiikPortalCapture *capture, const char *command) {
+ if (capture == NULL || !capture->remote_input || capture->session == NULL ||
+ xdp_session_get_session_state(capture->session) != XDP_SESSION_ACTIVE) return FALSE;
+ double x, y;
+ int code, down;
+ char extra;
+ if (strcmp(command, "Z") == 0) {
+ piik_portal_input_reset(capture);
+ } else if (sscanf(command, "M %lf %lf %c", &x, &y, &extra) == 2 && isfinite(x) && isfinite(y) &&
+ x >= 0 && x <= 1 && y >= 0 && y <= 1) {
+ xdp_session_pointer_position(capture->session, capture->node_id,
+ x * (capture->input_width - 1), y * (capture->input_height - 1));
+ } else if (sscanf(command, "R %lf %lf %c", &x, &y, &extra) == 2 && isfinite(x) && isfinite(y) &&
+ fabs(x) <= 32767 && fabs(y) <= 32767) {
+ xdp_session_pointer_motion(capture->session, x, y);
+ } else if (sscanf(command, "K %d %d %c", &code, &down, &extra) == 2 &&
+ code > 0 && code < 256 && (down == 0 || down == 1)) {
+ if (down || capture->keys[code]) xdp_session_keyboard_key(capture->session, FALSE, code, down);
+ capture->keys[code] = down;
+ } else if (sscanf(command, "B %d %d %c", &code, &down, &extra) == 2 &&
+ code >= 0 && code < 5 && (down == 0 || down == 1)) {
+ if (down || capture->buttons[code]) xdp_session_pointer_button(capture->session, buttons[code], down);
+ capture->buttons[code] = down;
+ } else if (sscanf(command, "W %d %c", &code, &extra) == 1 && code >= -1200 && code <= 1200) {
+ // Piik uses positive-up wheel ticks; Portal uses positive-down axis motion.
+ xdp_session_pointer_axis(capture->session, TRUE, 0, -code);
+ } else if (sscanf(command, "U %d %c", &code, &extra) == 1 &&
+ code >= 0 && g_unichar_validate(code) && (code >= 32 || code == '\n' || code == '\t')) {
+ int keysym = code == '\n' ? 0xff0d : code == '\t' ? 0xff09 : code <= 255 ? code : 0x01000000 | code;
+ xdp_session_keyboard_key(capture->session, TRUE, keysym, XDP_KEY_PRESSED);
+ xdp_session_keyboard_key(capture->session, TRUE, keysym, XDP_KEY_RELEASED);
+ } else return FALSE;
+ return TRUE;
+}
diff --git a/native/capture/linux/input.test.c b/native/capture/linux/input.test.c
new file mode 100644
index 00000000..ca7e8b3f
--- /dev/null
+++ b/native/capture/linux/input.test.c
@@ -0,0 +1,71 @@
+// Exercise input semantics without acquiring desktop permission or injecting input.
+#include "portal.h"
+
+static XdpSessionState session_state = XDP_SESSION_ACTIVE;
+static guint events, last_stream;
+static int held_key, held_button, last_keysym;
+static double last_x, last_y;
+
+XdpSessionState xdp_session_get_session_state(XdpSession *session) {
+ (void)session;
+ return session_state;
+}
+void xdp_session_keyboard_key(XdpSession *session, gboolean keysym, int key, XdpKeyState state) {
+ (void)session;
+ ++events;
+ if (keysym) last_keysym = key;
+ else held_key = state == XDP_KEY_PRESSED ? key : 0;
+}
+void xdp_session_pointer_button(XdpSession *session, int button, XdpButtonState state) {
+ (void)session;
+ ++events;
+ held_button = state == XDP_BUTTON_PRESSED ? button : 0;
+}
+void xdp_session_pointer_position(XdpSession *session, guint stream, double x, double y) {
+ (void)session;
+ ++events;
+ last_stream = stream; last_x = x; last_y = y;
+}
+void xdp_session_pointer_motion(XdpSession *session, double x, double y) {
+ (void)session;
+ ++events;
+ last_x = x; last_y = y;
+}
+void xdp_session_pointer_axis(XdpSession *session, gboolean finish, double x, double y) {
+ (void)session; (void)finish;
+ ++events;
+ last_x = x; last_y = y;
+}
+
+int main(void) {
+ PiikPortalCapture capture = {.session = (XdpSession *)&events, .node_id = 42,
+ .input_width = 1920, .input_height = 1080};
+ g_assert_false(piik_portal_input(&capture, "K 30 1"));
+ g_assert_cmpuint(events, ==, 0);
+ capture.remote_input = TRUE;
+ g_assert_true(piik_portal_input(&capture, "M 1 1"));
+ g_assert_cmpuint(last_stream, ==, 42);
+ g_assert_cmpfloat(last_x, ==, 1919);
+ g_assert_cmpfloat(last_y, ==, 1079);
+ g_assert_true(piik_portal_input(&capture, "W -120")); // Browser scroll down.
+ g_assert_cmpfloat(last_x, ==, 0);
+ g_assert_cmpfloat(last_y, ==, 120);
+ g_assert_true(piik_portal_input(&capture, "W 24")); // Fractional scroll up.
+ g_assert_cmpfloat(last_y, ==, -24);
+ g_assert_true(piik_portal_input(&capture, "K 30 1"));
+ g_assert_true(piik_portal_input(&capture, "B 2 1"));
+ g_assert_cmpint(held_key, ==, 30);
+ g_assert_cmpint(held_button, ==, 273);
+ g_assert_true(piik_portal_input(&capture, "U 20013"));
+ g_assert_cmpint(last_keysym, ==, 0x01004e2d);
+ g_assert_true(piik_portal_input(&capture, "Z"));
+ g_assert_cmpint(held_key, ==, 0);
+ g_assert_cmpint(held_button, ==, 0);
+ g_assert_false(piik_portal_input(&capture, "M nan 0"));
+ g_assert_false(piik_portal_input(&capture, "K 256 1"));
+ session_state = XDP_SESSION_CLOSED;
+ guint previous = events;
+ g_assert_false(piik_portal_input(&capture, "K 30 1"));
+ g_assert_cmpuint(events, ==, previous);
+ return 0;
+}
diff --git a/native/capture/linux/main.c b/native/capture/linux/main.c
index c4e6628d..8996fd40 100644
--- a/native/capture/linux/main.c
+++ b/native/capture/linux/main.c
@@ -74,6 +74,7 @@ struct CaptureRun {
guint original_output;
const EncoderInfo *encoder_info;
const char *restore_token;
+ PiikPortalCapture *portal;
GMutex lock;
char *failure;
gint stopping;
@@ -321,9 +322,10 @@ static int write_probe(void) {
json,
"{\"protocol\":%d,\"platform\":\"linux\",\"platformBuild\":%s,"
"\"videoCapture\":%s,\"softwareVP8\":false,\"processAudio\":false,\"systemAudio\":%s,\"microphone\":%s,"
- "\"adapters\":[",
+ "\"remoteInput\":%s,\"adapters\":[",
kCaptureProtocol, build, video ? "true" : "false",
- audio ? "true" : "false", audio ? "true" : "false");
+ audio ? "true" : "false", audio ? "true" : "false",
+ video && piik_portal_input_available() ? "true" : "false");
g_free(build);
if (encoders->len > 0) {
g_string_append(json,
@@ -702,6 +704,7 @@ static gboolean set_output_active(VideoOutput *output, gboolean enabled) {
}
static gboolean apply_control(CaptureRun *run, char *line) {
+ if (g_str_has_prefix(line, "I ")) return piik_portal_input(run->portal, line + 2);
char *values[4] = {0};
guint count = 0;
g_auto(GStrv) tokens = g_strsplit_set(line, " \t\r", -1);
@@ -1025,9 +1028,10 @@ static GstFlowReturn video_sample(GstAppSink *sink, gpointer data) {
char *status = g_strdup_printf(
"{\"state\":\"active\",\"codec\":\"h264\",\"hardwareOnly\":true,"
"\"profileLevelId\":\"%s\",\"width\":%u,\"height\":%u,"
- "\"fps\":%u,\"restoreToken\":%s,\"outputs\":%s}",
+ "\"fps\":%u,\"restoreToken\":%s,\"outputs\":%s,\"remoteInput\":%s}",
nal.profile_level_id, run->profile.width, run->profile.height,
- run->profile.frame_rate, token, profiles);
+ run->profile.frame_rate, token, profiles,
+ run->portal != NULL && run->portal->remote_input ? "true" : "false");
g_free(token);
g_free(profiles);
gboolean active_written = write_status(status);
@@ -1149,6 +1153,12 @@ static char *pipewire_target(const PiikPortalCapture *portal) {
: g_strdup_printf("path=%u", portal->node_id);
}
+static void portal_closed(XdpSession *session, gpointer data) {
+ (void)session;
+ CaptureRun *run = data;
+ fail_run(run, "desktop sharing permission ended");
+}
+
static int capture_video(int count, char **values) {
CaptureRun run = {.last_input_timestamp = GST_CLOCK_TIME_NONE};
gboolean encoded = count > 1 && strcmp(values[1], "--encoded-video") == 0;
@@ -1165,8 +1175,9 @@ static int capture_video(int count, char **values) {
const EncoderInfo *encoder_info = g_ptr_array_index(encoders, encoder_index);
GError *error = NULL;
PiikPortalCapture portal = {.pipewire_fd = -1};
+ gboolean remote_input = g_strcmp0(g_getenv("PIIK_CAPTURE_REMOTE_INPUT"), "1") == 0;
if (!encoded && !piik_portal_capture_open(
- g_getenv("PIIK_XDP_RESTORE_TOKEN"), &portal, &error)) {
+ g_getenv("PIIK_XDP_RESTORE_TOKEN"), remote_input, &portal, &error)) {
fprintf(stderr, "Piik capture unavailable: %s\n",
error == NULL ? "screen selection failed" : error->message);
g_clear_error(&error);
@@ -1222,6 +1233,8 @@ static int capture_video(int count, char **values) {
run.pipeline = pipeline;
run.encoder_info = encoder_info;
run.restore_token = portal.restore_token;
+ run.portal = &portal;
+ if (portal.session != NULL) g_signal_connect(portal.session, "closed", G_CALLBACK(portal_closed), &run);
g_mutex_init(&run.lock);
int result = 2;
GstElement *source = gst_bin_get_by_name(GST_BIN(pipeline), "source");
@@ -1284,8 +1297,9 @@ static int capture_video(int count, char **values) {
"\"adapterIndex\":0,\"adapterName\":%s,"
"\"adapterIdentity\":\"gstreamer-hardware-h264\","
"\"encoderIndex\":%u,\"encoderName\":%s,"
- "\"encoderIdentity\":%s,\"outputs\":%s}",
- adapter_name, encoder_index, encoder_name, encoder_identity, profiles);
+ "\"encoderIdentity\":%s,\"outputs\":%s,\"remoteInput\":%s}",
+ adapter_name, encoder_index, encoder_name, encoder_identity, profiles,
+ portal.remote_input ? "true" : "false");
g_free(adapter_name);
g_free(encoder_name);
g_free(encoder_identity);
@@ -1293,6 +1307,7 @@ static int capture_video(int count, char **values) {
result = run_pipeline(&run, starting);
g_free(starting);
cleanup:
+ if (portal.session != NULL) g_signal_handlers_disconnect_by_data(portal.session, &run);
if (run.encoded_source != NULL) gst_object_unref(run.encoded_source);
for (guint index = 0; index < run.output_count; ++index) {
if (run.outputs[index].encoder != NULL) gst_object_unref(run.outputs[index].encoder);
diff --git a/native/capture/linux/portal.c b/native/capture/linux/portal.c
index 4defa3bf..0c0ad901 100644
--- a/native/capture/linux/portal.c
+++ b/native/capture/linux/portal.c
@@ -3,11 +3,19 @@
#include <gio/gio.h>
#include <unistd.h>
+// Ordinary capture keeps working with the existing system libportal. Remote
+// input needs its restore-capable API to retain the screen across quality changes.
+extern void xdp_portal_create_remote_desktop_session_full(
+ XdpPortal *, XdpDeviceType, XdpOutputType, XdpRemoteDesktopFlags,
+ XdpCursorMode, XdpPersistMode, const char *, GCancellable *,
+ GAsyncReadyCallback, gpointer) __attribute__((weak));
+
typedef struct {
GMainLoop *loop;
XdpPortal *portal;
XdpSession *session;
GError *error;
+ gboolean remote_input;
} PortalRequest;
static void finish_request(PortalRequest *request, GError *error) {
@@ -30,8 +38,9 @@ static void session_created(GObject *source, GAsyncResult *result,
gpointer data) {
PortalRequest *request = data;
GError *error = NULL;
- request->session = xdp_portal_create_screencast_session_finish(
- XDP_PORTAL(source), result, &error);
+ request->session = request->remote_input
+ ? xdp_portal_create_remote_desktop_session_finish(XDP_PORTAL(source), result, &error)
+ : xdp_portal_create_screencast_session_finish(XDP_PORTAL(source), result, &error);
if (request->session == NULL) {
finish_request(request, error);
return;
@@ -62,7 +71,27 @@ gboolean piik_portal_available(void) {
return available;
}
-gboolean piik_portal_capture_open(const char *restore_token,
+gboolean piik_portal_input_available(void) {
+ if (xdp_portal_create_remote_desktop_session_full == NULL) return FALSE;
+ GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
+ if (bus == NULL) return FALSE;
+ GVariant *reply = g_dbus_connection_call_sync(bus,
+ "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop",
+ "org.freedesktop.DBus.Properties", "Get",
+ g_variant_new("(ss)", "org.freedesktop.portal.RemoteDesktop", "AvailableDeviceTypes"),
+ G_VARIANT_TYPE("(v)"), G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL);
+ g_object_unref(bus);
+ if (reply == NULL) return FALSE;
+ GVariant *value = NULL;
+ g_variant_get(reply, "(v)", &value);
+ gboolean available = g_variant_is_of_type(value, G_VARIANT_TYPE_UINT32) &&
+ (g_variant_get_uint32(value) & 3) == 3;
+ g_variant_unref(value);
+ g_variant_unref(reply);
+ return available;
+}
+
+gboolean piik_portal_capture_open(const char *restore_token, gboolean remote_input,
PiikPortalCapture *capture,
GError **error) {
g_return_val_if_fail(capture != NULL, FALSE);
@@ -74,21 +103,40 @@ gboolean piik_portal_capture_open(const char *restore_token,
PortalRequest request = {
.loop = g_main_loop_new(NULL, FALSE),
.portal = capture->portal,
+ .remote_input = remote_input,
};
- xdp_portal_create_screencast_session(
+ const char *token = restore_token != NULL && restore_token[0] != '\0' ? restore_token : NULL;
+ if (remote_input) {
+ if (!piik_portal_input_available()) {
+ g_main_loop_unref(request.loop);
+ g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, "desktop remote input is unavailable");
+ piik_portal_capture_close(capture);
+ return FALSE;
+ }
+ xdp_portal_create_remote_desktop_session_full(
+ capture->portal, XDP_DEVICE_KEYBOARD | XDP_DEVICE_POINTER, XDP_OUTPUT_MONITOR,
+ XDP_REMOTE_DESKTOP_FLAG_NONE, XDP_CURSOR_MODE_EMBEDDED,
+ XDP_PERSIST_MODE_TRANSIENT, token, NULL, session_created, &request);
+ } else xdp_portal_create_screencast_session(
capture->portal, XDP_OUTPUT_MONITOR | XDP_OUTPUT_WINDOW,
XDP_SCREENCAST_FLAG_NONE, XDP_CURSOR_MODE_EMBEDDED,
XDP_PERSIST_MODE_PERSISTENT,
- restore_token != NULL && restore_token[0] != '\0' ? restore_token : NULL,
+ token,
NULL, session_created, &request);
g_main_loop_run(request.loop);
g_main_loop_unref(request.loop);
+ capture->session = request.session;
if (request.error != NULL) {
g_propagate_error(error, request.error);
piik_portal_capture_close(capture);
return FALSE;
}
- capture->session = request.session;
+ capture->remote_input = remote_input;
+ if (remote_input && (xdp_session_get_devices(capture->session) & 3) != 3) {
+ g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED, "keyboard and pointer permission was not granted");
+ piik_portal_capture_close(capture);
+ return FALSE;
+ }
GVariant *streams = xdp_session_get_streams(capture->session);
if (streams == NULL) {
@@ -103,6 +151,10 @@ gboolean piik_portal_capture_open(const char *restore_token,
gboolean found = g_variant_iter_next(&iterator, "(u@a{sv})",
&capture->node_id, &properties);
if (properties != NULL) {
+ if (remote_input) {
+ if (!g_variant_lookup(properties, "logical_size", "(ii)", &capture->input_width, &capture->input_height))
+ g_variant_lookup(properties, "size", "(ii)", &capture->input_width, &capture->input_height);
+ }
guint64 serial = 0;
if (g_variant_lookup(properties, "pipewire-serial", "t", &serial) &&
serial > 0) {
@@ -111,7 +163,7 @@ gboolean piik_portal_capture_open(const char *restore_token,
g_variant_unref(properties);
}
g_variant_unref(streams);
- if (!found || capture->node_id == 0) {
+ if (!found || capture->node_id == 0 || (remote_input && (capture->input_width <= 0 || capture->input_height <= 0))) {
g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_FAILED,
"portal returned an invalid PipeWire stream");
piik_portal_capture_close(capture);
@@ -131,6 +183,7 @@ gboolean piik_portal_capture_open(const char *restore_token,
void piik_portal_capture_close(PiikPortalCapture *capture) {
if (capture == NULL) return;
+ piik_portal_input_reset(capture);
if (capture->pipewire_fd >= 0) close(capture->pipewire_fd);
capture->pipewire_fd = -1;
g_clear_pointer(&capture->restore_token, g_free);
diff --git a/native/capture/linux/portal.h b/native/capture/linux/portal.h
index f4928c76..496c18c9 100644
--- a/native/capture/linux/portal.h
+++ b/native/capture/linux/portal.h
@@ -11,12 +11,18 @@ typedef struct {
char *target_object;
int pipewire_fd;
char *restore_token;
+ gboolean remote_input;
+ gint input_width, input_height;
+ gboolean keys[256], buttons[5];
} PiikPortalCapture;
gboolean piik_portal_available(void);
-gboolean piik_portal_capture_open(const char *restore_token,
+gboolean piik_portal_input_available(void);
+gboolean piik_portal_capture_open(const char *restore_token, gboolean remote_input,
PiikPortalCapture *capture,
GError **error);
void piik_portal_capture_close(PiikPortalCapture *capture);
+gboolean piik_portal_input(PiikPortalCapture *capture, const char *command);
+void piik_portal_input_reset(PiikPortalCapture *capture);
#endif
diff --git a/package-lock.json b/package-lock.json
index 07715038..85335e21 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -7,6 +7,7 @@
"name": "piik",
"license": "MIT",
"devDependencies": {
+ "@oddbird/popover-polyfill": "0.7.3",
"@types/node": "24.13.3",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
@@ -479,6 +480,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@oddbird/popover-polyfill": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/@oddbird/popover-polyfill/-/popover-polyfill-0.7.3.tgz",
+ "integrity": "sha512-uOY7RLqS1M12u+EzZHQ8vPSh3NjwDlb4qwJ1WDzQ0inZ14+47Vv0NNs+1Lh4PtX1nLiiCbfJyIxPRHsgBTvhvg==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
"node_modules/@oxc-project/types": {
"version": "0.144.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.144.0.tgz",
diff --git a/package.json b/package.json
index eefb5f6d..83499dae 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"check": "npm run typecheck && npm test && npm run build"
},
"devDependencies": {
+ "@oddbird/popover-polyfill": "0.7.3",
"@types/node": "24.13.3",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
diff --git a/public/favicon.ico b/public/favicon.ico
index 5ac25e15..022f182f 100644
Binary files a/public/favicon.ico and b/public/favicon.ico differ
diff --git a/public/favicon.png b/public/favicon.png
index 38249675..c7c29487 100644
Binary files a/public/favicon.png and b/public/favicon.png differ
diff --git a/public/favicon.svg b/public/favicon.svg
index c1ddd7ab..f3d12ad6 100644
--- a/public/favicon.svg
+++ b/public/favicon.svg
@@ -1,16 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 128 128" fill="none">
<defs>
- <linearGradient id="tile" x1="24" y1="4" x2="104" y2="128" gradientUnits="userSpaceOnUse"><stop stop-color="#304752"/><stop offset="1" stop-color="#1b2b38"/></linearGradient>
+ <linearGradient id="tile" x1="32" y1="0" x2="96" y2="128" gradientUnits="userSpaceOnUse"><stop stop-color="#2c424b"/><stop offset=".48" stop-color="#233841"/><stop offset="1" stop-color="#1c3039"/></linearGradient>
+ <linearGradient id="edge" x1="40" y1="0" x2="88" y2="128" gradientUnits="userSpaceOnUse"><stop stop-color="#d8e7e8" stop-opacity=".22"/><stop offset=".55" stop-color="#d8e7e8" stop-opacity=".055"/><stop offset="1" stop-color="#d8e7e8" stop-opacity=".025"/></linearGradient>
</defs>
- <style>@media(max-width:24px){.mascot{stroke-width:2.6}}</style>
+ <style>@media(max-width:24px){.mascot{stroke-width:2.7}.sparkle,.rim{display:none}.eye{r:1.5}}</style>
<rect width="128" height="128" rx="28" fill="url(#tile)"/>
- <rect x=".75" y=".75" width="126.5" height="126.5" rx="27.25" stroke="#ffffff" stroke-width="1.5" stroke-opacity=".18"/>
- <g class="mascot" transform="translate(12 10) scale(3.25)" stroke="#e5eee9" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
+ <rect class="rim" x=".6" y=".6" width="126.8" height="126.8" rx="27.4" stroke="url(#edge)" stroke-width="1.2"/>
+ <g class="mascot" transform="translate(0 -2) scale(4)" stroke="#f4f3e9" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
<rect x="4" y="8" width="24" height="18" rx="4"/>
<path d="m11 4 5 4 5-4"/>
<path d="M10 29l2-3m10 3-2-3"/>
- <circle cx="11.5" cy="16.5" r="1.25" fill="#e5eee9" stroke="none"/>
+ <circle class="eye" cx="11.5" cy="16.5" r="1.25" fill="#f4f3e9" stroke="none"/>
<path d="M19 17c1.5-1.8 3.2-1.8 4.7 0"/>
</g>
- <path d="m106 22 2.5 6.5L115 31l-6.5 2.5L106 40l-2.5-6.5L97 31l6.5-2.5Z" fill="#f2c05c"/>
+ <path class="sparkle" d="m112 12 2 5 5 2-5 2-2 5-2-5-5-2 5-2Z" fill="#f2c05c"/>
</svg>
diff --git a/scripts/app-icons.mjs b/scripts/app-icons.mjs
index bee44a9c..99efe5dc 100644
--- a/scripts/app-icons.mjs
+++ b/scripts/app-icons.mjs
@@ -1,5 +1,4 @@
import {
- chmodSync,
mkdirSync,
readFileSync,
writeFileSync,
@@ -131,7 +130,7 @@ function writeMacAssets(packageRoot, version, revision, entries) {
'<plist version="1.0"><dict>',
"<key>CFBundleDevelopmentRegion</key><string>en</string>",
"<key>CFBundleDisplayName</key><string>Piik App</string>",
- "<key>CFBundleExecutable</key><string>launcher</string>",
+ "<key>CFBundleExecutable</key><string>piik-app</string>",
"<key>CFBundleIconFile</key><string>piik.icns</string>",
"<key>CFBundleIdentifier</key><string>tv.piik.app</string>",
"<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>",
@@ -148,19 +147,6 @@ function writeMacAssets(packageRoot, version, revision, entries) {
].join("\n"),
"utf8",
);
- const launcher = join(macos, "launcher");
- writeFileSync(
- launcher,
- [
- "#!/bin/sh",
- "set -eu",
- 'base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
- 'exec "$base/../../../piik-app" "$@"',
- "",
- ].join("\n"),
- "utf8",
- );
- chmodSync(launcher, 0o755);
}
export function writeAppPlatformAssets({
diff --git a/scripts/app-package-targets.mjs b/scripts/app-package-targets.mjs
index 5a693b0c..7df45910 100644
--- a/scripts/app-package-targets.mjs
+++ b/scripts/app-package-targets.mjs
@@ -77,6 +77,12 @@ export function appPackageTarget(id) {
return APP_PACKAGE_TARGETS.find((target) => target.id === id) ?? null;
}
+// Finder can relocate a downloaded .app independently of its ZIP neighbours.
+// Keep the executable and its existing relative runtime paths inside the bundle.
+export function appPackageDirectory(target) {
+ return target.goos === "darwin" ? "Piik App.app/Contents/MacOS" : "";
+}
+
export function goBuildEnvironment(target) {
return {
...process.env,
diff --git a/scripts/assemble-app.mjs b/scripts/assemble-app.mjs
index c42cc270..2fdc0838 100644
--- a/scripts/assemble-app.mjs
+++ b/scripts/assemble-app.mjs
@@ -20,7 +20,7 @@ import {
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import { appPackageTarget, goBuildEnvironment, CLOUDFLARED_VERSION } from "./app-package-targets.mjs";
+import { appPackageTarget, appPackageDirectory, goBuildEnvironment, CLOUDFLARED_VERSION } from "./app-package-targets.mjs";
import { writeAppPlatformAssets } from "./app-icons.mjs";
import { writeAppLicenseNotices } from "./package-licenses.mjs";
import { tarExecutable } from "./archive-tool.mjs";
@@ -213,6 +213,7 @@ if (!existsSync(artifactPath) || sha256(artifactPath) !== descriptor.artifactSha
const temporaryRoot = resetBuildWorkspace(repositoryRoot, "app-package", target.id, "assembly");
const packageRoot = join(temporaryRoot, "package");
+const runtimeRoot = join(packageRoot, appPackageDirectory(target));
const releaseRoot = join(temporaryRoot, "release");
let outputOwned = false;
try {
@@ -227,11 +228,11 @@ try {
// Build the Web assets the Go binary embeds. The checkout is clean and at the
// release revision, so this reproduces that release's Web assets.
runNpm(["run", "build:web"], repositoryRoot);
- mkdirSync(packageRoot, { recursive: true });
+ mkdirSync(runtimeRoot, { recursive: true });
let packagedCapture = null;
if (capturePath) {
- const nativeRoot = join(packageRoot, "runtime", "native");
+ const nativeRoot = join(runtimeRoot, "runtime", "native");
mkdirSync(nativeRoot, { recursive: true });
packagedCapture = join(nativeRoot, target.captureName);
copyFileSync(capturePath, packagedCapture);
@@ -240,7 +241,7 @@ try {
let packagedTunnel = null;
if (tunnelPath) {
- const tunnelRoot = join(packageRoot, "runtime", "tunnel");
+ const tunnelRoot = join(runtimeRoot, "runtime", "tunnel");
mkdirSync(tunnelRoot, { recursive: true });
const tunnelName = target.tunnelName;
packagedTunnel = join(tunnelRoot, tunnelName);
@@ -249,7 +250,7 @@ try {
}
const appName = target.appName;
- const appPath = join(packageRoot, appName);
+ const appPath = join(runtimeRoot, appName);
const goCommand = process.env.PIIK_GO?.trim() || "go";
run(goCommand, [
"build",
@@ -262,7 +263,7 @@ try {
], repositoryRoot, goBuildEnvironment(target));
chmodSync(appPath, 0o755);
assertTargetExecutable(appPath, target, "App executable");
- writeAppLicenseNotices(repositoryRoot, packageRoot, goCommand, target,
+ writeAppLicenseNotices(repositoryRoot, runtimeRoot, goCommand, target,
packagedTunnel ? CLOUDFLARED_VERSION : null);
const platformAssets = writeAppPlatformAssets({
packageRoot,
@@ -271,7 +272,7 @@ try {
revision,
iconPath: join(repositoryRoot, "cmd", "piik-app", "piik.ico"),
});
- writeFileSync(join(packageRoot, "REVISION"), `${revision}\n`, "ascii");
+ writeFileSync(join(runtimeRoot, "REVISION"), `${revision}\n`, "ascii");
assertCleanRevision(repositoryRoot, revision);
mkdirSync(dirname(outputRoot), { recursive: true });
@@ -289,11 +290,9 @@ try {
target: target.id,
platform: target.goos,
arch: target.goarch,
- app: appName,
- nativeCapture: packagedCapture ? `runtime/native/${target.captureName}` : null,
- publicTunnel: packagedTunnel
- ? `runtime/tunnel/${target.tunnelName}`
- : null,
+ app: relative(packageRoot, appPath).replaceAll("\\", "/"),
+ nativeCapture: packagedCapture ? relative(packageRoot, packagedCapture).replaceAll("\\", "/") : null,
+ publicTunnel: packagedTunnel ? relative(packageRoot, packagedTunnel).replaceAll("\\", "/") : null,
platformAssets,
})}\n`);
} catch (error) {
diff --git a/scripts/package-app-candidate.mjs b/scripts/package-app-candidate.mjs
index 16f915f6..48648599 100644
--- a/scripts/package-app-candidate.mjs
+++ b/scripts/package-app-candidate.mjs
@@ -20,7 +20,7 @@ import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { fileURLToPath } from "node:url";
-import { appPackageTarget, CLOUDFLARED_VERSION } from "./app-package-targets.mjs";
+import { appPackageTarget, appPackageDirectory, CLOUDFLARED_VERSION } from "./app-package-targets.mjs";
import { createZip, extractZip, tarExecutable } from "./archive-tool.mjs";
import { assertCleanRevision, resetBuildWorkspace } from "./build-workspace.mjs";
@@ -238,27 +238,28 @@ async function verifyLocalPackage(root, target, temporaryRoot) {
}
async function verifyPackage(root, target, revision, temporaryRoot) {
- const packagedRevision = readFileSync(join(root, "REVISION"), "ascii").trim();
+ const runtimeRoot = join(root, appPackageDirectory(target));
+ const packagedRevision = readFileSync(join(runtimeRoot, "REVISION"), "ascii").trim();
if (packagedRevision !== revision) fail("App package revision mismatch");
for (const file of ["LICENSE", "THIRD-PARTY-NOTICES.txt",
"runtime/tunnel/THIRD-PARTY-NOTICES.txt"]) {
- if (!existsSync(join(root, file)) || readFileSync(join(root, file)).length === 0) {
+ if (!existsSync(join(runtimeRoot, file)) || readFileSync(join(runtimeRoot, file)).length === 0) {
fail(`App package license text is missing: ${file}`);
}
}
- const app = join(root, target.appName);
- const tunnel = join(root, "runtime", "tunnel", target.tunnelName);
+ const app = join(runtimeRoot, target.appName);
+ const tunnel = join(runtimeRoot, "runtime", "tunnel", target.tunnelName);
run(app, ["--help"], root);
run(tunnel, ["--version"], root);
verifyPlatformAssets(root, target);
if (target.captureName) {
- const capture = join(root, "runtime", "native", target.captureName);
+ const capture = join(runtimeRoot, "runtime", "native", target.captureName);
const probe = JSON.parse(run(capture, ["--probe"], root));
if (probe?.protocol !== 7) fail("Packaged native capture probe is invalid");
}
- await verifyLocalPackage(root, target, temporaryRoot);
+ await verifyLocalPackage(runtimeRoot, target, temporaryRoot);
}
function verifyPlatformAssets(root, target) {
@@ -288,23 +289,23 @@ function verifyPlatformAssets(root, target) {
}
if (target.goos === "darwin") {
const bundle = join(root, "Piik App.app");
- const launcher = join(bundle, "Contents", "MacOS", "launcher");
+ const executable = join(bundle, "Contents", "MacOS", target.appName);
const plist = join(bundle, "Contents", "Info.plist");
const icon = join(bundle, "Contents", "Resources", "piik.icns");
- if (!existsSync(launcher) || !existsSync(plist) || !existsSync(icon)) {
- fail("macOS App app icon assets are missing");
+ if (!existsSync(executable) || !existsSync(plist) || !existsSync(icon)) {
+ fail("macOS App bundle is incomplete");
}
if (!readFileSync(icon).subarray(0, 4).equals(Buffer.from("icns"))) {
fail("macOS App icon is not ICNS");
}
const plistText = readFileSync(plist, "utf8");
if (
+ !plistText.includes(`<key>CFBundleExecutable</key><string>${target.appName}</string>`) ||
!plistText.includes("<key>NSScreenCaptureUsageDescription</key>") ||
!plistText.includes("<key>NSAudioCaptureUsageDescription</key>")
) {
- fail("macOS App capture usage descriptions are missing");
+ fail("macOS App entry or capture usage descriptions are missing");
}
- if (process.platform === "darwin") run(launcher, ["--help"], root);
}
}
diff --git a/scripts/package-licenses.mjs b/scripts/package-licenses.mjs
index 3ac89480..3cb5cf3d 100644
--- a/scripts/package-licenses.mjs
+++ b/scripts/package-licenses.mjs
@@ -14,7 +14,7 @@ const section = (label, body) => `\n===== ${label} =====\n\n${body.trim()}\n`;
// The packages the Vite bundle ships to the Browser. Nothing installs
// node_modules at runtime any more, so this list is the notice contract rather
// than package.json's dependencies field.
-const WEB_BUNDLE_PACKAGES = ["react", "react-dom", "sdp-transform", "semver", "zod"];
+const WEB_BUNDLE_PACKAGES = ["@oddbird/popover-polyfill", "react", "react-dom", "sdp-transform", "semver", "zod"];
// Both binaries embed the Web bundle, which serves its own notice file.
const WEB_NOTICE_LINE = "Web dependencies: served at /third-party-licenses.txt\n";
diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.ts
index 444dda8b..609471c4 100644
--- a/scripts/peer-assisted-benchmark.ts
+++ b/scripts/peer-assisted-benchmark.ts
@@ -2545,7 +2545,7 @@ async function startHost(
5_000, "sharing settings", signal);
if (codecMode !== "auto") {
await evaluate(cdp, page, `(() => {
- const technical = document.querySelector('#host-advanced-door details');
+ const technical = document.querySelector('#host-advanced-door .lr-sharing-technical');
if (technical instanceof HTMLDetailsElement && !technical.open) technical.querySelector('summary')?.click();
})()`);
await waitForPage(
diff --git a/site/docs/.vitepress/theme/style.css b/site/docs/.vitepress/theme/style.css
index 8334f24e..e5dc8de2 100644
--- a/site/docs/.vitepress/theme/style.css
+++ b/site/docs/.vitepress/theme/style.css
@@ -1,30 +1,19 @@
+@import "../../../../src/client/ui/palette.css";
+
:root {
--vp-font-family-base: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
--vp-font-family-mono: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace;
- --vp-c-brand-1: #256b47;
- --vp-c-brand-2: #367b57;
- --vp-c-brand-3: #256b47;
- --vp-c-brand-soft: #256b4718;
- --vp-c-bg: #fafaf3;
- --vp-c-bg-alt: #e9f2ee;
- --vp-c-bg-soft: #e9f2ee;
- --vp-c-text-1: #22303e;
- --vp-c-text-2: #52635e;
- --vp-c-divider: #c6d6cc;
- --vp-code-block-bg: #e9f2ee;
-}
-.dark {
- --vp-c-brand-1: #9bdbb2;
- --vp-c-brand-2: #b0e6c3;
- --vp-c-brand-3: #9bdbb2;
- --vp-c-brand-soft: #9bdbb218;
- --vp-c-bg: #1b2d34;
- --vp-c-bg-alt: #14232b;
- --vp-c-bg-soft: #14232b;
- --vp-c-text-1: #eef4eb;
- --vp-c-text-2: #b3c4bd;
- --vp-c-divider: #3b5155;
- --vp-code-block-bg: #14232b;
+ --vp-c-brand-1: var(--action-text);
+ --vp-c-brand-2: var(--action);
+ --vp-c-brand-3: var(--action-deep);
+ --vp-c-brand-soft: color-mix(in srgb, var(--action) 10%, transparent);
+ --vp-c-bg: var(--paper);
+ --vp-c-bg-alt: var(--wall);
+ --vp-c-bg-soft: var(--wall);
+ --vp-c-text-1: var(--ink);
+ --vp-c-text-2: var(--muted);
+ --vp-c-divider: var(--line);
+ --vp-code-block-bg: var(--wall);
}
.VPNavBarTitle .identity { gap: 8px; font-size: 24px; letter-spacing: -.045em; }
.VPNavBarTitle .mascot { width: 30px; height: 30px; }
diff --git a/site/film/film.css b/site/film/film.css
index 3c804213..1e410c93 100644
--- a/site/film/film.css
+++ b/site/film/film.css
@@ -1,7 +1,8 @@
-:root { color-scheme: light; --wall:#e9f2ee; --paper:#fafaf3; --ink:#22303e; --muted:#52635e; --line:#c6d6cc; --accent:#e4572e; }
-@media (prefers-color-scheme:dark) { :root { color-scheme:dark; --wall:#14232b; --paper:#1b2d34; --ink:#eef4eb; --muted:#b3c4bd; --line:#3b5155; --accent:#f28d66; } }
-:root[data-theme="light"] { color-scheme:light; --wall:#e9f2ee; --paper:#fafaf3; --ink:#22303e; --muted:#52635e; --line:#c6d6cc; --accent:#e4572e; }
-:root[data-theme="dark"] { color-scheme:dark; --wall:#14232b; --paper:#1b2d34; --ink:#eef4eb; --muted:#b3c4bd; --line:#3b5155; --accent:#f28d66; }
+@import "../../src/client/ui/palette.css";
+@import "../../src/client/components/living/button.css";
+:root { color-scheme: light; --accent:#e4572e; }
+@media (prefers-color-scheme:dark) { :root:not([data-theme="light"]) { color-scheme:dark; --wall:var(--piik-dark-wall); --paper:var(--piik-dark-paper); --ink:var(--piik-dark-ink); --accent:#f28d66; } }
+:root[data-theme="dark"] { color-scheme:dark; --accent:#f28d66; }
* { box-sizing:border-box; }
:root { --spring:cubic-bezier(.3,1.45,.45,1); }
body { margin:0; background:var(--wall); color:var(--ink); font:15px/1.6 ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; -webkit-font-smoothing:antialiased; }
@@ -35,9 +36,9 @@ body[data-ready] .fallback { display:none; }
.play-film svg { width:23px; height:23px; }
.duration { padding-left:14px; border-left:1px solid #ffffff45; color:#b6c9c2; font-size:12px; font-weight:500; font-variant-numeric:tabular-nums; }
.quiet-play { min-height:44px; padding:6px 14px; font-size:12px; color:#52635e; }
-.play-film { transition:transform .22s cubic-bezier(.2,.9,.3,1.4),background .2s; }
-.play-film:hover { transform:translateY(-3px); background:#314557; }
-.play-film:active { transform:translateY(2px); }
+.play-film { transition:var(--control-motion),background .2s; }
+.play-film:is(:hover,:focus-visible) { transform:var(--control-hover-transform); background:#314557; }
+.play-film:active { transform:var(--control-press-transform); box-shadow:none; transition-duration:80ms; }
#reduced-note { flex-basis:100%; text-align:center; font-size:12px; margin:0; }
.transport { --wall-2:#ffffff18; position:relative; display:flex; align-items:center; gap:4px; width:min(620px,calc(100% - 48px)); margin:12px auto 14px; border:1px solid #ffffff20; border-radius:16px; padding:4px 10px; background:rgb(34 48 62 / 78%); color:#fafaf3; box-shadow:0 4px 20px #14232b15; }
.lr-btn svg { display:block; }
diff --git a/site/film/index.html b/site/film/index.html
index 8258eec8..1461196d 100644
--- a/site/film/index.html
+++ b/site/film/index.html
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
- <meta name="theme-color" content="#e9f2ee" />
+ <meta name="theme-color" content="#f4f3ef" />
<meta name="description" content="Share the good stuff. See how Piik shares games, movies, drawings and photos with friends, in a 76-second film." />
<title>Piik — Share the good stuff.</title>
<link rel="icon" href="../favicon.ico" />
diff --git a/site/film/ui/main.tsx b/site/film/ui/main.tsx
index b0e7d9f7..100f1262 100644
--- a/site/film/ui/main.tsx
+++ b/site/film/ui/main.tsx
@@ -15,8 +15,9 @@ import {
import { CaptureSourcePicker } from "../../../src/client/components/living/CaptureSourcePicker";
import { RoomInteractions } from "../../../src/client/components/living/RoomInteractions";
import { RoomInteractionSession } from "../../../src/client/lib/room-interactions";
-import { RoomChatToggle } from "../../../src/client/components/living/RoomChatOverlay";
+import { RoomChatOverlaySettings, RoomChatToggle } from "../../../src/client/components/living/RoomChatOverlay";
import { HostMicrophone } from "../../../src/client/components/living/HostMicrophone";
+import { HostShareControls } from "../../../src/client/components/living/HostShareControls";
import { PlaybackControlsView } from "../../../src/client/components/living/PlaybackControls";
import { StatusIndicator } from "../../../src/client/components/living/StatusIndicator";
import { Lcd, RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../../../src/client/components/living/RoomChip";
@@ -235,7 +236,7 @@ function Screen({ shot }: { shot: Shot }) {
picture={{ supported: true, active: false, failed: false, toggle: async () => {} }}
togglePlayback={noop} toggleFullscreen={noop} toggleMute={noop} setLevel={noop}
onToggleTheater={noop} onReconnect={noop} reconnectAvailable
- extraActions={<RoomChatToggle session={session} />} />}
+ overlayAction={<RoomChatToggle session={session} />} overlaySettings={<RoomChatOverlaySettings session={session} />} />}
{shot === "picker" && (
<CaptureSourcePicker
nativeSources={{
@@ -278,15 +279,14 @@ function Screen({ shot }: { shot: Shot }) {
</div>
)}
</StageTv>
- {!viewer && <div className="lr-host-share-controls lr-media-controls" role="group" aria-label={t("host.shareControls")}>
+ {!viewer && <HostShareControls actions={live ? <>
<HostMicrophone enabled={false} volume={1} onToggle={noop} />
- {live && <>
- <Btn icon="pause" cap="host.pause" title="host.pause" hint="hint-pause" draw="host-share-toggle" />
<Btn icon="switchSource" cap="host.switchSource" title="host.switchSource" hint="hint-switch-source" />
- </>}
- <Btn icon="sliders" cap="host.settings.button" title="host.advanced" hint="hint-advanced" expanded={false} />
- {live && <Btn icon="stop" tone="danger" cap="host.stop" title="host.stop" hint="hint-share-stop" />}
- </div>}
+ </> : null}
+ settings={<Btn icon="sliders" cap="host.settings.button" title="host.advanced" hint="hint-advanced" expanded={false} />}
+ pause={live && <Btn icon="pause" cap="host.pause" title="host.pause" hint="hint-pause" draw="host-share-toggle" />}
+ ending={live && <Btn icon="stop" tone="danger" cap="host.stop" title="host.stop" hint="hint-share-stop" />}
+ />}
<div className="lr-stage-notices" />
<RoomInteractions
session={live ? session : null}
@@ -366,7 +366,7 @@ function Screen({ shot }: { shot: Shot }) {
</div>
<span className="lr-divider" aria-hidden="true" />
<RowGroup>
- <span className="lr-toggle" role="group" aria-label={t("host.policy")} data-selected="private">
+ <span className="lr-toggle" role="group" aria-label={t("host.policy")}>
<button type="button" aria-pressed={false}><Glyph name="globe" size={19} /><Cap k="host.policy.open" /></button>
<button type="button" className="is-selected" aria-pressed><Glyph name="lock" size={19} /><Cap k="host.policy.private" /></button>
</span>
diff --git a/site/index.html b/site/index.html
index 1e69e61b..2275f682 100644
--- a/site/index.html
+++ b/site/index.html
@@ -8,7 +8,7 @@
name="description"
content="Free, open-source screen sharing for private live streams with friends. Share games, watch movies together, or self-host Piik. Viewers join in a browser."
/>
- <meta name="theme-color" content="#e9f2ee" />
+ <meta name="theme-color" content="#f4f3ef" />
<title>Piik — Free, open-source screen sharing</title>
<link rel="canonical" href="https://piik.tv/" />
<link rel="icon" href="./favicon.ico" />
@@ -738,8 +738,8 @@
</p>
</div>
<p class="release-note" id="download-status">
- <span lang="en">Choose your system, then download and extract.<br /><strong>2.0 and 1.x are incompatible.</strong> Update the App and its Site together, then refresh your browser. <a href="./docs/getting-started.html?lang=en#upgrading">Upgrade guide</a></span>
- <span lang="zh-CN">选择对应系统,下载后解压。<br /><strong>2.0 与 1.x 不兼容。</strong>App 与所用站点需要一起升级,随后刷新网页。<a href="./docs/zh/getting-started.html#版本升级">升级说明</a></span>
+ <span lang="en">Choose your system, then download and extract.<br /><strong>2.x and 1.x are incompatible.</strong> When upgrading from 1.x, update the App and its Site together, then refresh your browser. <a href="./docs/getting-started.html?lang=en#upgrading">Upgrade guide</a></span>
+ <span lang="zh-CN">选择对应系统,下载后解压。<br /><strong>2.x 与 1.x 不兼容。</strong>从 1.x 升级时,App 与所用站点需要一起更新,随后刷新网页。<a href="./docs/zh/getting-started.html#版本升级">升级说明</a></span>
</p>
<div class="download-cards">
<article class="download-card" aria-labelledby="download-windows">
@@ -826,7 +826,7 @@
</article>
</div>
<div class="download-help">
- <a class="button" href="https://github.com/TNTcraftHIM/Piik/releases"><span lang="en">More downloads</span><span lang="zh-CN">更多下载</span><span aria-hidden="true"> ↗</span></a>
+ <a class="button" href="https://github.com/TNTcraftHIM/Piik"><span lang="en">View on GitHub</span><span lang="zh-CN">GitHub 项目</span><span aria-hidden="true"> ↗</span></a>
<p><span lang="en">Physical-device coverage for the macOS and Linux apps is still limited. If you have a device, we'd welcome your <a href="https://github.com/TNTcraftHIM/Piik/issues">test results and feedback</a>.</span><span lang="zh-CN">macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span></p>
</div>
</section>
diff --git a/site/styles.css b/site/styles.css
index 49859fdb..8f05e9a7 100644
--- a/site/styles.css
+++ b/site/styles.css
@@ -1,18 +1,12 @@
+@import "../src/client/ui/palette.css";
@import "../src/client/components/living/language-control.css";
@import "../src/client/components/living/button.css";
@import "../src/client/ui/glyph.css";
:root {
color-scheme: light;
- --wall: #e9f2ee;
- --paper: #fafaf3;
- --ink: #22303e;
- --muted: #52635e;
- --line: #c6d6cc;
- --green: #256b47;
--orange: #e4572e;
--soft-orange: #f7e5cc;
- --button-ink: #fafaf3;
--drawing: #22303e;
--art-mint: #c4e3ce;
--art-paper: #fffdf4;
@@ -24,15 +18,11 @@
--couch-dark: #cd8845;
--comic-beat: 3.2s;
--spring: cubic-bezier(.3, 1.45, .45, 1);
- --wall-2: color-mix(in srgb, var(--ink) 7%, var(--paper));
- --control-edge: color-mix(in srgb, var(--ink) 62%, var(--paper));
- --control-hover: var(--wall-2);
- --control-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 13%, transparent);
}
@media (prefers-color-scheme: dark) {
- :root:not([data-theme="light"]) { color-scheme: dark; --wall: #14232b; --paper: #1b2d34; --ink: #eef4eb; --muted: #b3c4bd; --line: #3b5155; --green: #9bdbb2; --orange: #f28d66; --soft-orange: #3d342c; --button-ink: #14232b; }
+ :root:not([data-theme="light"]) { color-scheme: dark; --wall: var(--piik-dark-wall); --paper: var(--piik-dark-paper); --ink: var(--piik-dark-ink); --wall-2: var(--piik-dark-wall-2); --control-hover: var(--piik-dark-hover); --action: var(--piik-dark-action); --action-deep: var(--piik-dark-action); --action-ink: var(--piik-dark-action-ink); --action-text: var(--piik-dark-action-text); --control-selected: var(--piik-dark-selected); --control-selected-ink: var(--piik-dark-selected-ink); --orange: #f28d66; --soft-orange: #3d342c; }
}
-:root[data-theme="dark"] { color-scheme: dark; --wall: #14232b; --paper: #1b2d34; --ink: #eef4eb; --muted: #b3c4bd; --line: #3b5155; --green: #9bdbb2; --orange: #f28d66; --soft-orange: #3d342c; --button-ink: #14232b; }
+:root[data-theme="dark"] { color-scheme: dark; --orange: #f28d66; --soft-orange: #3d342c; }
* { box-sizing: border-box; }
html { scroll-behavior: smooth; scroll-padding-top: 30px; }
body { margin: 0; background: var(--wall); color: var(--ink); font: 16px/1.6 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; -webkit-font-smoothing: antialiased; }
@@ -45,7 +35,7 @@ button, select { font: inherit; color: inherit; }
button, select, summary { cursor: pointer; }
button { background: none; }
button, a, select, summary { -webkit-tap-highlight-color: transparent; touch-action: manipulation; }
-:focus-visible { outline: 3px solid var(--orange); outline-offset: 5px; }
+:focus-visible { outline: 3px solid var(--action); outline-offset: 5px; }
h1, h2, h3, p { margin: 0; }
h1, h2, h3 { text-wrap: balance; }
.phrase { display: inline-block; }
@@ -60,24 +50,24 @@ svg { display: block; }
.site-header { min-height: 100px; display: flex; align-items: center; gap: 32px; border-bottom: 1px solid var(--line); }
.site-header nav { display: flex; flex-wrap: wrap; column-gap: 25px; margin-left: auto; }
.site-header nav a { display: inline-flex; align-items: center; min-height: 44px; font-size: 14px; font-weight: 600; text-decoration: none; }
-.site-header nav a:is(:hover, :focus-visible), .footer-links a:is(:hover, :focus-visible) { color: var(--green); }
+.site-header nav a:is(:hover, :focus-visible), .footer-links a:is(:hover, :focus-visible) { color: var(--action-text); }
.preferences { display: flex; align-items: center; flex: none; gap: 10px; border-left: 1px solid var(--line); padding-left: 24px; }
.preferences .lr-lang { --lang-count: 2; }
.hero { display: grid; grid-template-columns: 1fr 1.08fr; align-items: center; gap: 18px; padding-block: 76px 77px; }
.hero-copy { position: relative; z-index: 1; min-width: 0; padding-bottom: 9px; }
-.eyebrow { display: flex; align-items: center; gap: 9px; color: var(--green); font-size: 11px; font-weight: 750; letter-spacing: .12em; text-transform: uppercase; }
-.status-dot { width: 7px; height: 7px; flex: none; border-radius: 100%; background: var(--green); box-shadow: 0 0 0 4px color-mix(in srgb, var(--green) 10%, transparent); }
+.eyebrow { display: flex; align-items: center; gap: 9px; color: var(--action-text); font-size: 11px; font-weight: 750; letter-spacing: .12em; text-transform: uppercase; }
+.status-dot { width: 7px; height: 7px; flex: none; border-radius: 100%; background: var(--action-text); box-shadow: 0 0 0 4px color-mix(in srgb, var(--action-text) 10%, transparent); }
h1 { font-size: clamp(49px, 5.7vw, 76px); line-height: 1.06; margin-block: 22px 23px; }
.highlight { position: relative; white-space: nowrap; }
.highlight::after { content: ""; position: absolute; left: 1px; right: -2px; bottom: -5px; height: 6px; background: var(--orange); border-radius: 50%; transform: rotate(-2deg); }
.hero-description { font-size: 18px; line-height: 1.8; color: var(--muted); margin-bottom: 28px; }
.hero-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 16px 24px; }
.text-link { display: inline-flex; align-items: center; min-height: 44px; font-size: 13px; font-weight: 650; }
-.button { display: inline-flex; justify-content: center; align-items: center; gap: 29px; min-height: 54px; padding: 12px 25px; border: 2px solid var(--ink); border-radius: 999px; text-decoration: none; font-size: 14px; font-weight: 700; transition: transform .22s cubic-bezier(.2, .9, .3, 1.4); }
+.button { display: inline-flex; justify-content: center; align-items: center; gap: 29px; min-height: 54px; padding: 12px 25px; border: 2px solid var(--ink); border-radius: 999px; text-decoration: none; font-size: 14px; font-weight: 700; transition: var(--control-motion); }
.button svg { width: 22px; height: 22px; }
-.primary { background: var(--ink); color: var(--button-ink); box-shadow: 0 4px 0 color-mix(in srgb, var(--ink) 18%, transparent); }
-.button:not(:disabled):is(:hover, :focus-visible) { transform: translateY(-3px); box-shadow: 0 7px 0 color-mix(in srgb, var(--ink) 18%, transparent); }
-.button:not(:disabled):active { transform: translateY(2px); box-shadow: 0 1px 0 color-mix(in srgb, var(--ink) 18%, transparent); }
+.primary { border-color: var(--primary); background: var(--primary); color: var(--primary-ink); box-shadow: var(--control-shadow); }
+.button:not(:disabled):is(:hover, :focus-visible) { transform: var(--control-hover-transform); box-shadow: var(--control-shadow); }
+.button:not(:disabled):active { transform: var(--control-press-transform); box-shadow: none; transition-duration: 80ms; }
.hero-note { color: var(--muted); font-size: 12px; line-height: 1.7; margin-top: 18px; }
.film-actions { display:flex; align-items:center; flex-wrap:wrap; gap:0 20px; margin-top:18px; }
.film-link { display:inline-flex; align-items:center; gap:10px; min-height:44px; text-decoration:none; font-size:12px; font-weight:650; }
@@ -114,8 +104,8 @@ h2 { font-size: clamp(30px, 3.25vw, 42px); line-height: 1.2; margin-top: 12px; }
.step-art:disabled { cursor: default; }
.art-replay { position: absolute; right: max(0px, calc(50% - 100px)); bottom: 0; color: var(--muted); font-size: 18px; }
.step-art:disabled .art-replay { display: none; }
-.steps li:is(:hover, :focus-within) .art-replay { color: var(--green); }
-.step-number { font-size: 11px; font-weight: 700; letter-spacing: .1em; color: var(--green); margin-bottom: 8px; }
+.steps li:is(:hover, :focus-within) .art-replay { color: var(--action-text); }
+.step-number { font-size: 11px; font-weight: 700; letter-spacing: .1em; color: var(--action-text); margin-bottom: 8px; }
.step-number span { color: var(--line); margin-left: 5px; }
h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.35; }
.steps li > p:last-child { margin-top: 12px; font-size: 14px; line-height: 1.75; color: var(--muted); }
@@ -133,16 +123,17 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3
.download-card h3 { font-size: 25px; }
.download-card > p { margin-top: 8px; color: var(--muted); font-size: 12px; line-height: 1.8; }
.download-architecture { position: relative; display: inline-grid; grid-auto-flow: column; grid-auto-columns: 1fr; min-width: 0; max-width: 100%; margin: 16px 0 20px; padding: 4px; border: 1px solid var(--line); border-radius: 24px; background: var(--wall); }
-.download-architecture:not(:disabled)::before { content: ""; position: absolute; inset: 4px auto 4px 4px; box-sizing: border-box; width: calc((100% - 8px) / 2); border: 1px solid var(--line); border-radius: 18px; background: var(--paper); box-shadow: 0 2px 0 color-mix(in srgb, var(--line) 40%, transparent); transition: transform 260ms var(--spring); pointer-events: none; }
+.download-architecture:not(:disabled)::before { content: ""; position: absolute; inset: 4px auto 4px 4px; box-sizing: border-box; width: calc((100% - 8px) / 2); border: 1px solid var(--action); border-radius: 18px; background: var(--control-selected); box-shadow: 0 2px 0 color-mix(in srgb, var(--line) 40%, transparent); transition: transform 260ms var(--spring); pointer-events: none; }
.download-architecture:has(> label:nth-of-type(2) input:checked)::before { transform: translateX(100%); }
.download-architecture label { position: relative; min-width: 0; }
.download-architecture input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; }
.download-architecture input:disabled { cursor: default; }
.download-architecture label > span { position: relative; display: flex; align-items: center; justify-content: center; height: 100%; min-height: 36px; padding: 6px 12px; border: 1px solid transparent; border-radius: 18px; font-size: 12px; font-weight: 600; pointer-events: none; transition: color 140ms ease, transform 180ms var(--spring); }
-.download-architecture input:checked + span { color: var(--green); }
-.download-architecture input:enabled:is(:hover, :focus-visible) + span { color: var(--green); transform: translateY(-1px); }
-.download-architecture input:enabled:active + span { transform: scale(.9); }
-.download-architecture input:focus-visible + span { outline: 3px solid var(--orange); outline-offset: 3px; }
+.download-architecture input:checked + span { color: var(--control-selected-ink); }
+.download-architecture input:enabled:is(:hover, :focus-visible) + span { transform: translateY(-1px); }
+.download-architecture input:enabled:not(:checked):is(:hover, :focus-visible) + span { color: var(--action-text); }
+.download-architecture input:enabled:active + span { transform: var(--control-press-transform); transition-duration: 80ms; }
+.download-architecture input:focus-visible + span { outline: 3px solid var(--action); outline-offset: 3px; }
.download-architecture:disabled { border-color: transparent; background: transparent; padding-inline: 0; }
.download-architecture:disabled label > span { padding-inline: 0; border-color: transparent; background: transparent; color: var(--muted); box-shadow: none; }
.download-button { width: 100%; gap: 10px; padding: 12px 15px; border-width: 1.5px; min-height: 48px; font-size: 13px; }
@@ -151,17 +142,17 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3
.start-section { padding-block: 45px 67px; }
.guide-links { display: flex; flex-wrap: wrap; justify-content: center; gap: 9px; margin: 28px 0; }
.guide-links a { display: inline-flex; align-items: center; min-height: 44px; padding: 8px 18px; background: var(--paper); border: 1px solid var(--line); border-radius: 999px; text-decoration: none; font-size: 13px; font-weight: 650; }
-.guide-links a:is(:hover, :focus-visible) { border-color: var(--green); color: var(--green); }
+.guide-links a:is(:hover, :focus-visible) { border-color: var(--action-text); color: var(--action-text); }
.guide { margin-top: 15px; border: 1px solid var(--line); border-radius: 24px; background: var(--paper); }
.guide > summary { padding: 24px 28px; border-radius: 24px; }
-.guide-number { display: grid; place-items: center; flex: none; width: 39px; height: 39px; border: 1px solid var(--line); border-radius: 13px; font-size: 12px; font-weight: 750; color: var(--green); }
+.guide-number { display: grid; place-items: center; flex: none; width: 39px; height: 39px; border: 1px solid var(--line); border-radius: 13px; font-size: 12px; font-weight: 750; color: var(--action-text); }
.guide-heading { flex: 1; font-size: 21px; }
.guide-heading small { display: block; margin-top: 4px; color: var(--muted); font-size: 12px; font-weight: 400; }
.guide-body { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr); gap: 38px; padding: 5px 30px 30px; }
.guide-steps { margin: 0; padding-left: 25px; }
.guide-steps > li { padding-left: 8px; margin-bottom: 23px; font-size: 14px; line-height: 1.8; }
.guide-steps > li:last-child { margin-bottom: 0; }
-.guide-steps > li::marker { color: var(--green); font-size: 12px; font-weight: 750; }
+.guide-steps > li::marker { color: var(--action-text); font-size: 12px; font-weight: 750; }
.guide-steps strong { font-weight: 700; }
.guide-body p { max-width: none; margin: 6px 0 0; padding: 0; color: var(--muted); font-size: 13px; line-height: 1.85; }
.guide-note { align-self: start; min-width: 0; padding: 23px; border: 1px solid var(--line); border-radius: 18px; background: var(--wall); }
@@ -175,7 +166,7 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3
.launch-files dd { margin: 0; }
.guide code { overflow-wrap: anywhere; font: .95em ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; }
.watch-guide { display: flex; gap: 24px; margin-top: 28px; padding: 28px; border: 1px solid var(--line); border-radius: 24px; }
-.watch-guide > svg { flex: none; width: 42px; height: 42px; color: var(--green); }
+.watch-guide > svg { flex: none; width: 42px; height: 42px; color: var(--action-text); }
.watch-guide ol { padding-left: 20px; margin-block: 15px; font-size: 14px; line-height: 1.8; }
.watch-guide p { max-width: 820px; color: var(--muted); font-size: 13px; line-height: 1.85; }
.modes { margin: 15px 0 20px; font-size: 14px; }
@@ -184,23 +175,23 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3
.modes dd { color: var(--muted); margin: 2px 0 0; font-size: 13px; }
.faq-section { display: grid; grid-template-columns: 1fr 1.9fr; gap: 55px; border-top: 1px solid var(--line); padding-block: 61px 71px; }
.faq-intro h2 { margin-top: 15px; }
-.faq-tv { width: 76px; height: 76px; margin-top: 30px; transform: rotate(-7deg); color: var(--green); }
+.faq-tv { width: 76px; height: 76px; margin-top: 30px; transform: rotate(-7deg); color: var(--action-text); }
.questions details { border-bottom: 1px solid var(--line); }
.questions details:first-child { border-top: 1px solid var(--line); }
.faq-more { margin-top: 22px; color: var(--muted); font-size: 14px; }
.faq-more a { color: var(--ink); }
summary { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 21px 0; font-size: 15px; font-weight: 650; list-style: none; }
summary::-webkit-details-marker { display: none; }
-summary::after { content: "+"; flex: none; width: 22px; font-size: 21px; font-weight: 400; text-align: center; color: var(--green); }
+summary::after { content: "+"; flex: none; width: 22px; font-size: 21px; font-weight: 400; text-align: center; color: var(--action-text); }
details[open] > summary::after { content: "−"; }
details p { max-width: 610px; padding: 0 24px 23px 0; color: var(--muted); font-size: 14px; line-height: 1.85; }
.project-note { display: flex; align-items: flex-start; gap: 30px; padding: 32px 36px; background: var(--soft-orange); border: 1px solid color-mix(in srgb, var(--orange) 30%, var(--line)); border-radius: 18px; }
-.project-tv { width: 62px; height: 62px; flex: none; color: var(--green); }
+.project-tv { width: 62px; height: 62px; flex: none; color: var(--action-text); }
.project-content { flex: 1; min-width: 0; }
.project-note h2 { margin: 0; font-size: clamp(23px, 2.2vw, 29px); letter-spacing: -.035em; }
.project-note p { max-width: 790px; margin-block: 12px; color: var(--muted); font-size: 14px; }
.project-note a { display: inline-flex; align-items: center; min-height: 44px; padding-block: 6px; font-size: 14px; font-weight: 650; }
-.project-note a:is(:hover, :focus-visible) { color: var(--green); }
+.project-note a:is(:hover, :focus-visible) { color: var(--action-text); }
.project-note .eyebrow { margin: 0 0 8px; font-size: 11px; }
.docs-links { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 22px; margin: 22px 0; padding: 18px 0 0; border-top: 1px solid color-mix(in srgb, var(--orange) 30%, var(--line)); list-style: none; }
.docs-links p { margin: 0; font-size: 13px; }
@@ -214,7 +205,7 @@ details p { max-width: 610px; padding: 0 24px 23px 0; color: var(--muted); font-
.display-settings { flex-basis: 100%; text-align: right; }
.display-settings > summary { justify-content: flex-end; gap: 8px; min-height: 44px; padding: 0; font-size: 12px; font-weight: 400; }
.display-settings label { display: flex; align-items: center; justify-content: flex-end; gap: 8px; min-height: 44px; font-size: 12px; }
-.display-settings input { accent-color: var(--green); width: 16px; height: 16px; margin: 0; }
+.display-settings input { accent-color: var(--action-text); width: 16px; height: 16px; margin: 0; }
.display-settings p { max-width: none; padding: 0; font-size: 12px; }
.footer-note { flex-basis: 100%; text-align: right; margin-top: 9px; color: var(--muted); font-size: 11px; }
html[lang="zh-CN"] h1 { font-size: clamp(45px, 5.4vw, 72px); line-height: 1.24; letter-spacing: -.03em; }
@@ -319,11 +310,11 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }
/* Small, finite scenes; the whole step owns hover, the button also supports tap/keys. */
@media (prefers-reduced-motion: no-preference) {
.step-art g { transform-box: fill-box; transform-origin: center; }
- .steps li:is(:hover, :focus-within) .screen-cursor { animation: choose-screen var(--comic-beat) ease-in-out; }
- .steps li:is(:hover, :focus-within) .chosen-window { animation: window-response var(--comic-beat) ease-in-out; }
- .steps li:is(:hover, :focus-within) .invite-plane { animation: send-invite var(--comic-beat) ease-in-out; }
- .steps li:is(:hover, :focus-within) .invite-note { animation: note-response var(--comic-beat) ease-in-out; }
- .steps li:is(:hover, :focus-within) .sofa-friend { animation: take-a-seat var(--comic-beat) ease-out; }
+ .steps li:is(:hover, :focus-within) .screen-cursor { animation: choose-screen var(--comic-beat) ease-in-out infinite; }
+ .steps li:is(:hover, :focus-within) .chosen-window { animation: window-response var(--comic-beat) ease-in-out infinite; }
+ .steps li:is(:hover, :focus-within) .invite-plane { animation: send-invite var(--comic-beat) ease-in-out infinite; }
+ .steps li:is(:hover, :focus-within) .invite-note { animation: note-response var(--comic-beat) ease-in-out infinite; }
+ .steps li:is(:hover, :focus-within) .sofa-friend { animation: take-a-seat var(--comic-beat) ease-out infinite; }
.steps li:is(:hover, :focus-within) .sofa-friend + .sofa-friend { animation-delay: .12s; }
/* Keep finished timelines replayable; every scene ends at its original pose. */
.steps li:is(:hover, :focus-within) .step-art [class] { animation-fill-mode: both; }
diff --git a/src/client/App.tsx b/src/client/App.tsx
index 7ad215b4..c91a9940 100644
--- a/src/client/App.tsx
+++ b/src/client/App.tsx
@@ -33,7 +33,7 @@ import { Glyph } from "./ui/icons";
import { applyLaunchCopy, useCopy } from "./ui/copy";
import { consoleLanguage } from "./locales";
import { initTheme } from "./ui/theme";
-import { installBrowserDebug, withBrowserDebug } from "./lib/debug";
+import { debugError, installBrowserDebug, withBrowserDebug } from "./lib/debug";
const TooltipPreviewPage = import.meta.env.DEV
? lazy(() => import("./pages/TooltipPreviewPage").then((module) => ({ default: module.TooltipPreviewPage })))
@@ -115,11 +115,16 @@ export function App() {
}, [lang, vis, launchedByClient]);
return (
- <RouteBoundary>
- <Suspense fallback={<RouteLoader />}>
- <AppRoute />
- </Suspense>
- </RouteBoundary>
+ <div className="lr-app-shell">
+ <RouteBoundary>
+ <Suspense fallback={<RouteLoader />}>
+ <AppRoute />
+ </Suspense>
+ </RouteBoundary>
+ {appRoute.kind !== "client" && <footer className="lr-web-version">
+ Piik Web {import.meta.env.VITE_PIIK_VERSION ?? "development"}
+ </footer>}
+ </div>
);
}
@@ -135,6 +140,10 @@ class RouteBoundary extends Component<
return { failed: true };
}
+ componentDidCatch(error: Error): void {
+ debugError("app", "route-failed", error);
+ }
+
render(): ReactNode {
return this.state.failed ? (
<StaticRoute
@@ -392,6 +401,7 @@ function SiteAccessGate({
return (
<HostPage
roomInteractionsAvailable={capabilities?.roomInteractions === true}
+ roomReactionIds={capabilities?.roomReactionIds}
hostRoomSessionAvailable={capabilities?.hostRoomSession === true}
launchedByClient={launchedByClient}
sfuAvailable={capabilities?.sfu === true}
diff --git a/src/client/components/living/AppConnectionButton.tsx b/src/client/components/living/AppConnectionButton.tsx
index 7103dc07..31369c9e 100644
--- a/src/client/components/living/AppConnectionButton.tsx
+++ b/src/client/components/living/AppConnectionButton.tsx
@@ -1,9 +1,11 @@
import { useEffect, useId, useRef, useState } from "react";
import { activateClient, isClientActivated, watchClientActivation } from "../../lib/session";
+import { useProjectLink } from "../../lib/use-project-link";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
import { Tooltip } from "./Tooltip";
import { Comic } from "./Comic";
+import { useAnchoredPopover } from "./use-anchored-popover";
interface AppConnectionProps {
sourcePicker?: boolean;
@@ -25,9 +27,11 @@ function AppConnectionControl({ sourcePicker = false, onConnected }: AppConnecti
const { t, vis } = useCopy();
const [state, setState] = useState<"idle" | "busy" | "ready" | "unavailable" | "incompatible">("idle");
const [helpOpen, setHelpOpen] = useState(false);
+ const downloadURL = useProjectLink("/#download", "https://github.com/TNTcraftHIM/Piik/releases/latest", helpOpen);
const helpId = useId();
const trigger = useRef<HTMLButtonElement>(null);
const help = useRef<HTMLDivElement>(null);
+ useAnchoredPopover(trigger, help);
const pending = useRef<{ controller: AbortController; popup: Window | null } | null>(null);
const healthCheck = useRef<AbortController | null>(null);
useEffect(() => {
@@ -56,13 +60,6 @@ function AppConnectionControl({ sourcePicker = false, onConnected }: AppConnecti
return () => { healthCheck.current?.abort(); window.removeEventListener("focus", onFocus); unwatch(); };
}, [sourcePicker]);
useEffect(() => () => { pending.current?.controller.abort(); pending.current?.popup?.close(); }, []);
- useEffect(() => {
- // A one-shot disclosure follows its trigger again on the next opening.
- const close = () => help.current?.hidePopover();
- window.addEventListener("resize", close);
- window.addEventListener("scroll", close);
- return () => { window.removeEventListener("resize", close); window.removeEventListener("scroll", close); };
- }, []);
function showHelp(): void {
if (trigger.current) help.current?.showPopover({ source: trigger.current });
@@ -159,17 +156,7 @@ function AppConnectionControl({ sourcePicker = false, onConnected }: AppConnecti
className="lr-app-connect-help" onToggle={event => {
setHelpOpen(event.newState === "open");
if (event.newState !== "open" || !trigger.current) return;
- const panel = event.currentTarget;
- const rect = trigger.current.getBoundingClientRect();
- if (rect.bottom <= 0 || rect.top >= window.innerHeight) { panel.hidePopover(); return; }
- const below = window.innerHeight - rect.bottom - 16;
- const above = rect.top - 16;
- const openAbove = below < panel.scrollHeight && above > below;
- panel.classList.toggle("is-above", openAbove);
- panel.style.maxHeight = `${Math.max(0, openAbove ? above : below)}px`;
- panel.style.left = `${Math.max(8, Math.min(rect.right - panel.offsetWidth, window.innerWidth - panel.offsetWidth - 8))}px`;
- panel.style.top = `${Math.max(8, openAbove ? rect.top - panel.offsetHeight - 8 : rect.bottom + 8)}px`;
- panel.querySelector<HTMLButtonElement>("button")?.focus();
+ event.currentTarget.querySelector<HTMLButtonElement>("button")?.focus();
}}>
<div className="lr-app-connect-head">
<div className="lr-app-connect-scene" aria-hidden="true">{helpOpen && <Comic kind={state === "incompatible" ? "warning" : "signal-failed"} theme="paper" />}</div>
@@ -183,7 +170,7 @@ function AppConnectionControl({ sourcePicker = false, onConnected }: AppConnecti
<button type="button" className="lr-btn" aria-label={t("common.retry")} onClick={() => void connect()}>
<Glyph name="refresh" size={16} /><span className={vis ? "visually-hidden" : undefined}>{t("common.retry")}</span>
</button>
- <a className="lr-btn" href="https://piik.tv/#download" target="_blank" rel="noopener noreferrer" aria-label={t("client.connect.download")}>
+ <a className="lr-btn" href={downloadURL} target="_blank" rel="noopener noreferrer" aria-label={t("client.connect.download")}>
<Glyph name="arrowDown" size={16} /><span className={vis ? "visually-hidden" : undefined}>{t("client.connect.download")}</span>
</a>
</div>
diff --git a/src/client/components/living/AppReleaseNotice.tsx b/src/client/components/living/AppReleaseNotice.tsx
index a7e25b9e..3775026f 100644
--- a/src/client/components/living/AppReleaseNotice.tsx
+++ b/src/client/components/living/AppReleaseNotice.tsx
@@ -17,26 +17,22 @@ export function AppReleaseNotice({ update }: { update: ReleaseUpdateNotice }) {
const major = update.kind === "major-update";
const label = `${t(labels[update.kind])} · ${update.version}`;
return <div className="lr-client-release">
- <div className="lr-client-project-links">
- <Tooltip kind="update-available" text={major ? t("client.update.majorHint") : vis ? update.version : label}>
- <a className="lr-btn lr-client-update" href={update.url} target="_blank" rel="noopener noreferrer"
- aria-label={label} aria-describedby={major ? warningId : undefined}>
- <Glyph name={major ? "alert" : "arrowUp"} size={17} />
- <span className={vis ? "visually-hidden" : undefined}>{label}</span>
- {vis && <span aria-hidden="true">{update.version}</span>}
- </a>
- </Tooltip>
- <div className="lr-client-release-links">
- <a href={update.releaseURL} target="_blank" rel="noopener noreferrer" aria-label={t("client.update.notes")}>
- {vis ? <Glyph name="window" size={17} /> : t("client.update.notes")}<span aria-hidden="true"> ↗</span>
- </a>
- <a href="https://piik.tv/#download" target="_blank" rel="noopener noreferrer" aria-label={t("client.update.downloads")}>
- {vis ? <Glyph name="arrowDown" size={17} /> : t("client.update.downloads")}<span aria-hidden="true"> ↗</span>
- </a>
- </div>
- </div>
- {major && <p id={warningId} className={vis ? "visually-hidden" : "lr-client-release-warning"}>
- {t("client.update.majorHint")}
- </p>}
+ <Tooltip kind="update-available" text={major ? t("client.update.majorHint") : vis ? update.version : label}>
+ <a className="lr-btn lr-client-update" href={update.url} target="_blank" rel="noopener noreferrer"
+ aria-label={label} aria-describedby={major ? warningId : undefined}>
+ <Glyph name={major ? "alert" : "arrowUp"} size={17} />
+ <span className={vis ? "visually-hidden" : undefined}>{label}</span>
+ {vis && <span aria-hidden="true">{update.version}</span>}
+ </a>
+ </Tooltip>
+ <a className="lr-client-release-mirror" href="https://gitee.com/TNTcraftHIM/Piik/releases"
+ target="_blank" rel="noopener noreferrer" aria-label={t("client.update.downloads")}>
+ {vis ? <>Gitee <Glyph name="arrowDown" size={14} /></> : t("client.update.downloads")}
+ <span aria-hidden="true">↗</span>
+ </a>
+ {major && <a id={warningId} className="lr-client-release-warning" href={update.releaseURL}
+ target="_blank" rel="noopener noreferrer" aria-label={t("client.update.majorHint")}>
+ {vis ? <Glyph name="alert" size={17} /> : t("client.update.majorHint")}<span aria-hidden="true"> ↗</span>
+ </a>}
</div>;
}
diff --git a/src/client/components/living/CaptureSourcePicker.tsx b/src/client/components/living/CaptureSourcePicker.tsx
index ec2e5edc..632aed96 100644
--- a/src/client/components/living/CaptureSourcePicker.tsx
+++ b/src/client/components/living/CaptureSourcePicker.tsx
@@ -1,9 +1,10 @@
-import { useCallback, useEffect, useId, useRef, useState } from "react";
+import { useCallback, useEffect, useId, useRef, useState, type CSSProperties } from "react";
import type { NativeCaptureTarget } from "../../native/wire";
import { audioApplicationKey, audioApplications, nativeCaptureTargetKey } from "../../native/capture-selection";
import { useCopy } from "../../ui/copy";
import { Glyph, type GlyphName } from "../../ui/icons";
+import { navigateTabs } from "../../ui/tab-navigation";
import { Tooltip } from "./Tooltip";
import { HintComic } from "./hints";
import { Pill } from "./primitives";
@@ -190,7 +191,7 @@ export function CaptureSourcePicker({
<div className="lr-source-picker-panel">
<header className="lr-source-picker-head">
<span className="lr-source-picker-mark" aria-hidden="true">
- <Glyph name="share" size={22} draw="capture-source" />
+ <Glyph name="window" size={22} draw="capture-source" />
</span>
{vis ? null : (
<span className="lr-source-picker-copy">
@@ -209,34 +210,11 @@ export function CaptureSourcePicker({
</header>
<div
- className="lr-source-picker-tabs"
- style={{ gridTemplateColumns: `repeat(${tabs.length}, minmax(0, 1fr))` }}
+ className="lr-toggle lr-source-picker-tabs"
+ style={{ "--lr-segments": tabs.length, "--lr-selected-index": tabs.indexOf(activeTab) } as CSSProperties}
role="tablist"
aria-label={t("host.sourcePicker.title")}
- onKeyDown={(event) => {
- if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key))
- return;
- const available = tabs.filter(tabAvailable);
- if (!available.length) return;
- const index = available.indexOf(activeTab);
- const next =
- event.key === "Home"
- ? 0
- : event.key === "End"
- ? available.length - 1
- : (index +
- (event.key === "ArrowRight" ? 1 : -1) +
- available.length) %
- available.length;
- const nextTab = available[next]!;
- event.preventDefault();
- setTab(nextTab);
- event.currentTarget
- .querySelector<HTMLButtonElement>(
- `[data-source-tab="${nextTab}"]`,
- )
- ?.focus();
- }}
+ onKeyDown={navigateTabs}
>
{tabs.map((value) => {
const button = (
@@ -244,6 +222,7 @@ export function CaptureSourcePicker({
type="button"
role="tab"
id={`${pickerId}-${value}`}
+ className={activeTab === value ? "is-selected" : undefined}
data-source-tab={value}
aria-controls={`${pickerId}-panel`}
aria-selected={activeTab === value}
diff --git a/src/client/components/living/Comic.tsx b/src/client/components/living/Comic.tsx
index 6e6656cf..26bdfacf 100644
--- a/src/client/components/living/Comic.tsx
+++ b/src/client/components/living/Comic.tsx
@@ -546,21 +546,23 @@ function SceneSignal({ theme, state, peer = false }: {
<style>{`
.vls-signal-message{animation:vlsSignalMessage var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
.vls-signal-retry{transform-box:fill-box;transform-origin:center;animation:vlsSignalRetry var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
-.vls-signal-result{transform-box:fill-box;transform-origin:center;animation:vlsSignalResult var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-signal-page{animation:vlsSignalPage var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
@keyframes vlsSignalMessage{0%{transform:translateX(0);opacity:0}8%{opacity:1}40%{transform:translateX(82px);opacity:1}55%,100%{transform:translateX(82px);opacity:0}}
@keyframes vlsSignalRetry{0%{transform:rotate(0)}55%,100%{transform:rotate(360deg)}}
-@keyframes vlsSignalResult{0%,8%,42%,100%{transform:none}20%{transform:scale(.9)}30%{transform:scale(1.04)}}
+@keyframes vlsSignalPage{0%,12%,48%,100%{transform:none}22%{transform:translateY(-3px)}34%{transform:translateY(1px)}}
${rmBlock(["vls-signal-message", "vls-signal-retry"], [
[".vls-signal-message", "opacity:1;transform:translateX(41px)"],
[".vls-signal-retry", "transform:none"],
])}
-${rmBlock(["vls-signal-result"], [[".vls-signal-result", "transform:none"]], false)}
+${rmBlock(["vls-signal-page"], [[".vls-signal-page", "transform:none"]], false)}
`}</style>
<Frame x={4} w={312} theme={theme} result />
- <BrowserWindow x={24} y={23} w={96} h={50}>
- <circle cx={37} cy={43} r={3} fill={color} />
- <path d="M47 43h56 M34 55h36 M77 55h26 M34 64h69" stroke={LINE} strokeWidth={2} strokeLinecap="round" />
- </BrowserWindow>
+ <g className={state === "connecting" || state === "recovering" ? undefined : "vls-signal-page"}>
+ <BrowserWindow x={24} y={23} w={96} h={50}>
+ <circle cx={37} cy={43} r={3} fill={color} />
+ <path d="M47 43h56 M34 55h36 M77 55h26 M34 64h69" stroke={LINE} strokeWidth={2} strokeLinecap="round" />
+ </BrowserWindow>
+ </g>
{peer ? <BrowserWindow x={251} y={25} w={47} h={46} /> : <ServerBox x={254} y={25} w={42} h={46} />}
<path
d={state === "connecting" ? "M130 48H244" : "M130 48H164 M204 48H244"}
@@ -583,11 +585,11 @@ ${rmBlock(["vls-signal-result"], [[".vls-signal-result", "transform:none"]], fal
<path d="M175 43a11 11 0 0 1 19-2l2 3 M190 44h6v-6 M193 53a11 11 0 0 1-19 2l-2-3 M178 52h-6v6" />
</g>
) : state === "connected" ? (
- <path className="vls-signal-result" d="M174 48l7 7 14-17" stroke={color} strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" fill="none" />
+ <path d="M174 48l7 7 14-17" stroke={color} strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" fill="none" />
) : state === "failed" ? (
- <RedX cx={184} cy={48} arm={8} className="vls-signal-result" />
+ <RedX cx={184} cy={48} arm={8} />
) : (
- <g className="vls-signal-result" stroke={color} strokeWidth={2.5} strokeLinecap="round" fill="none">
+ <g stroke={color} strokeWidth={2.5} strokeLinecap="round" fill="none">
<path d="M174 43h5 M174 53h5 M189 43h5 M189 53h5 M176 59l16-22" />
</g>
)}
@@ -1546,7 +1548,7 @@ export const Comic = memo(function Comic({
const resolvedTone = tone ?? presentation.tone;
const resolvedMotion = motion ?? presentation.motion;
const style = {
- ...comicStyle(resolvedTone, resolvedMotion),
+ ...comicStyle(resolvedTone),
"--comic-neutral": resolvedTheme === "paper" ? "var(--ink)" : "#48597a",
width: size != null ? `${size}px` : "min(320px, 86%)",
height: "auto",
diff --git a/src/client/components/living/FloatingPanel.tsx b/src/client/components/living/FloatingPanel.tsx
index da676017..a23914e4 100644
--- a/src/client/components/living/FloatingPanel.tsx
+++ b/src/client/components/living/FloatingPanel.tsx
@@ -2,12 +2,12 @@ import { useLayoutEffect, useRef, useState, type PointerEvent, type ReactNode, t
import { createPortal } from "react-dom";
import { useCopy } from "../../ui/copy";
import { Glyph, type GlyphName } from "../../ui/icons";
-import { openPanelWindow, panelWindowAPI, SurfaceDocument } from "../../ui/panel-window";
+import { usePanelWindow, panelWindowAPI, SurfaceDocument } from "../../ui/panel-window";
import { Tooltip } from "./Tooltip";
import "./floating-panel.css";
-const PANEL_SIZES = { default: { width: 420, height: 560 }, large: { width: 560, height: 680 } };
-const COMPACT_SIZES = { default: { width: 304, height: undefined }, large: { width: 380, height: 460 } };
+const PANEL_SIZE = { width: 420, height: 560 };
+const COMPACT_SIZE = { width: 304, height: undefined };
type PanelGesture = "move" | "nw" | "se";
type PanelChange = { x: number; y: number } | { rect: DOMRect; corner: "nw" | "se"; dx: number; dy: number };
@@ -20,23 +20,12 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
}) {
const { t, vis } = useCopy();
const [open, setOpen] = useState(false);
- const [surfaceDocument, setSurfaceDocument] = useState<Document | null>(null);
- const detached = Boolean(surfaceDocument && surfaceDocument !== document);
- const [openingWindow, setOpeningWindow] = useState(false);
- const [windowFailed, setWindowFailed] = useState(false);
- const [container] = useState(() => {
- if (!detachable || typeof document === "undefined") return null;
- const node = document.createElement("div");
- node.style.display = "contents";
- return node;
- });
- const slot = useRef<HTMLSpanElement>(null);
- const lifetime = useRef<AbortController | null>(null);
+ const panelWindow = usePanelWindow(detachable);
+ const { container, slot, surfaceDocument, detached } = panelWindow;
const panelRef = useRef<HTMLElement>(null);
- const positionMenu = useRef<HTMLDetailsElement>(null);
- const sizes = compact ? COMPACT_SIZES : PANEL_SIZES;
+ const defaultSize = compact ? COMPACT_SIZE : PANEL_SIZE;
const position = useRef({ x: 1, y: 1 });
- const preferredSize = useRef(sizes.default);
+ const preferredSize = useRef(defaultSize);
const placePanel = useRef<((change?: PanelChange) => void) | null>(null);
const gesture = useRef<{ pointerId: number; x: number; y: number; rect: DOMRect; kind: PanelGesture } | null>(null);
const suppressDragClick = useRef(false);
@@ -47,35 +36,30 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
};
useLayoutEffect(() => {
- if (!container || !slot.current) return;
- slot.current.append(container);
- return () => { lifetime.current?.abort(); container.remove(); };
- }, [container]);
+ const panel = panelRef.current;
+ if (!panel) return;
+ const owner = panel.ownerDocument;
+ const hideOutsideFullscreen = () => {
+ if (!owner.fullscreenElement || owner.fullscreenElement.contains(panel)) return false;
+ // A room tool outside the fullscreen subtree must not cover the picture.
+ // Adoption already hides its popover, so report the closed state even
+ // when the browser has no further toggle event to deliver on return.
+ panel.hidePopover();
+ setOpen(false);
+ onOpenChange?.(false, owner);
+ return true;
+ };
+ // Adoption removes native popovers from the old document's top layer.
+ if (surfaceDocument && !hideOutsideFullscreen()) panel.showPopover();
+ owner.addEventListener("fullscreenchange", hideOutsideFullscreen);
+ return () => owner.removeEventListener("fullscreenchange", hideOutsideFullscreen);
+ }, [surfaceDocument]);
useLayoutEffect(() => {
if (!surfaceDocument) return;
- // Adoption removes native popovers from the old document's top layer.
- panelRef.current?.showPopover();
if (surfaceDocument !== document) surfaceDocument.title = `${title} · Piik`;
}, [surfaceDocument, title]);
- async function detach() {
- if (!container || openingWindow) return;
- const controller = new AbortController();
- lifetime.current = controller;
- const { signal } = controller;
- setOpeningWindow(true);
- setWindowFailed(false);
- if (positionMenu.current) positionMenu.current.open = false;
- try {
- await openPanelWindow(container, signal, owner => {
- setSurfaceDocument(owner);
- onOpenChange?.(true, owner);
- });
- } catch { if (!signal.aborted) setWindowFailed(true); }
- finally { if (!signal.aborted) setOpeningWindow(false); }
- }
-
useLayoutEffect(() => {
const panel = panelRef.current;
if (!open || !panel) return;
@@ -100,14 +84,12 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
function startGesture(event: PointerEvent<HTMLElement>, kind: PanelGesture) {
if (!event.isPrimary || event.button !== 0 || !panelRef.current) return;
- if (kind === "move" && (event.target as Element).closest("button, .lr-floating-positions")) return;
+ if (kind === "move" && (event.target as Element).closest("button")) return;
panelRef.current.getAnimations().forEach(animation => animation.finish());
gesture.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY,
rect: panelRef.current.getBoundingClientRect(), kind };
- // Capture on the summary preserves its native click/keyboard activation.
- const handle = (event.target as Element).closest<HTMLElement>("summary") ?? event.currentTarget;
- handle.focus({ preventScroll: true });
- handle.setPointerCapture(event.pointerId);
+ event.currentTarget.focus({ preventScroll: true });
+ event.currentTarget.setPointerCapture(event.pointerId);
}
useLayoutEffect(() => {
const panel = panelRef.current;
@@ -156,9 +138,8 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
const top = (viewport?.offsetTop ?? 0) + 12;
const bottom = top + (viewport?.height ?? document.documentElement.clientHeight) - 24;
const below = anchor.bottom + 8;
- const headroom = anchor.top - top >= panel.offsetHeight + 136 ? 128 : 0;
place({ x: anchor.x + anchor.width / 2 - panel.offsetWidth / 2,
- y: below + panel.offsetHeight <= bottom ? below : anchor.top - panel.offsetHeight - 8 - headroom });
+ y: below + panel.offsetHeight <= bottom ? below : anchor.top - panel.offsetHeight - 8 });
}
viewport?.addEventListener("resize", resize);
viewport?.addEventListener("scroll", resize);
@@ -178,7 +159,7 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
const panel = <SurfaceDocument.Provider value={surfaceDocument}>
<section id={id} ref={panelRef} popover="manual" role="dialog" tabIndex={-1} className={`lr-floating-surface lr-floating-panel ${className}`}
- style={sizes.default}
+ style={defaultSize}
aria-label={title}
onPointerDownCapture={() => { suppressDragClick.current = false; }}
onPointerMove={event => {
@@ -210,10 +191,7 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
// Opening to read must not summon a phone's keyboard.
event.currentTarget.focus({ preventScroll: true });
} else {
- lifetime.current?.abort();
- setOpeningWindow(false);
- setWindowFailed(false);
- if (positionMenu.current) positionMenu.current.open = false;
+ panelWindow.close();
if (event.currentTarget.contains(document.activeElement)) focusTrigger();
}
}}>
@@ -230,40 +208,10 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
<span className="lr-floating-title">{!detached && <Glyph name="grip" size={17} />}
{vis ? <Glyph name={icon} size={18} /> : <b>{title}</b>}</span>
<span id={`${id}-move-hint`} className="visually-hidden">{t("floating.moveHint")}</span>
- {!detached && <details ref={positionMenu} className="lr-floating-position"
- onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node)) event.currentTarget.open = false; }}
- onKeyDown={event => {
- if (event.key !== "Escape" || event.defaultPrevented || event.nativeEvent.isComposing || !event.currentTarget.open) return;
- event.stopPropagation(); event.currentTarget.open = false;
- event.currentTarget.querySelector("summary")?.focus();
- }}>
- <summary aria-label={t("floating.position")}><Glyph name="move" size={16} />{!vis && <span>{t("floating.position")}</span>}</summary>
- <div className="lr-floating-positions" role="group" aria-label={t("floating.position")}>
- {(["topLeft", "topRight", "bottomLeft", "bottomRight"] as const).map((corner, index) => {
- const x = index % 2, y = Math.floor(index / 2);
- return <button key={corner} type="button" aria-label={t(`floating.position.${corner}`)} onClick={() => {
- position.current = { x, y }; placePanel.current?.();
- if (positionMenu.current) { positionMenu.current.open = false; positionMenu.current.querySelector("summary")?.focus(); }
- }}>
- <svg viewBox="0 0 28 22" width="28" height="22" aria-hidden="true">
- <rect x="1" y="1" width="26" height="20" rx="4" fill="none" stroke="currentColor" strokeWidth="1.5" />
- <rect x={x ? 16 : 4} y={y ? 12 : 4} width="8" height="6" rx="1.5" fill="currentColor" />
- </svg>{!vis && <span>{t(`floating.position.${corner}`)}</span>}
- </button>;
- })}
- {(["default", "large"] as const).map(size => <button key={size} type="button" className="lr-floating-size"
- onClick={() => {
- preferredSize.current = sizes[size]; placePanel.current?.();
- if (positionMenu.current) { positionMenu.current.open = false; positionMenu.current.querySelector("summary")?.focus(); }
- }} aria-label={t(`floating.size.${size}`)}>
- <Glyph name={size === "large" ? "expand" : "contract"} size={18} />{!vis && <span>{t(`floating.size.${size}`)}</span>}
- </button>)}
- </div>
- </details>}
{detachable && !detached && panelWindowAPI(typeof window === "undefined" ? null : window) &&
- <Tooltip kind="hint-chat-detach" place="below" text={vis ? undefined : t("floating.detach")}>
- <button type="button" className="lr-popover-close" disabled={openingWindow}
- aria-label={t("floating.detach")} onClick={() => { void detach(); }}>
+ <Tooltip kind="hint-window-detach" place="below" text={vis ? undefined : t("floating.detach")}>
+ <button type="button" className="lr-popover-close" disabled={panelWindow.opening}
+ aria-label={t("floating.detach")} onClick={() => { void panelWindow.open(); }}>
<Glyph name="pip" size={18} />
</button>
</Tooltip>}
@@ -271,7 +219,7 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
panelRef.current?.hidePopover(); focusTrigger();
}}><Glyph name="x" size={16} /></button>}
</header>
- {windowFailed && <p className="lr-floating-error" role="status">{t("floating.detachFailed")}</p>}
+ {panelWindow.failed && <p className="lr-floating-error" role="status">{t("floating.detachFailed")}</p>}
{children}
{!detached && (["nw", "se"] as const).map(corner => <span key={corner} className={`lr-floating-resize is-${corner}`}
role="group" tabIndex={0} aria-label={t("floating.resize")} aria-describedby={`${id}-resize-hint`}
diff --git a/src/client/components/living/HostRemoteControl.tsx b/src/client/components/living/HostRemoteControl.tsx
new file mode 100644
index 00000000..fc9e0d25
--- /dev/null
+++ b/src/client/components/living/HostRemoteControl.tsx
@@ -0,0 +1,149 @@
+import { useEffect, useId, useRef, useState, type CSSProperties } from "react";
+import { createPortal } from "react-dom";
+import type { RemoteControlRequest } from "../../native/wire";
+import type { RemoteControlMode, RemoteInputPlatform } from "../../remote-control/protocol";
+import { readRoomPreferences, saveRoomPreferences } from "../../lib/room-preferences";
+import { useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
+import { Btn, NameTag, SwitchItem } from "./primitives";
+import { FloatingPanel } from "./FloatingPanel";
+import { Tooltip } from "./Tooltip";
+import "./remote-control.css";
+
+// Form drafts stay here; the App snapshot owns applied authorization.
+export function HostRemoteControl({ mode, platform, requests, disabled, onPolicy, onDecide }: {
+ mode: RemoteControlMode;
+ platform: RemoteInputPlatform;
+ requests: (RemoteControlRequest & { name: string })[];
+ disabled?: boolean;
+ onPolicy: (mode: RemoteControlMode, password?: string) => Promise<void>;
+ onDecide: (id: string, allow: boolean) => Promise<void>;
+}) {
+ const { t, vis } = useCopy();
+ const id = useId();
+ const [open, setOpen] = useState(false);
+ const [surfaceDocument, setSurfaceDocument] = useState<Document | null>(null);
+ const detached = Boolean(surfaceDocument && surfaceDocument !== document);
+ const [draft, setDraft] = useState(() => mode === "off" ? readRoomPreferences().remoteControlMode : mode);
+ const [preparing, setPreparing] = useState(false);
+ const [password, setPassword] = useState("");
+ const [failedId, setFailedId] = useState<string | null>(null);
+ const [pendingActions, setPendingActions] = useState<Map<string, symbol>>(() => new Map());
+ const latestOperation = useRef<symbol | null>(null);
+ const busy = pendingActions.size > 0;
+ const pending = requests.filter(request => request.state === "pending").length;
+ const controller = requests.find(request => request.state !== "pending");
+ useEffect(() => {
+ setDraft(mode === "off" ? readRoomPreferences().remoteControlMode : mode);
+ setPassword(""); setPreparing(false);
+ if (mode !== "off") saveRoomPreferences({ remoteControlMode: mode });
+ }, [mode]);
+ const perform = async (id: string, operation: () => Promise<void>) => {
+ const identity = Symbol();
+ latestOperation.current = identity;
+ setPendingActions(current => new Map(current).set(id, identity)); setFailedId(null);
+ try { await operation(); if (latestOperation.current === identity) setPassword(""); }
+ catch { if (latestOperation.current === identity) setFailedId(id === "enable" ? "policy" : id.replace(/^stop:/, "")); }
+ finally {
+ setPendingActions(current => {
+ if (current.get(id) !== identity) return current;
+ const next = new Map(current); next.delete(id); return next;
+ });
+ }
+ };
+ const applyPolicy = (nextMode: RemoteControlMode, password?: string) => {
+ // Cancel the local enable submission without asserting an applied grant.
+ if (nextMode === "off") setPendingActions(current => {
+ const next = new Map(current); next.delete("enable"); return next;
+ });
+ return perform(nextMode !== "off" && mode === "off" ? "enable" : "policy", () => onPolicy(nextMode, password));
+ };
+ return <>
+ <span className="lr-remote-trigger">
+ <Btn id={`${id}-trigger`} icon="mouse" cap="remote.title"
+ title={detached ? "floating.focus" : pending ? "remote.requests" : controller?.state === "suspended" ? "remote.hostFocus" : controller ? "remote.controlling" : "remote.title"} hint={detached ? "hint-window-detach" : "hint-remote-control"}
+ tone={mode !== "off" || open ? "on" : undefined}
+ popoverTarget={detached ? undefined : id} expanded={open} controls={detached ? undefined : id}
+ onClick={detached ? () => surfaceDocument?.defaultView?.focus() : undefined} />
+ {pending > 0 && <span className="lr-remote-count" role="status" aria-label={`${t("remote.requests")} · ${pending}`}>{pending}</span>}
+ </span>
+ {createPortal(<FloatingPanel id={id} trigger={`${id}-trigger`} title={t("remote.title")} icon="mouse" compact anchorOnOpen detachable
+ className="lr-remote-panel" onOpenChange={(opened, owner) => {
+ setOpen(opened);
+ setSurfaceDocument(owner);
+ if (!opened) {
+ setPassword(""); setPreparing(false);
+ setDraft(mode === "off" ? readRoomPreferences().remoteControlMode : mode);
+ }
+ }}>
+ <div className="lr-floating-scroll lr-remote-panel-body">
+ <SwitchItem checked={mode !== "off"} label={t("remote.title")} hint="hint-remote-control"
+ disabled={mode === "off" && (busy || disabled)}
+ onChange={enabled => {
+ if (enabled && draft === "password" && !password) setPreparing(true);
+ else void applyPolicy(enabled ? draft : "off", enabled && draft === "password" ? password : undefined);
+ }} />
+ {pendingActions.has("enable") && mode === "off" && <div className="lr-remote-enable-pending" role="status">
+ <Glyph name="loader" size={18} className="lr-spin" />
+ <Btn icon="x" cap="remote.cancel" title="remote.cancel" hint="hint-remote-stop"
+ onClick={() => void applyPolicy("off")} />
+ </div>}
+ {requests.length > 0 && <div className="lr-remote-requests">
+ {[...requests].sort((a, b) => Number(a.state === "pending") - Number(b.state === "pending")).map(request => <div className="lr-remote-request" key={request.id} role="group" aria-label={request.name}>
+ <div><NameTag name={request.name} identity={request.peerId} />
+ <p><Glyph name={request.state === "suspended" ? "pause" : request.state === "active" ? "mouse" : "clock"} size={14} />
+ <span className={vis ? "visually-hidden" : undefined}>{t(request.state === "suspended" ? "remote.hostFocus" : request.state === "active" ? "remote.controlling" : "remote.waiting")}</span></p>
+ {failedId === request.id && <p role="alert"><Glyph name="alert" size={14} />
+ <span className={vis ? "visually-hidden" : undefined}>{t("remote.decisionFailed")}</span></p>}</div>
+ <div className="lr-remote-request-actions">
+ <Btn icon="x" title={request.state !== "pending" ? "remote.stop" : "remote.decline"} cap={request.state !== "pending" ? "remote.stop" : "remote.decline"}
+ hint="hint-remote-stop" disabled={pendingActions.has(`stop:${request.id}`)} onClick={() => void perform(`stop:${request.id}`, () => onDecide(request.id, false))} />
+ {request.state === "pending" && <Btn icon="check" tone="primary" title="remote.allow" cap="remote.allow" hint="hint-remote-control"
+ disabled={busy || disabled} onClick={() => void perform(request.id, () => onDecide(request.id, true))} />}
+ </div>
+ </div>)}
+ {!vis && pending > 0 && <p className="lr-remote-note">{t("remote.consent")}</p>}
+ </div>}
+ {(mode !== "off" || preparing) && <form className="lr-remote-settings" onSubmit={event => {
+ event.preventDefault();
+ void applyPolicy(draft, draft === "password" ? password : undefined);
+ }}>
+ {!vis && <span className="lr-remote-field-label">{t("remote.authorization")}</span>}
+ <div className="lr-toggle lr-remote-modes" role="group" aria-label={t("remote.authorization")}
+ style={{ "--lr-segments": 3, "--lr-selected-index": ["ask", "room", "password"].indexOf(draft) } as CSSProperties}>
+ {(["ask", "room", "password"] as const).map((value, index) => <Tooltip key={value}
+ kind="hint-remote-control" text={vis ? undefined : t(`remote.help.${value}`)}>
+ <button type="button" className={draft === value ? "is-selected" : undefined} aria-pressed={draft === value}
+ aria-label={t(`remote.mode.${value}`)} disabled={busy || disabled}
+ onClick={() => { setDraft(value); setPassword(""); }}>
+ {vis ? <Glyph name={(["check", "users", "key"] as const)[index]} size={18} /> : t(`remote.mode.${value}`)}
+ </button>
+ </Tooltip>)}
+ </div>
+ {!vis && <p className="lr-remote-note">{t(`remote.help.${draft}`)}</p>}
+ {draft === "password" && <label className="lr-input">
+ <Glyph name="key" size={18} />
+ <input type="password" autoComplete="new-password" required maxLength={128} value={password} autoFocus={preparing}
+ aria-label={t("remote.password")} placeholder={vis ? "" : t("remote.password")}
+ disabled={busy || disabled} onChange={event => setPassword(event.target.value)} />
+ </label>}
+ {(draft !== mode || draft === "password") && <div className="lr-remote-policy-actions">
+ {preparing && !busy && <Btn icon="x" title="common.cancel" cap="common.cancel" onClick={() => {
+ setPreparing(false); setPassword(""); setDraft(readRoomPreferences().remoteControlMode);
+ (surfaceDocument ?? document).getElementById(id)?.querySelector<HTMLButtonElement>('[role="switch"]')?.focus();
+ }} />}
+ <Btn icon="check" title="remote.apply" cap="remote.apply" type="submit" tone="primary"
+ hint="hint-remote-control" disabled={busy || disabled || (draft === "password" && !password)} />
+ </div>}
+ </form>}
+ {failedId === "policy" && <p role="alert"><Glyph name="alert" size={14} />
+ <span className={vis ? "visually-hidden" : undefined}>{t(platform === "darwin" && mode === "off" ? "remote.macPermission" : "remote.decisionFailed")}</span></p>}
+ {!vis && <p className="lr-remote-note">{t(platform === "linux" && mode === "off" ? "remote.linuxEnable" : "remote.policyLifetime")}</p>}
+ {(mode === "room" || mode === "password" || requests.some(request => request.state !== "pending")) && <p className="lr-remote-note">
+ {platform === "linux" ? <><Glyph name="mouse" size={14} /> <span className={vis ? "visually-hidden" : undefined}>{t("remote.linuxStop")}</span></>
+ : <>{vis ? <Glyph name="keyboard" size={14} /> : t("remote.shortcut")} <kbd>{platform === "darwin" ? "Ctrl + Option + F10" : "Ctrl + Alt + F10"}</kbd></>}
+ </p>}
+ </div>
+ </FloatingPanel>, document.body)}
+ </>;
+}
diff --git a/src/client/components/living/HostShareControls.tsx b/src/client/components/living/HostShareControls.tsx
new file mode 100644
index 00000000..ece22db7
--- /dev/null
+++ b/src/client/components/living/HostShareControls.tsx
@@ -0,0 +1,18 @@
+import type { ReactNode } from "react";
+import { useCopy } from "../../ui/copy";
+
+// Shared by the room and its previews; actions and their state belong to the caller.
+export function HostShareControls({ actions, settings, remote, pause, ending }: {
+ actions?: ReactNode; settings: ReactNode; remote?: ReactNode; pause?: ReactNode; ending?: ReactNode;
+}) {
+ const { t } = useCopy();
+ return <div className="lr-host-controls">
+ <div className="lr-host-share-controls lr-media-controls" role="group" aria-label={t("host.shareControls")}>
+ {(actions || pause || ending) && <div className="lr-host-action-dock">
+ {actions && <div className="lr-host-control-group">{actions}</div>}
+ {(pause || ending) && <div className="lr-host-control-group">{pause}{ending}</div>}
+ </div>}
+ <div className="lr-host-tool-dock">{settings}{remote}</div>
+ </div>
+ </div>;
+}
diff --git a/src/client/components/living/LanguageControl.tsx b/src/client/components/living/LanguageControl.tsx
index 71f0e198..69b0722b 100644
--- a/src/client/components/living/LanguageControl.tsx
+++ b/src/client/components/living/LanguageControl.tsx
@@ -2,6 +2,7 @@ import { useEffect, useId, useRef, type KeyboardEvent } from "react";
import { locales, type Lang } from "../../locales";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
+import { useAnchoredPopover } from "./use-anchored-popover";
// The registry owns languages; the native popover owns visibility and dismissal.
// This control adds Piik's presentation, viewport placement and menu navigation.
@@ -12,40 +13,20 @@ export function LanguageControl() {
const menuRef = useRef<HTMLSpanElement>(null);
const extraLanguages = (Object.keys(locales) as Lang[]).filter((key): boolean => key !== "zh" && key !== "en");
const selectedExtra = !vis && extraLanguages.includes(lang) ? locales[lang] : null;
+ useAnchoredPopover(triggerRef, menuRef, { maxHeight: 360, enabled: extraLanguages.length > 0 });
useEffect(() => {
const menu = menuRef.current;
const trigger = triggerRef.current;
if (!menu || !trigger) return;
- const place = () => {
- if (!menu.matches(":popover-open")) return;
- const rect = trigger.getBoundingClientRect();
- if (rect.bottom <= 0 || rect.top >= window.innerHeight) {
- menu.hidePopover();
- return;
- }
- const below = Math.max(0, window.innerHeight - rect.bottom - 16);
- const above = Math.max(0, rect.top - 16);
- const openAbove = below < Math.min(menu.scrollHeight, 360) && above > below;
- menu.style.maxHeight = `${Math.min(360, openAbove ? above : below)}px`;
- menu.classList.toggle("is-above", openAbove);
- const top = openAbove ? rect.top - menu.offsetHeight - 8 : Math.max(8, rect.bottom + 8);
- menu.style.left = `${Math.max(8, Math.min(rect.right - menu.offsetWidth, window.innerWidth - menu.offsetWidth - 8))}px`;
- menu.style.top = `${top}px`;
- };
const opened = () => {
if (!menu.matches(":popover-open")) return;
- place();
const selected = menu.querySelector<HTMLButtonElement>('[aria-checked="true"]');
(selected ?? menu.querySelector<HTMLButtonElement>("button"))?.focus();
};
menu.addEventListener("toggle", opened);
- window.addEventListener("resize", place);
- window.addEventListener("scroll", place, true);
return () => {
menu.removeEventListener("toggle", opened);
- window.removeEventListener("resize", place);
- window.removeEventListener("scroll", place, true);
};
}, [extraLanguages.length]);
diff --git a/src/client/components/living/Pawn.tsx b/src/client/components/living/Pawn.tsx
index edb53419..691d3330 100644
--- a/src/client/components/living/Pawn.tsx
+++ b/src/client/components/living/Pawn.tsx
@@ -1,6 +1,7 @@
import { useLayoutEffect, useRef, type CSSProperties } from "react";
import { HostMark } from "./HostMark";
import { bindParticipantMotion, participantMotion } from "./participant-motion";
+import { useSurfaceDocument } from "../../ui/panel-window";
/** The accepted A silhouette, shared with the explanatory cast. */
export function PersonShape({ eyes = true, gaze = 0, eyeClassName, host }: {
@@ -24,10 +25,11 @@ export function PawnSvg({ color, host, identity }: {
color: string; host?: boolean; identity?: string;
}) {
const root = useRef<SVGSVGElement>(null);
+ const surfaceDocument = useSurfaceDocument();
const motion = identity ? participantMotion(identity) : null;
useLayoutEffect(() => {
if (identity && root.current) return bindParticipantMotion(root.current, identity);
- }, [identity]);
+ }, [identity, surfaceDocument]);
return <svg ref={root} className="lr-person" viewBox="0 0 48 56" width="40" height="48"
aria-hidden="true" data-motion={identity ? "" : undefined} style={motion ? {
"--person-duration": `${motion.duration}ms`,
diff --git a/src/client/components/living/PlaybackControls.tsx b/src/client/components/living/PlaybackControls.tsx
index c7dcd999..550aac42 100644
--- a/src/client/components/living/PlaybackControls.tsx
+++ b/src/client/components/living/PlaybackControls.tsx
@@ -1,32 +1,43 @@
-import { useEffect, useRef, useState, type RefObject, type ReactNode } from "react";
+import { useEffect, useId, useRef, useState, type RefObject, type ReactNode } from "react";
+import { createPortal } from "react-dom";
import { ViewerAudio, type ViewerAudioSnapshot } from "../../media/viewer-audio";
import { useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
import { debugError } from "../../lib/debug";
-import { Btn } from "./primitives";
+import { Btn, Cap } from "./primitives";
+import { ViewerPlaybackSettings, type ViewerPlaybackSettingsProps } from "./ViewerPlaybackSettings";
import { Tooltip } from "./Tooltip";
+import { useAnchoredPopover } from "./use-anchored-popover";
import { usePlaybackControlsVisibility } from "./use-playback-controls-visibility";
import { usePictureInPicture } from "./use-picture-in-picture";
import { bindPlaybackGestures } from "./playback-gestures";
import { toggleVideoFullscreen, videoFullscreenState, type FullscreenVideo } from "./video-fullscreen";
import "./playback-controls.css";
+import "./floating-panel.css";
+
+type PlaybackVisibility = ReturnType<typeof usePlaybackControlsVisibility>;
// Reflect the existing media element; binding, autoplay recovery and room
// presentation retain their existing owners.
export function PlaybackControls({
- videoRef, stream, audioTrackKey, canPlay, theaterMode, onPlay,
+ videoRef, stream, audioTrackKey, audioAvailable, canPlay, theaterMode, onPlay,
onToggleTheater, onReconnect, reconnectAvailable,
- extraActions,
+ overlayAction, overlaySettings, remoteActions, settings,
}: {
videoRef: RefObject<HTMLVideoElement | null>;
stream: MediaStream | null;
audioTrackKey?: string;
+ audioAvailable?: boolean | null;
canPlay: boolean;
theaterMode: boolean;
onPlay: () => void;
onToggleTheater: () => void;
onReconnect: () => void;
reconnectAvailable: boolean;
- extraActions?: ReactNode;
+ overlayAction?: ReactNode;
+ overlaySettings?: ReactNode;
+ remoteActions?: ReactNode;
+ settings?: ViewerPlaybackSettingsProps;
}) {
const audioRef = useRef<ViewerAudio | null>(null);
const controlsRef = useRef<HTMLDivElement | null>(null);
@@ -37,7 +48,7 @@ export function PlaybackControls({
const [hasAudio, setHasAudio] = useState(false);
const [fullscreen, setFullscreen] = useState({ supported: false, ready: false, active: false });
const [fullscreenFailed, setFullscreenFailed] = useState(false);
- const hidden = usePlaybackControlsVisibility(videoRef, controlsRef, paused || !canPlay);
+ const visibility = usePlaybackControlsVisibility(videoRef, controlsRef, paused || !canPlay);
const picture = usePictureInPicture(videoRef);
const togglePlayback = () => {
@@ -89,7 +100,6 @@ export function PlaybackControls({
video.addEventListener("keydown", onKey);
document.addEventListener("fullscreenchange", syncFullscreen);
const unbindGestures = bindPlaybackGestures(video,
- () => actionsRef.current.togglePlayback(),
() => actionsRef.current.toggleFullscreen());
return () => {
unbindGestures();
@@ -113,8 +123,8 @@ export function PlaybackControls({
const silent = audio.muted || audio.level === 0;
- return <PlaybackControlsView controlsRef={controlsRef} hidden={hidden} audio={audio}
- paused={paused} hasAudio={hasAudio} canPlay={canPlay} theaterMode={theaterMode}
+ return <PlaybackControlsView controlsRef={controlsRef} visibility={visibility} audio={audio}
+ paused={paused} hasAudio={hasAudio && audioAvailable !== false} canPlay={canPlay} theaterMode={theaterMode}
fullscreen={fullscreen} fullscreenFailed={fullscreenFailed} picture={picture}
togglePlayback={togglePlayback} toggleFullscreen={toggleFullscreen}
toggleMute={() => {
@@ -124,37 +134,65 @@ export function PlaybackControls({
audioRef.current?.setLevel(level);
audioRef.current?.setMuted(false);
}} onToggleTheater={onToggleTheater} onReconnect={onReconnect}
- reconnectAvailable={reconnectAvailable} extraActions={extraActions} />;
+ reconnectAvailable={reconnectAvailable} overlayAction={overlayAction} overlaySettings={overlaySettings} remoteActions={remoteActions} settings={settings} />;
}
// The film shares the rendered controls; the component above alone owns media effects.
export function PlaybackControlsView({
- controlsRef, hidden, audio, paused, hasAudio, canPlay, theaterMode,
+ controlsRef, visibility, audio, paused, hasAudio, canPlay, theaterMode,
fullscreen, fullscreenFailed, picture, togglePlayback, toggleFullscreen,
- toggleMute, setLevel, onToggleTheater, onReconnect, reconnectAvailable, extraActions,
+ toggleMute, setLevel, onToggleTheater, onReconnect, reconnectAvailable, overlayAction, overlaySettings, remoteActions, settings,
}: {
- controlsRef?: RefObject<HTMLDivElement | null>; hidden?: boolean;
+ controlsRef?: RefObject<HTMLDivElement | null>; visibility?: PlaybackVisibility;
audio: ViewerAudioSnapshot; paused: boolean; hasAudio: boolean; canPlay: boolean;
theaterMode: boolean; fullscreen: { supported: boolean; ready: boolean; active: boolean };
fullscreenFailed?: boolean;
picture: Pick<ReturnType<typeof usePictureInPicture>, "active" | "supported" | "failed" | "toggle">;
togglePlayback: () => void; toggleFullscreen: () => void; toggleMute: () => void;
setLevel: (level: number) => void; onToggleTheater: () => void; onReconnect: () => void;
- reconnectAvailable: boolean; extraActions?: ReactNode;
+ reconnectAvailable: boolean; overlayAction?: ReactNode; overlaySettings?: ReactNode; remoteActions?: ReactNode;
+ settings?: ViewerPlaybackSettingsProps;
}) {
const { t, vis } = useCopy();
+ const controlsId = useId();
+ const localControlsRef = useRef<HTMLDivElement>(null);
+ const barRef = controlsRef ?? localControlsRef;
+ const menuRef = useRef<HTMLDivElement>(null);
+ const [chin, setChin] = useState<HTMLElement | null>(null);
+ useEffect(() => {
+ setChin(barRef.current?.closest(".lr-tv")?.querySelector<HTMLElement>(".lr-tv-chin") ?? null);
+ }, [barRef]);
+ useAnchoredPopover(barRef, menuRef, { align: "center", minVisibleHeight: settings || overlaySettings ? 160 : Infinity });
const silent = audio.muted || audio.level === 0;
const percent = Math.round(audio.level * 100);
+ const pipTitle = picture.failed ? "playback.pipFailed" : !picture.supported ? "playback.pipUnavailable"
+ : picture.active ? "playback.exitPip" : !canPlay ? "playback.pipWaiting" : "playback.pip";
+ const theaterTitle = theaterMode ? "viewer.theater.exit" : "viewer.theater";
+ const displayActions = (caption: boolean) => <>
+ <Btn icon={picture.active ? "pipExit" : "pip"} draw="playback-pip" title={pipTitle}
+ cap={caption ? (picture.active ? "playback.exitPip" : "playback.pip") : undefined} hintTone={picture.failed ? "bad" : undefined}
+ hint={!picture.supported || picture.failed || (!picture.active && !canPlay) ? "hint-pip-unavailable" : picture.active ? "hint-pip-exit" : "hint-pip"}
+ pressed={picture.active} disabled={!picture.supported || (!picture.active && !canPlay)}
+ onClick={() => { void picture.toggle(); }} />
+ {!fullscreen.active && <Btn icon={theaterMode ? "theaterExit" : "theater"} draw="playback-theater" title={theaterTitle}
+ cap={caption ? theaterTitle : undefined} hint={theaterMode ? "hint-theater-exit" : "hint-theater"}
+ pressed={theaterMode} onClick={onToggleTheater} />}
+ </>;
+ const reveal = <button type="button" className="lr-playback-reveal" aria-label={t("playback.showControls")}
+ aria-controls={controlsId} aria-expanded={!visibility?.hidden}
+ onClick={() => barRef.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true })}>
+ <Glyph name="chevron" size={18} className="lr-playback-reveal-arrow" />
+ </button>;
- return (
- <div ref={controlsRef} className={`lr-playback lr-media-controls${hidden ? " is-hidden" : ""}`} data-can-play={canPlay} role="group" aria-label={t("playback.controls")}>
- <span className="lr-playback-audio">
+ return <>
+ <div id={controlsId} ref={barRef} className={`lr-playback lr-host-share-controls lr-media-controls${visibility?.hidden ? " is-hidden" : ""}`}
+ role="group" aria-label={t("playback.controls")}>
+ <span className="lr-playback-watch">
<Btn icon={paused ? "play" : "pause"}
draw="playback-state"
title={paused ? "playback.play" : "playback.pause"}
hint={paused ? "hint-local-play" : "hint-local-pause"}
disabled={!canPlay} onClick={togglePlayback} />
- <span className="lr-playback-separator" aria-hidden="true" />
<Btn icon={!hasAudio || silent ? "speakerOff" : "speaker"}
draw="playback-sound"
title={!hasAudio ? "playback.noAudio" : silent ? "playback.unmute" : "playback.mute"}
@@ -164,30 +202,22 @@ export function PlaybackControlsView({
text={vis ? undefined : t(!hasAudio ? "playback.noAudio" : audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")}
className="lr-playback-volume">
<input type="range" min={0} max={audio.boostAvailable ? 200 : 100} step={1}
- value={percent} disabled={!hasAudio}
- aria-label={t(audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")} aria-valuetext={`${percent}%`}
+ value={hasAudio ? percent : 0} disabled={!hasAudio}
+ aria-label={t(audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")}
+ aria-valuetext={hasAudio ? `${percent}%` : t("playback.noAudio")}
onChange={(event) => setLevel(Number(event.target.value) / 100)} />
</Tooltip>
- <span className={`lr-playback-level${percent > 100 ? " is-boosted" : ""}`} aria-hidden="true">
- {hasAudio ? `${percent}%` : "—"}
+ <span className={`lr-playback-level${hasAudio && percent > 100 ? " is-boosted" : ""}`} aria-hidden="true">
+ {hasAudio ? `${percent}%` : null}
</span>
+ {overlayAction}
</span>
+ {remoteActions}
<span className="lr-playback-view">
- {extraActions}
- <Btn icon="refresh" title="viewer.reconnect" hint="hint-reconnect" draw="playback-reconnect"
- disabled={!reconnectAvailable} onClick={onReconnect} />
- <Btn icon={picture.active ? "pipExit" : "pip"} draw="playback-pip"
- hintTone={picture.failed ? "bad" : undefined}
- title={picture.failed ? "playback.pipFailed" : !picture.supported ? "playback.pipUnavailable"
- : picture.active ? "playback.exitPip" : !canPlay ? "playback.pipWaiting" : "playback.pip"}
- hint={!picture.supported || picture.failed || (!picture.active && !canPlay) ? "hint-pip-unavailable" : picture.active ? "hint-pip-exit" : "hint-pip"}
- pressed={picture.active} disabled={!picture.supported || (!picture.active && !canPlay)}
- onClick={() => { void picture.toggle(); }} />
- {!fullscreen.active ? <Btn icon={theaterMode ? "theaterExit" : "theater"}
- draw="playback-theater"
- title={theaterMode ? "viewer.theater.exit" : "viewer.theater"}
- hint={theaterMode ? "hint-theater-exit" : "hint-theater"}
- pressed={theaterMode} onClick={onToggleTheater} /> : null}
+ <PlaybackMore panel={menuRef} settings={settings} overlaySettings={overlaySettings} onReconnect={onReconnect} reconnectAvailable={reconnectAvailable}>
+ {displayActions(true)}
+ </PlaybackMore>
+ <span className="lr-playback-secondary">{displayActions(false)}</span>
{fullscreen.supported && !theaterMode ? (
<Btn icon={fullscreen.active ? "contract" : "expand"}
draw="playback-fullscreen"
@@ -202,5 +232,39 @@ export function PlaybackControlsView({
) : null}
</span>
</div>
- );
+ {chin && !theaterMode && !fullscreen.active ? createPortal(reveal, chin) : reveal}
+ </>;
+}
+
+// Native popover owns dismissal and focus return. The same actions above render
+// directly on wide players and in this compact disclosure on narrow players.
+function PlaybackMore({ panel, children, settings, overlaySettings, onReconnect, reconnectAvailable }: {
+ panel: RefObject<HTMLDivElement | null>; children: ReactNode; settings?: ViewerPlaybackSettingsProps;
+ overlaySettings?: ReactNode;
+ onReconnect: () => void; reconnectAvailable: boolean;
+}) {
+ const { t } = useCopy();
+ const id = useId();
+ const [open, setOpen] = useState(false);
+ const reconnect = <Btn icon="refresh" title="viewer.reconnect" hint="hint-reconnect" draw="playback-reconnect"
+ cap="viewer.reconnect" disabled={!reconnectAvailable} onClick={() => {
+ panel.current?.hidePopover();
+ onReconnect();
+ }} />;
+ const display = <div className="lr-playback-display-menu">{children}</div>;
+ return <span className="lr-playback-more">
+ <Btn icon="sliders" title="playback.more" hint="hint-advanced" popoverTarget={id} expanded={open} controls={id} />
+ <div id={id} ref={panel} className={`lr-floating-surface lr-playback-menu${settings || overlaySettings ? " lr-playback-settings" : ""}`} popover="auto" aria-label={t("playback.more")}
+ onToggle={event => { if (event.target === event.currentTarget) setOpen(event.newState === "open"); }}
+ onClick={event => {
+ if (!event.defaultPrevented && event.target instanceof Element && event.target.closest(".lr-playback-display-menu button")) panel.current?.hidePopover();
+ }}>
+ {settings ? <ViewerPlaybackSettings {...settings} displayActions={display} reconnect={reconnect} />
+ : <div className="lr-playback-menu-actions">{display}{reconnect}</div>}
+ {overlaySettings && <section className="lr-playback-overlay-settings" aria-label={t("playback.overlay")}>
+ <h3><Glyph name="danmaku" size={17} /><Cap k="playback.overlay" /></h3>
+ {overlaySettings}
+ </section>}
+ </div>
+ </span>;
}
diff --git a/src/client/components/living/QualityPresets.tsx b/src/client/components/living/QualityPresets.tsx
index f6fdcbe9..eb44ea05 100644
--- a/src/client/components/living/QualityPresets.tsx
+++ b/src/client/components/living/QualityPresets.tsx
@@ -44,6 +44,15 @@ export function QualityPresets({ selected, limits = VIDEO_CAPTURE_LIMITS, disabl
</div>;
}
+export function PictureSettingsSummary({ value }: { value: QualityProfile }) {
+ const { t } = useCopy();
+ return <span className="lr-sharing-picture-summary" aria-label={t("host.settings.pictureLimits")}>
+ <span>{value.resolution.width} × {value.resolution.height}</span>
+ <span>{value.maxFramerate} fps</span>
+ <span>{value.maxBitrate / 1_000_000} Mbps</span>
+ </span>;
+}
+
export function ResolutionControl({ value, limits, disabled, onChange }: {
value: QualityResolution;
limits: VideoCaptureLimits;
@@ -80,7 +89,8 @@ export function ResolutionControl({ value, limits, disabled, onChange }: {
if (!event.currentTarget.contains(event.relatedTarget)) apply(event.currentTarget);
}}
onKeyDown={event => {
- if (!(event.target instanceof HTMLInputElement) || (event.key !== "Enter" && event.key !== "Escape")) return;
+ if (event.defaultPrevented || event.nativeEvent.isComposing ||
+ !(event.target instanceof HTMLInputElement) || (event.key !== "Enter" && event.key !== "Escape")) return;
event.preventDefault();
event.stopPropagation();
if (event.key === "Escape") reset(event.currentTarget);
@@ -159,7 +169,8 @@ function QualityNumberControl({ value, min, max, step, unit, name, label, disabl
aria-invalid={invalid || undefined} aria-describedby={invalid ? errorId : undefined}
onInput={() => setInvalid(false)}
onKeyDown={event => {
- if (event.key !== "Enter" && event.key !== "Escape") return;
+ if (event.defaultPrevented || event.nativeEvent.isComposing ||
+ (event.key !== "Enter" && event.key !== "Escape")) return;
event.preventDefault();
event.stopPropagation();
if (event.key === "Escape") reset();
diff --git a/src/client/components/living/RemoteControl.tsx b/src/client/components/living/RemoteControl.tsx
new file mode 100644
index 00000000..66ecf4c4
--- /dev/null
+++ b/src/client/components/living/RemoteControl.tsx
@@ -0,0 +1,317 @@
+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
+import { createPortal } from "react-dom";
+import { useCopy, type CopyKey } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
+import type { InputTransport } from "../../remote-control/input-route";
+import { RemoteInputSession, picturePoint, pictureRect, type RemoteInputState, type RemoteInputEvent } from "../../remote-control/input-session";
+import { RemoteTouchpad } from "../../remote-control/touchpad";
+import { RemoteViewport } from "../../remote-control/viewport";
+import { RemoteKeyboard } from "./RemoteKeyboard";
+import { Btn } from "./primitives";
+import { videoFullscreenState, type FullscreenVideo } from "./video-fullscreen";
+import type { VideoFit } from "../../media/video-geometry";
+import "./remote-control.css";
+
+// The video keeps its existing media owner. This temporary surface handles
+// input only while its current routed endpoint holds a local App grant.
+export function RemoteControl({ channel, videoRef, available, pictureFit }: {
+ channel: InputTransport | null; videoRef: RefObject<HTMLVideoElement | null>;
+ available: boolean;
+ pictureFit?: VideoFit;
+}) {
+ const { t, vis } = useCopy();
+ const [state, setState] = useState<RemoteInputState | null>(null);
+ const [locked, setLocked] = useState(false);
+ const [lockFailed, setLockFailed] = useState(false);
+ const [presentation, setPresentation] = useState<"playing" | "paused" | "external">("paused");
+ const [passwordOpen, setPasswordOpen] = useState(false);
+ const [password, setPassword] = useState("");
+ const [keyboardOpen, setKeyboardOpen] = useState(false);
+ const [keyboardDocument, setKeyboardDocument] = useState<Document | null>(null);
+ const keyboardDetached = Boolean(keyboardDocument && keyboardDocument !== document);
+ const [touch, setTouch] = useState(false);
+ const [zoomed, setZoomed] = useState(false);
+ const session = useRef<RemoteInputSession | null>(null);
+ const surface = useRef<HTMLDivElement | null>(null);
+ const cursor = useRef<SVGSVGElement | null>(null);
+ const touchpad = useRef<RemoteTouchpad | null>(null);
+ const viewport = useRef<RemoteViewport | null>(null);
+ const canControl = available && presentation === "playing";
+ const active = state?.state === "active" && canControl && channel?.readyState === "open";
+ const controlled = (state?.state === "active" || state?.state === "suspended") && canControl && channel?.readyState === "open";
+ const input = useCallback((event: RemoteInputEvent) => session.current?.input(event), []);
+ const reset = useCallback(() => { touchpad.current?.reset(); session.current?.input({ type: "reset" }); }, []);
+ const closeKeyboard = () => {
+ reset(); setKeyboardOpen(false); setKeyboardDocument(null); surface.current?.focus({ preventScroll: true });
+ };
+ const keyboardSurfaceChanged = useCallback((owner: Document) => {
+ reset(); setKeyboardDocument(owner);
+ }, [reset]);
+ const release = useCallback(() => {
+ reset();
+ if (document.pointerLockElement === surface.current && surface.current) document.exitPointerLock();
+ session.current?.release();
+ }, [reset]);
+
+ useEffect(() => {
+ setState(null);
+ setPasswordOpen(false); setPassword("");
+ if (!channel) return;
+ const current = new RemoteInputSession(channel, setState);
+ session.current = current;
+ return () => {
+ current.dispose(); session.current = null;
+ };
+ }, [channel]);
+ useEffect(() => {
+ if (controlled || state?.mode !== "password" || !canControl) {
+ setPasswordOpen(false); setPassword("");
+ }
+ }, [controlled, state?.mode, canControl]);
+ useEffect(() => {
+ if (!available) release();
+ }, [available, channel, release]);
+ useEffect(() => {
+ if (!active) { touchpad.current?.reset(); setKeyboardOpen(false); setKeyboardDocument(null); }
+ }, [active]);
+ useEffect(() => {
+ const video = videoRef.current;
+ const element = surface.current;
+ if (!controlled || !video || !element) { setTouch(false); return; }
+ const updateCursor = () => {
+ const picture = pictureRect(video);
+ const rect = surface.current?.getBoundingClientRect();
+ if (!picture || !rect || !cursor.current) return;
+ cursor.current.style.left = `${picture.left - rect.left + current.position.x * picture.width}px`;
+ cursor.current.style.top = `${picture.top - rect.top + current.position.y * picture.height}px`;
+ };
+ const view = new RemoteViewport(video, element, zoomed => {
+ setZoomed(zoomed);
+ current.position = view.visiblePosition(current.position);
+ updateCursor();
+ });
+ viewport.current = view;
+ const current = new RemoteTouchpad(
+ () => pictureRect(video),
+ event => session.current?.input(event),
+ delta => session.current?.scroll(delta, 0),
+ updateCursor,
+ view,
+ );
+ touchpad.current = current;
+ // Layout changes and decoded aspect-ratio changes share the input geometry.
+ const refresh = () => view.refresh();
+ const observer = new ResizeObserver(refresh);
+ observer.observe(video);
+ video.addEventListener("resize", refresh);
+ return () => {
+ observer.disconnect(); video.removeEventListener("resize", refresh);
+ current.reset(); view.reset(); touchpad.current = null; viewport.current = null;
+ };
+ }, [controlled, channel, videoRef]);
+ useEffect(() => { viewport.current?.refresh(); }, [pictureFit]);
+ useEffect(() => {
+ const video = videoRef.current as FullscreenVideo | null;
+ if (!video) return;
+ // Native PiP/fullscreen moves the picture away from the page's input surface.
+ // DOM fullscreen retains that surface and can continue controlling normally.
+ const syncPresentation = () => {
+ const external = document.pictureInPictureElement === video ||
+ video.webkitPresentationMode === "picture-in-picture" || videoFullscreenState(video).nativeActive;
+ const current = external ? "external" : video.paused || video.ended ? "paused" : "playing";
+ // Invalidate the request as well as its grant before a late approval arrives.
+ if (current !== "playing") release();
+ setPresentation(current);
+ };
+ const events = ["play", "pause", "ended", "emptied", "enterpictureinpicture", "leavepictureinpicture", "webkitpresentationmodechanged", "webkitbeginfullscreen", "webkitendfullscreen"];
+ syncPresentation();
+ events.forEach(event => video.addEventListener(event, syncPresentation));
+ return () => {
+ events.forEach(event => video.removeEventListener(event, syncPresentation));
+ };
+ }, [release, videoRef]);
+ useEffect(() => {
+ if (!controlled) return;
+ const element = surface.current;
+ element?.focus({ preventScroll: true });
+ const wheel = (event: WheelEvent) => { event.preventDefault(); session.current?.scroll(event.deltaY, event.deltaMode); };
+ element?.addEventListener("wheel", wheel, { passive: false });
+ // Release can land outside the picture after a drag. Observe it for this
+ // grant only; the native owner ignores buttons it never pressed.
+ const mouseUp = (event: MouseEvent) => session.current?.input({ type: "button", button: event.button, down: false });
+ window.addEventListener("mouseup", mouseUp, true);
+ const lockChanged = () => {
+ reset(); setLocked(document.pointerLockElement === element);
+ if (document.pointerLockElement === element) { setLockFailed(false); element?.focus({ preventScroll: true }); }
+ };
+ window.addEventListener("blur", reset);
+ document.addEventListener("pointerlockchange", lockChanged);
+ return () => {
+ element?.removeEventListener("wheel", wheel);
+ window.removeEventListener("mouseup", mouseUp, true);
+ window.removeEventListener("blur", reset);
+ document.removeEventListener("pointerlockchange", lockChanged);
+ if (document.pointerLockElement === element) document.exitPointerLock();
+ setLocked(false); setLockFailed(false);
+ };
+ }, [controlled, channel, release, reset]);
+ useEffect(() => {
+ if (!controlled) return;
+ const owners = [...new Set([document, ...(keyboardDocument ? [keyboardDocument] : [])])];
+ const hidden = () => {
+ reset();
+ // A visible detached keyboard is still an attended input surface.
+ if (owners.every(owner => owner.hidden || owner.defaultView?.closed)) release();
+ };
+ owners.forEach(owner => owner.addEventListener("visibilitychange", hidden));
+ hidden();
+ return () => owners.forEach(owner => owner.removeEventListener("visibilitychange", hidden));
+ }, [controlled, keyboardDocument, release, reset]);
+
+ if (!channel || channel.readyState !== "open" || !state || state.mode === "off") return null;
+ const point = (clientX: number, clientY: number) => {
+ const video = videoRef.current;
+ return video ? picturePoint(video, clientX, clientY) : null;
+ };
+ const buttonTitle = controlled ? "remote.stop" : state.state === "pending" ? "remote.cancel" : "remote.request";
+ const touchControls = touch || matchMedia("(pointer: coarse)").matches;
+ const statusIcon = state.reason === "busy" ? "users" : state.reason === "password" || state.state === "failed" ? "alert"
+ : state.state === "suspended" ? "pause" : "clock";
+ const feedback: CopyKey | undefined = state.reason ? `remote.reason.${state.reason}`
+ : state.state === "suspended" ? "remote.suspended" : state.state === "failed" ? "remote.failed"
+ : state.state === "pending" ? state.mode === "ask" ? "remote.pending" : "remote.connecting" : undefined;
+ const parent = videoRef.current?.parentElement;
+ return <>
+ <span className="lr-remote-controls" role="group" aria-label={t("remote.title")}>
+ <span className="lr-remote-viewer-control">
+ <Btn icon="mouse" title={presentation === "external" ? "remote.inlineRequired" : presentation === "paused" ? "remote.playbackRequired" : state.state === "unavailable" ? "remote.unavailable" : buttonTitle}
+ hint={controlled || state.state === "pending" ? "hint-remote-stop" : "hint-remote-control"}
+ hintText={feedback} hintTone={state.state === "failed" ? "warn" : undefined}
+ busy={state.state === "pending"} pressed={controlled} disabled={!canControl || state.state === "unavailable"}
+ onClick={() => {
+ if (controlled || state.state === "pending") release();
+ else if (state.mode === "password") setPasswordOpen(open => !open);
+ else session.current?.request();
+ }} />
+ {feedback && !passwordOpen && <span className="lr-remote-feedback" role="status">
+ <Glyph name={statusIcon} size={15} />
+ <span className={vis ? "visually-hidden" : undefined}>{t(feedback)}</span>
+ </span>}
+ </span>
+ <Btn icon="keyboard" title={keyboardDetached ? "floating.focus" : "remote.keyboard"} hint={keyboardDetached ? "hint-window-detach" : "hint-remote-keyboard"}
+ hintText={!active ? feedback ?? "remote.keyboardRequiresControl" : touchControls ? "remote.touchHelp" : undefined} expanded={keyboardOpen} disabled={!active}
+ onClick={() => {
+ if (keyboardDetached) keyboardDocument?.defaultView?.focus();
+ else if (keyboardOpen) closeKeyboard();
+ else { reset(); setKeyboardOpen(true); }
+ }} />
+ </span>
+ {parent && (controlled || state.state === "pending" || state.state === "failed" || state.reason || passwordOpen) && createPortal(<>
+ {passwordOpen && <form className="lr-remote-password" onSubmit={event => {
+ event.preventDefault(); session.current?.request(password); setPassword("");
+ }} onKeyDown={event => {
+ event.stopPropagation();
+ if (event.key === "Escape" && !event.defaultPrevented && !event.nativeEvent.isComposing) {
+ event.preventDefault(); setPasswordOpen(false); setPassword(""); release();
+ }
+ }}>
+ <div className="lr-remote-panel-header">
+ <strong><Glyph name="key" size={18} />{vis ? null : t("remote.password")}</strong>
+ <button type="button" className="lr-popover-close" aria-label={t("common.cancel")}
+ onClick={() => { setPasswordOpen(false); setPassword(""); release(); }}>
+ <Glyph name="x" size={17} />
+ </button>
+ </div>
+ <div className="lr-remote-policy-actions">
+ <label className="lr-input">
+ <input type="password" required autoFocus autoComplete="off" maxLength={128}
+ value={password} aria-label={t("remote.password")} disabled={state.state === "pending"}
+ onChange={event => setPassword(event.target.value)} />
+ </label>
+ <Btn icon="check" title="remote.request" hint="hint-remote-control" type="submit" disabled={!password || state.state === "pending"} />
+ </div>
+ {state.reason && <p role="status" className={state.reason === "password" ? "is-bad" : undefined}><Glyph name={statusIcon} size={16} />
+ <span className={vis ? "visually-hidden" : undefined}>{t(`remote.reason.${state.reason}`)}</span></p>}
+ </form>}
+ {controlled && <div ref={surface} className={`lr-remote-input-surface${active ? "" : " is-suspended"}${locked ? " is-locked" : ""}`} tabIndex={0}
+ aria-label={t("remote.surface")} role="application"
+ onContextMenu={event => event.preventDefault()}
+ onAuxClick={event => event.preventDefault()}
+ onPointerMove={event => {
+ if (event.pointerType === "touch") {
+ event.preventDefault(); event.stopPropagation();
+ touchpad.current?.move(event.pointerId, event.clientX, event.clientY); return;
+ }
+ setTouch(false);
+ if (document.pointerLockElement === surface.current) {
+ input({ type: "relative", dx: event.movementX, dy: event.movementY });
+ } else {
+ const position = point(event.clientX, event.clientY);
+ if (position) {
+ input({ type: "move", ...position });
+ if (touchpad.current) touchpad.current.position = position;
+ }
+ }
+ }}
+ onPointerDown={event => {
+ if (document.pointerLockElement !== surface.current) event.currentTarget.setPointerCapture(event.pointerId);
+ if (event.pointerType === "touch") {
+ event.preventDefault(); event.stopPropagation(); setTouch(true);
+ surface.current?.focus({ preventScroll: true });
+ touchpad.current?.down(event.pointerId, event.clientX, event.clientY);
+ }
+ }}
+ onPointerUp={event => {
+ if (event.pointerType === "touch") {
+ event.preventDefault(); event.stopPropagation(); touchpad.current?.up(event.pointerId);
+ }
+ }}
+ onClick={event => { event.preventDefault(); event.stopPropagation(); }}
+ onDoubleClick={event => { event.preventDefault(); event.stopPropagation(); }}
+ // Pointer down/up report the first/last mouse button only. Mouse events
+ // preserve chords such as holding right to aim while left clicks fire.
+ onMouseDown={event => {
+ if (event.button > 4) return;
+ event.preventDefault(); surface.current?.focus({ preventScroll: true });
+ if (document.pointerLockElement === surface.current) { input({ type: "button", button: event.button, down: true }); return; }
+ const position = point(event.clientX, event.clientY);
+ if (position) { input({ type: "move", ...position }); input({ type: "button", button: event.button, down: true }); }
+ }}
+ onPointerCancel={reset}
+ onLostPointerCapture={event => {
+ if (event.pointerType === "touch") touchpad.current?.cancel(event.pointerId);
+ // Normal mouse-up also releases capture. It must not release a key
+ // still held for movement or a keyboard/mouse chord.
+ else if (event.buttons !== 0) reset();
+ }}
+ onBlur={reset}
+ onKeyDown={event => {
+ event.preventDefault(); event.stopPropagation();
+ if (event.code === "F10" && event.ctrlKey && event.altKey) { release(); return; }
+ if (!event.nativeEvent.isComposing) input({ type: "key", code: event.code, down: true });
+ }}
+ onKeyUp={event => { event.preventDefault(); event.stopPropagation(); input({ type: "key", code: event.code, down: false }); }}>
+ <svg ref={cursor} className="lr-remote-touch-cursor" viewBox="0 0 24 28" aria-hidden="true" style={{ display: touch ? undefined : "none" }}>
+ <path d="M2 2v21l6-6 5 9 4-2-5-9h9Z" />
+ </svg>
+ </div>}
+ {controlled && zoomed && <div className="lr-remote-zoom">
+ <button type="button" className="lr-chip" aria-label={t("remote.resetZoom")}
+ onClick={() => { reset(); viewport.current?.reset(); surface.current?.focus({ preventScroll: true }); }}>1×</button>
+ </div>}
+ {active && keyboardOpen && <RemoteKeyboard input={input} touch={touchControls} platform={state.platform}
+ onSurfaceChange={keyboardSurfaceChanged}
+ mouseControl={!touchControls && "requestPointerLock" in HTMLElement.prototype && <span className="lr-remote-game-mouse"><Btn icon="gamepad"
+ title={lockFailed ? "remote.lockFailed" : locked ? "remote.releaseMouse" : "remote.gameMouse"}
+ cap={locked ? "remote.releaseMouse" : "remote.gameMouse"} pressed={locked}
+ hint={locked ? "hint-remote-mouse-release" : "hint-remote-mouse-lock"}
+ hintText={lockFailed ? "remote.lockFailed" : locked ? "remote.unlockMouse" : "remote.gameMouseHelp"}
+ hintTone={lockFailed ? "warn" : undefined}
+ onClick={() => void (async () => {
+ if (locked) document.exitPointerLock();
+ else try { await surface.current?.requestPointerLock(); setKeyboardOpen(false); } catch { setLockFailed(true); }
+ })()} /></span>}
+ close={closeKeyboard} />}
+ </>, parent)}
+ </>;
+}
diff --git a/src/client/components/living/RemoteKeyboard.tsx b/src/client/components/living/RemoteKeyboard.tsx
new file mode 100644
index 00000000..beefd9a4
--- /dev/null
+++ b/src/client/components/living/RemoteKeyboard.tsx
@@ -0,0 +1,216 @@
+import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import type { RemoteInputEvent } from "../../remote-control/input-session";
+import { REMOTE_TEXT_BYTES, type RemoteInputPlatform } from "../../remote-control/protocol";
+import { RemoteKeyboardPresses } from "../../remote-control/keyboard";
+import { readRoomPreferences, saveRoomPreferences, REMOTE_KEYBOARD_PAGES, type RoomPreferences } from "../../lib/room-preferences";
+import { isCopyKey, useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
+import { panelWindowAPI, SurfaceDocument, usePanelWindow } from "../../ui/panel-window";
+import { navigateTabs } from "../../ui/tab-navigation";
+import { Btn, Chip } from "./primitives";
+import { Tooltip } from "./Tooltip";
+import "./floating-panel.css";
+
+type Key = readonly [label: string, code: string, shifted?: string];
+const letters = (row: string): Key[] => [...row].map(letter => [letter, `Key${letter}`]);
+const functions = (start: number): Key[] => Array.from({ length: 6 }, (_, i) => [`F${start + i}`, `F${start + i}`]);
+const ROWS = {
+ letters: [letters("QWERTYUIOP"), letters("ASDFGHJKL"), letters("ZXCVBNM")],
+ symbols: [
+ [..."1234567890"].map((digit, i): Key => [digit, `Digit${digit}`, "!@#$%^&*()"[i]]),
+ [["`", "Backquote", "~"], ["-", "Minus", "_"], ["=", "Equal", "+"], ["[", "BracketLeft", "{"], ["]", "BracketRight", "}"], ["\\", "Backslash", "|"]],
+ [[";", "Semicolon", ":"], ["'", "Quote", '"'], [",", "Comma", "<"], [".", "Period", ">"], ["/", "Slash", "?"]],
+ ],
+ functions: [functions(1), functions(7), [["Caps", "CapsLock"], ["PrtSc", "PrintScreen"], ["ScrLk", "ScrollLock"], ["NumLk", "NumLock"]]],
+} satisfies Record<string, Key[][]>;
+const NAVIGATION: Key[] = [["Esc", "Escape"], ["Tab", "Tab"]];
+const EDITING: Key[] = [["Ins", "Insert"], ["Home", "Home"], ["PgUp", "PageUp"], ["Del", "Delete"], ["End", "End"], ["PgDn", "PageDown"]];
+const ARROWS: Key[] = [["↑", "ArrowUp"], ["←", "ArrowLeft"], ["↓", "ArrowDown"], ["→", "ArrowRight"]];
+type Page = RoomPreferences["keyboardPage"];
+const PAGES = REMOTE_KEYBOARD_PAGES;
+
+// The local input owns IME composition. Committed text and physical keys use
+// their existing input operations, without clipboard access or another channel.
+export function RemoteKeyboard({ input, close, mouseControl, touch, platform, onSurfaceChange }: {
+ input: (event: RemoteInputEvent) => void; close: () => void;
+ mouseControl?: ReactNode; touch: boolean;
+ platform: RemoteInputPlatform;
+ onSurfaceChange?: (owner: Document) => void;
+}) {
+ const { t, vis } = useCopy();
+ const id = useId();
+ const mac = platform === "darwin";
+ const command = mac ? "MetaLeft" : "ControlLeft";
+ const modifiersKeys: Key[] = [["Ctrl", "ControlLeft"],
+ [mac ? "Cmd" : platform === "windows" ? "Win" : "Super", "MetaLeft"], [mac ? "Opt" : "Alt", "AltLeft"], ["Shift", "ShiftLeft"]];
+ const shortcuts = [
+ [`${mac ? "Cmd" : "Ctrl"}+A`, "ControlA", [command, "KeyA"]],
+ [`${mac ? "Cmd" : "Ctrl"}+C`, "ControlC", [command, "KeyC"]],
+ [`${mac ? "Cmd" : "Ctrl"}+V`, "ControlV", [command, "KeyV"]],
+ ...(platform === "windows" ? [["Win", "MetaLeft", ["MetaLeft"]], ["Win+Space", "InputLanguage", ["MetaLeft", "Space"]]] as const
+ : mac ? [["Ctrl+Space", "InputLanguage", ["ControlLeft", "Space"]], ["Cmd+`", "SwitchWindow", ["MetaLeft", "Backquote"]]] as const : []),
+ [`${mac ? "Cmd" : "Alt"}+Tab`, mac ? "SwitchApp" : "SwitchWindow", [mac ? "MetaLeft" : "AltLeft", "Tab"]],
+ ] as const;
+ const [page, setPage] = useState<Page>(() => readRoomPreferences().keyboardPage);
+ const [text, setText] = useState("");
+ const [modifiers, setModifiers] = useState<string[]>([]);
+ const [combineKeys, setCombineKeys] = useState(() => readRoomPreferences().combineKeys);
+ const composing = useRef(false);
+ const editor = useRef<HTMLTextAreaElement>(null);
+ const textTooLong = new TextEncoder().encode(text).length > REMOTE_TEXT_BYTES;
+ const panel = useRef<HTMLElement>(null);
+ const panelWindow = usePanelWindow(true, onSurfaceChange);
+ const owner = panelWindow.surfaceDocument ?? document;
+ const presses = useMemo(() => new RemoteKeyboardPresses(input), [input]);
+ useEffect(() => {
+ panel.current?.focus({ preventScroll: true });
+ const reset = () => { presses.reset(); setModifiers([]); };
+ const hidden = () => { if (owner.hidden) reset(); };
+ reset();
+ owner.defaultView?.addEventListener("blur", reset);
+ owner.addEventListener("visibilitychange", hidden);
+ return () => {
+ owner.defaultView?.removeEventListener("blur", reset);
+ owner.removeEventListener("visibilitychange", hidden);
+ presses.reset();
+ };
+ }, [presses, owner]);
+ useEffect(() => {
+ if (owner !== document) owner.title = `${t("remote.keyboard")} · Piik`;
+ }, [owner, t]);
+ const rows = page === "text" ? [] : mac && page === "functions"
+ ? ROWS.functions.slice(0, 2)
+ : ROWS[page];
+
+ const releaseModifiers = () => {
+ modifiersKeys.forEach((_, index) => presses.up(-2 - index));
+ setModifiers([]);
+ };
+
+ const key = ([label, code, shifted]: Key) => {
+ const name = `remote.key.${code}`;
+ const caption = shifted && modifiers.includes("ShiftLeft") ? shifted : label;
+ return <button key={code} type="button" className="lr-chip"
+ data-key={code} aria-label={isCopyKey(name) ? t(name) : caption}
+ onPointerDown={event => {
+ if (event.button !== 0) return;
+ event.preventDefault(); event.currentTarget.setPointerCapture(event.pointerId);
+ presses.down(event.pointerId, [...modifiers, code], !modifiersKeys.some(([, value]) => value === code));
+ }}
+ onPointerUp={event => { presses.up(event.pointerId); releaseModifiers(); }}
+ onPointerCancel={() => { presses.reset(); setModifiers([]); }}
+ onLostPointerCapture={event => { presses.up(event.pointerId); releaseModifiers(); }}
+ onClick={event => {
+ if (event.detail === 0) { presses.tap([...modifiers, code]); releaseModifiers(); }
+ }}>
+ {caption}
+ </button>;
+ };
+
+ const modifier = ([label, code]: Key, index: number) => <span className="lr-remote-modifier-key" key={code}>
+ {combineKeys ? <Chip title={mac && code === "AltLeft" ? "Option" : label} selected={modifiers.includes(code)} onClick={() => {
+ const selected = modifiers.includes(code);
+ if (selected) presses.up(-2 - index);
+ else presses.down(-2 - index, [code], false);
+ setModifiers(current => selected ? current.filter(item => item !== code) : [...current, code]);
+ }}>{code === "ShiftLeft" ? "⇧" : label}</Chip> : key([code === "ShiftLeft" ? "⇧" : label, code])}
+ </span>;
+
+ const navigation = <div className="lr-remote-navigation">
+ <div className={`lr-remote-key-row lr-remote-navigation-actions${page === "functions" ? " is-editing" : page === "text" ? " is-text" : ""}`}>
+ {(page === "functions" ? EDITING.filter(([, code]) => !mac || code !== "Insert")
+ : [...NAVIGATION, ...(page === "text" ? [["⌫", "Backspace"], ["↵", "Enter"]] : [])]).map(item => key(item as Key))}
+ </div>
+ <div className="lr-remote-key-row lr-remote-arrows">{ARROWS.map(key)}</div>
+ </div>;
+
+ const keyboard = <SurfaceDocument.Provider value={owner}><section ref={panel} tabIndex={-1} className="lr-remote-keyboard" aria-label={t("remote.keyboard")}
+ onContextMenu={event => { if ((event.target as Element).closest("button")) event.preventDefault(); }}
+ onKeyDown={event => {
+ event.stopPropagation();
+ if (event.key === "Escape" && !event.defaultPrevented && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ if (panelWindow.detached) owner.defaultView?.close(); else close();
+ }
+ }} onKeyUp={event => event.stopPropagation()}>
+ <div className="lr-remote-panel-header">
+ <strong><Glyph name="keyboard" size={18} />{vis ? null : t("remote.keyboard")}</strong>
+ {!panelWindow.detached && <>
+ {panelWindowAPI(window) && <Tooltip kind="hint-window-detach" place="below" text={vis ? undefined : t("floating.detach")}>
+ <button type="button" className="lr-popover-close" aria-label={t("floating.detach")} disabled={panelWindow.opening}
+ onClick={() => { presses.reset(); setModifiers([]); void panelWindow.open(); }}><Glyph name="pip" size={18} /></button>
+ </Tooltip>}
+ <button type="button" className="lr-popover-close" aria-label={t("common.close")} onClick={close}><Glyph name="x" size={17} /></button>
+ </>}
+ </div>
+ {panelWindow.failed && <p className="lr-floating-error" role="status">{t("floating.detachFailed")}</p>}
+ <div className="lr-toggle lr-remote-key-pages" role="tablist" aria-label={t("remote.keyPages")}
+ style={{ "--lr-segments": PAGES.length, "--lr-selected-index": PAGES.indexOf(page) } as CSSProperties}
+ onKeyDown={navigateTabs}>
+ {PAGES.map(value => <button key={value} type="button" role="tab" id={`${id}-${value}`}
+ className={page === value ? "is-selected" : undefined} aria-selected={page === value}
+ aria-controls={`${id}-panel`} tabIndex={page === value ? 0 : -1}
+ aria-label={t(`remote.keys.${value}`)} onClick={() => {
+ presses.reset(); setModifiers([]); setPage(value); saveRoomPreferences({ keyboardPage: value });
+ }}>
+ {value === "letters" ? "ABC" : value === "symbols" ? "123" : value === "functions" ? "Fn" : vis ? <Glyph name="pencil" size={16} /> : t("remote.keys.text")}
+ </button>)}
+ </div>
+ <div id={`${id}-panel`} role="tabpanel" aria-labelledby={`${id}-${page}`}>
+ {page !== "text" ? <>
+ <div className={`lr-remote-key-layout is-${page}`}>
+ {rows.map((row, index) => <div className="lr-remote-key-row" key={index}>
+ {index === 2 && page !== "functions" && modifier(modifiersKeys[3], 3)}{row.map(key)}{index === 2 && page !== "functions" && key(["⌫", "Backspace"])}
+ </div>)}
+ </div>
+ {page === "functions" && <div className="lr-remote-key-row">{NAVIGATION.map(key)}{mac && key(["Caps", "CapsLock"])}{modifier(modifiersKeys[3], 3)}{key(["⌫", "Backspace"])}</div>}
+ <div className="lr-remote-key-row lr-remote-bottom-row">
+ {modifiersKeys.slice(0, 3).map(modifier)}{key(["␣", "Space"])}{key(["↵", "Enter"])}
+ </div>
+ {navigation}
+ <Tooltip kind="hint-key-combination" className="lr-remote-combine-hint" text={vis ? undefined : t("remote.combinationHelp")}>
+ <label className="lr-remote-combine-keys"><input type="checkbox" checked={combineKeys}
+ aria-label={t("remote.combinationMode")}
+ onChange={event => {
+ presses.reset(); setModifiers([]); setCombineKeys(event.target.checked);
+ saveRoomPreferences({ combineKeys: event.target.checked });
+ }} />
+ {vis ? <span aria-hidden="true"><kbd>⇧</kbd><span>+</span><kbd>…</kbd></span> : t("remote.combinationMode")}</label>
+ </Tooltip>
+ {!vis && <p>{t(combineKeys ? "remote.combinationHelp" : "remote.keyboardHelp")}</p>}
+ </> : <>
+ <form className="lr-remote-text-entry" onSubmit={event => {
+ event.preventDefault();
+ if (!text || textTooLong || composing.current) return;
+ input({ type: "text", text }); setText(""); editor.current?.focus();
+ }}>
+ <div className="lr-input lr-remote-text-field">
+ <textarea ref={editor} rows={4} value={text}
+ aria-label={t("remote.text")} placeholder={vis ? "" : t("remote.text")} autoComplete="off" autoCorrect="off" autoCapitalize="none" spellCheck={false}
+ aria-invalid={textTooLong || undefined}
+ aria-describedby={vis ? undefined : `${id}-text-help`}
+ enterKeyHint="enter" onChange={event => setText(event.target.value)}
+ onCompositionStart={() => { composing.current = true; }}
+ onCompositionEnd={() => { composing.current = false; }}
+ />
+ <div className="lr-remote-text-actions">
+ <Btn icon="send" cap="remote.typeText" title="remote.sendText" hint="hint-remote-keyboard" tone="primary" type="submit" disabled={!text || textTooLong} />
+ </div>
+ </div>
+ {textTooLong ? <p id={`${id}-text-help`} role="alert">{t("remote.textTooLong")}</p> : !vis && <p id={`${id}-text-help`}>{t("remote.textHelp")}</p>}
+ </form>
+ {navigation}
+ <div className="lr-remote-keys lr-remote-shortcuts">
+ {shortcuts.map(([label, name, codes]) => <button key={name} type="button" className="lr-chip"
+ aria-label={t(`remote.key.${name}`)} onClick={() => presses.tap(codes)}>{label}</button>)}
+ </div>
+ </>}
+ </div>
+ {!panelWindow.detached && mouseControl}
+ {!vis && touch && <p>{t("remote.touchHelp")}</p>}
+ </section></SurfaceDocument.Provider>;
+ return <span ref={panelWindow.slot} style={{ display: "contents" }}>
+ {panelWindow.container && createPortal(keyboard, panelWindow.container)}
+ </span>;
+}
diff --git a/src/client/components/living/RoomChatOverlay.tsx b/src/client/components/living/RoomChatOverlay.tsx
index b73cdfab..33f9aaf2 100644
--- a/src/client/components/living/RoomChatOverlay.tsx
+++ b/src/client/components/living/RoomChatOverlay.tsx
@@ -1,16 +1,19 @@
-import { useEffect, useSyncExternalStore, type CSSProperties } from "react";
+import { useEffect, useId, useSyncExternalStore, type CSSProperties } from "react";
import { CHAT_OVERLAY_DURATION_MS, RoomInteractionSession } from "../../lib/room-interactions";
+import { CHAT_OVERLAY_LIMITS } from "../../lib/room-preferences";
+import { useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
import { Btn } from "./primitives";
+import { Tooltip } from "./Tooltip";
import "./room-chat-overlay.css";
-export function RoomChatToggle({ session, caption = false }: { session: RoomInteractionSession | null; caption?: boolean }) {
- return session ? <ConnectedToggle key={session.key} session={session} caption={caption} /> : null;
+export function RoomChatToggle({ session }: { session: RoomInteractionSession | null }) {
+ return session ? <ConnectedToggle key={session.key} session={session} /> : null;
}
-function ConnectedToggle({ session, caption }: { session: RoomInteractionSession; caption: boolean }) {
+function ConnectedToggle({ session }: { session: RoomInteractionSession }) {
const { overlayEnabled } = useSyncExternalStore(session.subscribe, session.getSnapshot);
return <span className="lr-chat-overlay-toggle"><Btn icon="danmaku"
- cap={caption ? "interaction.overlay.label" : undefined}
title={overlayEnabled ? "interaction.overlay.hide" : "interaction.overlay.show"}
hint={overlayEnabled ? "hint-chat-overlay-hide" : "hint-chat-overlay-show"}
hintText={overlayEnabled ? "interaction.overlay.hideHint" : "interaction.overlay.showHint"}
@@ -18,6 +21,30 @@ function ConnectedToggle({ session, caption }: { session: RoomInteractionSession
onClick={() => session.setOverlayEnabled(!overlayEnabled)} /></span>;
}
+export function RoomChatOverlaySettings({ session }: { session: RoomInteractionSession }) {
+ const { overlayAppearance } = useSyncExternalStore(session.subscribe, session.getSnapshot);
+ const { t, vis } = useCopy();
+ const id = useId();
+ return <div className="lr-chat-overlay-settings">
+ {(["scale", "opacity"] as const).map(property => {
+ const percent = Math.round(overlayAppearance[property] * 100);
+ const label = t(`interaction.overlay.${property}`);
+ return <div className="lr-chat-setting" key={property}>
+ <label htmlFor={`${id}-${property}`}>
+ {vis ? <Glyph name={property === "scale" ? "textSize" : "opacity"} size={18} /> : label}
+ <output htmlFor={`${id}-${property}`}>{percent}%</output>
+ </label>
+ <Tooltip kind="hint-chat-settings" text={vis ? undefined : label}>
+ <input id={`${id}-${property}`} type="range" min={CHAT_OVERLAY_LIMITS[property][0] * 100}
+ max={CHAT_OVERLAY_LIMITS[property][1] * 100} step={10} value={percent}
+ aria-label={label} aria-valuetext={`${percent}%`}
+ onChange={event => session.setOverlayAppearance({ ...overlayAppearance, [property]: Number(event.target.value) / 100 })} />
+ </Tooltip>
+ </div>;
+ })}
+ </div>;
+}
+
export function RoomChatOverlay({ session, visible }: { session: RoomInteractionSession | null; visible: boolean }) {
return session ? <ConnectedOverlay key={session.key} session={session} visible={visible} /> : null;
}
diff --git a/src/client/components/living/RoomChatSettings.tsx b/src/client/components/living/RoomChatSettings.tsx
index 7cb02143..ec53bc2f 100644
--- a/src/client/components/living/RoomChatSettings.tsx
+++ b/src/client/components/living/RoomChatSettings.tsx
@@ -1,35 +1,19 @@
-import { useId, useSyncExternalStore } from "react";
-import { CHAT_HISTORY_LIMIT, CHAT_OVERLAY_LIMITS, RoomInteractionSession } from "../../lib/room-interactions";
+import { useSyncExternalStore } from "react";
+import { CHAT_HISTORY_LIMIT, RoomInteractionSession } from "../../lib/room-interactions";
import { downloadBlob } from "../../lib/download";
import { formatChatTranscript } from "../../lib/room-chat-export";
import { useCopy } from "../../ui/copy";
-import { Glyph } from "../../ui/icons";
import { Btn } from "./primitives";
-import { Tooltip } from "./Tooltip";
+import { RoomChatOverlaySettings } from "./RoomChatOverlay";
export function RoomChatSettings({ session }: { session: RoomInteractionSession }) {
- const { overlayAppearance, messages } = useSyncExternalStore(session.subscribe, session.getSnapshot);
+ const { messages } = useSyncExternalStore(session.subscribe, session.getSnapshot);
const { t, vis } = useCopy();
- const id = useId();
- return <div className="lr-chat-settings">
+ return <div className="lr-floating-scroll lr-chat-settings">
{!vis && <p>{t("interaction.settingsHint")}</p>}
- {(["scale", "opacity"] as const).map(property => {
- const percent = Math.round(overlayAppearance[property] * 100);
- const label = t(`interaction.overlay.${property}`);
- return <div className="lr-chat-setting" key={property}>
- <label htmlFor={`${id}-${property}`}>
- {vis ? <Glyph name={property === "scale" ? "textSize" : "opacity"} size={18} /> : label}
- <output htmlFor={`${id}-${property}`}>{percent}%</output>
- </label>
- <Tooltip kind="hint-chat-settings" text={vis ? undefined : label}>
- <input id={`${id}-${property}`} type="range" min={CHAT_OVERLAY_LIMITS[property][0] * 100}
- max={CHAT_OVERLAY_LIMITS[property][1] * 100} step={10} value={percent}
- aria-label={label} aria-valuetext={`${percent}%`}
- onChange={event => session.setOverlayAppearance({ ...overlayAppearance, [property]: Number(event.target.value) / 100 })} />
- </Tooltip>
- </div>;
- })}
+ <RoomChatOverlaySettings session={session} />
<div className="lr-chat-export">
+ {!vis && <p>{t("interaction.ephemeral")}</p>}
<Btn icon="save" title="interaction.export" cap="interaction.export" hint="hint-chat-export"
hintText="interaction.exportHint" disabled={!messages.length} onClick={() => {
downloadBlob(new Blob([formatChatTranscript(messages)], { type: "text/plain;charset=utf-8" }),
diff --git a/src/client/components/living/RoomInteractions.tsx b/src/client/components/living/RoomInteractions.tsx
index 9f0c5a2d..1bb58ecb 100644
--- a/src/client/components/living/RoomInteractions.tsx
+++ b/src/client/components/living/RoomInteractions.tsx
@@ -1,6 +1,7 @@
-import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
-import { normalizeChatText, MAX_CHAT_CODE_POINTS, REACTION_IDS, isThrow } from "../../../shared/room-interactions";
+import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type RefObject } from "react";
+import { normalizeChatText, MAX_CHAT_CODE_POINTS, isThrow, type ReactionId } from "../../../shared/room-interactions";
import { RoomInteractionSession } from "../../lib/room-interactions";
+import { readRoomPreferences, saveRoomPreferences } from "../../lib/room-preferences";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
import { Btn, SwitchItem } from "./primitives";
@@ -8,12 +9,14 @@ import { participantColor } from "./participant-color";
import { FloatingPanel } from "./FloatingPanel";
import { PawnSvg } from "./Pawn";
import { Couch, type CouchProps } from "./Couch";
-import { RoomReaction, ReactionIcon } from "./RoomReaction";
+import { RoomReaction } from "./RoomReaction";
+import { RoomReactionGrid, RoomReactionPicker, type InteractionParticipant } from "./RoomReactionPicker";
+import { RoomReactionActivity } from "./RoomReactionActivity";
+import { Tooltip } from "./Tooltip";
import { RoomChatToggle } from "./RoomChatOverlay";
import { RoomChatSettings } from "./RoomChatSettings";
import "./room-interactions.css";
-interface Participant { peerId: string; displayName: string }
type Props = CouchProps & { session: RoomInteractionSession | null };
export function RoomInteractions(props: Props) {
@@ -35,19 +38,22 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
const [chatDocument, setChatDocument] = useState<Document | null>(null);
const detached = Boolean(chatDocument && chatDocument !== document);
const [settingsOpen, setSettingsOpen] = useState(false);
- const [effects, setEffects] = useState(true);
+ const [effects, setEffects] = useState(() => readRoomPreferences().interactionEffects);
const [target, setTarget] = useState<string | null>(null);
+ const [panelTarget, setPanelTarget] = useState<string | null>(null);
const [draft, setDraft] = useState("");
const [lastSeen, setLastSeen] = useState<string | null>(null);
const [visible, setVisible] = useState(false);
const [following, setFollowing] = useState(true);
const area = useRef<HTMLDivElement>(null);
+ const panelArea = useRef<HTMLDivElement>(null);
const anchor = useRef<HTMLButtonElement | null>(null);
+ const panelAnchor = useRef<HTMLElement | null>(null);
const log = useRef<HTMLDivElement>(null);
const readingPosition = useRef(0);
const id = useId();
const menuId = `${id}-person`;
- const participants: Participant[] = [
+ const participants: InteractionParticipant[] = [
...(couch.host ? [{ peerId: couch.host.key, displayName: couch.host.name }] : []),
...couch.entries.map(entry => ({ peerId: entry.key, displayName: entry.name })),
];
@@ -56,6 +62,9 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
const unread = latest === lastSeen ? 0 : state.messages.length - unseenIndex - 1;
const canSend = state.ready && !state.pending && !state.coolingDown;
const person = participants.find(person => person.peerId === target);
+ const panelPerson = participants.find(person => person.peerId === panelTarget);
+ const latestReaction = state.reactions.at(-1);
+ const showChat = !settingsOpen;
const rosterKey = participants.map(person => person.peerId).join(",");
const inspect = target === couch.host?.key && couch.host.onSelect ? () => { if (!couch.host?.selected) couch.host?.onSelect?.(); }
: couch.entries.some(entry => entry.key === target && entry.selectable !== false) && couch.onSelect
@@ -68,6 +77,16 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
setDraft(current => normalizeChatText(current) === text ? "" : current);
}
}, [state.confirmed]);
+ useEffect(() => {
+ if (panelTarget && !panelPerson) setPanelTarget(null);
+ }, [panelTarget, panelPerson]);
+ useLayoutEffect(() => {
+ if (!panelTarget) return;
+ const selected = panelArea.current?.querySelector<HTMLButtonElement>('[aria-pressed="true"]');
+ selected?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ // Enter the tray on opening, without stealing focus when retargeting.
+ if (selected?.ownerDocument.activeElement === panelAnchor.current) selected.focus({ preventScroll: true });
+ }, [panelTarget, chatDocument]);
useLayoutEffect(() => {
const popup = document.getElementById(menuId);
if (!popup) return;
@@ -81,6 +100,21 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
anchor.current = trigger;
setTarget(key);
}
+ function sendReaction(reaction: ReactionId, targetPeerId?: string) {
+ session.send({ kind: "reaction", reaction, ...(targetPeerId ? { targetPeerId } : {}) });
+ }
+ function openPanelReactions(key: string, trigger: HTMLElement | null) {
+ panelAnchor.current = trigger;
+ setPanelTarget(key);
+ }
+ function dismissPicker(event: KeyboardEvent) {
+ if (event.key !== "Escape" || event.defaultPrevented || event.nativeEvent.isComposing || !panelPerson) return;
+ event.preventDefault();
+ setPanelTarget(null);
+ const opener = panelAnchor.current?.isConnected ? panelAnchor.current
+ : event.currentTarget.ownerDocument.getElementById(`${id}-express`);
+ opener?.focus({ preventScroll: true });
+ }
useLayoutEffect(() => {
// Moving a popover between documents resets its native scroll offset.
// Content owns reading position; following the latest message remains below.
@@ -107,13 +141,13 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
owner.removeEventListener("visibilitychange", sync);
setVisible(false);
};
- }, [chatOpen, chatDocument]);
+ }, [chatOpen, chatDocument, showChat]);
useEffect(() => {
- if (!chatOpen || !visible || !following || log.current?.ownerDocument.visibilityState !== "visible" ||
+ if (!showChat || !chatOpen || !visible || !following || log.current?.ownerDocument.visibilityState !== "visible" ||
!log.current?.getClientRects().length) return;
setLastSeen(latest);
log.current.scrollTop = log.current.scrollHeight;
- }, [latest, chatOpen, visible, following, chatDocument]);
+ }, [latest, chatOpen, visible, following, chatDocument, showChat, panelTarget]);
return <div className="lr-room-interactions">
<div className="visually-hidden" role="log" aria-label={t("interaction.reactions")}
@@ -129,24 +163,32 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
<FloatingPanel id={id} trigger={`${id}-toggle`} icon="chat" className="lr-interaction-panel" detachable
title={t(settingsOpen ? "interaction.settings" : "interaction.title")}
onOpenChange={(open, owner) => { setChatOpen(open); setChatDocument(owner); }}>
- {settingsOpen && <RoomChatSettings session={session} />}
- <div className="lr-chat-history" hidden={settingsOpen}>
- <div className="lr-chat-log" role="log" aria-label={t("interaction.title")} aria-live="polite" aria-relevant="additions" tabIndex={0} ref={log}
+ {settingsOpen && <>
+ <div className="lr-interaction-back"><Btn icon="chat" title="interaction.back" cap="interaction.back"
+ hint="hint-chat-open" onClick={() => setSettingsOpen(false)} /></div>
+ <RoomChatSettings session={session} />
+ </>}
+ <div className="lr-interaction-conversation" hidden={!showChat} ref={panelArea} onKeyDown={dismissPicker}>
+ <div className="lr-chat-history">
+ <div className="lr-chat-log" role="log" aria-label={t("interaction.chat")} aria-live="polite" aria-relevant="additions" tabIndex={0} ref={log}
onScroll={event => {
const node = event.currentTarget;
readingPosition.current = node.scrollTop;
setFollowing(node.scrollHeight - node.scrollTop - node.clientHeight < 40);
}}>
{state.messages.length === 0 ? <div className="lr-chat-empty">
- <span className="lr-chat-welcome" aria-hidden="true">{participants.slice(0, 2).map(person =>
- <PawnSvg key={person.peerId} identity={person.peerId} color={participantColor(person.peerId)} host={person.peerId === couch.host?.key} />)}
- <Glyph name="chat" size={24} /></span><p>{vis ? "···" : t("interaction.empty")}</p>
+ <Glyph name="chat" size={24} /><p>{vis ? "···" : t("interaction.empty")}</p>
</div> : state.messages.map((message, index) => {
const previous = state.messages[index - 1];
const continuation = previous?.sender.peerId === message.sender.peerId && previous.sender.displayName === message.sender.displayName;
+ const participant = participants.find(person => person.peerId === message.sender.peerId);
+ const avatar = <PawnSvg color={participantColor(message.sender.peerId)} host={message.sender.role === "host"} />;
return <div key={message.id} className={`lr-chat-message${message.isSelf ? " is-self" : ""}${continuation ? " is-continuation" : ""}`}>
- {!continuation && <span className="lr-chat-avatar" aria-hidden="true"><PawnSvg
- color={participantColor(message.sender.peerId)} host={message.sender.role === "host"} /></span>}
+ {!continuation && (participant ? <button type="button" className="lr-chat-avatar"
+ aria-label={t("interaction.withPerson", { name: participant.displayName })}
+ aria-expanded={panelTarget === participant.peerId} aria-controls={`${id}-reactions`}
+ onClick={event => openPanelReactions(participant.peerId, event.currentTarget)}>{avatar}</button>
+ : <span className="lr-chat-avatar" aria-hidden="true">{avatar}</span>)}
<div className="lr-chat-bubble">
<span className={continuation ? "visually-hidden" : "lr-chat-author"}>{message.sender.displayName}
{message.sender.role === "host" && <span className="visually-hidden"> · {t("common.host")}</span>}</span>
@@ -155,89 +197,88 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
</div>;
})}
</div>
- {!following && state.messages.length > 0 && <button type="button" className="lr-chat-latest" onClick={() => {
+ {!following && !panelPerson && state.messages.length > 0 && <button type="button" className="lr-chat-latest" onClick={() => {
setFollowing(true); log.current?.focus({ preventScroll: true });
}}><Glyph name="arrowDown" size={15} /><span className={vis ? "visually-hidden" : undefined}>
{unread ? t("interaction.unread", { count: String(unread) }) : t("interaction.latest")}</span></button>}
+ {chatOpen && !settingsOpen && effects && !panelPerson && latestReaction &&
+ <RoomReactionActivity key={latestReaction.id} reaction={latestReaction} participants={participants}
+ hostPeerId={couch.host?.key} now={session.now} />}
</div>
- <form className="lr-chat-compose" hidden={settingsOpen} onSubmit={event => {
+ <div id={`${id}-reactions`} className="lr-floating-scroll lr-interaction-picker" hidden={!panelPerson}>
+ <div className="lr-interaction-people-scroll">
+ <div className="lr-interaction-people" role="group" aria-label={t("interaction.participant")}>
+ {participants.map(person => {
+ const name = person.peerId === state.peerId && !vis ? t("common.you") : person.displayName;
+ return <span key={person.peerId} data-room-peer={person.peerId}>
+ <Tooltip overflow={{ text: name, selector: ".lr-pawn-name" }}>
+ <button type="button" className={`lr-pawn${person.peerId === state.peerId ? " is-you" : ""}`}
+ aria-label={t("interaction.withPerson", { name: person.displayName })}
+ aria-pressed={panelTarget === person.peerId}
+ onClick={() => setPanelTarget(person.peerId)}>
+ <PawnSvg color={participantColor(person.peerId)} identity={person.peerId} host={person.peerId === couch.host?.key} />
+ <span className="lr-pawn-name">{name}</span>
+ </button>
+ </Tooltip>
+ </span>;
+ })}
+ </div>
+ </div>
+ <RoomReactionGrid person={panelPerson} selfPeerId={state.peerId} reactionIds={state.reactionIds} canSend={canSend} onSend={sendReaction} />
+ </div>
+ {chatOpen && !settingsOpen && panelPerson && effects &&
+ <ReactionEffects state={state} participants={participants} area={panelArea} now={session.now} />}
+ </div>
+ <form className="lr-chat-compose" hidden={!showChat} onKeyDown={dismissPicker} onSubmit={event => {
event.preventDefault();
const text = normalizeChatText(draft);
if (text && canSend) { setFollowing(true); session.send({ kind: "chat", text }); }
}}>
+ <div className="lr-chat-input-row">
<input value={draft} onChange={event => setDraft(event.target.value)} maxLength={MAX_CHAT_CODE_POINTS * 2}
aria-label={t("interaction.placeholder")} placeholder={vis ? "···" : t("interaction.placeholder")}
- autoComplete="off"
+ name="message" autoComplete="off" onFocus={() => setPanelTarget(null)}
onKeyDown={event => { if (event.key === "Enter" && event.nativeEvent.isComposing) event.preventDefault(); }} />
<Btn type="submit" icon="send" title="interaction.send" hint="hint-chat-send" tone="primary" busy={state.pending?.payload.kind === "chat"}
disabled={!canSend || !normalizeChatText(draft)} />
+ </div>
+ <div className="lr-chat-tools">
+ <Btn id={`${id}-express`} icon="smile" title="interaction.express" cap="interaction.express"
+ hint="hint-reaction-picker"
+ expanded={Boolean(panelPerson)} controls={`${id}-reactions`} tone={panelPerson ? "on" : undefined}
+ onClick={() => {
+ if (panelPerson) setPanelTarget(null);
+ else openPanelReactions(state.peerId!, panelArea.current?.ownerDocument.getElementById(`${id}-express`) ?? null);
+ }} />
+ <RoomChatToggle session={session} />
+ <span className="lr-chat-count" aria-hidden="true" style={{ visibility: draft ? undefined : "hidden" }}>
+ {Array.from(draft).length} / {MAX_CHAT_CODE_POINTS}</span>
+ <Btn icon="sliders" title="interaction.settings" hint="hint-chat-settings"
+ onClick={() => { setPanelTarget(null); setSettingsOpen(true); }} />
+ </div>
</form>
- <footer className="lr-chat-footer">
- <div className="lr-chat-actions">
- <RoomChatToggle session={session} caption />
- <Btn icon={settingsOpen ? "chat" : "sliders"}
- title={settingsOpen ? "interaction.back" : "interaction.settings"}
- hint={settingsOpen ? "hint-chat-open" : "hint-chat-settings"}
- pressed={settingsOpen} tone={settingsOpen ? "on" : undefined}
- onClick={() => setSettingsOpen(value => !value)} />
- </div>
- <div className="lr-interaction-status" role="status">
- {state.error ? <><Glyph name="alert" size={14} /><span className={vis ? "visually-hidden" : undefined}>{t(`interaction.error.${state.error}`)}</span></>
- : !state.ready ? <><Glyph name="network" size={14} /><span className={vis ? "visually-hidden" : undefined}>{t("interaction.reconnecting")}</span></>
- : !vis && <span>{t("interaction.ephemeral")}</span>}
- </div>
- {!settingsOpen && <span className="lr-chat-count" aria-hidden="true" style={{ visibility: draft ? undefined : "hidden",
- minWidth: `${String(MAX_CHAT_CODE_POINTS).length * 2 + 3}ch` }}>{Array.from(draft).length} / {MAX_CHAT_CODE_POINTS}</span>}
- </footer>
+ {(state.error || !state.ready) && <div className="lr-interaction-status" role="status">
+ <Glyph name={state.error ? "alert" : "network"} size={14} />
+ <span className={vis ? "visually-hidden" : undefined}>{t(state.error ? `interaction.error.${state.error}` : "interaction.reconnecting")}</span>
+ </div>}
</FloatingPanel>
<div className="lr-interaction-couch" ref={area}>
<Couch {...couch} participantAction={{ open: openReactions, target, controls: menuId }}
footerAction={<span className="lr-interaction-chat-toggle">
<Btn id={`${id}-toggle`} icon="chat" title={detached ? "interaction.focus" : chatOpen ? "interaction.close" : "interaction.open"}
cap="interaction.open" expanded={chatOpen} controls={detached ? undefined : id}
- hint={detached ? "hint-chat-detach" : chatOpen ? "hint-close" : "hint-chat-open"}
+ hint={detached ? "hint-window-detach" : chatOpen ? "hint-close" : "hint-chat-open"}
tone={chatOpen ? "on" : undefined} popoverTarget={detached ? undefined : id}
onClick={detached ? () => chatDocument?.defaultView?.focus() : undefined} />
{unread > 0 && <span className="lr-interaction-unread" aria-label={t("interaction.unread", { count: String(unread) })}>{unread}</span>}
</span>} />
- {effects && state.reactions.map((reaction, index) => {
- const payload = reaction.payload;
- if (payload.kind !== "reaction") return null;
- // Only one's own expression replaces one's previous expression.
- // Receiving a gift never speaks for that person or hides their reaction.
- const covered = !payload.targetPeerId && !isThrow(payload.reaction) && state.reactions.slice(index + 1).some(next =>
- next.payload.kind === "reaction" && !next.payload.targetPeerId && !isThrow(next.payload.reaction) &&
- next.sender.peerId === reaction.sender.peerId);
- if (covered) return null;
- return participants.some(person => person.peerId === reaction.sender.peerId) &&
- (!payload.targetPeerId || participants.some(person => person.peerId === payload.targetPeerId)) &&
- <RoomReaction key={reaction.id} reaction={reaction} area={area} now={session.now} />;
- })}
+ {effects && <ReactionEffects state={state} participants={participants} area={area} now={session.now} />}
</div>
<FloatingPanel id={menuId} trigger={anchor} compact anchorOnOpen icon="smile" className="lr-person-menu"
title={t("interaction.express")} onOpenChange={open => { if (!open) setTarget(null); }}>
- <div className="lr-person-menu-body">
- <div className="lr-person-menu-target" role="group"
- aria-label={person ? t("interaction.withPerson", { name: person.displayName }) : t("interaction.express")}>
- <span className="lr-person-menu-name">
- <span className="lr-person-menu-portrait">{person
- ? <PawnSvg color={participantColor(person.peerId)} host={person.peerId === couch.host?.key} />
- : <Glyph name="smile" size={22} />}</span>
- <span>{!vis && <small>{t(target === state.peerId ? "interaction.express" : "interaction.toPerson")}</small>}
- <b>{person?.displayName ?? t("interaction.participant")}</b></span>
- </span>
- </div>
- {[false, true].filter(throws => !throws || (person && target !== state.peerId)).map(throws => <div key={String(throws)} className={throws ? "lr-reaction-props" : "lr-reaction-grid"}>
- {REACTION_IDS.filter(reaction => isThrow(reaction) === throws).map(reaction => <button key={reaction} type="button"
- aria-label={t(`interaction.reaction.${reaction}`)} aria-disabled={!canSend || !person}
- onClick={() => {
- if (!canSend || !person) return;
- session.send({ kind: "reaction", reaction, ...(target !== state.peerId ? { targetPeerId: person.peerId } : {}) });
- }}>
- <ReactionIcon reaction={reaction} />
- {throws && !vis && <span>{t(reaction === "tomato" ? "interaction.prop.tomato" : "interaction.prop.poop")}</span>}
- </button>)}
- </div>)}
+ <div className="lr-floating-scroll lr-person-menu-body">
+ <RoomReactionPicker person={person} selfPeerId={state.peerId} hostPeerId={couch.host?.key}
+ reactionIds={state.reactionIds} canSend={canSend} onSend={sendReaction} />
{state.error || !state.ready ? <div className="lr-interaction-status" role="status">
<Glyph name={state.error ? "alert" : "network"} size={14} />
<span className={vis ? "visually-hidden" : undefined}>{t(state.error ? `interaction.error.${state.error}` : "interaction.reconnecting")}</span>
@@ -247,10 +288,32 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
<span className="visually-hidden">{vis && t("host.details")}</span>
</button>}
{target === state.peerId && <div className="lr-interaction-effects">
- <SwitchItem checked={effects} onChange={setEffects} label={t("interaction.effects")} />
+ <SwitchItem checked={effects} onChange={enabled => {
+ setEffects(enabled); saveRoomPreferences({ interactionEffects: enabled });
+ }} label={t("interaction.effects")} />
{vis && <Glyph name="smile" size={17} />}
</div>}
</div>
</FloatingPanel>
</div>;
}
+
+function ReactionEffects({ state, participants, area, now }: {
+ state: ReturnType<RoomInteractionSession["getSnapshot"]>;
+ participants: InteractionParticipant[];
+ area: RefObject<HTMLDivElement | null>;
+ now: () => number;
+}) {
+ return state.reactions.map((reaction, index) => {
+ const payload = reaction.payload;
+ if (payload.kind !== "reaction") return null;
+ // A gift never speaks for its recipient or replaces their own expression.
+ const covered = !payload.targetPeerId && !isThrow(payload.reaction) && state.reactions.slice(index + 1).some(next =>
+ next.payload.kind === "reaction" && !next.payload.targetPeerId && !isThrow(next.payload.reaction) &&
+ next.sender.peerId === reaction.sender.peerId);
+ if (covered) return null;
+ return participants.some(person => person.peerId === reaction.sender.peerId) &&
+ (!payload.targetPeerId || participants.some(person => person.peerId === payload.targetPeerId)) &&
+ <RoomReaction key={reaction.id} reaction={reaction} area={area} now={now} />;
+ });
+}
diff --git a/src/client/components/living/RoomReaction.tsx b/src/client/components/living/RoomReaction.tsx
index 94e27c2d..87db8c4b 100644
--- a/src/client/components/living/RoomReaction.tsx
+++ b/src/client/components/living/RoomReaction.tsx
@@ -1,8 +1,9 @@
-import { useLayoutEffect, useRef, type CSSProperties, type RefObject } from "react";
+import { useEffect, useRef, type CSSProperties, type RefObject } from "react";
import { REACTION_DURATION_MS, REACTION_GLYPHS, isThrow, type ReactionId } from "../../../shared/room-interactions";
import type { RoomInteraction } from "../../lib/room-interactions";
import { identityHash } from "../../lib/identity-hash";
import { Glyph } from "../../ui/icons";
+import { useSurfaceDocument } from "../../ui/panel-window";
/** Props use the same small silhouette in the picker and on the couch. */
export function ReactionIcon({ reaction }: { reaction: ReactionId }) {
@@ -47,11 +48,16 @@ export function RoomReaction({ reaction, area, now }: {
reaction: RoomInteraction & { expiresAt: number }; area: RefObject<HTMLDivElement | null>; now: () => number;
}) {
const flight = useRef<HTMLDivElement>(null);
+ const surfaceDocument = useSurfaceDocument();
const payload = reaction.payload;
- useLayoutEffect(() => {
+ // A newly mounted surface must attach its parent ref before placement starts.
+ useEffect(() => {
const root = area.current;
const element = flight.current;
if (!root || !element || payload.kind !== "reaction") return;
+ const owner = root.ownerDocument;
+ const view = owner.defaultView;
+ if (!view) return;
const pawn = (peer: string) => root.querySelector<SVGSVGElement>(`[data-room-peer="${CSS.escape(peer)}"] .lr-person`);
const sender = pawn(reaction.sender.peerId);
const recipient = pawn(payload.targetPeerId ?? reaction.sender.peerId);
@@ -63,8 +69,8 @@ export function RoomReaction({ reaction, area, now }: {
element.style.visibility = "hidden";
return;
}
- frame = requestAnimationFrame(place);
- if (document.hidden || !sender.getClientRects().length || !recipient.getClientRects().length) {
+ frame = view.requestAnimationFrame(place);
+ if (owner.hidden || !sender.getClientRects().length || !recipient.getClientRects().length) {
element.style.visibility = "hidden";
impact?.cancel();
return;
@@ -85,7 +91,7 @@ export function RoomReaction({ reaction, area, now }: {
place();
const body = recipient.querySelector<SVGGElement>(".lr-reaction-body");
if (isThrow(payload.reaction) && payload.targetPeerId && body &&
- !window.matchMedia("(prefers-reduced-motion: reduce)").matches && !root.closest("[data-comic-reduced-motion]")) {
+ !view.matchMedia("(prefers-reduced-motion: reduce)").matches && !root.closest("[data-comic-reduced-motion]")) {
const elapsed = Math.max(0, REACTION_DURATION_MS - (reaction.expiresAt - now()));
const delay = REACTION_DURATION_MS * .32 - elapsed;
if (delay > -560) {
@@ -98,8 +104,8 @@ export function RoomReaction({ reaction, area, now }: {
], { duration: 560, delay, easing: "ease-out" });
}
}
- return () => { cancelAnimationFrame(frame); impact?.cancel(); };
- }, [area, reaction, payload, now]);
+ return () => { view.cancelAnimationFrame(frame); impact?.cancel(); };
+ }, [area, reaction, payload, now, surfaceDocument]);
if (payload.kind !== "reaction") return null;
const gift = Boolean(payload.targetPeerId && !isThrow(payload.reaction));
return <div ref={flight} className={`lr-reaction-flight ${payload.targetPeerId ? gift ? "is-gift" : "is-throw" : "is-expression"}`}
@@ -108,7 +114,7 @@ export function RoomReaction({ reaction, area, now }: {
// CSS restarts after display:none or reduced motion. Event expiry still
// owns time, including a late mount when effects are shown again.
for (const animation of (event.target as Element).getAnimations()) {
- if (animation instanceof CSSAnimation && animation.animationName.startsWith("lr-reaction-")) {
+ if ("animationName" in animation && (animation as CSSAnimation).animationName.startsWith("lr-reaction-")) {
animation.currentTime = Math.min(REACTION_DURATION_MS, Math.max(0, REACTION_DURATION_MS - (reaction.expiresAt - now())));
}
}
diff --git a/src/client/components/living/RoomReactionActivity.tsx b/src/client/components/living/RoomReactionActivity.tsx
new file mode 100644
index 00000000..a028bf21
--- /dev/null
+++ b/src/client/components/living/RoomReactionActivity.tsx
@@ -0,0 +1,34 @@
+import { useRef } from "react";
+import type { RoomInteraction } from "../../lib/room-interactions";
+import { Glyph } from "../../ui/icons";
+import { PawnSvg } from "./Pawn";
+import { participantColor } from "./participant-color";
+import { RoomReaction } from "./RoomReaction";
+import type { InteractionParticipant } from "./RoomReactionPicker";
+
+/** The compact window shows the latest live action without adding chat history or a timer. */
+export function RoomReactionActivity({ reaction, participants, hostPeerId, now }: {
+ reaction: RoomInteraction & { expiresAt: number };
+ participants: InteractionParticipant[];
+ hostPeerId?: string;
+ now: () => number;
+}) {
+ const area = useRef<HTMLDivElement>(null);
+ if (reaction.payload.kind !== "reaction") return null;
+ const { targetPeerId } = reaction.payload;
+ const sender = participants.find(person => person.peerId === reaction.sender.peerId);
+ const recipient = participants.find(person => person.peerId === targetPeerId);
+ if (!sender || (targetPeerId && !recipient)) return null;
+ return <div className="lr-interaction-activity" ref={area} aria-hidden="true">
+ <div className="lr-interaction-activity-people">
+ {[sender, ...(recipient ? [recipient] : [])].map((person, index) => <span key={person.peerId}>
+ {index > 0 && <Glyph name="arrowRight" size={14} />}
+ <span className="lr-interaction-activity-person" data-room-peer={person.peerId}>
+ <PawnSvg color={participantColor(person.peerId)} identity={person.peerId} host={person.peerId === hostPeerId} />
+ <span>{person.displayName}</span>
+ </span>
+ </span>)}
+ </div>
+ <RoomReaction reaction={reaction} area={area} now={now} />
+ </div>;
+}
diff --git a/src/client/components/living/RoomReactionPicker.tsx b/src/client/components/living/RoomReactionPicker.tsx
new file mode 100644
index 00000000..e771fb13
--- /dev/null
+++ b/src/client/components/living/RoomReactionPicker.tsx
@@ -0,0 +1,57 @@
+import { isThrow, type ReactionId } from "../../../shared/room-interactions";
+import { useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
+import { PawnSvg } from "./Pawn";
+import { participantColor } from "./participant-color";
+import { ReactionIcon } from "./RoomReaction";
+import { Tooltip } from "./Tooltip";
+
+export interface InteractionParticipant { peerId: string; displayName: string }
+
+/** The couch shortcut and detached room share the same choices and target semantics. */
+export function RoomReactionPicker({ person, selfPeerId, hostPeerId, reactionIds, canSend, onSend }: {
+ person: InteractionParticipant | undefined;
+ selfPeerId: string | null;
+ hostPeerId?: string;
+ reactionIds: readonly ReactionId[];
+ canSend: boolean;
+ onSend: (reaction: ReactionId, targetPeerId?: string) => void;
+}) {
+ const { t, vis } = useCopy();
+ const self = person?.peerId === selfPeerId;
+ return <>
+ <div className="lr-person-menu-target" role="group"
+ aria-label={person ? t("interaction.withPerson", { name: person.displayName }) : t("interaction.express")}>
+ <span className="lr-person-menu-name">
+ <span className="lr-person-menu-portrait">{person
+ ? <PawnSvg color={participantColor(person.peerId)} host={person.peerId === hostPeerId} />
+ : <Glyph name="smile" size={22} />}</span>
+ <span>{!vis && <small>{t(self ? "interaction.express" : "interaction.toPerson")}</small>}
+ <Tooltip overflow={{ text: person?.displayName ?? t("interaction.participant"), selector: "b" }}>
+ <b>{person?.displayName ?? t("interaction.participant")}</b>
+ </Tooltip></span>
+ </span>
+ </div>
+ <RoomReactionGrid person={person} selfPeerId={selfPeerId} reactionIds={reactionIds} canSend={canSend} onSend={onSend} />
+ </>;
+}
+
+export function RoomReactionGrid({ person, selfPeerId, reactionIds, canSend, onSend }: {
+ person: InteractionParticipant | undefined;
+ selfPeerId: string | null;
+ reactionIds: readonly ReactionId[];
+ canSend: boolean;
+ onSend: (reaction: ReactionId, targetPeerId?: string) => void;
+}) {
+ const { t, vis } = useCopy();
+ const self = person?.peerId === selfPeerId;
+ return <div className="lr-reaction-grid">
+ {reactionIds.filter(reaction => !isThrow(reaction) || (person && !self)).map(reaction => <button key={reaction} type="button"
+ className={isThrow(reaction) ? "lr-btn lr-reaction-prop" : "lr-reaction-option"}
+ aria-label={t(`interaction.reaction.${reaction}`)} aria-disabled={!canSend || !person}
+ onClick={() => { if (canSend && person) onSend(reaction, self ? undefined : person.peerId); }}>
+ <ReactionIcon reaction={reaction} />
+ {isThrow(reaction) && !vis && <span>{t(`interaction.reaction.${reaction}`)}</span>}
+ </button>)}
+ </div>;
+}
diff --git a/src/client/components/living/RouteTree.tsx b/src/client/components/living/RouteTree.tsx
index 7315695a..779cdc04 100644
--- a/src/client/components/living/RouteTree.tsx
+++ b/src/client/components/living/RouteTree.tsx
@@ -34,6 +34,7 @@ const PAWN_CENTER_X = 20;
const PAWN_SCALE = 0.82;
const PAWN_CENTER_Y = 24;
const LABEL_GAP = 12;
+const SFU_HALF_WIDTH = 20;
function centeredPawnX(centerX: number, scale: number): number {
return centerX - PAWN_CENTER_X * scale;
@@ -304,9 +305,10 @@ export const RouteTree = memo(function RouteTree({
</Tooltip>
</foreignObject>;
};
- const linkPath = (parent: { x: number; y: number }, child: { x: number; y: number }) => outline
- ? `M ${parent.x - 17} ${parent.y} H ${parent.x - 28} V ${child.y} H ${child.x - 18}`
- : `M ${parent.x + 20} ${parent.y} Q ${(parent.x + child.x) / 2} ${parent.y + (child.y - parent.y) * 0.55}, ${child.x - 18} ${child.y}`;
+ const linkPath = (parent: { x: number; y: number }, child: { x: number; y: number },
+ { from = outline ? 17 : 20, to = 18 } = {}) => outline
+ ? `M ${parent.x - from} ${parent.y} H ${parent.x - 28} V ${child.y} H ${child.x - to}`
+ : `M ${parent.x + from} ${parent.y} Q ${(parent.x + child.x) / 2} ${parent.y + (child.y - parent.y) * 0.55}, ${child.x - to} ${child.y}`;
const sfuChildPoints = sfuChildren.map((child) => ({
child,
point: pos.get(child.key)!,
@@ -354,19 +356,19 @@ export const RouteTree = memo(function RouteTree({
{sfuPos ? (
<>
<path
- d={linkPath(hostPos, sfuPos)}
+ d={linkPath(hostPos, sfuPos, { to: SFU_HALF_WIDTH })}
className={edgeClass("sfu")}
/>
{outline ? sfuChildPoints.map(({ child, point }) => <path key={`edge-${child.key}`}
- d={linkPath(sfuPos!, point)} className={edgeClass("sfu", child.ready)} />) : sfuChildren.length === 1 ? (
+ d={linkPath(sfuPos!, point, { from: SFU_HALF_WIDTH })} className={edgeClass("sfu", child.ready)} />) : sfuChildren.length === 1 ? (
<path
- d={`M ${sfuPos.x + 20} ${sfuPos.y} L ${pos.get(sfuChildren[0]!.key)!.x - 18} ${pos.get(sfuChildren[0]!.key)!.y}`}
+ d={`M ${sfuPos.x + SFU_HALF_WIDTH} ${sfuPos.y} L ${pos.get(sfuChildren[0]!.key)!.x - 18} ${pos.get(sfuChildren[0]!.key)!.y}`}
className={edgeClass("sfu", sfuChildren[0]!.ready)}
/>
) : sfuRail ? (
<>
<path
- d={`M ${sfuPos.x + 20} ${sfuPos.y} H ${sfuRail.x}`}
+ d={`M ${sfuPos.x + SFU_HALF_WIDTH} ${sfuPos.y} H ${sfuRail.x}`}
className={edgeClass("sfu")}
/>
<path
@@ -408,9 +410,9 @@ export const RouteTree = memo(function RouteTree({
<>
<g
className="lr-route-sfu"
- transform={`translate(${sfuPos.x - 20}, ${sfuPos.y - 16})`}
+ transform={`translate(${sfuPos.x - SFU_HALF_WIDTH}, ${sfuPos.y - 16})`}
>
- <rect width="40" height="32" rx="7" />
+ <rect width={SFU_HALF_WIDTH * 2} height="32" rx="7" />
<path d="M8 12h24M8 20h24" />
</g>
<text
diff --git a/src/client/components/living/ShareFailureHelp.tsx b/src/client/components/living/ShareFailureHelp.tsx
index 4c4a6575..54d51945 100644
--- a/src/client/components/living/ShareFailureHelp.tsx
+++ b/src/client/components/living/ShareFailureHelp.tsx
@@ -1,4 +1,5 @@
import { useId, useRef, useState } from "react";
+import { useProjectLink } from "../../lib/use-project-link";
import type { StatusDescriptor } from "../../ui/media-status";
import { useCopy, type CopyKey } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
@@ -18,7 +19,8 @@ export function ShareFailureHelp({ status, label, code, checks }: {
const [open, setOpen] = useState(false);
const [copied, setCopied] = useState<"idle" | "done" | "failed">("idle");
const hint = (status.tooltip ?? status.comic)!;
- const guide = `https://piik.tv/docs/${lang === "zh" ? "zh/" : ""}troubleshooting.html`;
+ 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);
return <>
<StatusIndicator status={status} label={label} onActivate={() => {
setCopied("idle");
diff --git a/src/client/components/living/SharingSettings.tsx b/src/client/components/living/SharingSettings.tsx
index 9b32eb94..7d90098c 100644
--- a/src/client/components/living/SharingSettings.tsx
+++ b/src/client/components/living/SharingSettings.tsx
@@ -1,28 +1,48 @@
-import type { ReactNode } from "react";
+import { useState, type ReactNode } from "react";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
+import { navigateTabs } from "../../ui/tab-navigation";
import { Cap } from "./primitives";
// Presentation only. Capture, preferences and pending operations stay with the Host.
-export function SharingSettings({ id, open, busy, presets, picture, audio, technical }: {
+export function SharingSettings({ id, open, busy, presets, picture, pictureSummary, audio, connection }: {
id: string; open: boolean; busy?: boolean;
- presets: ReactNode; picture?: ReactNode; audio: ReactNode; technical?: ReactNode;
+ presets: ReactNode; picture?: ReactNode; pictureSummary?: ReactNode; audio: ReactNode; connection?: ReactNode;
}) {
const { t } = useCopy();
+ const [tab, setTab] = useState<"picture" | "sound">("picture");
return <div id={id} className={`lr-sharing-settings lr-door-reveal${open ? " is-open" : ""}`}>
<div>{open ? <section className="lr-sharing-panel" aria-label={t("host.advanced")} aria-busy={busy}>
- <section className="lr-sharing-section" aria-label={t("host.settings.picture")}>
- <h2 aria-label={t("host.settings.picture")}><Glyph name="tv" size={20} /><Cap k="host.settings.picture" /></h2>
+ <div className="lr-toggle lr-sharing-tabs" role="tablist" aria-label={t("host.advanced")} onKeyDown={navigateTabs}>
+ {(["picture", "sound"] as const).map(value => <button key={value} type="button" role="tab"
+ id={`${id}-${value}-tab`} className={tab === value ? "is-selected" : undefined}
+ aria-label={t(`host.settings.${value}`)} aria-selected={tab === value}
+ aria-controls={`${id}-${value}`} tabIndex={tab === value ? 0 : -1} onClick={() => setTab(value)}>
+ <Glyph name={value === "picture" ? "tv" : "speaker"} size={18} /><Cap k={`host.settings.${value}`} />
+ </button>)}
+ </div>
+ <section id={`${id}-picture`} className="lr-sharing-section" role="tabpanel" tabIndex={0}
+ aria-labelledby={`${id}-picture-tab`} hidden={tab !== "picture"}>
{presets}
- {picture}
+ {picture ? <details className="lr-sharing-picture-details">
+ <summary aria-label={t("host.settings.pictureDetails")}>
+ <span><Glyph name="sliders" size={17} /><Cap k="host.settings.pictureDetails" /></span>
+ {pictureSummary}
+ <Glyph name="chevron" size={17} className="lr-sharing-chevron" />
+ </summary>
+ <div>{picture}</div>
+ </details> : null}
</section>
- <section className="lr-sharing-section" aria-label={t("host.settings.sound")}>
- <h2 aria-label={t("host.settings.sound")}><Glyph name="speaker" size={20} /><Cap k="host.settings.sound" /></h2>
+ <section id={`${id}-sound`} className="lr-sharing-section" role="tabpanel" tabIndex={0}
+ aria-labelledby={`${id}-sound-tab`} hidden={tab !== "sound"}>
<div className="lr-sharing-audio-controls">{audio}</div>
</section>
- {technical ? <details className="lr-sharing-technical">
- <summary aria-label={t("host.settings.technical")}><Glyph name="sliders" size={17} /><Cap k="host.settings.technical" /></summary>
- <div>{technical}</div>
+ {connection ? <details className="lr-sharing-connection">
+ <summary aria-label={t("host.settings.connection")}>
+ <span><Glyph name="branch" size={17} /><Cap k="host.settings.connection" /></span>
+ <Glyph name="chevron" size={17} className="lr-sharing-chevron" />
+ </summary>
+ <div>{connection}</div>
</details> : null}
</section> : null}</div>
</div>;
diff --git a/src/client/components/living/Tooltip.tsx b/src/client/components/living/Tooltip.tsx
index 783d39b3..c7328a1c 100644
--- a/src/client/components/living/Tooltip.tsx
+++ b/src/client/components/living/Tooltip.tsx
@@ -185,13 +185,19 @@ export function Tooltip({
tipRef.current?.style.setProperty("--tooltip-max-width", `${Math.max(0, vw - EDGE_MARGIN * 2)}px`);
tipRef.current?.style.setProperty("--tooltip-max-height", `${Math.max(0, vh - EDGE_MARGIN * 2)}px`);
const rect = wrap.getBoundingClientRect();
+ // Popovers and fullscreen present a separate subtree. Their DOM ancestors
+ // outside that surface retain page geometry and cannot place its hints.
+ const surface = wrap.closest<HTMLElement>("[popover], :fullscreen");
+ const insideSurface = (element: HTMLElement | null) => element && (!surface || surface.contains(element)) ? element : null;
// A wrapped control row remains one working area, including on narrow screens.
- const controlBar = wrap.closest<HTMLElement>(".lr-playback, .lr-source-picker-options, .lr-host-share-controls");
+ const controlBar = insideSurface(wrap.closest<HTMLElement>(".lr-playback, .lr-source-picker-options, .lr-host-share-controls"));
const playback = controlBar?.classList.contains("lr-playback");
const avoid = controlBar?.getBoundingClientRect() ?? rect;
- const player = wrap.closest<HTMLElement>(".lr-tv-screen")?.getBoundingClientRect();
+ const screen = insideSurface(wrap.closest<HTMLElement>(".lr-tv-screen"));
+ const player = screen?.getBoundingClientRect();
+ const mediaBoundary = insideSurface(wrap.closest<HTMLElement>(".lr-tv")) ?? screen;
const below = playback
- ? wrap.closest<HTMLElement>(".lr-tv")?.getBoundingClientRect().bottom ?? avoid.bottom
+ ? mediaBoundary?.getBoundingClientRect().bottom ?? avoid.bottom
: avoid.bottom;
const measured = panelMounted ? (tipRef.current?.offsetWidth ?? 0) : 0;
const width = Math.max(0, Math.min(measured || 320, vw - EDGE_MARGIN * 2));
@@ -201,7 +207,7 @@ export function Tooltip({
(panelMounted ? tipRef.current?.offsetHeight : 0) || FALLBACK_PANEL_HEIGHT;
const fitsAbove = avoid.top - panelHeight - EDGE_MARGIN >= y + EDGE_MARGIN;
const fitsBelow = !vh || below + panelHeight + EDGE_MARGIN <= bottom - EDGE_MARGIN;
- const preferredPlace = wrap.closest(".lr-tv-chin, .lr-host-share-controls") ? "below" : place;
+ const preferredPlace = insideSurface(wrap.closest<HTMLElement>(".lr-tv-chin")) || controlBar?.classList.contains("lr-host-share-controls") ? "below" : place;
let livePlace: Placement =
preferredPlace === "above"
? fitsAbove || !fitsBelow
@@ -282,6 +288,21 @@ export function Tooltip({
tip?.hidePopover?.();
}
}, [panelMounted, caption, kind]);
+ useLayoutEffect(() => {
+ if (!ownerDocument || !panelMounted) return;
+ const fullscreenChanged = () => {
+ const tip = tipRef.current;
+ if (!tip?.matches(":popover-open")) return;
+ const fullscreen = ownerDocument.fullscreenElement;
+ if (fullscreen && wrapRef.current && !fullscreen.contains(wrapRef.current)) { dismissPanel(); return; }
+ // An already-open popover otherwise remains below the new fullscreen root.
+ tip.hidePopover();
+ tip.showPopover();
+ pickAlignRef.current();
+ };
+ ownerDocument.addEventListener("fullscreenchange", fullscreenChanged);
+ return () => ownerDocument.removeEventListener("fullscreenchange", fullscreenChanged);
+ }, [ownerDocument, panelMounted]);
useEffect(() => {
const view = ownerDocument?.defaultView;
if (!interactionOpen || !panelMounted || !view) return;
@@ -290,6 +311,13 @@ export function Tooltip({
view.cancelAnimationFrame(frame);
frame = view.requestAnimationFrame(() => pickAlignRef.current());
};
+ // A parent popover places itself after opening, and movable panels update
+ // their inset without scrolling the page. Follow that owner's final layout.
+ const surface = wrapRef.current?.closest<HTMLElement>("[popover]");
+ const observer = new ResizeObserver(schedulePick);
+ for (const element of [wrapRef.current, tipRef.current, surface]) if (element) observer.observe(element);
+ const movement = new MutationObserver(schedulePick);
+ if (surface) movement.observe(surface, { attributes: true, attributeFilter: ["style"] });
schedulePick();
const viewport = view.visualViewport;
viewport?.addEventListener("resize", schedulePick);
@@ -298,6 +326,8 @@ export function Tooltip({
view.addEventListener("scroll", schedulePick, true);
return () => {
view.cancelAnimationFrame(frame);
+ observer.disconnect();
+ movement.disconnect();
viewport?.removeEventListener("resize", schedulePick);
viewport?.removeEventListener("scroll", schedulePick);
view.removeEventListener("resize", schedulePick);
@@ -548,7 +578,7 @@ export function Tooltip({
}) : children}
<span ref={tipRef} id={tooltipId} popover="manual"
data-tone={resolvedTone}
- style={{ ...comicStyle(resolvedTone, resolvedMotion), "--comic-repeat": "infinite", left: position.left, top: position.top, "--tooltip-caret": `${position.caret}px` } as CSSProperties}
+ style={{ ...comicStyle(resolvedTone), left: position.left, top: position.top, "--tooltip-caret": `${position.caret}px` } as CSSProperties}
className={`lr-comic-tip${kind ? " has-comic" : ""}${caption !== undefined ? " is-text" : ""}${placeClass}`} role="tooltip" aria-hidden={!interactionOpen}>
{panelMounted ? <span className="lr-comic-tip-content">
{kind ? isHintKind(kind)
diff --git a/src/client/components/living/ViewerPlaybackSettings.tsx b/src/client/components/living/ViewerPlaybackSettings.tsx
new file mode 100644
index 00000000..4b2b70b3
--- /dev/null
+++ b/src/client/components/living/ViewerPlaybackSettings.tsx
@@ -0,0 +1,59 @@
+import type { ReactNode } from "react";
+import type { ViewerRoutePreference } from "../../../shared/protocol";
+import type { VideoFit } from "../../media/video-geometry";
+import { useCopy } from "../../ui/copy";
+import { Glyph } from "../../ui/icons";
+import { Cap, Chip, RowGroup } from "./primitives";
+
+export interface ViewerPlaybackSettingsProps {
+ pictureFit: VideoFit;
+ setPictureFit: (fit: VideoFit) => void;
+ route?: {
+ preference: ViewerRoutePreference;
+ sfuAvailable: boolean;
+ sfuOnly: boolean;
+ peerOnly: boolean;
+ disabled: boolean;
+ rejected: boolean;
+ onChange: (preference: ViewerRoutePreference) => void;
+ };
+}
+
+// Local display and incoming-route intent only; media and routing keep their owners.
+export function ViewerPlaybackSettings({ pictureFit, setPictureFit, route, displayActions, reconnect }: ViewerPlaybackSettingsProps & {
+ displayActions: ReactNode; reconnect: ReactNode;
+}) {
+ const { t, vis } = useCopy();
+ const routeHint = route?.rejected ? "playback.routeRejected" : route?.sfuOnly ? "playback.routeSfuOnly"
+ : route?.peerOnly ? "playback.routePeerOnly" : !route?.sfuAvailable ? "playback.routeNoSfu"
+ : `playback.routeHint.${route.preference}` as const;
+ return <div className="lr-viewer-settings">
+ <section aria-label={t("playback.pictureFit")}>
+ <div className="lr-viewer-settings-heading"><h3><Glyph name="tv" size={17} /><Cap k="playback.pictureFit" /></h3></div>
+ <RowGroup>{(["contain", "cover", "fill"] as const).map(fit => <Chip key={fit}
+ selected={pictureFit === fit} title={t(`playback.fit.${fit}`)} hint={`hint-fit-${fit}`} onClick={() => setPictureFit(fit)}>
+ {vis && <Glyph name={fit === "contain" ? "fitContain" : fit === "cover" ? "fitCover" : "fitStretch"} size={20} />}
+ <Cap k={`playback.fit.${fit}`} />
+ </Chip>)}</RowGroup>
+ {!vis && <p>{t(pictureFit === "cover" ? "playback.fitCrop" : pictureFit === "fill" ? "playback.fitStretch" : "playback.fitFull")}</p>}
+ {displayActions}
+ </section>
+ <section aria-label={t("playback.connection")}>
+ <div className="lr-viewer-settings-heading">
+ <h3><Glyph name="branch" size={17} /><Cap k="playback.connection" /></h3>
+ {reconnect}
+ </div>
+ {route && <>
+ <RowGroup>{(["auto", "p2p", "sfu"] as const).map(preference => <Chip key={preference}
+ selected={route.preference === preference} title={t(`playback.route.${preference}`)}
+ disabled={route.disabled || (preference === "p2p" && route.sfuOnly) || (preference === "sfu" && !route.sfuAvailable)}
+ hint={preference === "auto" ? undefined : preference === "p2p" ? "hint-route-p2p" : "hint-route-sfu"}
+ onClick={() => { if (route.preference !== preference) route.onChange(preference); }}>
+ {vis && <Glyph name={preference === "auto" ? "branch" : preference === "p2p" ? "link" : "server"} size={17} />}
+ <Cap k={`playback.route.${preference}`} />
+ </Chip>)}</RowGroup>
+ {!vis && <p className={route.rejected ? "is-error" : undefined} role={route.rejected ? "status" : undefined}>{t(routeHint)}</p>}
+ </>}
+ </section>
+ </div>;
+}
diff --git a/src/client/components/living/button.css b/src/client/components/living/button.css
index 74c5cc28..0d0f9247 100644
--- a/src/client/components/living/button.css
+++ b/src/client/components/living/button.css
@@ -1,4 +1,10 @@
/* Shared control geometry and motion for the application and static website. */
+:root {
+ --control-hover-transform: translateY(-2px);
+ --control-press-transform: translateY(2px);
+ --control-motion: transform 260ms var(--spring);
+}
+button { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
.lr-btn {
display: inline-grid;
grid-auto-flow: column;
@@ -14,18 +20,21 @@
white-space: nowrap;
text-decoration: none;
box-shadow: var(--control-shadow);
- transition: transform 260ms var(--spring), background-color 140ms ease, border-color 140ms ease;
+ transition: var(--control-motion), background-color 140ms ease, border-color 140ms ease;
}
-.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: translateY(-2px); }
+.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: var(--control-hover-transform); }
.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-primary):not(.is-on):not(.is-danger) { background: var(--control-hover); border-color: var(--ink); }
-.lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.95); box-shadow: none; transition-duration: 80ms; }
-.lr-btn.is-primary { border-color: var(--action-deep); background: var(--action-deep); color: #fff; }
-.lr-btn.is-primary:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--action-deep) 88%, #000); }
+.lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: var(--control-press-transform); box-shadow: none; transition-duration: 80ms; }
+.lr-btn.is-primary { --primary-fill: var(--primary); border-color: var(--primary-fill); background: var(--primary-fill); color: var(--primary-ink); }
+.lr-btn.is-primary:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { --primary-fill: color-mix(in srgb, var(--primary) 88%, #000); }
.lr-btn.is-danger { border-color: var(--danger); color: color-mix(in srgb, var(--danger) 70%, var(--ink)); }
.lr-btn.is-danger:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--danger) 10%, var(--paper)); }
-.lr-btn.is-on { border-color: var(--ink); background: var(--ink); color: var(--paper); }
+.lr-btn.is-on { border-color: var(--action); background: var(--control-selected); color: var(--control-selected-ink); box-shadow: inset 0 0 0 1px var(--action), var(--control-shadow); }
+.lr-btn.is-on:active:not(:disabled):not([aria-disabled="true"]) { box-shadow: inset 0 0 0 1px var(--action); }
.lr-btn .lr-cap { margin-left: 2px; font-size: 12.5px; font-weight: 600; }
.lr-theme-toggle { min-width: 40px; height: 40px; }
@media (prefers-reduced-motion: reduce) {
+ :root { --control-hover-transform: none; --control-press-transform: none; }
.lr-btn { transform: none !important; transition: none !important; }
}
+html[data-reduced-motion] { --control-hover-transform: none; --control-press-transform: none; }
diff --git a/src/client/components/living/comic-presentation.ts b/src/client/components/living/comic-presentation.ts
index 8588f381..057d3006 100644
--- a/src/client/components/living/comic-presentation.ts
+++ b/src/client/components/living/comic-presentation.ts
@@ -86,11 +86,11 @@ const COLOURS: Record<ComicTone, string> = {
bad: "var(--danger)",
};
-export function comicStyle(tone: ComicTone, motion: ComicMotion): CSSProperties {
+export function comicStyle(tone: ComicTone): CSSProperties {
return {
"--comic-tone": COLOURS[tone],
"--comic-duration": "3.2s",
- // Explanations inherit the tooltip's loop; standalone results play once.
- "--comic-repeat": motion === "progress" ? "infinite" : undefined,
+ // Scene poses distinguish progress from a settled result, not repetition.
+ "--comic-repeat": "infinite",
} as CSSProperties;
}
diff --git a/src/client/components/living/floating-panel.css b/src/client/components/living/floating-panel.css
index 131b162a..d99f0fce 100644
--- a/src/client/components/living/floating-panel.css
+++ b/src/client/components/living/floating-panel.css
@@ -1,22 +1,16 @@
-.lr-floating-surface { color: var(--ink); background: var(--paper); border: 1px solid var(--control-edge); border-radius: 24px; box-shadow: 0 12px 36px rgb(16 26 44 / .2), var(--control-shadow); }
-.lr-floating-panel { position: fixed; inset: auto 12px 12px auto; max-width: calc(100vw - 24px); max-height: calc(100dvh - 24px); margin: 0; padding: 16px; overflow: auto; overscroll-behavior: contain; transform-origin: right bottom; }
-.lr-floating-panel:popover-open { display: flex; flex-direction: column; animation: lr-floating-enter 180ms var(--spring); }
+.lr-floating-surface { color: var(--ink); background: var(--surface-glaze) var(--paper); border: 1px solid var(--control-edge); border-radius: 24px; box-shadow: var(--panel-shadow); }
+.lr-floating-panel { position: fixed; inset: auto 12px 12px auto; max-width: calc(100vw - 24px); max-height: calc(100dvh - 24px); margin: 0; padding: 16px; overflow: auto; overscroll-behavior: contain; transform-origin: right bottom; container: floating-panel / inline-size; }
+.lr-floating-panel:is(:popover-open, .\:popover-open) { display: flex; flex-direction: column; animation: lr-floating-enter 180ms var(--spring); }
.lr-floating-panel:focus { outline: none; }
.lr-floating-panel:focus-visible { outline: 2px solid var(--action); outline-offset: -2px; }
-.lr-floating-header { display: flex; align-items: center; gap: 8px; min-height: 56px; flex-shrink: 0; margin: -16px -16px 0; padding: 6px 10px 6px 24px; border-bottom: 1px solid var(--wall-2); border-radius: 24px 24px 0 0; cursor: grab; user-select: none; touch-action: none; }
+/* Keep control outlines inside the scrollport without shifting content alignment. */
+.lr-floating-scroll { min-height: 0; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; margin-inline: -6px; padding-inline: 6px; }
+.lr-floating-header { display: flex; align-items: center; gap: 8px; min-height: 56px; flex-shrink: 0; margin: -16px -16px 0; padding: 6px 10px 6px 24px; border-bottom: 1px solid var(--wall-2); border-radius: 24px 24px 0 0; cursor: grab; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; touch-action: none; }
.lr-floating-header:active { cursor: grabbing; }
.lr-floating-header:focus-visible { outline: 2px solid var(--action); outline-offset: -3px; }
.lr-floating-title { display: flex; flex: 1; min-width: 0; align-items: center; gap: 7px; font-size: 14px; }
.lr-floating-title svg { flex: none; color: var(--muted); }
.lr-floating-title b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.lr-floating-position { position: relative; flex: none; }
-.lr-floating-position > summary { display: flex; align-items: center; gap: 5px; min-height: 40px; padding: 0 9px; border-radius: 12px; font-size: 12px; color: var(--muted); cursor: pointer; list-style: none; }
-.lr-floating-position > summary::-webkit-details-marker { display: none; }
-.lr-floating-position > summary:is(:hover, :focus-visible), .lr-floating-position[open] > summary { color: var(--ink); background: var(--control-hover); }
-.lr-floating-positions { position: absolute; z-index: 2; top: calc(100% + 6px); right: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 6px; width: 180px; padding: 8px; border: 1px solid var(--control-edge); border-radius: 18px; background: var(--paper); box-shadow: var(--control-shadow), 0 8px 24px #0002; }
-.lr-floating-positions button { display: grid; justify-items: center; gap: 6px; min-height: 60px; padding: 8px 4px; border: 0; border-radius: 10px; color: var(--ink); background: transparent; font-size: 11px; }
-.lr-floating-positions button:is(:hover, :focus-visible) { color: var(--action); background: var(--control-hover); }
-.lr-floating-positions .lr-floating-size { border-top: 1px solid var(--wall-2); }
.lr-floating-resize { position: absolute; z-index: 3; display: grid; place-items: center; width: 28px; height: 28px; color: var(--muted); cursor: nwse-resize; touch-action: none; user-select: none; }
.lr-floating-resize.is-nw { top: 1px; left: 1px; transform: rotate(180deg); }
.lr-floating-resize.is-se { right: 1px; bottom: 1px; }
@@ -24,17 +18,12 @@
.lr-floating-resize:focus-visible { outline: 2px solid var(--action); outline-offset: -4px; border-radius: 10px; }
@keyframes lr-floating-enter { from { opacity: 0; transform: translateY(8px) scale(.97); } to { opacity: 1; transform: none; } }
.lr-popover-close { display: grid; place-items: center; width: 36px; height: 36px; flex: none; background: transparent; color: var(--muted); border: 0; border-radius: 12px; cursor: pointer; }
-.lr-popover-close:is(:hover, :focus-visible) { background: var(--control-hover); color: var(--ink); }
+.lr-popover-close:is(:hover, :focus-visible):not(:disabled) { background: var(--control-hover); color: var(--ink); }
.lr-floating-error { padding: 8px 0; color: var(--danger); font-size: 12px; }
/* The browser owns the detached frame, movement and resizing. */
.lr-panel-window { background: var(--paper); }
-.lr-panel-window .lr-floating-panel { inset: 0 !important; width: 100% !important; height: 100dvh !important; max-width: none; max-height: none !important; padding: 12px; border: 0; border-radius: 0; box-shadow: none; animation: none; }
-.lr-panel-window .lr-floating-header { min-height: 40px; margin: -12px -12px 0; padding: 2px 8px 2px 14px; border-radius: 0; cursor: default; touch-action: auto; }
+.lr-panel-window .lr-floating-panel { inset: 0 !important; width: 100% !important; height: 100dvh !important; max-width: none; max-height: none !important; padding-top: 0; border-color: transparent; border-radius: 0; box-shadow: none; animation: none; }
+.lr-panel-window .lr-floating-header { display: none; }
.lr-panel-window .lr-chat-log { padding-block: 12px; }
-.lr-panel-window .lr-chat-footer { padding-right: 0; }
-[data-comic-reduced-motion] .lr-floating-panel:popover-open { animation: none; }
-@media (prefers-reduced-motion: reduce) { .lr-floating-panel:popover-open { animation: none; } }
-@media (max-width: 420px) {
- .lr-floating-panel { padding: 12px; }
- .lr-floating-header { margin: -12px -12px 0; padding: 6px 10px 6px 24px; }
-}
+[data-comic-reduced-motion] .lr-floating-panel:is(:popover-open, .\:popover-open) { animation: none; }
+@media (prefers-reduced-motion: reduce) { .lr-floating-panel:is(:popover-open, .\:popover-open) { animation: none; } }
diff --git a/src/client/components/living/hints/index.tsx b/src/client/components/living/hints/index.tsx
index d2ee2c33..796d9f8b 100644
--- a/src/client/components/living/hints/index.tsx
+++ b/src/client/components/living/hints/index.tsx
@@ -7,7 +7,7 @@
// by the tsx preview harness, which uses the classic JSX runtime.
import { createElement, memo, type CSSProperties } from "react";
-import type { HintKind, HintScene, MetricHintKind, InteractionHintKind } from "../../../ui/visual-kinds";
+import type { HintKind, HintScene, MetricHintKind, InteractionHintKind, RemoteHintKind } from "../../../ui/visual-kinds";
import { SET1_SCENES } from "./set1";
import { SET2_SCENES } from "./set2";
import { SET3_SCENES } from "./set3";
@@ -17,11 +17,16 @@ import { CONTROL_SCENES } from "./controls";
import { METRIC_SCENES } from "./metrics";
import { ADMISSION_SCENES } from "./admission";
import { INTERACTION_SCENES } from "./interactions";
+import { REMOTE_SCENES } from "./remote-control";
import { comicStyle, getComicPresentation, type ComicTone, type ComicMotion } from "../comic-presentation";
export type { HintKind, HintScene };
export const HINT_KINDS: readonly HintKind[] = [
+ "hint-fit-contain",
+ "hint-fit-cover",
+ "hint-fit-fill",
+ "hint-reaction-picker",
"hint-share-start",
"hint-share-stop",
"hint-microphone-on",
@@ -102,6 +107,7 @@ export const HINT_KINDS: readonly HintKind[] = [
"hint-pip-unavailable",
...Object.keys(METRIC_SCENES) as MetricHintKind[],
...Object.keys(INTERACTION_SCENES) as InteractionHintKind[],
+ ...Object.keys(REMOTE_SCENES) as RemoteHintKind[],
];
export const HINT_SCENES: Record<HintKind, HintScene> = {
@@ -114,6 +120,7 @@ export const HINT_SCENES: Record<HintKind, HintScene> = {
...METRIC_SCENES,
...ADMISSION_SCENES,
...INTERACTION_SCENES,
+ ...REMOTE_SCENES,
};
const HINT_KIND_SET: ReadonlySet<string> = new Set(HINT_KINDS);
@@ -138,7 +145,7 @@ export const HintComic = memo(function HintComic({
const resolvedTone = tone ?? defaults.tone;
const resolvedMotion = motion ?? defaults.motion;
const style: CSSProperties = {
- ...comicStyle(resolvedTone, resolvedMotion),
+ ...comicStyle(resolvedTone),
width: size != null ? `${size}px` : "min(320px, 86%)",
height: "auto",
display: "block",
diff --git a/src/client/components/living/hints/interactions.tsx b/src/client/components/living/hints/interactions.tsx
index 92c24c9f..6077a51c 100644
--- a/src/client/components/living/hints/interactions.tsx
+++ b/src/client/components/living/hints/interactions.tsx
@@ -65,7 +65,7 @@ function ChatSettingsHint({ theme }: { theme: ComicTheme }) {
</g>)}</>;
}
-function ChatWindowHint({ theme }: { theme: ComicTheme }) {
+function PanelWindowHint({ theme }: { theme: ComicTheme }) {
return <><InteractionMotion />{[0, 160].map((x, index) => {
const floating = Boolean(index);
return <g key={x}>
@@ -76,7 +76,7 @@ function ChatWindowHint({ theme }: { theme: ComicTheme }) {
<rect x={x + (floating ? 88 : 76)} y={floating ? 9 : 28} width={floating ? 48 : 34} height={floating ? 58 : 38}
rx={5} fill="var(--paper)" stroke={YOU} strokeWidth={2} />
<path d={`M${x + (floating ? 96 : 82)} ${floating ? 19 : 36}h${floating ? 22 : 18}`} stroke={FAINT} strokeWidth={2} strokeLinecap="round" />
- <g transform={`translate(${x + (floating ? 96 : 81)} ${floating ? 29 : 42}) scale(${floating ? .85 : .65})`}><Bubble x={0} y={0} /></g>
+ <g transform={`translate(${x + (floating ? 98 : 83)} ${floating ? 30 : 43})`}><Glyph name="sliders" size={floating ? 27 : 20} /></g>
</g>
</g>;
})}</>;
@@ -95,12 +95,31 @@ function ChatExportHint({ theme }: { theme: ComicTheme }) {
</g>)}</>;
}
+const ReactionPickerHint: HintScene = ({ theme }) => <>
+ <InteractionMotion />
+ {[0, 160].map((x, index) => <g key={x}>
+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />
+ <rect x={x + 24} y={66} width={112} height={20} rx={7} fill="var(--wall-2)" stroke={FAINT} strokeWidth={2} />
+ <g transform={`translate(${x + 31} 68)`}><Glyph name="smile" size={16} /></g>
+ {index ? <g className="vls-talk-bubble">
+ <rect x={x + 24} y={12} width={112} height={49} rx={7} fill="var(--paper)" stroke={YOU} strokeWidth={2} />
+ <Pawn x={x + 57} yb={34} s={6} eyes /><Pawn x={x + 100} yb={34} s={6} color={SKY} eyes />
+ {(["smile", "heart", "star"] as const).map((name, i) => <g key={name} transform={`translate(${x + 43 + i * 27} 39)`}>
+ <Glyph name={name} size={15} />
+ </g>)}
+ </g> : <>
+ <Pawn x={x + 57} yb={54} s={10} eyes /><Pawn x={x + 104} yb={54} s={10} color={SKY} eyes />
+ </>}
+ </g>)}
+</>;
+
export const INTERACTION_SCENES: Record<InteractionHintKind, HintScene> = {
+ "hint-reaction-picker": ReactionPickerHint,
"hint-chat-open": props => <ChatHint {...props} />,
"hint-chat-send": props => <ChatHint {...props} send />,
"hint-chat-settings": props => <ChatSettingsHint {...props} />,
"hint-chat-export": props => <ChatExportHint {...props} />,
- "hint-chat-detach": props => <ChatWindowHint {...props} />,
+ "hint-window-detach": props => <PanelWindowHint {...props} />,
"hint-chat-overlay-show": props => <OverlayHint {...props} show />,
"hint-chat-overlay-hide": props => <OverlayHint {...props} show={false} />,
};
diff --git a/src/client/components/living/hints/playback.tsx b/src/client/components/living/hints/playback.tsx
index 9280f8b4..162ff81e 100644
--- a/src/client/components/living/hints/playback.tsx
+++ b/src/client/components/living/hints/playback.tsx
@@ -1,3 +1,4 @@
+import { useId } from "react";
import {
BrowserWindow, FAINT, Frame, INK_STAGE, LIVE, MiniTv, Pawn, SKY, TV_BODY, TV_EDGE, YOU, rmBlock,
} from "../Comic";
@@ -187,7 +188,35 @@ function PictureHint({ theme, exit = false, unavailable = false }: Parameters<Hi
</>;
}
+// The same 4:3 picture demonstrates the three local display operations.
+function PictureFitHint({ theme, fit }: Parameters<HintScene>[0] & { fit: "contain" | "cover" | "fill" }) {
+ const clip = useId();
+ const picture = <><rect width={80} height={60} fill="var(--wall-2)" />
+ <circle cx={40} cy={24} r={15} fill={SKY} />
+ <path d="M0 60 22 34 40 52 60 30 80 55v5Z" fill={YOU} />
+ <rect x={1} y={1} width={78} height={58} fill="none" stroke={FAINT} strokeWidth={2} /></>;
+ return <>
+ <PlaybackMotion />
+ <Frame x={4} w={152} theme={theme} />
+ <Frame x={164} w={152} theme={theme} result />
+ <g transform="translate(40 18)">{picture}</g>
+ <defs><clipPath id={clip}><rect x={184} y={18} width={112} height={60} rx={3} /></clipPath></defs>
+ <g className="vls-pb-chrome-in">
+ <rect x={184} y={18} width={112} height={60} rx={3} fill={TV_BODY} />
+ <g clipPath={`url(#${clip})`}>
+ <g transform={fit === "contain" ? "translate(200 18)" : fit === "cover" ? "translate(184 6) scale(1.4)" : "translate(184 18) scale(1.4 1)"}>
+ {picture}
+ </g>
+ </g>
+ <rect x={184} y={18} width={112} height={60} rx={3} fill="none" stroke="var(--ink)" strokeWidth={2} />
+ </g>
+ </>;
+}
+
export const PLAYBACK_SCENES: Record<PlaybackHintKind, HintScene> = {
+ "hint-fit-contain": props => <PictureFitHint {...props} fit="contain" />,
+ "hint-fit-cover": props => <PictureFitHint {...props} fit="cover" />,
+ "hint-fit-fill": props => <PictureFitHint {...props} fit="fill" />,
"hint-local-play": (props) => <PlaybackHint {...props} paused={false} />,
"hint-local-pause": (props) => <PlaybackHint {...props} paused />,
"hint-volume": (props) => <AudioHint {...props} action="volume" />,
diff --git a/src/client/components/living/hints/remote-control.tsx b/src/client/components/living/hints/remote-control.tsx
new file mode 100644
index 00000000..d22e3e71
--- /dev/null
+++ b/src/client/components/living/hints/remote-control.tsx
@@ -0,0 +1,87 @@
+import { FAINT, Frame, MiniTv, Pawn, SKY, rmBlock } from "../Comic";
+import { Glyph } from "../../../ui/icons";
+import type { ComicTheme, HintScene, RemoteHintKind } from "../../../ui/visual-kinds";
+
+function RemoteMotion() {
+ return <style>{`
+.vls-remote-cursor{animation:vlsRemoteCursor var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-remote-stop{animation:vlsRemoteStop var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-remote-pan{animation:vlsRemotePan var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}
+.vls-combination-modifier{animation:vlsCombinationModifier var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+.vls-combination-key{animation:vlsCombinationKey var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}
+@keyframes vlsRemoteCursor{0%,10%{transform:translate(-10px,8px);opacity:0}24%{opacity:1}42%,100%{transform:none;opacity:1}}
+@keyframes vlsRemoteStop{0%,12%{opacity:1}36%,100%{opacity:0}}
+@keyframes vlsRemotePan{0%,12%,72%,100%{transform:none}40%{transform:translateX(-9px)}}
+@keyframes vlsCombinationModifier{0%,10%,82%,100%{opacity:0}22%,68%{opacity:1}}
+@keyframes vlsCombinationKey{0%,40%,82%,100%{opacity:0}50%,68%{opacity:1}}
+${rmBlock(["vls-remote-cursor", "vls-remote-stop", "vls-remote-pan", "vls-combination-modifier", "vls-combination-key"], [
+ [".vls-remote-cursor", "transform:none;opacity:1"],
+ [".vls-remote-stop", "opacity:0"], [".vls-remote-pan", "transform:none"],
+ [".vls-combination-modifier,.vls-combination-key", "opacity:1"],
+])}
+`}</style>;
+}
+
+function Cursor({ x, y }: { x: number; y: number }) {
+ return <path d={`M${x} ${y}v16l4-4 4 7 3-2-4-7 7-1Z`} fill="#dfe8f2" stroke={SKY} strokeWidth={1.5} strokeLinejoin="round" />;
+}
+
+function ControlHint({ theme, stop = false }: { theme: ComicTheme; stop?: boolean }) {
+ return <><RemoteMotion />{[0, 160].map((x, index) => <g key={x}>
+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />
+ <MiniTv x={x + 49} y={22} w={70} h={42} />
+ <Pawn x={x + 27} yb={83} s={11} color={SKY} eyes gaze={2} />
+ <Pawn x={x + 133} yb={83} s={11} host eyes gaze={-2} />
+ <g transform={`translate(${x + 51} 70)`}><Glyph name="mouse" size={17} /></g>
+ <path d={`M${x + 72} 72h35v11h-35Z m5 5h25`} fill="none" stroke={FAINT} strokeWidth={2} strokeLinejoin="round" />
+ {stop || index ? <g className={index ? stop ? "vls-remote-stop" : "vls-remote-cursor" : undefined}>
+ <Cursor x={x + 82} y={35} />
+ </g> : <g transform={`translate(${x + 124} 20)`}><Glyph name="clock" size={17} /></g>}
+ {Boolean(index) && <g transform={`translate(${x + 124} 20)`}><Glyph name={stop ? "x" : "check"} size={17} /></g>}
+ </g>)}</>;
+}
+
+function MouseLockHint({ theme, lock }: { theme: ComicTheme; lock: boolean }) {
+ return <><RemoteMotion />{[0, 160].map((x, index) => {
+ const captured = index ? lock : !lock;
+ return <g key={x}>
+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />
+ <MiniTv x={x + 25} y={15} w={110} h={58} />
+ <g className={captured ? "vls-remote-pan" : undefined}>
+ <path d={`M${x + 45} 56l12-18 13 12 15-20 27 26Z`} fill={SKY} opacity={.6} />
+ </g>
+ {captured ? <path d={`M${x + 80} 33v7m0 8v7m-11-11h7m8 0h7`} stroke="#dfe8f2" strokeWidth={2} strokeLinecap="round" />
+ : <g className={index ? "vls-remote-cursor" : undefined}><Cursor x={x + 82} y={37} /></g>}
+ <g transform={`translate(${x + 72} 73)`}><Glyph name="mouse" size={16} /></g>
+ {captured && <path d={`M${x + 62} 80h-9l4-4m-4 4 4 4m41-4h9l-4-4m4 4-4 4`}
+ fill="none" stroke={FAINT} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />}
+ </g>;
+ })}</>;
+}
+
+export const REMOTE_SCENES: Record<RemoteHintKind, HintScene> = {
+ "hint-key-combination": ({ theme }) => <><RemoteMotion />{[0, 160].map((x, index) => <g key={x}>
+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />
+ <g transform={`translate(${x + 30} 26)`}>
+ <rect width={40} height={40} rx={8} fill="none" stroke={FAINT} strokeWidth={2} />
+ <rect className="vls-combination-modifier" width={40} height={40} rx={8} fill={SKY} fillOpacity={.25} stroke={SKY} strokeWidth={2} />
+ <path d="m20 10-10 11h6v9h8v-9h6Z" fill="none" stroke={FAINT} strokeWidth={2} strokeLinejoin="round" />
+ </g>
+ <path d={`M${x + 76} 46h8m-4-4v8`} stroke={FAINT} strokeWidth={2} strokeLinecap="round" />
+ <g transform={`translate(${x + 90} 26)`}>
+ <rect width={40} height={40} rx={8} fill="none" stroke={FAINT} strokeWidth={2} />
+ {Boolean(index) && <rect className="vls-combination-key" width={40} height={40} rx={8} fill={SKY} fillOpacity={.25} stroke={SKY} strokeWidth={2} />}
+ <path d="m11 29 9-18 9 18m-14-6h10" fill="none" stroke={FAINT} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />
+ </g>
+ </g>)}</>,
+ "hint-remote-keyboard": ({ theme }) => <><RemoteMotion />{[0, 160].map((x, index) => <g key={x}>
+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />
+ <MiniTv x={x + 40} y={13} w={80} h={45} />
+ <g transform={`translate(${x + 64} 60)`}><Glyph name="keyboard" size={32} /></g>
+ {Boolean(index) && <g className="vls-remote-cursor"><path d={`M${x + 57} 35h16m5 0h12m-33 7h25`} fill="none" stroke={SKY} strokeWidth={3} strokeLinecap="round" /></g>}
+ </g>)}</>,
+ "hint-remote-control": props => <ControlHint {...props} />,
+ "hint-remote-stop": props => <ControlHint {...props} stop />,
+ "hint-remote-mouse-lock": props => <MouseLockHint {...props} lock />,
+ "hint-remote-mouse-release": props => <MouseLockHint {...props} lock={false} />,
+};
diff --git a/src/client/components/living/language-control.css b/src/client/components/living/language-control.css
index 9b120033..7f46937b 100644
--- a/src/client/components/living/language-control.css
+++ b/src/client/components/living/language-control.css
@@ -19,6 +19,7 @@
width: calc((100% - 8px) / var(--lang-count));
border-radius: 999px;
background: var(--ink);
+ box-shadow: inset 0 0 0 2px var(--action);
transition: transform 260ms var(--spring);
pointer-events: none;
}
@@ -43,7 +44,7 @@
}
.lr-lang > button:is(:hover, :focus-visible) { opacity: 1; transform: translateY(-1px); }
.lr-lang > button:is(:hover, :focus-visible):not(.is-selected) { background: var(--wall-2); }
-.lr-lang > button:active { transform: scale(.9); }
+.lr-lang > button:active { transform: var(--control-press-transform); transition-duration: 80ms; }
.lr-lang > .is-selected { color: var(--paper); opacity: 1; }
@media (prefers-reduced-motion: reduce) {
.lr-lang::before, .lr-lang > button { transition: none; }
diff --git a/src/client/components/living/participant-color.ts b/src/client/components/living/participant-color.ts
index e7493e35..5ad57bb3 100644
--- a/src/client/components/living/participant-color.ts
+++ b/src/client/components/living/participant-color.ts
@@ -1,11 +1,15 @@
-// Theme tokens reserve warm upholstery and gold for the room and Host crown.
-const PARTICIPANT_COLORS = [
- "var(--pawn-1)", "var(--pawn-2)", "var(--pawn-3)", "var(--pawn-4)",
- "var(--pawn-5)", "var(--pawn-6)", "var(--pawn-7)", "var(--pawn-8)",
-];
+import { identityHash } from "../../lib/identity-hash";
+// Identity alone owns the colour across the couch, chat and topology. Leave the
+// upholstery/crown's amber range out; vary lightness and chroma independently.
export function participantColor(identity: string): string {
- let hash = 0;
- for (const char of identity) hash = (hash * 31 + char.charCodeAt(0)) | 0;
- return PARTICIPANT_COLORS[Math.abs(hash) % PARTICIPANT_COLORS.length]!;
+ // Avalanche the decorative hash so similar IDs do not cluster in one hue.
+ let seed = identityHash(identity);
+ seed = Math.imul(seed ^ (seed >>> 16), 0x85ebca6b);
+ seed = Math.imul(seed ^ (seed >>> 13), 0xc2b2ae35);
+ seed = (seed ^ (seed >>> 16)) >>> 0;
+ const hue = (140 + (seed & 0xffff) / 0xffff * 250) % 360;
+ const lightness = 0.59 + ((seed >>> 16) & 255) / 255 * 0.18;
+ const chroma = 0.11 + (seed >>> 24) / 255 * 0.08;
+ return `oklch(${lightness.toFixed(4)} ${chroma.toFixed(4)} ${hue.toFixed(4)})`;
}
diff --git a/src/client/components/living/participant-motion.ts b/src/client/components/living/participant-motion.ts
index 57d34647..abec55bc 100644
--- a/src/client/components/living/participant-motion.ts
+++ b/src/client/components/living/participant-motion.ts
@@ -18,24 +18,26 @@ export function participantMotionPhase(identity: string, now: number): number {
/** Native animation timelines keep running without a JS tick or room messages. */
export function bindParticipantMotion(root: SVGSVGElement, identity: string): () => void {
+ const owner = root.ownerDocument;
+ const view = owner.defaultView;
const sync = () => {
- if (document.hidden) return;
- const timeline = document.timeline.currentTime;
+ if (owner.hidden || !view) return;
+ const timeline = owner.timeline.currentTime;
if (typeof timeline !== "number") return;
// Sample wall time at this rendered frame, not at each component's mount.
- const phase = participantMotionPhase(identity, Date.now() - performance.now() + timeline);
+ const phase = participantMotionPhase(identity, Date.now() - view.performance.now() + timeline);
for (const animation of root.getAnimations({ subtree: true })) {
- if (animation instanceof CSSAnimation && animation.animationName.startsWith("lr-person-")) {
+ if ("animationName" in animation && (animation as CSSAnimation).animationName.startsWith("lr-person-")) {
animation.startTime = timeline - phase;
}
}
};
// animationstart also covers returning from reduced motion.
root.addEventListener("animationstart", sync);
- document.addEventListener("visibilitychange", sync);
+ owner.addEventListener("visibilitychange", sync);
sync();
return () => {
root.removeEventListener("animationstart", sync);
- document.removeEventListener("visibilitychange", sync);
+ owner.removeEventListener("visibilitychange", sync);
};
}
diff --git a/src/client/components/living/playback-controls.css b/src/client/components/living/playback-controls.css
index 360ec4be..3a9041c7 100644
--- a/src/client/components/living/playback-controls.css
+++ b/src/client/components/living/playback-controls.css
@@ -1,54 +1,108 @@
.lr-playback {
position: absolute;
inset: auto 0 0;
+ justify-self: center;
z-index: 4;
display: flex;
- flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 6px 12px max(6px, env(safe-area-inset-bottom));
border-top: 1.5px solid color-mix(in srgb, var(--ink) 24%, transparent);
color: var(--ink);
- background: color-mix(in srgb, var(--paper) 78%, transparent);
box-shadow: 0 -4px 18px rgb(0 0 0 / 8%);
transition: opacity 180ms ease, transform 220ms var(--spring);
}
+.lr-playback.lr-media-controls { flex-wrap: nowrap; }
.lr-playback.is-hidden { opacity: 0; transform: translateY(6px); pointer-events: none; }
-/* Let the bar's actual height (including wrapping) reserve overlay space. */
-.lr-tv-screen:has(> .lr-playback) { display: grid; width: 100%; grid-template: minmax(0, 1fr) auto / minmax(0, 1fr); }
-/* Keep the primary status readable when narrow controls wrap to a second row. */
+.lr-playback:has([popover]:is(:popover-open, .\:popover-open)) { opacity: 1; transform: none; pointer-events: auto; }
+/* The picture spans the toolbar row; tools use the row below it. Remote input
+ uses the same geometry, so a grant never resizes the picture or moves the bar. */
+.lr-tv-screen:has(> .lr-playback) { display: grid; width: 100%; aspect-ratio: auto; grid-template: minmax(0, 1fr) auto auto / minmax(0, 1fr); }
+/* Keep the primary status readable above compact controls. */
.lr-tv-screen:has(> .lr-playback):has(> .lr-tv-overlay) { min-height: 168px; }
-.lr-tv-screen:has(> .lr-playback) > video { grid-area: 1 / 1 / -1 / -1; min-height: 0; }
-.lr-tv-screen > .lr-playback { position: relative; inset: auto; grid-area: 2 / 1; }
+.lr-tv-screen:has(> .lr-playback) > video { grid-area: 1 / 1 / 3 / 2; min-height: 0; aspect-ratio: 16 / 9; height: auto; }
+.lr-room.is-theater .lr-tv-screen:has(> .lr-playback) > video,
+.lr-tv-screen:fullscreen:has(> .lr-playback) > video { aspect-ratio: auto; height: 100%; }
+.lr-tv-screen > .lr-remote-input-surface { grid-area: 1 / 1 / 3 / 2; }
+.lr-tv-screen > .lr-playback { position: relative; inset: auto; grid-area: 2 / 1; max-width: calc(100% - 16px); margin-bottom: 8px; }
+/* Remote taps belong to input. The local pull stays on the bezel, outside the
+ picture; theater/fullscreen use the same pull at the screen's bottom edge. */
+.lr-playback-reveal { display: none; position: absolute; bottom: 1px; right: 18px; z-index: 4; width: 64px; height: 24px; padding: 0; border: 1px solid color-mix(in srgb, var(--piik-dark-ink) 25%, transparent); border-radius: 8px; background: color-mix(in srgb, var(--piik-dark-ink) 14%, var(--frame)); box-shadow: 0 1px 0 var(--surface-shade); color: var(--piik-dark-ink); cursor: pointer; transition: background-color 160ms ease; }
+.lr-playback-reveal > svg { transition: transform 160ms var(--spring); }
+.lr-playback-reveal:is(:hover, :focus-visible) { background: color-mix(in srgb, var(--piik-dark-ink) 24%, var(--frame)); }
+.lr-playback-reveal:is(:hover, :focus-visible) > svg { transform: translateY(1px); }
+.lr-playback-reveal:active > svg { transform: none; }
+.lr-playback-reveal:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
+.lr-tv-screen > .lr-playback-reveal { right: 50%; bottom: 0; translate: 50% 0; border-radius: 10px 10px 0 0; border-bottom: 0; }
+.lr-playback-reveal-arrow { rotate: 180deg; }
+.lr-tv:has(> .lr-tv-screen > .lr-remote-input-surface):has(> .lr-tv-screen > .lr-playback.is-hidden) > .lr-tv-chin > .lr-playback-reveal,
+.lr-tv-screen:has(> .lr-remote-input-surface):has(> .lr-playback.is-hidden) > .lr-playback-reveal { display: grid; place-items: center; }
+.lr-tv:has(.lr-remote-password, .lr-playback :is(.lr-remote-feedback, [popover]:popover-open, [popover].\:popover-open)) .lr-playback-reveal { display: none; }
+.lr-tv-screen:has(> .lr-remote-password) > .lr-playback { opacity: 1; transform: none; pointer-events: auto; }
.lr-tv-screen:has(> .lr-playback) > .lr-tv-overlay { grid-area: 1 / 1 / 2 / 2; }
-.lr-tv-screen:has(> .lr-playback[data-can-play="true"]) > video { cursor: pointer; }
+/* Dim the whole picture, including behind the bar; only the message reserves it. */
+.lr-tv-screen:has(> .lr-playback)::after { grid-area: 1 / 1 / 3 / 2; }
.lr-tv-screen:has(> .lr-playback.is-hidden) > video { cursor: none; }
/* The video's own focus outline is clipped by the screen; mark its container. */
-.lr-tv-screen:has(> .lr-playback):has(:focus-visible) { outline: 3px solid var(--action); outline-offset: 2px; }
+.lr-tv-screen:has(> .lr-playback):has(> video:focus-visible) { outline: 3px solid var(--action); outline-offset: 2px; }
.lr-playback .lr-btn {
display: grid; place-items: center; flex: none;
min-width: 0; width: 44px; height: 44px; padding: 0;
}
-.lr-playback-audio { display: flex; align-items: center; flex: 1; gap: 8px; min-width: min-content; }
-.lr-playback-separator { flex: none; width: 1px; height: 20px; background: currentColor; opacity: .22; }
-.lr-playback-volume { flex: 0 1 144px; min-width: 32px; }
+.lr-playback-watch { display: flex; align-items: center; flex: 1; gap: 8px; min-width: 0; }
+.lr-playback-volume { flex: 0 1 144px; min-width: 24px; }
.lr-playback-volume input { width: 100%; min-width: 0; height: 44px; padding: 0; margin: 0; accent-color: var(--action); cursor: pointer; }
.lr-playback-level { flex: none; width: 4ch; text-align: right; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }
-.lr-playback-level.is-boosted { color: var(--action); }
-.lr-playback-view { display: inline-flex; align-items: center; flex: none; gap: 4px; margin-left: auto; border-left: 1px solid var(--wall-2); padding-left: 8px; }
+.lr-playback-level.is-boosted { color: var(--action-text); }
+.lr-playback > :is(.lr-remote-controls, .lr-playback-view) { display: inline-flex; align-items: center; flex: none; gap: 4px; }
+.lr-playback > :is(.lr-remote-controls, .lr-playback-view)::before { content: ""; flex: none; width: 1px; height: 20px; margin-right: 4px; background: var(--control-edge); }
+.lr-playback-secondary { display: inline-flex; align-items: center; gap: inherit; }
+.lr-playback-more { display: inline-flex; }
+.lr-playback-menu { position: fixed; inset: auto; margin: 0; padding: 8px; max-width: calc(100vw - 16px); overflow: auto; overscroll-behavior: contain; }
+.lr-playback-menu:is(:popover-open, .\:popover-open) { display: grid; gap: 6px; animation: lr-language-open 180ms var(--spring); }
+.lr-playback-menu-actions { display: grid; gap: 6px; }
+.lr-playback-settings { width: min(560px, calc(100vw - 16px)); padding: 16px; container: playback-settings / inline-size; }
+.lr-viewer-settings { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; width: 100%; }
+.lr-viewer-settings section { min-width: 0; }
+.lr-viewer-settings-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 36px; margin-bottom: 12px; }
+.lr-viewer-settings h3, .lr-playback-overlay-settings h3 { display: flex; align-items: center; gap: 8px; margin: 0; font-size: 12px; font-weight: 650; }
+.lr-viewer-settings-heading .lr-btn { display: flex; align-items: center; gap: 5px; width: auto; height: 36px; padding: 0 8px; font-size: 12px; white-space: nowrap; }
+.lr-viewer-settings .lr-row-group { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
+.lr-viewer-settings .lr-row-group > * { min-width: 0; }
+.lr-viewer-settings .lr-chip { display: flex; align-items: center; justify-content: center; gap: 5px; width: 100%; min-height: 40px; padding: 6px; font-size: 12px; white-space: nowrap; }
+.lr-playback-overlay-settings { margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--control-edge); }
+.lr-playback-overlay-settings .lr-chat-overlay-settings { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; margin-top: 8px; }
+.lr-viewer-settings p { color: var(--muted); font-size: 11px; line-height: 1.6; margin: 10px 0 0; }
+.lr-viewer-settings p.is-error { color: var(--danger); }
+.lr-playback-display-menu { display: none; }
+.lr-playback-menu .lr-comic-tip-wrap { display: block; }
+.lr-playback-menu-actions .lr-btn { display: flex; justify-content: flex-start; width: 100%; padding: 0 12px; gap: 8px; }
.lr-tv-screen:fullscreen { width: 100%; height: 100%; border: 0; border-radius: 0; }
-.lr-tv-screen:has(> .lr-playback) { container-type: inline-size; }
-@container (max-width: 440px) {
+.lr-tv-screen:has(> .lr-playback) { container: media-stage / inline-size; }
+@container media-stage (max-width: 640px) {
+ .lr-playback-secondary, .lr-playback-level { display: none; }
+ .lr-playback-display-menu { display: grid; gap: 6px; }
+ .lr-playback-settings .lr-playback-display-menu { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-top: 12px; }
+ .lr-playback-display-menu .lr-btn { display: flex; justify-content: center; gap: 6px; width: 100%; padding: 6px 8px; height: auto; min-height: 40px; font-size: 12px; }
+}
+@container media-stage (max-width: 440px) {
.lr-tv-screen > .lr-tv-overlay.has-comic { gap: 4px; padding: 6px; }
.lr-tv-overlay > .lr-waiting-caption { min-height: 1.4em; }
.lr-tv-overlay > .lr-waiting-caption > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
- .lr-playback { gap: 6px; padding: 4px 8px max(4px, env(safe-area-inset-bottom)); }
- .lr-playback .lr-btn { width: clamp(32px, 11cqw, 44px); }
- .lr-playback-audio { gap: 4px; }
- .lr-playback-separator, .lr-playback-level { display: none; }
+ .lr-playback.lr-media-controls { gap: 4px; padding: 4px 4px max(4px, env(safe-area-inset-bottom)); }
+ .lr-playback .lr-btn { width: clamp(24px, 9cqw, 44px); }
+ .lr-playback-menu .lr-btn { width: auto; }
+ .lr-playback-menu-actions .lr-btn, .lr-playback-display-menu .lr-btn { width: 100%; }
+ .lr-playback-watch { gap: 2px; }
.lr-playback-volume { flex: 1; }
- .lr-playback-view { gap: 2px; border: 0; padding: 0; }
+ .lr-playback > :is(.lr-remote-controls, .lr-playback-view) { gap: 2px; }
+ .lr-playback > :is(.lr-remote-controls, .lr-playback-view)::before { margin-right: 0; }
}
@media (prefers-reduced-motion: reduce) {
- .lr-playback, .lr-playback .lr-btn { transition: none; }
+ .lr-playback, .lr-playback .lr-btn, .lr-playback-reveal, .lr-playback-reveal > svg { transition: none; }
+ .lr-playback-menu:is(:popover-open, .\:popover-open), .lr-playback-settings { animation: none; }
+}
+
+@container playback-settings (max-width: 480px) {
+ .lr-viewer-settings { grid-template-columns: minmax(0, 1fr); gap: 16px; }
}
diff --git a/src/client/components/living/playback-gestures.ts b/src/client/components/living/playback-gestures.ts
index cd16bb1a..b3df13df 100644
--- a/src/client/components/living/playback-gestures.ts
+++ b/src/client/components/living/playback-gestures.ts
@@ -1,47 +1,18 @@
-// A native double-click follows two clicks. Defer only the picture shortcut;
-// visible controls and keyboard actions remain immediate.
-const SINGLE_CLICK_MS = 500;
-
export function bindPlaybackGestures(
video: HTMLVideoElement,
- togglePlayback: () => void,
toggleFullscreen: () => void,
): () => void {
const listeners = new AbortController();
const options = { signal: listeners.signal };
- let timer: ReturnType<typeof setTimeout> | undefined;
let pointerType = "";
- const cancel = () => {
- clearTimeout(timer);
- timer = undefined;
- };
-
- // Beginning another action retires an uncommitted picture click, including
- // the second press of a double-click or an action in the control bar.
+ // Picture taps only reveal controls. Playback belongs to its explicit button;
+ // remote input consumes its own double-clicks before they reach the video.
video.parentElement?.addEventListener("pointerdown", (event) => {
pointerType = event.pointerType;
- cancel();
- }, options);
- video.parentElement?.addEventListener("keydown", cancel, options);
- video.parentElement?.addEventListener("pointercancel", cancel, options);
- video.addEventListener("click", (event) => {
- if (event.defaultPrevented || event.button !== 0 || event.detail !== 1 || pointerType === "touch") return;
- cancel();
- const source = video.srcObject;
- timer = setTimeout(() => {
- timer = undefined;
- if (video.srcObject === source) togglePlayback();
- }, SINGLE_CLICK_MS);
}, options);
video.addEventListener("dblclick", (event) => {
if (event.defaultPrevented || event.button !== 0 || pointerType === "touch") return;
- cancel();
toggleFullscreen();
}, options);
- for (const event of ["play", "pause", "emptied"]) video.addEventListener(event, cancel, options);
-
- return () => {
- cancel();
- listeners.abort();
- };
+ return () => listeners.abort();
}
diff --git a/src/client/components/living/primitives.tsx b/src/client/components/living/primitives.tsx
index cc22843f..38927005 100644
--- a/src/client/components/living/primitives.tsx
+++ b/src/client/components/living/primitives.tsx
@@ -118,7 +118,7 @@ export function Btn({
</button>
);
return hint ? (
- <Tooltip kind={hint} tone={hintTone} motion={hintMotion} text={vis ? undefined : hintText ? t(hintText) : label}>{button}</Tooltip>
+ <Tooltip kind={hint} disabled={expanded} tone={hintTone} motion={hintMotion} text={vis ? undefined : hintText ? t(hintText) : label}>{button}</Tooltip>
) : (
button
);
diff --git a/src/client/components/living/remote-control.css b/src/client/components/living/remote-control.css
new file mode 100644
index 00000000..e3ccab39
--- /dev/null
+++ b/src/client/components/living/remote-control.css
@@ -0,0 +1,123 @@
+.lr-tv-screen > .lr-remote-input-surface { position: absolute; inset: 0; z-index: 3; cursor: default; touch-action: none; overflow: hidden; outline: 2px solid var(--primary); outline-offset: -2px; border-radius: inherit; }
+.lr-remote-input-surface.is-suspended { outline-color: var(--muted); cursor: default; pointer-events: none; }
+.lr-remote-input-surface.is-locked { cursor: none; }
+.lr-remote-viewer-control { position: relative; display: inline-flex; align-items: center; gap: 4px; min-width: 0; }
+.lr-remote-feedback { display: flex; align-items: center; gap: 5px; max-width: 180px; font-size: 12px; line-height: 1.3; color: inherit; }
+.lr-remote-feedback > svg { flex: none; }
+.lr-tv-screen > .lr-playback:has(.lr-remote-feedback) { opacity: 1; transform: none; pointer-events: auto; }
+.lr-remote-trigger { display: inline-flex; position: relative; }
+.lr-remote-count { position: absolute; top: -4px; right: -3px; min-width: 20px; padding: 0 5px; border: 2px solid var(--paper); border-radius: 12px; background: var(--action-deep); color: var(--action-ink); font: 600 11px/16px var(--font); text-align: center; pointer-events: none; }
+.lr-remote-panel-body { padding-block: 14px 6px; }
+.lr-remote-panel-body > .lr-switch-item { margin-bottom: 12px; }
+.lr-remote-enable-pending { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
+.lr-remote-enable-pending > svg { color: var(--muted); }
+.lr-remote-panel-header { display: flex; align-items: center; gap: 10px; margin: -4px -4px 10px 0; }
+.lr-remote-panel-header strong { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; font-size: 14px; }
+.lr-remote-settings { display: grid; gap: 10px; padding: 12px 0; }
+.lr-remote-field-label { font-size: 12px; font-weight: 650; }
+.lr-remote-modes.lr-toggle { display: grid; }
+.lr-remote-modes > .lr-comic-tip-wrap { min-width: 0; }
+.lr-remote-modes button { min-width: 0; height: auto; min-height: 40px; padding: 6px 4px; font: 600 12px/1.3 var(--font); white-space: normal; }
+.lr-remote-policy-actions { display: flex; align-items: center; gap: 8px; }
+.lr-remote-settings > .lr-remote-policy-actions > * { flex: 1; }
+.lr-remote-settings .lr-remote-policy-actions .lr-btn { width: 100%; height: 42px; }
+.lr-remote-policy-actions .lr-input { flex: 1; min-width: 0; }
+.lr-remote-policy-actions .lr-input input { min-width: 0; width: 100%; }
+.lr-remote-password p { display: flex; align-items: center; gap: 6px; color: var(--warn); margin: 8px auto 0; font-size: 12px; }
+.lr-remote-password p.is-bad { color: var(--danger); }
+.lr-remote-password > * { max-width: 360px; margin-inline: auto; }
+.lr-remote-panel p { font-size: 12px; line-height: 1.5; margin: 0; }
+.lr-remote-panel p[role="alert"] { color: var(--danger); }
+.lr-remote-request p, .lr-remote-panel p[role="alert"] { display: flex; align-items: center; gap: 6px; }
+.lr-remote-request p > svg, .lr-remote-panel p[role="alert"] > svg { flex: none; }
+.lr-remote-panel-body > .lr-remote-note + .lr-remote-note { margin-top: 8px; }
+.lr-remote-panel .lr-remote-note > svg { vertical-align: middle; }
+.lr-remote-note, .lr-remote-request p { color: var(--muted); }
+.lr-remote-requests { padding-bottom: 12px; margin-bottom: 4px; border-bottom: 1px solid var(--wall-2); }
+.lr-remote-request { display: grid; gap: 10px; padding: 10px 0; }
+.lr-remote-request + .lr-remote-request { border-top: 1px solid var(--control-edge); }
+.lr-remote-request > div:first-child { min-width: 0; }
+.lr-remote-request-actions { display: flex; gap: 8px; max-width: 100%; }
+.lr-remote-request-actions > .lr-comic-tip-wrap { flex: 1; }
+.lr-remote-request-actions .lr-btn { width: 100%; }
+.lr-remote-note kbd { white-space: nowrap; font: 12px var(--mono); }
+.lr-remote-touch-cursor { position: absolute; width: 22px; height: 26px; left: 50%; top: 50%; pointer-events: none; filter: drop-shadow(0 1px 2px #0008); }
+.lr-remote-touch-cursor path { fill: #fff; stroke: #22313e; stroke-width: 1.5; stroke-linejoin: round; }
+.lr-remote-zoom { grid-area: 1 / 1 / 2 / 2; z-index: 4; align-self: start; justify-self: end; padding: 8px; }
+.lr-remote-zoom .lr-chip { display: grid; place-items: center; width: 44px; height: 40px; padding: 0; border-width: 1px; background: var(--paper); font: 600 13px var(--mono); letter-spacing: 0; }
+.lr-remote-game-mouse { display: flex; justify-content: center; margin-top: 8px; }
+:is(.lr-remote-keyboard, .lr-remote-password) { grid-area: 3 / 1; z-index: 4; padding: 10px 12px 12px; background: var(--paper); color: var(--ink); border-top: 1px solid var(--control-edge); }
+:is(.lr-remote-keyboard, .lr-remote-password) .lr-input { padding: 0 10px; }
+:is(.lr-remote-keyboard, .lr-remote-password) input { font-size: 16px; }
+:is(.lr-remote-keyboard, .lr-remote-password) .lr-btn { width: 40px; height: 40px; min-width: 0; padding: 0; }
+.lr-remote-game-mouse .lr-btn { width: auto; padding: 0 12px; }
+.lr-remote-keys { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; margin-bottom: 10px; }
+.lr-remote-shortcuts:has(> :nth-child(4):last-child) { grid-template-columns: repeat(4, minmax(0, 1fr)); }
+.lr-remote-keyboard { min-height: 0; max-height: 65dvh; overflow-y: auto; overscroll-behavior: contain; outline: none; }
+.lr-remote-keyboard > .lr-remote-panel-header { position: sticky; top: -10px; z-index: 1; background: var(--paper); }
+.lr-remote-keyboard > * { max-width: 640px; margin-inline: auto; }
+.lr-remote-keyboard .lr-remote-key-pages { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-bottom: 12px; }
+.lr-remote-keyboard .lr-remote-key-pages button { min-width: 0; height: 36px; padding: 4px 8px; font-size: 12px; letter-spacing: 0; }
+.lr-remote-key-row { display: flex; justify-content: center; gap: 4px; margin-bottom: 6px; }
+.lr-remote-key-row .lr-chip { flex: 1; }
+.lr-remote-key-layout.is-letters .lr-remote-key-row:not(:last-child) .lr-chip { flex: 0 1 calc((100% - 36px) / 10); }
+.lr-remote-modifier-key { display: flex; flex: 1; min-width: 0; }
+.lr-remote-modifier-key .lr-chip { width: 100%; }
+.lr-remote-key-layout .lr-remote-modifier-key, .lr-remote-key-layout [data-key="Backspace"] { flex: 1.5; }
+.lr-remote-bottom-row { margin-top: 10px; }
+.lr-remote-bottom-row > .lr-remote-modifier-key { min-width: 40px; }
+.lr-remote-bottom-row [data-key="Space"] { flex: 3; }
+.lr-remote-bottom-row [data-key="Enter"] { flex: 2; min-width: 44px; }
+.lr-remote-navigation { display: flex; align-items: end; gap: 12px; margin-top: 10px; }
+.lr-remote-navigation-actions { flex: 1; min-width: 0; }
+.lr-remote-navigation-actions.is-text { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
+.lr-remote-navigation-actions.is-editing { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); }
+.lr-remote-navigation-actions.is-editing:has(> :nth-child(5):last-child) > :first-child { grid-column: 2; }
+.lr-remote-arrows { flex: 0 0 36%; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); }
+.lr-remote-arrows [data-key="ArrowUp"] { grid-column: 2; }
+.lr-remote-arrows [data-key="ArrowLeft"] { grid-column: 1; }
+.lr-remote-text-entry { display: grid; gap: 8px; margin-bottom: 14px; }
+.lr-remote-text-entry .lr-remote-text-field { display: flex; flex-direction: column; align-items: stretch; height: auto; gap: 8px; padding: 10px; }
+.lr-remote-text-field textarea { width: 100%; min-height: 96px; max-height: 30dvh; resize: vertical; padding: 0; border: 0; outline: 0; background: transparent; color: inherit; font: 16px/1.5 var(--mono); tab-size: 4; }
+.lr-remote-text-field textarea::placeholder { color: var(--muted); font-family: var(--font); opacity: 1; }
+.lr-remote-text-actions { display: flex; justify-content: end; }
+.lr-remote-keyboard .lr-remote-text-entry p[role="alert"] { color: var(--danger); }
+.lr-remote-text-entry .lr-btn { flex: none; width: auto; gap: 6px; padding-inline: 12px; }
+.lr-remote-keyboard .lr-remote-text-entry p { margin: 0; text-align: start; }
+:is(.lr-remote-keys, .lr-remote-key-row) .lr-chip { justify-content: center; padding: 4px 0; width: 100%; min-width: 0; min-height: 38px; border-width: 1px; border-radius: 9px; font: 600 12px var(--mono); letter-spacing: 0; white-space: nowrap; touch-action: none; }
+.lr-remote-keyboard p { margin-block: 8px 0; text-align: center; color: var(--muted); font-size: 12px; line-height: 1.5; }
+:is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen):has(.lr-remote-keyboard) { grid-template-rows: minmax(min(120px, 30dvh), 1fr) auto minmax(0, auto); }
+:is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen) .lr-remote-keyboard { max-height: none; overflow-y: auto; overscroll-behavior: contain; }
+:is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen) .lr-remote-keyboard > .lr-remote-panel-header { position: sticky; top: -10px; z-index: 1; background: var(--paper); }
+.lr-panel-window .lr-remote-keyboard { min-height: 100dvh; border: 0; padding: 12px; }
+.lr-panel-window .lr-remote-keyboard > .lr-remote-panel-header { display: none; }
+/* In short fullscreen/theater viewports, keep the picture beside the keyboard
+ instead of spending the entire height on keys and playback controls. */
+@media (min-width: 600px) and (max-height: 520px) and (orientation: landscape) {
+ :is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen):has(.lr-remote-keyboard) { grid-template: minmax(0, 1fr) auto / minmax(0, 1fr) minmax(280px, 44%); }
+ :is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen) .lr-remote-keyboard { grid-area: 1 / 2 / 3 / 3; border-top: 0; border-left: 1px solid var(--control-edge); }
+ :is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen):has(.lr-remote-keyboard) > .lr-playback { width: 100%; container: media-stage / inline-size; gap: 4px; padding-inline: 6px; }
+ :is(.lr-room.is-theater .lr-tv-screen, .lr-tv-screen:fullscreen) .lr-remote-key-row .lr-chip { min-height: 32px; }
+}
+@media (max-width: 580px) {
+ .lr-remote-shortcuts { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+ .lr-remote-shortcuts:has(> :nth-child(4):last-child) { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+}
+@media (max-width: 380px) {
+ .lr-remote-keyboard { padding-inline: 6px; }
+ .lr-remote-key-row { gap: 3px; }
+ .lr-remote-key-layout.is-letters .lr-remote-key-row:not(:last-child) .lr-chip { flex-basis: calc((100% - 27px) / 10); }
+}
+@container media-stage (max-width: 640px) {
+ .lr-remote-feedback { position: absolute; top: -2px; right: -2px; justify-content: center; width: 18px; height: 18px; border-radius: 50%; background: var(--paper); box-shadow: 0 0 0 1px var(--control-edge); pointer-events: none; }
+ .lr-remote-feedback > span:not(.visually-hidden) { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
+}
+
+.lr-comic-tip-wrap.lr-remote-combine-hint { display: flex; justify-content: center; }
+.lr-remote-combine-keys { display: flex; align-items: center; justify-content: center; gap: 7px; margin-top: 10px; font-size: 12px; cursor: pointer; }
+.lr-remote-combine-keys input { width: 16px; height: 16px; margin: 0; accent-color: var(--action); }
+.lr-remote-combine-keys > span { display: inline-flex; align-items: center; gap: 6px; }
+.lr-remote-combine-keys kbd {
+ display: grid; place-items: center; min-width: 24px; height: 24px;
+ border: 1px solid var(--line); border-radius: 5px; font: 600 14px var(--mono);
+}
diff --git a/src/client/components/living/room-chat-overlay.css b/src/client/components/living/room-chat-overlay.css
index cc818287..a92fc924 100644
--- a/src/client/components/living/room-chat-overlay.css
+++ b/src/client/components/living/room-chat-overlay.css
@@ -17,9 +17,12 @@
@container (height < 78px) { .lr-chat-flight[data-lane="1"] { visibility: hidden; } }
@container (height < 44px) { .lr-chat-flight { visibility: hidden; } }
.lr-chat-overlay-toggle { display: inline-flex; }
-@container (max-width: 440px) {
- .lr-playback:has(.lr-chat-overlay-toggle) .lr-btn { width: clamp(28px, 9cqw, 40px); }
-}
+.lr-chat-overlay-settings { display: grid; gap: 18px; }
+.lr-chat-setting { min-width: 0; }
+.lr-chat-setting > label { display: flex; justify-content: space-between; align-items: center; gap: 12px; min-height: 28px; font-size: 13px; }
+.lr-chat-setting output { color: var(--muted); font: 12px var(--mono); }
+.lr-chat-setting > .lr-comic-tip-wrap { display: flex; width: 100%; }
+.lr-chat-setting input[type="range"] { width: 100%; min-height: 40px; margin: 0; accent-color: var(--action); cursor: pointer; }
[data-comic-reduced-motion] .lr-chat-flight { animation: none; left: 12px; }
@media (prefers-reduced-motion: reduce) {
.lr-chat-flight { animation: none; left: 12px; }
diff --git a/src/client/components/living/room-interactions.css b/src/client/components/living/room-interactions.css
index 758367c4..dbbc71b5 100644
--- a/src/client/components/living/room-interactions.css
+++ b/src/client/components/living/room-interactions.css
@@ -1,25 +1,53 @@
.lr-room-interactions { position: relative; width: min(960px, 100%); margin: 0 auto; }
.lr-interaction-couch { position: relative; }
+.lr-interaction-conversation { position: relative; display: flex; flex: 1; flex-direction: column; min-height: 0; --gift-arc: 40px; --gift-lift: 32px; }
+.lr-interaction-conversation[hidden] { display: none; }
+.lr-interaction-conversation .lr-reaction-flight { overflow: hidden; }
+/* The picker belongs to the composer; opening it never moves the input or reading position. */
+.lr-interaction-people-scroll { overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; padding: 4px 0; margin-bottom: 4px; border-bottom: 1px solid var(--wall-2); }
+.lr-interaction-people { display: flex; gap: 4px; width: max-content; min-width: 100%; }
+.lr-interaction-people > span { display: flex; flex: none; max-width: 148px; }
+.lr-interaction-people .lr-comic-tip-wrap { width: 100%; }
+.lr-interaction-people .lr-pawn { display: flex; width: 100%; min-width: 0; min-height: 44px; gap: 6px; padding: 6px 10px; border-radius: 14px; transition: transform 150ms var(--spring), background-color 140ms ease; }
+.lr-interaction-people .lr-pawn.is-you::after { display: none; }
+.lr-interaction-people .lr-person { flex: none; width: 22px; height: 28px; }
+.lr-interaction-panel .lr-interaction-people .lr-pawn-name { min-width: 0; max-width: 100%; margin: 0; padding: 0; font-size: 12px; font-weight: 600; line-height: 1.4; background: none; color: inherit; box-shadow: none; }
+.lr-interaction-panel .lr-interaction-people .lr-pawn:is(:hover, :focus-visible) { background: var(--control-hover); }
+.lr-interaction-people .lr-pawn:focus-visible { outline-offset: -3px; }
+.lr-interaction-panel .lr-interaction-people .lr-pawn[aria-pressed="true"] { background: var(--control-selected); color: var(--control-selected-ink); box-shadow: inset 0 0 0 1px var(--action); }
+.lr-interaction-picker { flex: 0 1 auto; max-height: calc(100% - 60px); padding-block: 4px 6px; border-top: 1px solid var(--wall-2); }
+.lr-interaction-picker[hidden] { display: none; }
+.lr-interaction-picker:not([hidden]) { transform-origin: center bottom; animation: lr-floating-enter 150ms var(--spring); }
+.lr-interaction-back { flex: none; padding: 14px 0 0; }
+.lr-interaction-back .lr-btn { min-width: 36px; height: 36px; padding: 0 10px; gap: 4px; }
+.lr-interaction-activity { position: absolute; z-index: 2; right: 4px; bottom: 8px; max-width: calc(100% - 8px); padding-top: 68px; pointer-events: none; --gift-arc: 30px; --gift-lift: 30px; }
+.lr-interaction-activity-people, .lr-interaction-activity-people > span { display: flex; align-items: center; gap: 12px; min-width: 0; }
+.lr-interaction-activity-people { padding: 8px 12px; border: 1px solid var(--control-edge); border-radius: 18px; background: color-mix(in srgb, var(--paper) 96%, transparent); box-shadow: var(--control-shadow); }
+.lr-interaction-activity-people > span > svg { flex: none; color: var(--muted); }
+.lr-interaction-activity-person { display: grid; justify-items: center; gap: 4px; min-width: 0; width: 76px; }
+.lr-interaction-activity-person .lr-person { width: 28px; height: 34px; }
+.lr-interaction-activity-person > span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; color: var(--muted); }
.lr-couch-footer.has-action { gap: 4px; width: fit-content; margin: 0 auto; padding: 3px; background: var(--paper); border: 1px solid var(--control-edge); border-radius: 18px; color: var(--ink); }
.lr-couch-footer.has-action .lr-couch-count { padding: 0 12px 0 9px; border: 0; border-right: 1px solid var(--control-edge); border-radius: 0; background: transparent; color: var(--muted); }
.lr-interaction-chat-toggle { display: flex; position: relative; }
-.lr-interaction-unread { align-self: flex-start; margin: -4px 0 0 -8px; z-index: 1; min-width: 22px; padding: 2px 6px; border-radius: 20px; color: var(--paper); background: var(--action); font: 700 11px var(--mono); text-align: center; }
-.lr-chat-compose, .lr-chat-footer { flex-shrink: 0; }
+.lr-interaction-unread { align-self: flex-start; margin: -4px 0 0 -8px; z-index: 1; min-width: 22px; padding: 2px 6px; border-radius: 20px; color: var(--action-ink); background: var(--action-deep); font: 700 11px var(--mono); text-align: center; }
+.lr-chat-compose { flex-shrink: 0; }
.lr-interaction-effects { display: flex; align-items: center; gap: 8px; min-height: 40px; width: fit-content; margin-top: 8px; font-size: 12px; font-weight: 400; color: var(--muted); }
-.lr-chat-history { position: relative; flex: 1; min-height: 96px; }
-.lr-chat-log { height: 100%; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-gutter: stable; padding: 18px 2px; }
-.lr-chat-latest { position: absolute; bottom: 8px; left: 50%; translate: -50% 0; display: flex; align-items: center; gap: 6px; min-height: 36px; max-width: calc(100% - 16px); padding: 6px 12px; border: 1px solid var(--control-edge); border-radius: 18px; background: var(--paper); color: var(--ink); box-shadow: var(--control-shadow); font-size: 12px; white-space: nowrap; }
+.lr-chat-history { position: relative; flex: 1; min-height: 0; }
+.lr-chat-log { height: 100%; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-gutter: stable; padding: 16px 2px; }
+.lr-chat-latest { position: absolute; z-index: 6; bottom: 8px; left: 50%; translate: -50% 0; display: flex; align-items: center; gap: 6px; min-height: 36px; max-width: calc(100% - 16px); padding: 6px 12px; border: 1px solid var(--control-edge); border-radius: 18px; background: var(--paper); color: var(--ink); box-shadow: var(--control-shadow); font-size: 12px; white-space: nowrap; }
.lr-chat-latest:is(:hover, :focus-visible) { background: var(--control-hover); }
.lr-chat-empty { display: grid; place-content: center; justify-items: center; gap: 10px; height: 100%; color: var(--muted); font-size: 13px; }
.lr-chat-empty p { margin: 0; }
-.lr-chat-welcome { position: relative; display: flex; gap: 4px; padding-top: 20px; }
-.lr-chat-welcome > svg:last-child { position: absolute; top: 0; right: 0; color: var(--action); }
-.lr-chat-message { position: relative; display: flex; padding: 0 20px 0 34px; margin: 12px 0 0; }
+.lr-chat-message { position: relative; display: flex; padding: 0 20px 0 46px; margin: 12px 0 0; }
.lr-chat-message:first-child { margin-top: 0; }
-.lr-chat-message.is-self { justify-content: flex-end; padding: 0 34px 0 20px; }
+.lr-chat-message.is-self { justify-content: flex-end; padding: 0 46px 0 20px; }
.lr-chat-message.is-continuation { margin-top: 4px; }
-.lr-chat-avatar { position: absolute; top: 1px; left: 0; }
+.lr-chat-avatar { position: absolute; top: 1px; left: 0; display: grid; place-items: center; width: 40px; height: 40px; padding: 0; border: 0; border-radius: 12px; background: transparent; color: inherit; }
.lr-chat-avatar .lr-person { width: 28px; height: 34px; }
+button.lr-chat-avatar { cursor: pointer; transition: background-color 140ms ease; }
+button.lr-chat-avatar:is(:hover, :focus-visible) { background: var(--control-hover); }
+button.lr-chat-avatar:focus-visible { outline-offset: -3px; }
.lr-chat-message.is-self .lr-chat-avatar { left: auto; right: 0; }
.lr-chat-bubble { min-width: 0; }
.lr-chat-author { display: block; margin: 0 4px 5px; font-size: 11px; color: var(--muted); overflow-wrap: anywhere; }
@@ -27,53 +55,53 @@
.lr-chat-message p { padding: 9px 13px; margin: 0; border-radius: 4px 16px 16px; background: var(--wall); overflow-wrap: anywhere; white-space: pre-wrap; font-size: 14px; line-height: 1.6; }
.lr-chat-message.is-self p { background: color-mix(in srgb, var(--action) 11%, var(--paper)); border-radius: 16px 4px 16px 16px; }
.lr-chat-message.is-continuation p { border-radius: 16px; }
-.lr-chat-compose { display: flex; align-items: center; gap: 4px; margin-top: 8px; padding: 4px; border: 1px solid var(--control-edge); border-radius: 20px; background: var(--wall); }
+.lr-chat-compose { margin-top: 12px; padding: 6px; border: 1px solid var(--control-edge); border-radius: 20px; background: var(--wall); }
.lr-chat-compose:has(input:focus-visible) { outline: 3px solid var(--action); outline-offset: 2px; }
-.lr-chat-compose > input { min-width: 0; flex: 1; width: 0; height: 44px; border: 0; outline: none; border-radius: 14px; padding: 0 10px; background: transparent; color: var(--ink); font-size: 16px; }
-.lr-chat-compose .lr-btn { flex: none; width: 44px; height: 44px; min-width: 44px; min-height: 44px; padding: 0; border-radius: 15px; }
-.lr-chat-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; min-height: 40px; margin-top: 8px; padding-right: 12px; color: var(--muted); font-size: 11px; line-height: 1.5; }
-.lr-chat-actions { display: flex; flex: none; align-items: center; gap: 6px; }
-.lr-chat-footer .lr-chat-overlay-toggle { flex: none; }
-.lr-chat-footer .lr-btn { min-height: 36px; padding: 0 8px; }
-.lr-chat-history[hidden], .lr-chat-compose[hidden] { display: none; }
-.lr-chat-settings { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; padding: 18px 2px; }
+.lr-chat-input-row { display: flex; align-items: center; gap: 6px; }
+.lr-chat-input-row > input { min-width: 0; flex: 1; width: 0; height: 44px; border: 0; outline: none; border-radius: 14px; padding: 0 10px; background: transparent; color: var(--ink); font-size: 16px; }
+.lr-chat-input-row .lr-btn { flex: none; width: 40px; height: 40px; min-width: 40px; padding: 0; border-radius: 14px; }
+.lr-chat-tools { display: flex; align-items: center; gap: 2px; padding-top: 4px; color: var(--muted); font-size: 11px; line-height: 1.5; }
+.lr-chat-tools .lr-btn { flex: none; min-width: 36px; height: 36px; padding: 0 8px; gap: 6px; border-color: transparent; background: transparent; box-shadow: none; color: var(--muted); }
+.lr-chat-tools .lr-btn:is(:hover, :focus-visible) { background: var(--control-hover); color: var(--ink); }
+.lr-chat-tools .lr-btn.is-on { background: var(--control-selected); color: var(--control-selected-ink); }
+.lr-chat-tools .lr-chat-count { padding: 0 4px; }
+.lr-chat-compose[hidden] { display: none; }
+.lr-chat-settings { flex: 1; padding-block: 18px; }
.lr-chat-settings > p { margin: 0 0 20px; color: var(--muted); font-size: 12px; line-height: 1.6; }
-.lr-chat-setting { margin-bottom: 22px; }
-.lr-chat-setting > label { display: flex; justify-content: space-between; align-items: center; gap: 12px; min-height: 28px; font-size: 13px; }
-.lr-chat-setting output { color: var(--muted); font: 12px var(--mono); }
-.lr-chat-setting > .lr-comic-tip-wrap { display: flex; width: 100%; }
-.lr-chat-setting input[type="range"] { width: 100%; min-height: 40px; margin: 0; accent-color: var(--action); cursor: pointer; }
+.lr-chat-settings > .lr-chat-overlay-settings { margin-bottom: 22px; }
.lr-chat-export { display: grid; justify-items: start; gap: 8px; padding-top: 16px; border-top: 1px solid var(--wall-2); }
+.lr-chat-export > p { margin: 0 0 6px; color: var(--muted); font-size: 12px; line-height: 1.6; }
.lr-chat-export small { color: var(--muted); font-size: 12px; line-height: 1.6; }
-.lr-chat-footer .lr-interaction-status { flex: 1 1 140px; min-width: 0; min-height: 0; margin: 0; overflow-wrap: anywhere; }
.lr-chat-count { flex: none; margin-left: auto; font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
-.lr-interaction-status { display: flex; align-items: center; gap: 6px; min-height: 24px; margin-top: 6px; font-size: 11px; color: var(--muted); }
+.lr-interaction-status { display: flex; flex: none; align-items: center; gap: 6px; min-height: 24px; margin-top: 6px; font-size: 11px; line-height: 1.5; color: var(--muted); }
+.lr-interaction-status > svg { flex: none; }
.lr-person-menu { transform-origin: center bottom; }
-.lr-person-menu-body { flex: 1; min-height: 0; padding-top: 12px; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; }
-.lr-person-menu-target { margin-bottom: 10px; }
-.lr-person-menu-name { display: flex; align-items: center; gap: 10px; min-width: 0; }
-.lr-person-menu-name > span:last-child { min-width: 0; }
+.lr-person-menu-body { flex: 1; padding-block: 12px 6px; }
+.lr-person-menu-target { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; }
+.lr-person-menu-name { display: flex; flex: 1; align-items: center; gap: 8px; min-width: 0; }
+.lr-person-menu-name > span:last-child { flex: 1; min-width: 0; }
+.lr-person-menu-name .lr-comic-tip-wrap { width: 100%; min-width: 0; }
.lr-person-menu-name small { display: block; color: var(--muted); font-size: 11px; line-height: 1.6; }
-.lr-person-menu-name b { display: block; font-size: 14px; font-weight: 650; overflow-wrap: anywhere; }
+.lr-person-menu-name b { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 650; }
.lr-person-menu-portrait { display: grid; place-items: center; width: 34px; height: 40px; flex: none; }
.lr-person-menu-portrait .lr-person { width: 30px; height: 36px; }
-.lr-reaction-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; }
-.lr-reaction-props { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 10px; }
-:is(.lr-reaction-grid, .lr-reaction-props) button { display: flex; align-items: center; justify-content: center; gap: 6px; min-height: 44px; padding: 4px; border: 1px solid transparent; background: transparent; color: inherit; border-radius: 14px; font-size: 26px; cursor: pointer; touch-action: manipulation; transition: background-color 140ms ease, border-color 140ms ease; }
-.lr-reaction-props button { background: var(--wall); }
-.lr-reaction-props button > span { font-size: 12px; }
-:is(.lr-reaction-grid, .lr-reaction-props) button[aria-disabled="true"] { opacity: .4; cursor: default; }
-:is(.lr-reaction-grid, .lr-reaction-props) button > :first-child { transition: transform 180ms var(--spring); }
-:is(.lr-reaction-grid, .lr-reaction-props) button:is(:hover, :focus-visible):not([aria-disabled="true"]) { background: var(--control-hover); border-color: var(--action); }
-:is(.lr-reaction-grid, .lr-reaction-props) button:is(:hover, :focus-visible):not([aria-disabled="true"]) > :first-child { transform: translateY(-2px); }
-:is(.lr-reaction-grid, .lr-reaction-props) button:active:not([aria-disabled="true"]) > :first-child { transform: scale(.9); }
+.lr-reaction-grid { display: grid; grid-template-columns: repeat(14, minmax(0, 1fr)); gap: 4px; }
+.lr-reaction-grid button { min-width: 0; min-height: 44px; cursor: pointer; touch-action: manipulation; }
+.lr-reaction-option { grid-column: span 2; display: grid; place-items: center; padding: 4px; border: 1px solid transparent; background: transparent; color: inherit; border-radius: 14px; font-size: 26px; line-height: 1; transition: background-color 140ms ease, border-color 140ms ease; }
+.lr-reaction-prop { grid-column: span 7; height: auto; margin-top: 6px; padding: 6px 4px; gap: 4px; border-width: 1px; border-radius: 14px; background: var(--wall); font-size: 12px; font-weight: 600; line-height: 1.3; white-space: normal; text-wrap: balance; }
+.lr-reaction-prop > svg { width: 26px; height: 26px; }
+.lr-reaction-grid button[aria-disabled="true"] { opacity: .4; cursor: default; }
+.lr-reaction-option > :first-child { transition: transform 180ms var(--spring); }
+.lr-reaction-option:is(:hover, :focus-visible):not([aria-disabled="true"]) { background: var(--control-hover); border-color: var(--action); }
+.lr-reaction-option:is(:hover, :focus-visible):not([aria-disabled="true"]) > :first-child { transform: translateY(-2px); }
+.lr-reaction-option:active:not([aria-disabled="true"]) > :first-child { transform: scale(.9); }
.lr-person-menu-details { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; min-height: 40px; padding: 8px; margin-top: 8px; border: 0; border-radius: 12px; background: transparent; color: var(--muted); font-size: 12px; cursor: pointer; }
.lr-person-menu-details:is(:hover, :focus-visible) { background: var(--control-hover); color: var(--ink); }
.lr-person-menu .lr-interaction-effects { font-size: 11px; }
/* Theater keeps the same top-layer chat; the picture never changes size. */
.lr-room.is-theater .lr-room-interactions { position: absolute; top: 12px; right: 12px; z-index: 5; width: auto; }
.lr-room.is-theater .lr-room-interactions .lr-couch { display: block; width: auto; margin: 0; }
-.lr-room.is-theater .lr-room-interactions :is(.lr-couch-seating, .lr-couch-count, .lr-reaction-flight) { display: none; }
+.lr-room.is-theater .lr-interaction-couch :is(.lr-couch-seating, .lr-couch-count, .lr-reaction-flight) { display: none; }
.lr-pawn[aria-expanded="true"] { background: color-mix(in srgb, var(--paper) 72%, transparent); border-radius: 18px; }
.lr-reaction-flight { position: absolute; inset: 0; pointer-events: none; z-index: 5; overflow: visible; }
/* The path positions the center; percentage translation centers any glyph size. */
@@ -82,16 +110,16 @@
.lr-reaction-glyph > svg { width: 34px; height: 34px; }
.is-tomato .lr-reaction-glyph { animation-name: lr-reaction-squash; }
.is-poop .lr-reaction-glyph { animation-name: lr-reaction-plop; }
-:is(.is-clap, .is-laugh, .is-party) .lr-reaction-glyph { animation-name: lr-reaction-bounce; }
+:is(.is-clap, .is-laugh, .is-clown, .is-party, .is-thumbsup) .lr-reaction-glyph { animation-name: lr-reaction-bounce; }
:is(.is-heart, .is-wow, .is-fire, .is-star) .lr-reaction-glyph { animation-name: lr-reaction-pulse; }
-.is-eyes .lr-reaction-glyph { animation-name: lr-reaction-peek; }
+:is(.is-eyes, .is-eyeroll) .lr-reaction-glyph { animation-name: lr-reaction-peek; }
.is-sleep .lr-reaction-glyph { animation-name: lr-reaction-doze; }
.lr-reaction-accents { position: absolute; left: 50%; top: 50%; translate: -50% -50%; overflow: visible; fill: #efb94e; }
.lr-reaction-accents.is-heart { fill: #e77585; }
.lr-reaction-accents.is-tomato { fill: #e96c55; }
.lr-reaction-accents.is-poop { fill: #b09b82; opacity: .65; }
.lr-reaction-accents.is-fire { fill: #ed9b58; }
-.lr-reaction-accents:is(.is-eyes, .is-sleep) { fill: var(--muted); }
+.lr-reaction-accents:is(.is-eyes, .is-eyeroll, .is-sleep) { fill: var(--muted); }
.lr-reaction-accents.is-sleep { font: 700 12px var(--mono); }
.lr-reaction-accents.is-party > :nth-child(2n) { fill: #65b7aa; }
.lr-reaction-accents.is-party > :nth-child(3n) { fill: #e77585; }
@@ -124,9 +152,9 @@
@keyframes lr-reaction-gift {
0% { opacity: 0; transform: translate(var(--from-x), calc(var(--from-y) - 28px)) scale(.7); }
12% { opacity: 1; transform: translate(var(--from-x), calc(var(--from-y) - 40px)) scale(.9); }
- 35% { transform: translate(calc((var(--from-x) + var(--to-x)) / 2), calc(min(var(--from-y), var(--to-y)) - 100px)) scale(1); }
- 52%, 80% { opacity: 1; transform: translate(var(--to-x), calc(var(--to-y) - 76px)) scale(1); }
- 100% { opacity: 0; transform: translate(var(--to-x), calc(var(--to-y) - 84px)) scale(.94); }
+ 35% { transform: translate(calc((var(--from-x) + var(--to-x)) / 2), calc(min(var(--from-y), var(--to-y)) - var(--gift-arc, 100px))) scale(1); }
+ 52%, 80% { opacity: 1; transform: translate(var(--to-x), calc(var(--to-y) - var(--gift-lift, 76px))) scale(1); }
+ 100% { opacity: 0; transform: translate(var(--to-x), calc(var(--to-y) - var(--gift-lift, 76px) - 8px)) scale(.94); }
}
@keyframes lr-reaction-wiggle {
0%, 52%, 86%, 100% { transform: none; }
@@ -188,19 +216,18 @@
72%, 100% { opacity: 0; transform: translate(var(--spark-x), var(--spark-y)) rotate(var(--spark-turn)) scale(.6); }
}
[data-comic-reduced-motion] .lr-reaction-projectile { animation: none; transform: translate(var(--to-x), calc(var(--to-y) - 33px)); }
-[data-comic-reduced-motion] .is-gift .lr-reaction-projectile { transform: translate(var(--to-x), calc(var(--to-y) - 76px)); }
+[data-comic-reduced-motion] .is-gift .lr-reaction-projectile { transform: translate(var(--to-x), calc(var(--to-y) - var(--gift-lift, 76px))); }
[data-comic-reduced-motion] .lr-reaction-body { transform: none !important; }
[data-comic-reduced-motion] .lr-reaction-glyph { animation: none; }
[data-comic-reduced-motion] .lr-reaction-accents { display: none; }
-[data-comic-reduced-motion] :is(.lr-reaction-grid, .lr-reaction-props) button > :first-child { transition: none; transform: none !important; }
+[data-comic-reduced-motion] .lr-reaction-grid button > :first-child { transition: none; transform: none !important; }
+[data-comic-reduced-motion] .lr-interaction-picker { animation: none; }
@media (prefers-reduced-motion: reduce) {
+ .lr-interaction-picker { animation: none !important; }
.lr-reaction-projectile { animation: none; transform: translate(var(--to-x), calc(var(--to-y) - 33px)); }
- .is-gift .lr-reaction-projectile { transform: translate(var(--to-x), calc(var(--to-y) - 76px)); }
+ .is-gift .lr-reaction-projectile { transform: translate(var(--to-x), calc(var(--to-y) - var(--gift-lift, 76px))); }
.lr-reaction-body { transform: none !important; }
.lr-reaction-glyph { animation: none; }
.lr-reaction-accents { display: none; }
- :is(.lr-reaction-grid, .lr-reaction-props) button > :first-child { transition: none; transform: none !important; }
-}
-@media (max-width: 420px) {
- .lr-chat-compose { gap: 6px; }
+ .lr-reaction-grid button > :first-child { transition: none; transform: none !important; }
}
diff --git a/src/client/components/living/use-anchored-popover.ts b/src/client/components/living/use-anchored-popover.ts
new file mode 100644
index 00000000..eab8c326
--- /dev/null
+++ b/src/client/components/living/use-anchored-popover.ts
@@ -0,0 +1,73 @@
+import { useLayoutEffect, type RefObject } from "react";
+
+// Native popovers own visibility, dismissal and focus. This only places a
+// menu beside its anchor, within the document displaying it.
+export function useAnchoredPopover(
+ trigger: RefObject<HTMLElement | null>, panel: RefObject<HTMLElement | null>,
+ { side = "below", align = "end", maxHeight = Infinity, minVisibleHeight = Infinity, enabled = true }: {
+ side?: "above" | "below"; align?: "end" | "center";
+ maxHeight?: number; minVisibleHeight?: number; enabled?: boolean;
+ } = {},
+) {
+ useLayoutEffect(() => {
+ const anchor = trigger.current, menu = panel.current;
+ if (!enabled || !anchor || !menu) return;
+ const view = menu.ownerDocument.defaultView;
+ if (!view) return;
+ const viewport = view.visualViewport;
+ const place = () => {
+ if (!menu.matches(":popover-open")) return;
+ const rect = anchor.getBoundingClientRect();
+ const left = (viewport?.offsetLeft ?? 0) + 8, top = (viewport?.offsetTop ?? 0) + 8;
+ const right = left + (viewport?.width ?? view.innerWidth) - 16;
+ const bottom = top + (viewport?.height ?? view.innerHeight) - 16;
+ if (!anchor.getClientRects().length || rect.bottom < top || rect.top > bottom || rect.right < left || rect.left > right) {
+ menu.hidePopover();
+ return;
+ }
+ const above = Math.max(0, rect.top - top - 8), below = Math.max(0, bottom - rect.bottom - 8);
+ const height = Math.min(menu.scrollHeight, maxHeight);
+ // Scrollable palettes can prefer their requested side without requiring
+ // every row to fit; compact menus retain the full-content threshold.
+ const preferredHeight = Math.min(height, minVisibleHeight);
+ const openAbove = side === "above" ? above >= preferredHeight || above > below : below < preferredHeight && above > below;
+ menu.style.maxWidth = `${right - left}px`;
+ menu.style.maxHeight = `${Math.min(maxHeight, openAbove ? above : below)}px`;
+ menu.classList.toggle("is-above", openAbove);
+ const x = align === "center" ? rect.left + (rect.width - menu.offsetWidth) / 2 : rect.right - menu.offsetWidth;
+ menu.style.left = `${Math.max(left, Math.min(x, right - menu.offsetWidth))}px`;
+ menu.style.top = `${Math.max(top, openAbove ? rect.top - menu.offsetHeight - 8 : rect.bottom + 8)}px`;
+ };
+ // The containing panel may reposition itself in the same resize. Measure
+ // after its layout owner has finished, including content/translation changes.
+ let frame = 0;
+ const schedule = () => {
+ view.cancelAnimationFrame(frame);
+ frame = view.requestAnimationFrame(place);
+ };
+ const observer = new ResizeObserver(schedule);
+ const toggled = () => {
+ observer.disconnect();
+ view.cancelAnimationFrame(frame);
+ if (!menu.matches(":popover-open")) return;
+ place(); observer.observe(menu); observer.observe(anchor);
+ const parentPopover = anchor.closest("[popover]");
+ if (parentPopover) observer.observe(parentPopover);
+ };
+ menu.addEventListener("toggle", toggled);
+ view.addEventListener("resize", schedule);
+ view.addEventListener("scroll", schedule, true);
+ viewport?.addEventListener("resize", schedule);
+ viewport?.addEventListener("scroll", schedule);
+ toggled();
+ return () => {
+ observer.disconnect();
+ view.cancelAnimationFrame(frame);
+ menu.removeEventListener("toggle", toggled);
+ view.removeEventListener("resize", schedule);
+ view.removeEventListener("scroll", schedule, true);
+ viewport?.removeEventListener("resize", schedule);
+ viewport?.removeEventListener("scroll", schedule);
+ };
+ }, [trigger, panel, side, align, maxHeight, minVisibleHeight, enabled]);
+}
diff --git a/src/client/components/living/use-playback-controls-visibility.ts b/src/client/components/living/use-playback-controls-visibility.ts
index 5c01dc2e..787050d0 100644
--- a/src/client/components/living/use-playback-controls-visibility.ts
+++ b/src/client/components/living/use-playback-controls-visibility.ts
@@ -7,7 +7,7 @@ export function usePlaybackControlsVisibility(
videoRef: RefObject<HTMLVideoElement | null>,
controlsRef: RefObject<HTMLDivElement | null>,
keepVisible: boolean,
-): boolean {
+) {
const [hidden, setHidden] = useState(false);
const pointerType = useRef("");
@@ -27,8 +27,12 @@ export function usePlaybackControlsVisibility(
window.clearTimeout(timer);
timer = undefined;
};
+ // Other surfaces in the TV (such as remote input) own their keyboard focus;
+ // only interaction with playback itself should pin its controls open.
+ const owns = (target: EventTarget | null) => target === video ||
+ (target instanceof Node && controls.contains(target));
const held = () => keepVisible || pressed || hoveringControls ||
- (screen.contains(document.activeElement) && document.activeElement?.matches(":focus-visible")) ||
+ (owns(document.activeElement) && document.activeElement?.matches(":focus-visible")) ||
controls.querySelector(":popover-open") !== null;
const scheduleHide = () => {
clearIdle();
@@ -49,7 +53,9 @@ export function usePlaybackControlsVisibility(
};
screen.addEventListener("pointermove", (event) => {
- if (event.pointerType === "touch") return;
+ // Remote input owns picture motion; its bezel pull reveals the controls.
+ if (event.pointerType === "touch" || screen.contains(document.pointerLockElement) ||
+ (event.target instanceof Element && event.target.closest(".lr-remote-input-surface"))) return;
// Cursor/style changes can emit stationary moves (Video.js #1068).
if (lastMove?.x === event.screenX && lastMove.y === event.screenY) return;
lastMove = { x: event.screenX, y: event.screenY };
@@ -76,16 +82,20 @@ export function usePlaybackControlsVisibility(
}
}, options);
screen.addEventListener("click", (event) => {
- // Native click excludes scrolling/cancelled gestures. A video tap only
- // reveals/hides controls; playback remains owned by the play button.
+ // Only the picture itself is a local reveal target. Remote input and
+ // other tools retain their clicks; the play button owns playback.
if (event.target === video && pointerType.current === "touch" && !held()) {
setHidden((current) => !current);
scheduleHide();
}
}, options);
- screen.addEventListener("focusin", show, options);
+ screen.addEventListener("focusin", event => {
+ if (owns(event.target)) show(); else scheduleHide();
+ }, options);
screen.addEventListener("focusout", scheduleHide, options);
- screen.addEventListener("keydown", show, options);
+ screen.addEventListener("keydown", event => {
+ if (owns(event.target)) show();
+ }, options);
// Popovers retain their DOM parent in the top layer. Their native toggle
// event resumes idle hiding after a tooltip/long-press has finished.
controls.addEventListener("toggle", show, { ...options, capture: true });
@@ -101,5 +111,5 @@ export function usePlaybackControlsVisibility(
};
}, [videoRef, controlsRef, keepVisible]);
- return keepVisible ? false : hidden;
+ return { hidden: keepVisible ? false : hidden };
}
diff --git a/src/client/lib/room-interactions.ts b/src/client/lib/room-interactions.ts
index 3f4d0539..d51a72d3 100644
--- a/src/client/lib/room-interactions.ts
+++ b/src/client/lib/room-interactions.ts
@@ -1,7 +1,8 @@
import { interactionPayloadSchema, type ClientMessage, type ServerMessage, type InteractionPayload } from "../../shared/protocol";
-import { INTERACTION_INTERVAL_MS, REACTION_DURATION_MS } from "../../shared/room-interactions";
+import { BASELINE_REACTION_IDS, INTERACTION_INTERVAL_MS, REACTION_DURATION_MS, REACTION_IDS, type ReactionId } from "../../shared/room-interactions";
import { createOpaqueId } from "./opaque-id";
import { identityHash } from "./identity-hash";
+import { CHAT_OVERLAY_LIMITS, readRoomPreferences, saveRoomPreferences } from "./room-preferences";
export type RoomInteraction = Omit<Extract<ServerMessage, { type: "room-interaction" }>, "payload"> & {
payload: InteractionPayload;
@@ -10,10 +11,10 @@ type Rejection = Extract<ServerMessage, { type: "room-interaction-rejected" }>["
export type InteractionError = Rejection | "offline" | "unconfirmed";
export const CHAT_OVERLAY_DURATION_MS = 6000;
export const CHAT_HISTORY_LIMIT = 1000;
-export const CHAT_OVERLAY_LIMITS = { scale: [.8, 1.3], opacity: [.4, 1] } as const;
type OverlayAppearance = { scale: number; opacity: number };
const CHAT_OVERLAY_LANES = 3;
interface InteractionState {
+ reactionIds: readonly ReactionId[];
ready: boolean;
peerId: string | null;
messages: (RoomInteraction & { isSelf: boolean })[];
@@ -26,7 +27,7 @@ interface InteractionState {
coolingDown: boolean;
error: InteractionError | null;
}
-const initialState = (): InteractionState => ({ ready: false, peerId: null, messages: [], reactions: [],
+const initialState = (): InteractionState => ({ reactionIds: BASELINE_REACTION_IDS, ready: false, peerId: null, messages: [], reactions: [],
overlayEnabled: false, overlayAppearance: { scale: 1, opacity: 1 }, overlayMessages: [],
pending: null, confirmed: null, coolingDown: false, error: null });
@@ -45,7 +46,16 @@ export class RoomInteractionSession {
private subscriptionStartedAt: number | null = null;
private serverOffset = 0;
- constructor(private readonly sendMessage: (message: ClientMessage) => boolean, readonly now = Date.now) {}
+ constructor(private readonly sendMessage: (message: ClientMessage) => boolean, readonly now = Date.now, reactionIds?: readonly string[]) {
+ const { overlayEnabled, overlayAppearance } = readRoomPreferences();
+ this.state = { ...this.state, overlayEnabled, overlayAppearance };
+ this.setSupportedReactions(reactionIds);
+ }
+
+ setSupportedReactions(reactionIds: readonly string[] = BASELINE_REACTION_IDS): void {
+ if (this.closed) return;
+ this.update({ reactionIds: REACTION_IDS.filter(id => reactionIds.includes(id)) });
+ }
getSnapshot = () => this.state;
subscribe = (listener: () => void) => {
this.listeners.add(listener);
@@ -121,7 +131,8 @@ export class RoomInteractionSession {
send(payload: InteractionPayload): boolean {
if (this.closed || !this.state.ready || this.state.pending || this.state.coolingDown ||
- !interactionPayloadSchema.safeParse(payload).success) return false;
+ !interactionPayloadSchema.safeParse(payload).success ||
+ payload.kind === "reaction" && !this.state.reactionIds.includes(payload.reaction)) return false;
const requestId = createOpaqueId();
try {
if (!this.sendMessage({ type: "send-room-interaction", requestId, payload })) {
@@ -141,6 +152,7 @@ export class RoomInteractionSession {
setOverlayEnabled(enabled: boolean) {
if (this.closed || this.state.overlayEnabled === enabled) return;
this.update({ overlayEnabled: enabled, overlayMessages: [] });
+ saveRoomPreferences({ overlayEnabled: enabled });
this.expireEffects();
}
@@ -157,6 +169,7 @@ export class RoomInteractionSession {
scale: Math.min(CHAT_OVERLAY_LIMITS.scale[1], Math.max(CHAT_OVERLAY_LIMITS.scale[0], appearance.scale)),
opacity: Math.min(CHAT_OVERLAY_LIMITS.opacity[1], Math.max(CHAT_OVERLAY_LIMITS.opacity[0], appearance.opacity)),
} });
+ saveRoomPreferences({ overlayAppearance: this.state.overlayAppearance });
}
private expireEffects() {
diff --git a/src/client/lib/room-preferences.ts b/src/client/lib/room-preferences.ts
new file mode 100644
index 00000000..1619dc8b
--- /dev/null
+++ b/src/client/lib/room-preferences.ts
@@ -0,0 +1,45 @@
+import { z } from "zod";
+import { viewerRoutePreferenceSchema } from "../../shared/protocol";
+import { remoteControlModeSchema } from "../remote-control/protocol";
+
+const STORAGE_KEY = "piik:room-preferences:v1";
+export const CHAT_OVERLAY_LIMITS = { scale: [.8, 1.3], opacity: [.4, 1] } as const;
+export const REMOTE_KEYBOARD_PAGES = ["letters", "symbols", "functions", "text"] as const;
+
+const roomPreferencesSchema = z.object({
+ pictureFit: z.enum(["contain", "cover", "fill"]).default("contain"),
+ routePreference: viewerRoutePreferenceSchema.default("auto"),
+ overlayEnabled: z.boolean().default(false),
+ overlayAppearance: z.object({
+ scale: z.number().min(CHAT_OVERLAY_LIMITS.scale[0]).max(CHAT_OVERLAY_LIMITS.scale[1]),
+ opacity: z.number().min(CHAT_OVERLAY_LIMITS.opacity[0]).max(CHAT_OVERLAY_LIMITS.opacity[1]),
+ }).default({ scale: 1, opacity: 1 }),
+ interactionEffects: z.boolean().default(true),
+ keyboardPage: z.enum(REMOTE_KEYBOARD_PAGES).default("letters"),
+ combineKeys: z.boolean().default(false),
+ remoteControlMode: remoteControlModeSchema.exclude(["off"]).default("ask"),
+});
+export type RoomPreferences = z.infer<typeof roomPreferencesSchema>;
+
+// Personal choices belong to this Browser origin, never to a room grant or
+// held input. Other preference owners (quality, language, theme) stay separate.
+export function readRoomPreferences(): RoomPreferences {
+ try {
+ const stored = window.localStorage.getItem(STORAGE_KEY);
+ const result = roomPreferencesSchema.safeParse(stored ? JSON.parse(stored) : {});
+ if (result.success) return result.data;
+ } catch {
+ // Room tools remain usable when optional Browser storage is unavailable.
+ }
+ return roomPreferencesSchema.parse({});
+}
+
+export function saveRoomPreferences(patch: Partial<RoomPreferences>): void {
+ const result = roomPreferencesSchema.safeParse({ ...readRoomPreferences(), ...patch });
+ if (!result.success) return;
+ try {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(result.data));
+ } catch {
+ // A preference write must not turn an applied action into a failure.
+ }
+}
diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.ts
index d6a4d7a0..b7ea4bb1 100644
--- a/src/client/lib/signaling.ts
+++ b/src/client/lib/signaling.ts
@@ -6,6 +6,7 @@ import {
type DisplayName,
type QualitySettings,
type RoutePolicy,
+ type ViewerRoutePreference,
type ServerMessage,
} from "../../shared/protocol";
import type { SignalConnectionState } from "../types";
@@ -77,6 +78,9 @@ function signalUrl(): string {
}
export class SignalingClient {
+ private remoteInputEnabled = false;
+ private audioPresenceEnabled = false;
+ private hostAudioAvailable: boolean | null = null;
interactions: RoomInteractionSession | null = null;
private socket: WebSocket | null = null;
private stopped = false;
@@ -101,22 +105,61 @@ export class SignalingClient {
private readonly identity: SignalingIdentity,
private readonly events: SignalingEvents,
private readonly now: () => number = Date.now,
- capabilities: { roomInteractions?: boolean } = {},
+ capabilities: { roomInteractions?: boolean; roomReactionIds?: readonly string[] } = {},
) {
- if (capabilities.roomInteractions) this.enableRoomInteractions();
+ if (capabilities.roomInteractions) this.enableRoomInteractions(capabilities.roomReactionIds);
}
// Capability discovery may finish after media authentication. Enabling room
// data must not replace the signaling connection or its healthy media.
- enableRoomInteractions(): RoomInteractionSession | null {
+ enableRoomInteractions(reactionIds?: readonly string[]): RoomInteractionSession | null {
if (this.stopped) return null;
if (!this.interactions) {
- this.interactions = new RoomInteractionSession(message => this.send(message), this.now);
+ this.interactions = new RoomInteractionSession(message => this.send(message), this.now, reactionIds);
if (this.authenticatedPeerId) this.interactions.authenticated(this.authenticatedPeerId);
+ } else {
+ this.interactions.setSupportedReactions(reactionIds);
}
return this.interactions;
}
+ enableRemoteInput(): void {
+ if (this.stopped || this.identity.role !== "host") return;
+ this.remoteInputEnabled = true;
+ if (this.authenticatedPeerId) this.send({ type: "subscribe-remote-input" });
+ }
+
+ enableAudioPresence(): void {
+ if (this.stopped) return;
+ this.audioPresenceEnabled = true;
+ this.flushAudioPresence();
+ }
+
+ setAudioAvailable(available: boolean): void {
+ if (this.identity.role !== "host") return;
+ this.hostAudioAvailable = available;
+ this.flushAudioPresence();
+ }
+
+ private flushAudioPresence(): void {
+ if (!this.audioPresenceEnabled || !this.authenticatedPeerId) return;
+ if (this.identity.role === "viewer") this.send({ type: "subscribe-audio-presence" });
+ else if (this.identity.shareGeneration && this.pendingShareGeneration === null && this.hostAudioAvailable !== null) {
+ this.send({ type: "set-audio-presence", shareGeneration: this.identity.shareGeneration, available: this.hostAudioAvailable });
+ }
+ }
+
+ enableViewerRouteSelection(preference: ViewerRoutePreference = "auto"): void {
+ if (this.stopped || this.identity.role !== "viewer") return;
+ this.identity.routePreference ??= preference;
+ if (this.authenticatedPeerId) this.setViewerRoutePreference(this.identity.routePreference);
+ }
+
+ setViewerRoutePreference(preference: ViewerRoutePreference): boolean {
+ return this.identity.role === "viewer" && this.identity.routePreference !== undefined &&
+ this.send({ type: "set-viewer-route-preference", preference });
+ }
+
start(): void {
if (this.socket || this.stopped) {
return;
@@ -231,6 +274,7 @@ export class SignalingClient {
this.identity.roomOnly = true;
this.pendingShareGeneration = null;
this.hostQualityIntent = null;
+ this.hostAudioAvailable = null;
return sent;
}
@@ -296,6 +340,7 @@ export class SignalingClient {
debugEvent("signal", "connecting", { role: this.identity.role, generation });
const socket = new WebSocket(signalUrl());
this.socket = socket;
+ let routeSelectionRequestedAtAuth = false;
socket.addEventListener("open", () => {
if (
@@ -310,6 +355,7 @@ export class SignalingClient {
protocol: SIGNALING_PROTOCOL,
...this.identity,
};
+ routeSelectionRequestedAtAuth = authenticate.role === "viewer" && authenticate.routePreference !== undefined;
socket.send(JSON.stringify(authenticate));
this.authenticationTimer = window.setTimeout(() => {
if (!this.authenticatedPeerId && this.socket === socket) {
@@ -383,11 +429,21 @@ export class SignalingClient {
debugEvent("signal", "authenticated", { role: this.identity.role, generation });
this.refreshSignalingWatchdog();
this.interactions?.authenticated(message.peerId);
+ if (this.remoteInputEnabled) this.send({ type: "subscribe-remote-input" });
+ // Discovery can complete after the authentication request was sent.
+ if (!routeSelectionRequestedAtAuth && this.identity.role === "viewer" && this.identity.routePreference !== undefined) {
+ this.setViewerRoutePreference(this.identity.routePreference);
+ }
this.reconcileHostShareState(message);
+ this.flushAudioPresence();
+ }
+ if (message.type === "viewer-route-preference" && this.identity.role === "viewer") {
+ this.identity.routePreference = message.preference;
}
if ((message.type === "sharing-started" || message.type === "sharing-start-failed") &&
this.pendingShareGeneration === message.shareGeneration) {
this.pendingShareGeneration = null;
+ if (message.type === "sharing-started") this.flushAudioPresence();
}
if (message.type === "sharing-start-failed" && this.identity.role === "host" &&
this.identity.shareGeneration === message.shareGeneration) {
diff --git a/src/client/lib/use-project-link.ts b/src/client/lib/use-project-link.ts
new file mode 100644
index 00000000..f2ab139f
--- /dev/null
+++ b/src/client/lib/use-project-link.ts
@@ -0,0 +1,35 @@
+import { useEffect, useState } from "react";
+
+const WEBSITE = "https://piik.tv";
+let availability: Promise<boolean> | undefined;
+
+/** Optional help/download navigation only; never gates App or room startup. */
+export function projectWebsiteAvailable(): Promise<boolean> {
+ return availability ??= (async () => {
+ const controller = new AbortController();
+ const timer = globalThis.setTimeout(() => controller.abort(), 3_000);
+ try {
+ const response = await fetch(WEBSITE + "/", {
+ method: "HEAD", credentials: "omit", referrerPolicy: "no-referrer",
+ cache: "no-store", signal: controller.signal,
+ });
+ return response.ok;
+ } catch {
+ return false;
+ } finally {
+ globalThis.clearTimeout(timer);
+ }
+ })();
+}
+
+export function useProjectLink(path: string, fallback: string, enabled = true): string {
+ const [available, setAvailable] = useState(false);
+ useEffect(() => {
+ if (!enabled) return;
+ let current = true;
+ void projectWebsiteAvailable().then(result => { if (current) setAvailable(result); });
+ return () => { current = false; };
+ }, [enabled]);
+ // A click before the optional probe finishes still has a working destination.
+ return available ? WEBSITE + path : fallback;
+}
diff --git a/src/client/locales/en.ts b/src/client/locales/en.ts
index 969136c8..e6187043 100644
--- a/src/client/locales/en.ts
+++ b/src/client/locales/en.ts
@@ -2,8 +2,114 @@ import type { CopyKey, PlayfulCatalog, TitleFrameCatalog } from "./zh";
// Community translations are data-only and type-checked against zh.
export const en: Record<CopyKey, string> = {
+ "remote.keyboard": "Remote keyboard",
+ "remote.keyboardRequiresControl": "Take control to use the remote keyboard",
+ "remote.keyPages": "Keyboard sections",
+ "remote.keys.letters": "Letter keys",
+ "remote.keys.symbols": "Numbers and symbols",
+ "remote.keys.functions": "Function keys",
+ "remote.keys.text": "Text",
+ "remote.keyboardHelp": "Hold a key to keep it pressed; let go to release.",
+ "remote.combinationHelp": "Select Ctrl, Shift or Alt, then another key. They release together.",
+ "remote.combinationMode": "Key combination mode",
+ "remote.key.Space": "Space",
+ "remote.key.Insert": "Insert",
+ "remote.key.Delete": "Delete",
+ "remote.key.Home": "Home",
+ "remote.key.End": "End",
+ "remote.key.PageUp": "Page up",
+ "remote.key.PageDown": "Page down",
+ "remote.key.CapsLock": "Toggle Caps Lock",
+ "remote.key.PrintScreen": "Print Screen",
+ "remote.key.ScrollLock": "Scroll Lock",
+ "remote.key.NumLock": "Num Lock",
+ "remote.text": "Type or paste text, commands or code",
+ "remote.sendText": "Type remotely",
+ "remote.typeText": "Type remotely",
+ "remote.textHelp": "Enter adds a new line. The button types at the remote cursor.",
+ "remote.textTooLong": "Split this into smaller sections (up to 2 KB each).",
+ "remote.touchHelp": "Swipe to move · Tap to click · Hold to drag. Two fingers: tap to right-click, swipe to scroll. Pinch to zoom; swipe with two fingers to pan when zoomed.",
+ "remote.resetZoom": "Reset picture zoom",
+ "remote.key.Escape": "Escape",
+ "remote.key.Tab": "Tab",
+ "remote.key.ArrowLeft": "Left arrow",
+ "remote.key.ArrowUp": "Up arrow",
+ "remote.key.ArrowDown": "Down arrow",
+ "remote.key.ArrowRight": "Right arrow",
+ "remote.key.Backspace": "Backspace",
+ "remote.key.Enter": "Enter",
+ "remote.key.ControlA": "Select all on the remote computer",
+ "remote.key.ControlC": "Copy on the remote computer",
+ "remote.key.ControlV": "Paste on the remote computer",
+ "remote.key.MetaLeft": "Open Start on the remote computer",
+ "remote.key.InputLanguage": "Switch the remote input language",
+ "remote.key.SwitchWindow": "Switch the remote window",
+ "remote.key.SwitchApp": "Switch the remote app",
+ "remote.title": "Remote control",
+ "remote.requests": "Control requests",
+ "remote.authorization": "Control permission",
+ "remote.mode.ask": "Ask each time",
+ "remote.mode.room": "Room Viewers",
+ "remote.mode.password": "Password",
+ "remote.help.ask": "Decide whether to allow each control request.",
+ "remote.help.room": "Any Viewer in this room can control this computer when no one else is controlling it.",
+ "remote.help.password": "Viewers can control this computer after entering the control password.",
+ "remote.policyLifetime": "Applies to this shared source only. Changing sources or stopping turns remote control off.",
+ "remote.password": "Control password",
+ "remote.apply": "Apply",
+ "remote.connecting": "Connecting control",
+ "remote.reason.password": "Incorrect control password",
+ "remote.reason.retry": "Please wait a moment and try again",
+ "remote.reason.busy": "Another Viewer is controlling. Please try again later",
+ "remote.request": "Request control",
+ "remote.inlineRequired": "Return the video to this page to control",
+ "remote.playbackRequired": "Play the video before requesting control",
+ "remote.unavailable": "Control is unavailable for the current share",
+ "remote.cancel": "Cancel request",
+ "remote.stop": "End control",
+ "remote.allow": "Allow control",
+ "remote.decline": "Decline",
+ "remote.surface": "Remote keyboard and mouse input",
+ "remote.controlling": "Controlling",
+ "remote.hostFocus": "Focus the shared window to resume control",
+ "remote.suspended": "Waiting for the Host to focus the shared window",
+ "remote.gameMouse": "Game mouse",
+ "remote.gameMouseHelp": "Capture the mouse for continuous game camera movement. Press Esc to release.",
+ "remote.releaseMouse": "Release mouse",
+ "remote.unlockMouse": "Press Esc to release the mouse. Control stays allowed.",
+ "remote.lockFailed": "Could not capture the mouse. Click again.",
+ "remote.pending": "Waiting for the Host to approve",
+ "remote.failed": "Remote control is unavailable. Request again.",
+ "remote.decisionFailed": "Couldn't apply this choice. Try again.",
+ "remote.macPermission": "Couldn't enable control. Allow Piik in System Settings → Privacy & Security → Accessibility, then try again.",
+ "remote.linuxStop": "End control here, or stop sharing from the system indicator.",
+ "remote.linuxEnable": "Choose the screen to control in the system dialog when enabling.",
+ "remote.consent": "Allowing control gives this Viewer access to this computer's mouse and keyboard.",
+ "remote.waiting": "Requesting control",
+ "remote.shortcut": "Stop immediately on this computer:",
"common.loading": "Loading",
- "playback.controls": "Local playback controls",
+ "playback.controls": "Player controls",
+ "playback.showControls": "Show playback controls",
+ "playback.overlay": "On-screen chat",
+ "playback.more": "Playback settings",
+ "playback.pictureFit": "Picture fit",
+ "playback.connection": "Connection",
+ "playback.fit.contain": "Fit",
+ "playback.fit.cover": "Fill",
+ "playback.fit.fill": "Stretch",
+ "playback.fitFull": "Show the whole picture at its original proportions.",
+ "playback.fitCrop": "Fill the player; some edges may be cropped.",
+ "playback.fitStretch": "Fill the player by stretching the picture.",
+ "playback.route.auto": "Auto",
+ "playback.route.p2p": "P2P only",
+ "playback.route.sfu": "SFU only",
+ "playback.routeHint.auto": "Prefer P2P, with server relay when needed.",
+ "playback.routeHint.p2p": "Receive only from other participants.",
+ "playback.routeHint.sfu": "Receive only from the server.",
+ "playback.routeSfuOnly": "This site requires server relay.",
+ "playback.routePeerOnly": "The host has disabled server relay.",
+ "playback.routeNoSfu": "Server relay is not enabled on this site.",
+ "playback.routeRejected": "This route is unavailable. Choose another option.",
"playback.play": "Play",
"playback.pause": "Pause on this device",
"playback.mute": "Mute",
@@ -86,11 +192,24 @@ export const en: Record<CopyKey, string> = {
"client.launch.localAccess": "Site passphrase (optional)",
"client.launch.accessSettings": "Site passphrase",
"client.launch.accessSet": "Set",
- "client.launch.localAccessHint": "If set, required to create rooms or join by code. Invite links grant access to their room.",
+ "client.launch.localAccessHint": "If set, the passphrase is required to create a room or join by room code.",
"client.launch.go": "Open Piik",
"client.launch.starting": "Preparing Piik",
"client.launch.error": "Room unavailable",
- "client.launch.reopen": "Check the error above and the terminal, then reopen Piik. Use Debug launch to record logs.",
+ "client.launch.reopen": "Reopen Piik to try again. Enable Debug launch if you need to record logs.",
+ "client.launch.errorDetails": "Technical details",
+ "client.launch.failure.tunnel-exited": "The public invitation service could not connect. Check your network or use App with an existing Piik Site.",
+ "client.launch.failure.tunnel-timeout": "The public invitation connection timed out. Check your network or use App with an existing Piik Site.",
+ "client.launch.failure.tunnel-unavailable": "The public invitation component is unavailable. Extract the complete Piik package again.",
+ "client.launch.failure.tunnel-start": "The public invitation component could not start. Check the technical details.",
+ "client.launch.failure.tunnel-stopped": "The public invitation disconnected. Create a new invitation and send the new link.",
+ "client.launch.failure.local-port": "The local service port is unavailable. Check whether Piik is already running.",
+ "client.launch.failure.local-network": "The local network address is unavailable. Check your network and select the invitation address again.",
+ "client.launch.failure.configuration": "App settings could not be applied. Check the technical details.",
+ "client.launch.failure.native-control": "The App connection service is unavailable. Check the technical details.",
+ "client.launch.failure.launcher": "The App launcher is unavailable. Check the technical details.",
+ "client.launch.failure.diagnostics": "Diagnostic logs could not be saved. Check the log folder and write permissions.",
+ "client.launch.failure.local-server": "The local room service is unavailable. Check the technical details.",
"client.launch.debug": "Debug launch",
"client.launch.debugHint": "Record App diagnostics and logs in pages opened from here. Press D in the terminal to export App logs.",
"client.launch.debugFailed": "Could not start diagnostics. Please try again.",
@@ -98,8 +217,7 @@ export const en: Record<CopyKey, string> = {
"client.update.available": "A newer Piik release is available",
"client.update.major": "New major Piik release",
"client.update.majorHint": "This update includes breaking changes. Read the release notes before upgrading.",
- "client.update.notes": "Release notes",
- "client.update.downloads": "More downloads",
+ "client.update.downloads": "Gitee mirror",
"client.update.differentBuild": "This build differs from the official release",
"client.update.official": "An official Piik release is available",
@@ -147,8 +265,9 @@ export const en: Record<CopyKey, string> = {
"host.microphone.voiceProcessing": "Noise & echo reduction",
"host.microphone.voiceProcessingHint": "When on, the browser reduces microphone noise and echo and adjusts volume automatically. When off, these features are disabled.",
"host.microphone.voiceProcessingUsage": "On for speech; off for music or virtual audio.",
- "interaction.open": "Chat",
- "interaction.title": "Chat",
+ "interaction.open": "Interact",
+ "interaction.title": "Interactions",
+ "interaction.chat": "Chat",
"interaction.settings": "Chat settings",
"interaction.settingsHint": "On-screen chat settings apply only to your picture.",
"interaction.back": "Back to chat",
@@ -157,22 +276,15 @@ export const en: Record<CopyKey, string> = {
"interaction.export": "Export chat",
"interaction.exportHint": "Save messages received on this page as a text file.",
"interaction.exportLimit": "Exports up to the latest {count} messages kept on this page.",
- "interaction.close": "Hide chat window",
- "interaction.focus": "Show chat window",
- "floating.detach": "Always-on-top chat",
- "floating.detachFailed": "Could not open the chat window. Try again.",
+ "interaction.close": "Hide interaction window",
+ "interaction.focus": "Show interaction window",
+ "floating.detach": "Open in always-on-top window",
+ "floating.focus": "Show detached window",
+ "floating.detachFailed": "Could not open the detached window. Try again.",
"floating.move": "Move window",
- "floating.moveHint": "Drag the title bar, use arrow keys to adjust, or choose a corner under Position.",
- "floating.position": "Position",
+ "floating.moveHint": "Drag the title bar or use arrow keys to move the window.",
"floating.resize": "Resize window",
- "floating.resizeHint": "Drag a corner or use arrow keys; preset sizes are under Position.",
- "floating.size.default": "Default size",
- "floating.size.large": "Large size",
- "floating.position.topLeft": "Top left",
- "floating.position.topRight": "Top right",
- "floating.position.bottomLeft": "Bottom left",
- "floating.position.bottomRight": "Bottom right",
- "interaction.overlay.label": "On screen",
+ "floating.resizeHint": "Drag a corner or use arrow keys to resize.",
"interaction.overlay.show": "Show chat on screen",
"interaction.overlay.hide": "Hide chat on screen",
"interaction.overlay.showHint": "Show new messages over the picture, just for you.",
@@ -180,8 +292,6 @@ export const en: Record<CopyKey, string> = {
"interaction.effects": "Show reaction effects",
"interaction.ephemeral": "Messages stay on this page and clear when you refresh.",
"interaction.empty": "Make yourself at home. Say hello.",
- "interaction.prop.tomato": "Toss tomato",
- "interaction.prop.poop": "Toss poop",
"interaction.placeholder": "Say something…",
"interaction.send": "Send",
"interaction.reactions": "Reactions",
@@ -204,14 +314,18 @@ export const en: Record<CopyKey, string> = {
"interaction.reaction.heart": "Love it",
"interaction.reaction.clap": "Applause",
"interaction.reaction.laugh": "Laugh",
+ "interaction.reaction.clown": "Clown",
+ "interaction.reaction.eyeroll": "Eye roll",
+ "interaction.reaction.thumbsup": "Thumbs up",
+ "interaction.reaction.thumbsdown": "Thumbs down",
"interaction.reaction.wow": "Mind blown",
"interaction.reaction.party": "Celebrate",
"interaction.reaction.fire": "On fire",
"interaction.reaction.eyes": "Watching",
"interaction.reaction.star": "Gold star",
"interaction.reaction.sleep": "Sleepy",
- "interaction.reaction.tomato": "Throw a tomato",
- "interaction.reaction.poop": "Throw some poop",
+ "interaction.reaction.tomato": "Toss tomato",
+ "interaction.reaction.poop": "Toss poop",
"host.microphone.mute": "Mute microphone",
"host.microphone.pending": "Opening microphone",
"host.microphone.browserOnly": "This capture method does not support a microphone yet. Choose Browser or Camera.",
@@ -365,11 +479,13 @@ export const en: Record<CopyKey, string> = {
"host.quality.1080p30": "1080p 30\u00a0fps",
"host.quality.1080p60": "1080p 60\u00a0fps",
"host.advanced": "Sharing settings",
- "host.settings.button": "Settings",
+ "host.settings.button": "Sharing settings",
"host.settings.picture": "Picture",
+ "host.settings.pictureDetails": "Fine-tune picture",
+ "host.settings.pictureLimits": "Current picture limits",
"host.settings.sound": "Sound",
- "host.settings.technical": "Connection & encoding",
+ "host.settings.connection": "Connection settings",
"host.advanced.resolution": "Resolution limit",
"host.advanced.framerate": "FPS limit",
"host.advanced.bitrate": "Bitrate limit",
diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts
index 2a0fe9f1..eadcc766 100644
--- a/src/client/locales/zh.ts
+++ b/src/client/locales/zh.ts
@@ -2,8 +2,114 @@ import type { GlyphName } from "../ui/icons";
// Canonical catalog: add keys here first; every other locale must match it.
export const zh = {
+ "remote.keyboard": "远程键盘",
+ "remote.keyboardRequiresControl": "取得控制权后可使用远程键盘",
+ "remote.keyPages": "键盘分区",
+ "remote.keys.letters": "字母键",
+ "remote.keys.symbols": "数字与符号",
+ "remote.keys.functions": "功能键",
+ "remote.keys.text": "文字",
+ "remote.keyboardHelp": "按住即长按,松手即松开。",
+ "remote.combinationHelp": "先选 Ctrl、Shift 等键,再按另一键;完成后自动松开。",
+ "remote.combinationMode": "组合键模式",
+ "remote.key.Space": "空格键",
+ "remote.key.Insert": "插入键",
+ "remote.key.Delete": "删除键",
+ "remote.key.Home": "Home 键",
+ "remote.key.End": "End 键",
+ "remote.key.PageUp": "向上翻页",
+ "remote.key.PageDown": "向下翻页",
+ "remote.key.CapsLock": "切换大小写锁定",
+ "remote.key.PrintScreen": "截屏键",
+ "remote.key.ScrollLock": "滚动锁定键",
+ "remote.key.NumLock": "数字锁定键",
+ "remote.text": "输入或粘贴文字、命令、代码",
+ "remote.sendText": "输入到对方",
+ "remote.typeText": "输入到对方",
+ "remote.textHelp": "回车可换行;点击按钮后输入到对方当前选中的位置。",
+ "remote.textTooLong": "内容较长,请分段输入(每次最多 2 KB)。",
+ "remote.touchHelp": "滑动移动 · 轻点点击 · 长按拖动。双指轻点右击、滑动滚动;捏合放大后,双指移动画面。",
+ "remote.resetZoom": "还原画面大小",
+ "remote.key.Escape": "退出键",
+ "remote.key.Tab": "制表键",
+ "remote.key.ArrowLeft": "向左",
+ "remote.key.ArrowUp": "向上",
+ "remote.key.ArrowDown": "向下",
+ "remote.key.ArrowRight": "向右",
+ "remote.key.Backspace": "退格键",
+ "remote.key.Enter": "回车键",
+ "remote.key.ControlA": "在对方电脑全选",
+ "remote.key.ControlC": "在对方电脑复制",
+ "remote.key.ControlV": "在对方电脑粘贴",
+ "remote.key.MetaLeft": "在对方电脑打开开始菜单",
+ "remote.key.InputLanguage": "切换对方电脑的输入法",
+ "remote.key.SwitchWindow": "切换对方电脑的窗口",
+ "remote.key.SwitchApp": "切换对方电脑的应用",
+ "remote.title": "远程控制",
+ "remote.requests": "控制请求",
+ "remote.authorization": "控制授权",
+ "remote.mode.ask": "每次询问",
+ "remote.mode.room": "房间观众",
+ "remote.mode.password": "控制密码",
+ "remote.help.ask": "收到请求后,由你决定是否允许控制。",
+ "remote.help.room": "本房间观众可直接取得空闲控制权,操作这台电脑。",
+ "remote.help.password": "观众输入控制密码后,可操作这台电脑。",
+ "remote.policyLifetime": "仅当前分享来源有效;换源或停播后关闭远控。",
+ "remote.password": "控制密码",
+ "remote.apply": "应用",
+ "remote.connecting": "正在取得控制权",
+ "remote.reason.password": "控制密码不正确",
+ "remote.reason.retry": "请稍等片刻后重试",
+ "remote.reason.busy": "已有其他观众正在控制,请稍后再试",
+ "remote.request": "请求控制",
+ "remote.inlineRequired": "将画面返回页面后,再请求控制",
+ "remote.playbackRequired": "播放画面后,再请求控制",
+ "remote.unavailable": "当前分享暂不可控制",
+ "remote.cancel": "取消请求",
+ "remote.stop": "结束控制",
+ "remote.allow": "允许控制",
+ "remote.decline": "拒绝",
+ "remote.surface": "远程键鼠控制区域",
+ "remote.controlling": "正在控制",
+ "remote.hostFocus": "切回共享窗口即可继续控制",
+ "remote.suspended": "等待房主切回共享窗口",
+ "remote.gameMouse": "游戏鼠标",
+ "remote.gameMouseHelp": "锁定鼠标,连续转动游戏视角;按 Esc 释放。",
+ "remote.releaseMouse": "释放鼠标",
+ "remote.unlockMouse": "按 Esc 释放鼠标,控制权限仍然保留",
+ "remote.lockFailed": "未能锁定鼠标,请再次点击",
+ "remote.pending": "等待房主允许",
+ "remote.failed": "远程控制不可用,请重新请求",
+ "remote.decisionFailed": "操作未完成,请重试",
+ "remote.macPermission": "未能开启控制。请在系统设置 → 隐私与安全性 → 辅助功能中允许 Piik,然后重试。",
+ "remote.linuxStop": "可在本面板结束控制,也可通过系统指示器停止共享。",
+ "remote.linuxEnable": "开启时,需在系统窗口中选择要控制的屏幕。",
+ "remote.consent": "允许后,对方可以操作这台电脑的鼠标和键盘。",
+ "remote.waiting": "请求控制",
+ "remote.shortcut": "本机立即结束控制:",
"common.loading": "正在加载",
- "playback.controls": "本机播放控制",
+ "playback.controls": "播放器控件",
+ "playback.showControls": "显示播控",
+ "playback.overlay": "弹幕",
+ "playback.more": "播放设置",
+ "playback.pictureFit": "画面显示",
+ "playback.connection": "连接",
+ "playback.fit.contain": "完整显示",
+ "playback.fit.cover": "等比铺满",
+ "playback.fit.fill": "拉伸铺满",
+ "playback.fitFull": "保留完整画面与原始比例。",
+ "playback.fitCrop": "保持比例铺满,边缘可能被裁切。",
+ "playback.fitStretch": "拉伸至播放器大小,画面比例可能改变。",
+ "playback.route.auto": "自动",
+ "playback.route.p2p": "仅 P2P",
+ "playback.route.sfu": "仅 SFU",
+ "playback.routeHint.auto": "优先 P2P,必要时使用服务器中转。",
+ "playback.routeHint.p2p": "只通过其他参与者接收画面。",
+ "playback.routeHint.sfu": "只通过服务器接收画面。",
+ "playback.routeSfuOnly": "此站点仅提供服务器中转。",
+ "playback.routePeerOnly": "房主已关闭服务器中转。",
+ "playback.routeNoSfu": "此站点未启用服务器中转。",
+ "playback.routeRejected": "此线路当前不可选,请重新选择。",
"playback.play": "播放",
"playback.pause": "暂停本机播放",
"playback.mute": "静音",
@@ -86,11 +192,24 @@ export const zh = {
"client.launch.localAccess": "站点口令(可选)",
"client.launch.accessSettings": "站点口令",
"client.launch.accessSet": "已设置",
- "client.launch.localAccessHint": "设置后,开房或凭房间号加入需要口令。邀请链接可直接进入对应房间。",
+ "client.launch.localAccessHint": "设置后,创建房间或凭房间号加入需要输入口令。",
"client.launch.go": "进入 Piik",
"client.launch.starting": "正在准备 Piik",
"client.launch.error": "房间暂不可用",
- "client.launch.reopen": "查看上方原因和终端详情,重新打开 Piik 后重试。可开启「诊断启动」记录日志。",
+ "client.launch.reopen": "重新打开 Piik 后重试;需要记录日志时,可开启「诊断启动」。",
+ "client.launch.errorDetails": "技术详情",
+ "client.launch.failure.tunnel-exited": "公网邀请服务未能建立连接。可检查网络,或通过已有 Piik 站点使用 App。",
+ "client.launch.failure.tunnel-timeout": "连接公网邀请服务超时。可检查网络,或通过已有 Piik 站点使用 App。",
+ "client.launch.failure.tunnel-unavailable": "公网邀请组件不可用,请重新完整解压 Piik 程序包。",
+ "client.launch.failure.tunnel-start": "无法启动公网邀请组件,请查看技术详情。",
+ "client.launch.failure.tunnel-stopped": "公网邀请已断开。重新创建后,请发送新的邀请链接。",
+ "client.launch.failure.local-port": "本地服务端口不可用,请检查是否已有 Piik 在运行。",
+ "client.launch.failure.local-network": "局域网地址不可用,请检查网络并重新选择邀请地址。",
+ "client.launch.failure.configuration": "无法应用 App 设置,请查看技术详情。",
+ "client.launch.failure.native-control": "App 联动服务不可用,请查看技术详情。",
+ "client.launch.failure.launcher": "App 启动页不可用,请查看技术详情。",
+ "client.launch.failure.diagnostics": "无法保存诊断日志,请检查日志目录及写入权限。",
+ "client.launch.failure.local-server": "本地房间服务不可用,请查看技术详情。",
"client.launch.debug": "诊断启动",
"client.launch.debugHint": "开启 App 诊断,从此页进入的网页也会记录日志。App 日志可在终端按 D 导出。",
"client.launch.debugFailed": "未能开启诊断,请重试。",
@@ -98,8 +217,7 @@ export const zh = {
"client.update.available": "发现新的 Piik 版本",
"client.update.major": "发现新的 Piik 大版本",
"client.update.majorHint": "此更新含不兼容改动。升级前请查看版本说明。",
- "client.update.notes": "版本说明",
- "client.update.downloads": "备用下载",
+ "client.update.downloads": "Gitee 备用下载",
"client.update.differentBuild": "当前构建与官方发行版不同",
"client.update.official": "可获取 Piik 正式发行版",
@@ -147,8 +265,9 @@ export const zh = {
"host.microphone.voiceProcessing": "降噪与回声消除",
"host.microphone.voiceProcessingHint": "开启后,浏览器会降低麦克风杂音、消除回声并自动调节音量;关闭后停用这些处理。",
"host.microphone.voiceProcessingUsage": "说话时开启;音乐或虚拟声卡输入时关闭。",
- "interaction.open": "聊天",
- "interaction.title": "聊天",
+ "interaction.open": "互动",
+ "interaction.title": "互动",
+ "interaction.chat": "聊天",
"interaction.settings": "聊天设置",
"interaction.settingsHint": "弹幕设置仅影响自己的画面。",
"interaction.back": "返回聊天",
@@ -157,22 +276,15 @@ export const zh = {
"interaction.export": "导出聊天记录",
"interaction.exportHint": "将本页收到的聊天记录保存为文本文件。",
"interaction.exportLimit": "导出本页保留的最近 {count} 条消息。",
- "interaction.close": "收起聊天窗口",
- "interaction.focus": "显示聊天窗口",
- "floating.detach": "置顶聊天窗口",
- "floating.detachFailed": "未能打开聊天窗口,请重试。",
+ "interaction.close": "收起互动窗口",
+ "interaction.focus": "显示互动窗口",
+ "floating.detach": "在置顶窗口中打开",
+ "floating.focus": "显示独立窗口",
+ "floating.detachFailed": "未能打开独立窗口,请重试。",
"floating.move": "移动窗口",
- "floating.moveHint": "拖动标题栏移动窗口;方向键可微调,也可以从「位置」选择角落。",
- "floating.position": "位置",
+ "floating.moveHint": "拖动标题栏移动窗口;方向键可微调。",
"floating.resize": "调整窗口大小",
- "floating.resizeHint": "拖动角落或按方向键调整大小,也可以从「位置」选择预设尺寸。",
- "floating.size.default": "默认大小",
- "floating.size.large": "大尺寸",
- "floating.position.topLeft": "左上角",
- "floating.position.topRight": "右上角",
- "floating.position.bottomLeft": "左下角",
- "floating.position.bottomRight": "右下角",
- "interaction.overlay.label": "弹幕",
+ "floating.resizeHint": "拖动角落或按方向键调整大小。",
"interaction.overlay.show": "显示弹幕",
"interaction.overlay.hide": "隐藏弹幕",
"interaction.overlay.showHint": "在画面上显示新消息,仅对自己生效。",
@@ -180,8 +292,6 @@ export const zh = {
"interaction.effects": "显示互动动效",
"interaction.ephemeral": "仅保留本页收到的消息,刷新后清空。",
"interaction.empty": "坐这儿,聊两句。",
- "interaction.prop.tomato": "丢番茄",
- "interaction.prop.poop": "丢便便",
"interaction.placeholder": "说点什么…",
"interaction.send": "发送",
"interaction.reactions": "表情与小道具",
@@ -204,6 +314,10 @@ export const zh = {
"interaction.reaction.heart": "比个心",
"interaction.reaction.clap": "鼓掌",
"interaction.reaction.laugh": "笑出声",
+ "interaction.reaction.clown": "小丑",
+ "interaction.reaction.eyeroll": "翻个白眼",
+ "interaction.reaction.thumbsup": "点赞",
+ "interaction.reaction.thumbsdown": "点踩",
"interaction.reaction.wow": "震惊",
"interaction.reaction.party": "撒花",
"interaction.reaction.fire": "太燃了",
@@ -365,11 +479,13 @@ export const zh = {
"host.quality.1080p30": "1080p 30\u00a0帧",
"host.quality.1080p60": "1080p 60\u00a0帧",
"host.advanced": "分享设置",
- "host.settings.button": "设置",
+ "host.settings.button": "分享设置",
"host.settings.picture": "画面",
+ "host.settings.pictureDetails": "画面细调",
+ "host.settings.pictureLimits": "当前画面上限",
"host.settings.sound": "声音",
- "host.settings.technical": "连接与编码",
+ "host.settings.connection": "连接设置",
"host.advanced.resolution": "分辨率上限",
"host.advanced.framerate": "帧率上限",
"host.advanced.bitrate": "视频码率上限",
diff --git a/src/client/main.tsx b/src/client/main.tsx
index a4358cf0..a596555e 100644
--- a/src/client/main.tsx
+++ b/src/client/main.tsx
@@ -3,13 +3,22 @@ import { createRoot } from "react-dom/client";
import { App } from "./App";
import "./styles.css";
-const root = document.getElementById("root");
-if (!root) {
- throw new Error("Application root was not found");
+async function main() {
+ // Room controls share the Popover API; install it before any component mounts.
+ if (!("popover" in HTMLElement.prototype)) {
+ await import("./ui/popover-polyfill");
+ }
+
+ const root = document.getElementById("root");
+ if (!root) {
+ throw new Error("Application root was not found");
+ }
+
+ createRoot(root).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+ );
}
-createRoot(root).render(
- <StrictMode>
- <App />
- </StrictMode>,
-);
+void main();
diff --git a/src/client/media/host-audio.ts b/src/client/media/host-audio.ts
index d01aa31a..77075484 100644
--- a/src/client/media/host-audio.ts
+++ b/src/client/media/host-audio.ts
@@ -16,19 +16,34 @@ export class HostAudio {
private closed = false;
constructor(source: MediaStream, private changed: (enabled: boolean) => void,
- private kind: BrowserCaptureSource = "browser") {
+ private kind: BrowserCaptureSource = "browser", private availabilityChanged: (available: boolean) => void = () => {}) {
this.source = source;
+ this.watchSource();
}
/** Capture facts come from the input, never the mixer destination track. */
get sourceStream(): MediaStream { return this.source; }
get sourceKind(): BrowserCaptureSource { return this.kind; }
+ get audioAvailable(): boolean {
+ return this.source.getAudioTracks().some(track => track.readyState === "live") ||
+ Boolean(this.microphone?.enabled && this.microphone.readyState === "live");
+ }
+ private reportAvailability = () => this.availabilityChanged(this.audioAvailable);
+ private watchSource() {
+ this.source.getAudioTracks().forEach(track => track.addEventListener("ended", this.reportAvailability));
+ }
+ private unwatchSource() {
+ this.source.getAudioTracks().forEach(track => track.removeEventListener("ended", this.reportAvailability));
+ }
attach(source: MediaStream, kind = this.kind): MediaStream {
const previous = this.source;
+ this.unwatchSource();
this.source = source;
+ this.watchSource();
this.kind = kind;
const output = this.compose();
+ this.reportAvailability();
if (previous !== source) previous.getAudioTracks().forEach((track) => track.stop());
return output;
}
@@ -58,6 +73,7 @@ export class HostAudio {
this.voiceProcessing = voiceProcessing;
if (this.microphone) this.microphone.enabled = enabled;
this.changed(enabled);
+ this.reportAvailability();
return null;
}
const hadContext = !!this.context;
@@ -89,11 +105,13 @@ export class HostAudio {
this.microphone = null;
this.compose();
this.changed(false);
+ this.reportAvailability();
};
const output = this.compose();
previous?.stop();
stream = null;
this.changed(true);
+ this.reportAvailability();
// Existing senders already borrow this destination. A device change is
// local input work, not another media/route replacement.
return hadContext ? null : output;
@@ -135,6 +153,7 @@ export class HostAudio {
dispose() {
this.closed = true;
+ this.unwatchSource();
this.microphone?.stop();
this.microphone = null;
this.source.getAudioTracks().forEach((track) => track.stop());
diff --git a/src/client/media/video-geometry.ts b/src/client/media/video-geometry.ts
new file mode 100644
index 00000000..73b19c52
--- /dev/null
+++ b/src/client/media/video-geometry.ts
@@ -0,0 +1,9 @@
+export type VideoFit = "contain" | "cover" | "fill";
+
+// Playback, remote input and magnification share the rendered picture dimensions.
+export function videoPictureSize(video: HTMLVideoElement, width: number, height: number): { width: number; height: number } {
+ if (video.style.objectFit === "fill") return { width, height };
+ const fit = video.style.objectFit === "cover" ? Math.max : Math.min;
+ const scale = fit(width / video.videoWidth, height / video.videoHeight);
+ return { width: video.videoWidth * scale, height: video.videoHeight * scale };
+}
diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.ts
index bcd26d22..a0d4ef22 100644
--- a/src/client/media/viewer-sfu-route.ts
+++ b/src/client/media/viewer-sfu-route.ts
@@ -22,6 +22,7 @@ import {
} from "./route-transition";
interface ViewerSubscriberTransport {
+ getRemoteInput?(): RTCDataChannel | null;
connect(config: SfuConnectionConfig): Promise<boolean>;
updateConfig(config: SfuConnectionConfig): void;
acceptSignal(message: SfuSignalMessage): Promise<void>;
@@ -51,6 +52,7 @@ interface ViewerSubscriberSlot {
}
interface ViewerSfuRouteEvents {
+ onInputChanged?: () => void;
activatePeer: (
assignment: ParticipantRouteAssignment,
revision?: number,
@@ -100,6 +102,7 @@ interface ViewerSfuRouteEvents {
}
export class ViewerSfuRoute {
+ getRemoteInput(): RTCDataChannel | null { return this.active?.subscriber.getRemoteInput?.() ?? null; }
private readonly route = new MediaRouteTransition();
private pending: ViewerSubscriberSlot | null = null;
private active: ViewerSubscriberSlot | null = null;
@@ -428,6 +431,7 @@ export class ViewerSfuRoute {
let slot: ViewerSubscriberSlot;
const subscriberEvents = {
send: this.events.send,
+ onInputChanged: () => { if (this.active === slot) this.events.onInputChanged?.(); },
onStream: (stream: MediaStream | null) => {
if (stream) {
this.handleStream(slot, stream);
diff --git a/src/client/native/client.ts b/src/client/native/client.ts
index 8190b448..b7ac074d 100644
--- a/src/client/native/client.ts
+++ b/src/client/native/client.ts
@@ -1,4 +1,5 @@
import type { z } from "zod";
+import type { RemoteControlMode } from "../remote-control/protocol";
import { debugError, debugEvent } from "../lib/debug";
import type {
@@ -338,6 +339,7 @@ export class NativeClient {
...shareInput,
...(excludeAudio ? { excludeAudio } : {}),
...(this.health.nativeMedia.microphone ? { microphoneMixing: true } : {}),
+ ...(this.health.nativeMedia.remoteInput ? { remoteInput: true } : {}),
...(this.health.nativeMedia.captureBorderControl ? { showCaptureBorder } : {}),
},
shareStartedResponseSchema,
@@ -699,6 +701,18 @@ export class NativeClient {
return update.done;
}
+ async setRemoteControl(shareId: string, requestId: string, allow: boolean): Promise<void> {
+ await this.request("set-remote-control", { shareId, requestId, allow }, nativeAckResponseSchema);
+ }
+
+ async setRemoteControlPolicy(shareId: string, mode: RemoteControlMode, password?: string): Promise<void> {
+ await this.request("set-remote-control-policy", { shareId, mode, ...(password !== undefined ? { password } : {}) }, nativeAckResponseSchema, null);
+ }
+
+ async setRemoteInputPeers(shareId: string, peers: { peerId: string; endpointId: string; secret: string }[]): Promise<void> {
+ await this.request("set-remote-input-peers", { shareId, peers }, nativeAckResponseSchema);
+ }
+
async stopShare(shareId: string): Promise<void> {
if (this.microphoneVolumeUpdate?.shareId === shareId) this.microphoneVolumeUpdate = null;
await this.request("stop-share", { shareId }, nativeAckResponseSchema);
diff --git a/src/client/native/media-bridge.ts b/src/client/native/media-bridge.ts
index a50870b6..b5a4151d 100644
--- a/src/client/native/media-bridge.ts
+++ b/src/client/native/media-bridge.ts
@@ -5,6 +5,7 @@ import { observeDebugConnection } from "../lib/debug-webrtc";
import type { ConnectionMetrics } from "../types";
import { preferScreenAudioStereo } from "../webrtc/screen-audio-sdp";
import { requireReceivingVideo } from "../webrtc/video-codec";
+import { RemoteInputChannel } from "../webrtc/remote-input-channel";
import {
collectConnectionMetrics,
decodedVideoFrames,
@@ -40,6 +41,7 @@ export class NativeMediaBridge {
readonly connectionId = createOpaqueId();
private readonly peer: RTCPeerConnection;
+ private readonly remoteInput: RemoteInputChannel;
private readonly lifetime = new AbortController();
private unsubscribe: (() => void) | null = null;
private edgeRequested = false;
@@ -56,7 +58,9 @@ export class NativeMediaBridge {
private readonly control: NativeMediaBridgeControl,
private readonly onFailed: () => void,
private readonly sourceConnectionId?: string,
+ onRemoteInput: () => void = () => {},
) {
+ this.remoteInput = new RemoteInputChannel(() => { if (!this.disposed) onRemoteInput(); });
let peer: RTCPeerConnection | undefined;
try {
this.stream = new MediaStream();
@@ -73,6 +77,8 @@ export class NativeMediaBridge {
return collectConnectionMetrics(this.peer, "receive", accumulator);
}
+ getRemoteInput(): RTCDataChannel | null { return this.remoteInput.current; }
+
async decodedVideoFrames(): Promise<number | null> {
const track = this.stream.getVideoTracks()[0];
return decodedVideoFrames(
@@ -86,6 +92,7 @@ export class NativeMediaBridge {
throw new NativeMediaBridgeError("Native media bridge is unavailable");
}
this.expectedAudio = expectedAudio;
+ this.remoteInput.attach(this.peer);
this.peer.addEventListener("track", (event) => {
if (this.disposed) return;
if (!this.stream.getTracks().includes(event.track)) this.stream.addTrack(event.track);
@@ -122,6 +129,7 @@ export class NativeMediaBridge {
dispose(): void {
if (this.disposed) return;
this.disposed = true;
+ this.remoteInput.dispose();
this.lifetime.abort();
this.rejectNegotiation?.(new NativeMediaBridgeError("Native media bridge failed"));
this.rejectNegotiation = null;
diff --git a/src/client/native/native-viewer-peer.ts b/src/client/native/native-viewer-peer.ts
index ffd95233..8f752e43 100644
--- a/src/client/native/native-viewer-peer.ts
+++ b/src/client/native/native-viewer-peer.ts
@@ -177,6 +177,7 @@ export class NativeCapableViewerPeer implements ViewerMediaPeer {
}
isRecovering(): boolean { return this.backend?.isRecovering() ?? false; }
+ getRemoteInput(): RTCDataChannel | null { return this.backend?.getRemoteInput?.() ?? null; }
hasConnection(): boolean { return this.backend?.hasConnection() ?? this.identity !== null; }
hasConnectionId(connectionId: string): boolean {
return this.backend?.hasConnectionId(connectionId) ??
@@ -230,6 +231,7 @@ export class NativeCapableViewerPeer implements ViewerMediaPeer {
}
class NativeViewerPeer implements ViewerMediaPeer {
+ getRemoteInput(): RTCDataChannel | null { return this.bridge?.getRemoteInput() ?? null; }
private currentIceConfig: PeerIceConfig;
private parentPeerId: string | null = null;
private connectionId: string | null = null;
@@ -533,6 +535,7 @@ class NativeViewerPeer implements ViewerMediaPeer {
this.client,
() => this.handlePlaybackFailure(bridge, connectionId),
connectionId,
+ () => { if (this.bridge === bridge) this.emit(); },
);
this.bridge = bridge;
void bridge.start(result.audio).then((stream) => {
diff --git a/src/client/native/wire.ts b/src/client/native/wire.ts
index ffc46ac9..cdc65317 100644
--- a/src/client/native/wire.ts
+++ b/src/client/native/wire.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { remoteControlModeSchema, remoteInputPlatformSchema } from "../remote-control/protocol";
import { sfuMediaSchema, positiveUint32Schema, qualityResolutionSchema, punchPredictionSchema,
nullableSafeEvidenceNumber, nullableSafeEvidenceInteger } from "../../shared/protocol";
@@ -41,6 +42,7 @@ export const nativeHealthSchema = nativeDiscoveryIdentitySchema.extend({
maxVideoFramerate: z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),
maxVideoBitrate: positiveUint32Schema.optional(),
receiverReuse: z.boolean().default(false),
+ remoteInput: z.boolean().optional(),
video: z.boolean().default(false),
processAudio: z.boolean().default(false),
systemAudio: z.boolean().default(false),
@@ -256,6 +258,7 @@ export const nativeAckResponseSchema = z
"share-stopped",
"share-paused",
"microphone-set",
+ "remote-control-set",
"publication-answer-accepted",
"publication-candidate-accepted",
"publication-layers-accepted",
@@ -269,7 +272,18 @@ const eventBase = {
shareId: opaqueIdentifierSchema,
};
+const remoteControlRequestSchema = z.object({
+ id: opaqueIdentifierSchema,
+ peerId: opaqueIdentifierSchema,
+ state: z.enum(["pending", "active", "suspended"]),
+}).strict();
+export type RemoteControlRequest = z.infer<typeof remoteControlRequestSchema>;
+
+export const remoteControlStateSchema = z.object({ mode: remoteControlModeSchema, platform: remoteInputPlatformSchema, requests: z.array(remoteControlRequestSchema) });
+export type RemoteControlState = z.infer<typeof remoteControlStateSchema>;
+
export const nativeEventSchema = z.discriminatedUnion("type", [
+ remoteControlStateSchema.extend({ ...eventBase, type: z.literal("remote-control-state") }).strict(),
z.object({ ...eventBase, type: z.literal("audio-state"), sourceAudio: z.boolean(), microphone: z.boolean(), failed: z.boolean() }).strict(),
z
.object({
diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsx
index 30cf2068..79b442ad 100644
--- a/src/client/pages/AppLauncherPage.tsx
+++ b/src/client/pages/AppLauncherPage.tsx
@@ -8,7 +8,7 @@ import { AppReleaseNotice } from "../components/living/AppReleaseNotice";
import { AppHeader } from "../components/living/Header";
import { LauncherForm, type AppMode } from "../components/living/LauncherForm";
import { Btn, Pill } from "../components/living/primitives";
-import { hasCopyPreference, useCopy } from "../ui/copy";
+import { hasCopyPreference, isCopyKey, useCopy } from "../ui/copy";
import { consoleLanguage } from "../locales";
import { Glyph } from "../ui/icons";
import { currentThemePreference } from "../ui/theme";
@@ -25,6 +25,7 @@ const launcherStateSchema = z.object({
defaultMode: z.enum(["local", "link"]),
target: z.string().optional(),
starting: z.boolean().optional(),
+ reason: z.string().optional(),
detail: z.string().optional(),
revision: z.string(),
version: z.string().default("development"),
@@ -36,7 +37,7 @@ const launcherStateSchema = z.object({
}).optional(),
});
const launcherResultSchema = z.object({ target: z.string().url() }).strict();
-const launcherErrorSchema = z.object({ detail: z.string() });
+const launcherErrorSchema = z.object({ reason: z.string().optional(), detail: z.string() });
export function AppLauncherPage() {
const { lang, vis, t } = useCopy();
@@ -45,8 +46,9 @@ export function AppLauncherPage() {
const [mode, setMode] = useState<AppMode>("link");
const [site, setSite] = useState("");
const [startupSite, setStartupSite] = useState("");
+ const [openOnApproval, setOpenOnApproval] = useState(false);
const [localAccessPassword, setLocalAccessPassword] = useState("");
- const [error, setError] = useState<{ kind: "load" | "launch"; detail?: string } | null>(null);
+ const [error, setError] = useState<{ kind: "load" | "launch"; reason?: string; detail?: string } | null>(null);
const [appDebug, setAppDebug] = useState<boolean | undefined>();
const [debug, setDebug] = useState(false);
const [debugBusy, setDebugBusy] = useState(false);
@@ -68,12 +70,15 @@ export function AppLauncherPage() {
} catch { return false; }
})();
const approvalCurrent = validSite && site === requestedSite;
+ const openSiteOnStart = site !== "" && startupSite === site;
useEffect(() => {
// The App's saved exact origin owns permission, including repeat connections.
// The requesting page still verifies authorized health before using App.
- if (approvalCurrent) window.opener?.postMessage({ type: "piik-app-approved", site: requestedSite }, requestedSite);
- }, [approvalCurrent, requestedSite]);
+ // The opener closes this page. Finish an explicitly selected startup
+ // preference first, and leave a failed save visible for correction.
+ if (approvalCurrent && !siteBusy && !siteError) window.opener?.postMessage({ type: "piik-app-approved", site: requestedSite }, requestedSite);
+ }, [approvalCurrent, requestedSite, siteBusy, siteError]);
useEffect(() => {
let current = true;
@@ -111,7 +116,7 @@ export function AppLauncherPage() {
setStartupSite(state.startupSite);
setAppDebug(state.debug);
setDebug(state.debug === true);
- setError(previous => state.detail ? { kind: "launch", detail: state.detail }
+ setError(previous => state.detail ? { kind: "launch", reason: state.reason, detail: state.detail }
: previous?.kind === "load" ? null : previous);
setLoading(false);
if (state.starting) timer = setTimeout(() => void readState(), 750);
@@ -206,7 +211,7 @@ export function AppLauncherPage() {
}
if (!response.ok) {
const failure = launcherErrorSchema.safeParse(await response.json().catch(() => null));
- setError({ kind: "launch", detail: failure.success ? failure.data.detail : undefined });
+ setError({ kind: "launch", ...(failure.success ? failure.data : {}) });
setStarting(false);
return;
}
@@ -218,15 +223,15 @@ export function AppLauncherPage() {
} finally { finish(); }
}
- async function changeSite(nextSite: string, setting: "site" | "startup-site" = "site"): Promise<void> {
+ async function changeSite(nextSite: string, setting: "site" | "startup-site" = "site", starAfterApproval = false): Promise<void> {
if (siteBusy) return;
const finish = beginStateChange();
setSiteBusy(true);
setSiteError(undefined);
- try {
+ async function save(setting: "site" | "startup-site", expectedSite: string): Promise<boolean> {
const response = await fetch(`/api/client-launcher/${setting}`, {
method: "POST", headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ site: nextSite, expectedSite: site }),
+ body: JSON.stringify({ site: nextSite, expectedSite }),
});
const result = launcherStateSchema.pick({ site: true, startupSite: true }).safeParse(await response.json().catch(() => null));
if (result.success) {
@@ -235,14 +240,19 @@ export function AppLauncherPage() {
}
if (response.status === 409 && result.success) {
setSiteError(t("client.connect.changed"));
- return;
+ return false;
}
if (!response.ok || !result.success) throw new Error("Could not save App settings");
+ return true;
+ }
+ try {
+ if (await save(setting, site) && starAfterApproval) await save("startup-site", nextSite);
} catch {
setSiteError(t("client.connect.saveFailed"));
} finally { finish(); setSiteBusy(false); }
}
+ const errorKey = `client.launch.failure.${error?.reason}`;
return (
<div className="lr-app">
<AppHeader homeHref="/client" diagnosticControl={appDebug === undefined ? null : (
@@ -289,23 +299,36 @@ export function AppLauncherPage() {
</div>
{!validSite && <Pill icon="alert" tone="bad" label={t("client.connect.invalid")} comic="signal-failed" />}
{siteError && <p role="alert">{siteError}</p>}
+ {validSite && <label className="lr-client-approval-startup">
+ <input type="checkbox" disabled={siteBusy}
+ checked={approvalCurrent ? openSiteOnStart : openOnApproval}
+ onChange={event => approvalCurrent
+ ? void changeSite(event.target.checked ? site : "", "startup-site")
+ : setOpenOnApproval(event.target.checked)} />
+ <Glyph name="star" size={18} />
+ <span className={vis ? "visually-hidden" : undefined}>{t("client.connect.openOnStart")}</span>
+ </label>}
<div className="lr-client-approval-actions">
<Btn icon="x" title={approvalCurrent ? "client.connect.close" : "common.cancel"} cap={approvalCurrent ? "client.connect.close" : "common.cancel"}
onClick={() => window.close()} />
{!approvalCurrent && <Btn icon="check" title="client.connect.approve" cap="client.connect.approve" tone="primary"
- hint="hint-client-site" busy={siteBusy} disabled={!validSite || siteBusy} onClick={() => void changeSite(requestedSite)} />}
+ hint="hint-client-site" busy={siteBusy} disabled={!validSite || siteBusy} onClick={() => void changeSite(requestedSite, "site", openOnApproval)} />}
</div>
</section>
) : (
<LauncherForm
roomError={error?.kind === "launch" ? <>
<Pill icon="alert" tone="bad" label={t("client.launch.error")} alert comic="signal-failed" />
- {error.detail && <p className="lr-client-launch-detail">{error.detail}</p>}
+ {isCopyKey(errorKey) && <p className={vis ? "visually-hidden" : "lr-client-launch-status"}>{t(errorKey)}</p>}
<p className={vis ? "visually-hidden" : "lr-client-launch-status"}>{t("client.launch.reopen")}</p>
+ {error.detail && <details className="lr-client-launch-technical">
+ <summary>{t("client.launch.errorDetails")}</summary>
+ <p className="lr-client-launch-detail">{error.detail}</p>
+ </details>}
</> : undefined}
mode={mode}
site={site}
- openSiteOnStart={site !== "" && startupSite === site}
+ openSiteOnStart={openSiteOnStart}
onToggleStartupSite={() => void changeSite(startupSite ? "" : site, "startup-site")}
localAccessPassword={localAccessPassword}
onModeChange={setMode}
diff --git a/src/client/pages/ControlsPreview.tsx b/src/client/pages/ControlsPreview.tsx
index a54de564..1031d925 100644
--- a/src/client/pages/ControlsPreview.tsx
+++ b/src/client/pages/ControlsPreview.tsx
@@ -1,31 +1,35 @@
import { useEffect, useRef, useState } from "react";
+import type { VideoFit } from "../media/video-geometry";
import { Btn, Chip, NameTag, Pill, SwitchItem } from "../components/living/primitives";
import { RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../components/living/RoomChip";
import { CaptureSourcePicker, type NativeSourceList } from "../components/living/CaptureSourcePicker";
import { LedStrip } from "../components/living/Header";
-import { StageTv } from "../components/living/Stage";
+import { StageOverlay, StageTv } from "../components/living/Stage";
import { HostMicrophone, HostMicrophoneSettings } from "../components/living/HostMicrophone";
import { LiveAudioExclusion } from "../components/living/AudioExclusionSelect";
import type { NativeCaptureTarget } from "../native/wire";
import { RoomInteractions } from "../components/living/RoomInteractions";
-import { RoomChatOverlay, RoomChatToggle } from "../components/living/RoomChatOverlay";
+import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";
import { RoomInteractionSession } from "../lib/room-interactions";
import { createOpaqueId } from "../lib/opaque-id";
import type { InteractionPayload } from "../../shared/protocol";
import { REACTION_IDS, type ReactionId } from "../../shared/room-interactions";
import { PlaybackControls } from "../components/living/PlaybackControls";
import { SharingSettings } from "../components/living/SharingSettings";
+import { HostShareControls } from "../components/living/HostShareControls";
+import { HostRemoteControl } from "../components/living/HostRemoteControl";
+import type { RemoteControlMode } from "../remote-control/protocol";
import { LauncherForm, type AppMode } from "../components/living/LauncherForm";
import { AppReleaseNotice } from "../components/living/AppReleaseNotice";
import { useTheaterMode } from "../components/living/use-theater-mode";
-import { AudioBitrateControl, PicturePreferenceControl, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";
+import { AudioBitrateControl, PicturePreferenceControl, PictureSettingsSummary, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";
import { RoomCodeInput } from "../components/living/RoomCodeInput";
import { MAX_SCREEN_AUDIO_BITRATE, VIDEO_CAPTURE_LIMITS, QUALITY_PROFILES, captureFramerateCeiling, matchingQualityProfileId, type QualityProfile } from "../media/quality";
import type { loadCameraPreviews } from "../media/camera-previews";
import { Tooltip } from "../components/living/Tooltip";
import { StatusIndicator } from "../components/living/StatusIndicator";
-import { deriveParticipantStatus } from "../ui/media-status";
+import { deriveParticipantStatus, STATUS_CATALOG } from "../ui/media-status";
import { Glyph } from "../ui/icons";
import { useCopy } from "../ui/copy";
import { PeoplePreview } from "./PeoplePreview";
@@ -57,10 +61,11 @@ export function ControlsPreview() {
const [voiceProcessing, setVoiceProcessing] = useState(true);
const [microphoneDevice, setMicrophoneDevice] = useState("");
const [sharingSettings, setSharingSettings] = useState(false);
+ const [remoteMode, setRemoteMode] = useState<RemoteControlMode>("off");
const [quality, setQuality] = useState<QualityProfile>(QUALITY_PROFILES["1080p30"]);
const [launchMode, setLaunchMode] = useState<AppMode>("link");
- const [majorUpdate, setMajorUpdate] = useState(true);
- const releaseVersion = majorUpdate ? "v2.0.0" : "v1.1.0";
+ const [majorUpdate, setMajorUpdate] = useState(false);
+ const releaseVersion = majorUpdate ? "v3.0.0" : "v2.2.0";
const releaseURL = `https://github.com/TNTcraftHIM/Piik/releases/tag/${releaseVersion}`;
const [launchSite, setLaunchSite] = useState("https://demo.piik.tv");
const [openSiteOnStart, setOpenSiteOnStart] = useState(false);
@@ -82,6 +87,8 @@ export function ControlsPreview() {
const [feedback, setFeedback] = useState("");
const [dial, setDial] = useState("60");
const [theater, setTheater] = useState(false);
+ const [pictureFit, setPictureFit] = useState<VideoFit>("contain");
+ const [viewerRoute, setViewerRoute] = useState<"auto" | "p2p" | "sfu">("auto");
const video = useRef<HTMLVideoElement>(null);
const notify = () => setFeedback(en ? "Got it. This is a preview." : "收到,只在预览里演示。" );
return <>
@@ -105,21 +112,28 @@ export function ControlsPreview() {
<Btn icon="network" title="host.topology" hint="hint-topology" onClick={notify} />
<Btn icon="sliders" title="host.advanced" hint="hint-advanced" onClick={notify} />
</div>
- <div className="lr-host-share-controls lr-media-controls" role="group" aria-label={t("host.shareControls")}>
+ </section>
+ <section id="sharing-preview" className="cp-card cp-sharing-preview">
+ <header><h2>{t("host.advanced")}</h2></header>
+ <HostShareControls actions={<>
<HostMicrophone enabled={microphone} paused={paused} volume={microphoneVolume}
onToggle={() => setMicrophone(value => !value)} />
- <Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
- hint={paused ? "hint-resume" : "hint-pause"} onClick={() => setPaused(!paused)} />
<Btn icon="switchSource" title="host.switchSource" cap="host.switchSource" hint="hint-switch-source" onClick={notify} />
- <Btn icon="sliders" cap="host.settings.button" title={sharingSettings ? "host.advanced.hide" : "host.advanced"}
+ </>}
+ settings={<Btn icon="sliders" cap="host.settings.button" title={sharingSettings ? "host.advanced.hide" : "host.advanced"}
hint={sharingSettings ? "hint-collapse" : "hint-advanced"} tone={sharingSettings ? "on" : undefined}
- expanded={sharingSettings} controls="preview-sharing-settings" onClick={() => setSharingSettings(value => !value)} />
- <Btn id="host-stop-share" icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />
- </div>
+ expanded={sharingSettings} controls="preview-sharing-settings" onClick={() => setSharingSettings(value => !value)} />}
+ remote={<HostRemoteControl mode={remoteMode} platform="windows" requests={[]}
+ disabled={paused} onPolicy={async mode => setRemoteMode(mode)} onDecide={async () => undefined} />}
+ pause={<Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
+ hint={paused ? "hint-resume" : "hint-pause"} onClick={() => setPaused(!paused)} />}
+ ending={<Btn id="host-stop-share" icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />}
+ />
<SharingSettings id="preview-sharing-settings" open={sharingSettings}
presets={<QualityPresets selected={matchingQualityProfileId(quality)}
onSelect={id => setQuality(current => ({ ...QUALITY_PROFILES[id], maxAudioBitrate: current.maxAudioBitrate }))} />}
+ pictureSummary={<PictureSettingsSummary value={quality} />}
picture={<><ResolutionControl value={quality.resolution} limits={VIDEO_CAPTURE_LIMITS} disabled={false}
onChange={resolution => setQuality(current => ({ ...current, resolution,
maxFramerate: Math.min(current.maxFramerate, captureFramerateCeiling(resolution)),
@@ -127,9 +141,18 @@ export function ControlsPreview() {
<VideoRateControls value={quality} limits={VIDEO_CAPTURE_LIMITS} disabled={false}
onChange={change => setQuality(current => ({ ...current, ...change }))} />
<PicturePreferenceControl value={quality.degradationPreference} disabled={false}
- onChange={degradationPreference => setQuality(current => ({ ...current, degradationPreference }))} /></>}
- audio={<><AudioBitrateControl value={quality.maxAudioBitrate ?? QUALITY_PROFILES["1080p30"].maxAudioBitrate} max={MAX_SCREEN_AUDIO_BITRATE}
- disabled={false} onChange={maxAudioBitrate => setQuality(current => ({ ...current, maxAudioBitrate }))} />
+ onChange={degradationPreference => setQuality(current => ({ ...current, degradationPreference }))} />
+ <div className="lr-door-group">
+ <span className="lr-door-glyph"><Glyph name="puzzle" size={19} /><span>{vis ? null : t("host.advanced.codec")}</span></span>
+ <div className="lr-row-group" role="group" aria-label={t("host.advanced.codec")}>
+ {(["vp8", "auto", "h264"] as const).map(mode => <Chip key={mode} selected={mode === "auto"} disabled
+ title={mode === "auto" ? t("host.advanced.codec.auto") : mode.toUpperCase()} hint="hint-codec">
+ {mode === "auto" && !vis ? t("host.advanced.codec.auto") : mode.toUpperCase()}
+ </Chip>)}
+ </div>
+ </div>
+ </>}
+ audio={<>
<div className="lr-door-group lr-source-audio-settings">
<SwitchItem checked={sound} onChange={setSound} label={t("host.sourcePicker.systemAudio")}
hint={sound ? "hint-stop-audio" : "hint-share-audio"} />
@@ -137,7 +160,17 @@ export function ControlsPreview() {
</div><HostMicrophoneSettings deviceId={microphoneDevice} onDevice={setMicrophoneDevice} loadDevices={previewMicrophones}
native enabled={microphone} disabled={paused} volume={microphoneVolume} onVolume={setMicrophoneVolume}
voiceProcessing={voiceProcessing} onVoiceProcessing={setVoiceProcessing} />
+ <AudioBitrateControl value={quality.maxAudioBitrate ?? QUALITY_PROFILES["1080p30"].maxAudioBitrate} max={MAX_SCREEN_AUDIO_BITRATE}
+ disabled={false} onChange={maxAudioBitrate => setQuality(current => ({ ...current, maxAudioBitrate }))} />
</>}
+ connection={
+ <div className="lr-row-group" role="group" aria-label={t("host.advanced.route")}>
+ <SwitchItem checked disabled onChange={notify} label={t("host.advanced.route.topo")}
+ note={t("host.advanced.route.topoHint")} hint="hint-topology" />
+ <SwitchItem checked={false} disabled onChange={notify} label={t("host.advanced.route.peerOnly")}
+ note={t("host.advanced.route.peerOnlyHint")} hint="hint-route-p2p" />
+ </div>
+ }
/>
</section>
<section id="option-preview" className="cp-card">
@@ -150,7 +183,7 @@ export function ControlsPreview() {
note={t("host.advanced.route.sfuOnlyHint")} hint="hint-route-sfu" />
</div>
<div className="cp-tools">
- <span className="lr-toggle" role="group" aria-label={t("host.policy")} data-selected={policy}>
+ <span className="lr-toggle" role="group" aria-label={t("host.policy")}>
{(["open", "private"] as const).map(value => <Tooltip key={value} kind={value === "open" ? "hint-admission-code" : "hint-policy-private"}
text={vis ? undefined : `${t(`host.policy.${value}`)} · ${t(value === "private" && roomPassword ? "host.policy.privatePasswordHint" : `host.policy.${value}Hint`)}`}>
<button type="button" className={policy === value ? "is-selected" : undefined} aria-pressed={policy === value}
@@ -243,8 +276,12 @@ export function ControlsPreview() {
<section id="playback-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">07</span><div><h2>{en ? "The playback bar" : "播放时,顺手就能找到。"}</h2>
<p>{en ? "This bar shows its waiting state. The playback test page includes a moving picture, volume and picture in picture." : "这里展示等待画面时的播放栏;动态画面、音量和小窗可进入完整播放预览试用。"}</p></div></header>
- <div className="cp-stage"><StageTv label={t("playback.controls")}><video ref={video} poster={POSTER} playsInline inert />
+ <div className="cp-stage"><StageTv label={t("playback.controls")} indicator={<StatusIndicator status={STATUS_CATALOG.joining} />}>
+ <video ref={video} poster={POSTER} playsInline inert style={{ objectFit: pictureFit }} />
+ <StageOverlay dim waiting icon={STATUS_CATALOG.joining.icon} message={t(STATUS_CATALOG.joining.labelKey)} comic={STATUS_CATALOG.joining.comic} />
<PlaybackControls videoRef={video} stream={null} canPlay={false} theaterMode={theater} onPlay={notify}
+ settings={{ pictureFit, setPictureFit, route: { preference: viewerRoute, onChange: setViewerRoute,
+ sfuAvailable: true, sfuOnly: false, peerOnly: false, disabled: false, rejected: false } }}
onToggleTheater={() => setTheater(!theater)} onReconnect={notify} reconnectAvailable />
</StageTv></div>
<p><a href="/__playback-preview">{en ? "Open the full playback preview" : "进入完整播放预览"} →</a></p>
@@ -275,7 +312,7 @@ export function ControlsPreview() {
</section>
<section id="interaction-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">09</span><div><h2>{en ? "A little company" : "聊两句,丢个番茄。"}</h2>
- <p>{en ? "Click a person for reactions. Move or resize either panel; supported browsers can pop chat out into an always-on-top window." : "点小人发表情;聊天与表情窗都能拖动、缩放。支持的浏览器还可将聊天弹出为置顶小窗。"}</p></div></header>
+ <p>{en ? "Chat and react in one window. Open reactions beside the message input; supported browsers can keep this window on top." : "聊天和表情都在一个窗口里。点输入区的「发表情」选择互动对象;支持的浏览器可以将窗口置顶。"}</p></div></header>
<InteractionControlsPreview />
</section>
</>;
@@ -300,7 +337,7 @@ function InteractionControlsPreview() {
requestId: message.requestId, occurredAt: Date.now(), sender, payload: message.payload });
});
return true;
- });
+ }, Date.now, REACTION_IDS);
model.authenticated(sender.peerId);
setSession(model);
return () => model.close();
@@ -322,15 +359,15 @@ function InteractionControlsPreview() {
</select>
</label>
<button type="button" className="lr-btn" onClick={() => receiveSample({ kind: "reaction", reaction,
- targetPeerId: viewer ? "preview-friend" : "preview-host",
+ targetPeerId: crowded ? "preview-friend-1" : viewer ? "preview-friend" : "preview-host",
})}><Glyph name="smile" size={18} />{lang === "en" ? "Receive a reaction" : "模拟收到表情"}</button>
</div><div className={theater ? "lr-room is-theater" : "cp-interaction-room"}><div className="lr-scene">
- <StageTv label={t("interaction.title")}>
+ <StageTv label={t("interaction.title")} indicator={<StatusIndicator status={STATUS_CATALOG.connected} />}>
<video ref={video} poster={POSTER} playsInline />
<RoomChatOverlay session={session} visible />
<PlaybackControls videoRef={video} stream={null} canPlay={false} onPlay={() => {}}
theaterMode={theater} onToggleTheater={() => setTheater(value => !value)} onReconnect={() => {}} reconnectAvailable={false}
- extraActions={<RoomChatToggle session={session} />} />
+ overlayAction={<RoomChatToggle session={session} />} overlaySettings={session && <RoomChatOverlaySettings session={session} />} />
</StageTv><RoomInteractions session={session}
view={viewer ? "viewer" : "host"} host={{ key: "preview-host", name: "Piik", you: !viewer }} entries={
Array.from({ length: crowded ? 20 : 1 }, (_, index) => ({
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 2ec5d765..63f9b1d6 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -26,6 +26,7 @@ import { AppHeader, LedStrip } from "../components/living/Header";
import { WelcomeLine } from "../components/living/WelcomeLine";
import type { CouchEntry } from "../components/living/Couch";
import { SharingSettings } from "../components/living/SharingSettings";
+import { HostShareControls } from "../components/living/HostShareControls";
import { HostMicrophone, HostMicrophoneSettings } from "../components/living/HostMicrophone";
import { LiveAudioExclusion } from "../components/living/AudioExclusionSelect";
import { RoomInteractions } from "../components/living/RoomInteractions";
@@ -52,7 +53,7 @@ import type { ComicKind } from "../components/living/Comic";
import type { HintKind } from "../ui/visual-kinds";
import type { ComicTone } from "../components/living/comic-presentation";
import { Tooltip } from "../components/living/Tooltip";
-import { AudioBitrateControl, PicturePreferenceControl, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";
+import { AudioBitrateControl, PicturePreferenceControl, PictureSettingsSummary, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";
import { RoomCodeInput, RoomCodeError } from "../components/living/RoomCodeInput";
import { MetricCell } from "../components/living/Metrics";
import {
@@ -79,6 +80,7 @@ import { say, useCopy, type CopyKey } from "../ui/copy";
import { resolveMediaFailure, type MediaFailure } from "../ui/media-failure";
import {
ApiError,
+ getRuntimeCapabilities,
createRoom,
replaceOwnedRoom,
updateRoomAccess,
@@ -178,7 +180,9 @@ import {
nativeCaptureTargetKey,
type NativeCapturePath,
} from "../native/capture-selection";
-import type { NativeCaptureTarget } from "../native/wire";
+import type { NativeCaptureTarget, RemoteControlState } from "../native/wire";
+import { HostRemoteControl } from "../components/living/HostRemoteControl";
+import { InputRoute } from "../remote-control/input-route";
import {
MAX_ENDPOINT_MEDIA_CHILDREN,
reconcileBoundedMediaChildren,
@@ -242,7 +246,7 @@ function captureDetails(stream: MediaStream, native = false, sourceAudio?: boole
? `${settings.width}x${settings.height}`
: null,
frameRate: settings?.frameRate ?? null,
- hasSourceAudio: sourceAudio ?? stream.getAudioTracks().length > 0,
+ hasSourceAudio: sourceAudio ?? stream.getAudioTracks().some(track => track.readyState === "live"),
};
}
@@ -320,6 +324,7 @@ function hostTerminationKey(reason: SignalingTerminationReason): CopyKey {
interface HostPageProps {
roomInteractionsAvailable?: boolean;
+ roomReactionIds?: readonly string[];
hostRoomSessionAvailable?: boolean;
sfuAvailable?: boolean;
sfuOnly?: boolean;
@@ -342,6 +347,7 @@ type ShareSourceSelection =
export function HostPage({
roomInteractionsAvailable = false,
+ roomReactionIds,
hostRoomSessionAvailable = false,
sfuAvailable = false,
sfuOnly = false,
@@ -375,6 +381,7 @@ export function HostPage({
useState<SignalConnectionState>("offline");
const [stream, setStream] = useState<MediaStream | null>(null);
const hostAudioRef = useRef<HostAudio | null>(null);
+ const audioAvailableRef = useRef(false);
const [microphoneEnabled, setMicrophoneEnabled] = useState(false);
const [interactionSession, setInteractionSession] = useState<RoomInteractionSession | null>(null);
const [microphoneVolume, setMicrophoneVolume] = useState(1);
@@ -387,6 +394,8 @@ export function HostPage({
return client ? client.microphones() : browserCaptureDevices("audioinput");
}, []);
const [nativeActive, setNativeActive] = useState(false);
+ const [remoteControlState, setRemoteControlState] = useState<RemoteControlState | null>(null);
+ const remoteInputPeersRef = useRef<Extract<ServerMessage, { type: "remote-input-peers" }>["peers"]>([]);
const [showCaptureBorder, setShowCaptureBorder] = useState(false);
const [nativeSources, setNativeSources] =
useState<NativeSourceList | null>(null);
@@ -605,6 +614,7 @@ export function HostPage({
const nativeShareGenerationRef = useRef<string | null>(null);
const serverShareGenerationRef = useRef<string | null>(null);
const nativeMediaBridgeRef = useRef<NativeMediaBridge | null>(null);
+ const nativeInputRoute = useMemo(() => new InputRoute(() => {}), []);
const nativeMediaIngressRef = useRef<NativeMediaIngress | null>(null);
const nativeEventCleanupRef = useRef<(() => void) | null>(null);
const nativeClientCloseCleanupRef = useRef<(() => void) | null>(null);
@@ -928,6 +938,7 @@ export function HostPage({
hostSfuRouteRef.current = null;
hostAudioRef.current?.dispose();
hostAudioRef.current = null;
+ audioAvailableRef.current = false;
setMicrophoneEnabled(false);
setMicrophonePending(false);
streamRef.current?.getTracks().forEach((track) => track.stop());
@@ -1247,14 +1258,24 @@ export function HostPage({
endSharing({ key: "native.fail.edge", failureCode: "app/browser-media/connection" }, true, "route-failed", "bad");
}
},
+ undefined,
+ () => {
+ if (nativeMediaBridgeRef.current === bridge && isCurrentShare(generation, shareGeneration)) {
+ nativeInputRoute.setUpstream(bridge?.getRemoteInput() ?? null);
+ }
+ },
);
nativeMediaBridgeRef.current = bridge;
nativeSourceAudioRef.current = undefined;
+ audioAvailableRef.current = false;
nativeSourceSelectionRef.current = selection;
nativeEventCleanup = client.onEvent((event) => {
if (event.shareId !== shareGeneration || !isCurrentShare(generation, shareGeneration) || nativeClientRef.current !== client) return;
+ if (event.type === "remote-control-state") setRemoteControlState(event);
if (event.type === "audio-state") {
nativeSourceAudioRef.current = event.sourceAudio;
+ audioAvailableRef.current = event.sourceAudio || event.microphone;
+ signalRef.current?.setAudioAvailable(audioAvailableRef.current);
setMicrophoneEnabled(event.microphone);
setDetails(previous => previous ? { ...previous, hasSourceAudio: event.sourceAudio } : previous);
if (event.failed) setNoticeValue({ kind: "key", key: "host.microphone.unavailable", target: "operation", comic: "warning", tone: "warn" });
@@ -1290,12 +1311,14 @@ export function HostPage({
}
if (nativeClientRef.current !== client) throw new NativeRequestError("unavailable", "start-share");
nativeSourceAudioRef.current ??= started.sourceAudio ?? started.audio;
+ audioAvailableRef.current = nativeSourceAudioRef.current || audioAvailableRef.current;
videoCodecRef.current = manualVideoCodecPreference(started.codec);
// Register ownership before waiting for the local bridge. A native edge
// may fail immediately after becoming ready.
ownNativeClient(client);
nativeShareGenerationRef.current = shareGeneration;
nativeModeRef.current = true;
+ if (client.health.nativeMedia.remoteInput) await client.setRemoteInputPeers(shareGeneration, remoteInputPeersRef.current);
setNativeActive(true);
const stream = await bridge.start(started.audio);
if (!isCurrentShare(generation, shareGeneration)) {
@@ -1581,6 +1604,7 @@ export function HostPage({
const shareGeneration = nativeShareGenerationRef.current;
const ingress = nativeMediaIngressRef.current;
nativeMediaIngressRef.current = null;
+ nativeInputRoute.dispose();
nativeMediaBridgeRef.current?.dispose();
nativeMediaBridgeRef.current = null;
ingress?.dispose();
@@ -1591,6 +1615,7 @@ export function HostPage({
nativeSourceAudioRef.current = undefined;
nativeSourceSelectionRef.current = null;
setNativeActive(false);
+ setRemoteControlState(null);
if (!client || !shareGeneration) {
releaseUnusedNativeClient();
return;
@@ -2084,7 +2109,9 @@ export function HostPage({
input.iceConfig,
input.stream,
input.profile,
- events,
+ { ...events, onInputChannel: nativeModeRef.current
+ ? (channel, connection) => nativeInputRoute.attachChild(channel, connection)
+ : undefined },
input.videoCodec,
candidate.connectionId,
input.natPredictionEnabled,
@@ -2507,7 +2534,10 @@ export function HostPage({
function connectRoomSignal(activeRoom: HostRoomState, shareGeneration?: string, allowReplacement = true): SignalingClient {
const previous = signalRef.current;
- if (hostRoomSessionAvailable && previous?.ownsHostRoom(activeRoom.roomId, activeRoom.hostToken)) return previous;
+ if (hostRoomSessionAvailable && previous?.ownsHostRoom(activeRoom.roomId, activeRoom.hostToken)) {
+ previous.setAudioAvailable(audioAvailableRef.current);
+ return previous;
+ }
previous?.stop();
let authenticated = false;
const hostClientId = getStableClientId("host", activeRoom.roomId);
@@ -2549,6 +2579,14 @@ export function HostPage({
},
onMessage: (message) => {
if (signalRef.current !== signal || !isCurrentRoomAuthority(activeRoom)) return;
+ if (message.type === "remote-input-peers") {
+ remoteInputPeersRef.current = message.peers;
+ const client = nativeClientRef.current, shareId = nativeShareGenerationRef.current;
+ if (client?.health.nativeMedia.remoteInput && nativeModeRef.current && shareId) {
+ void client.setRemoteInputPeers(shareId, message.peers).catch(error => debugError("native", "input-endpoints", error));
+ }
+ return;
+ }
const currentGeneration = activeGenerationRef.current;
const currentShareGeneration = shareGenerationRef.current;
const localShareActive =
@@ -2663,9 +2701,16 @@ export function HostPage({
},
},
undefined,
- { roomInteractions: roomInteractionsAvailable },
+ { roomInteractions: roomInteractionsAvailable, roomReactionIds },
);
signalRef.current = signal;
+ signal.setAudioAvailable(audioAvailableRef.current);
+ remoteInputPeersRef.current = [];
+ void getRuntimeCapabilities().then(capabilities => {
+ if (signalRef.current === signal && capabilities.roomInteractions) setInteractionSession(signal.enableRoomInteractions(capabilities.roomReactionIds));
+ if (signalRef.current === signal && capabilities.remoteInput) signal.enableRemoteInput();
+ if (signalRef.current === signal && capabilities.audioPresence) signal.enableAudioPresence();
+ }).catch(() => { /* Optional input does not block sharing. */ });
setInteractionSession(signal.interactions);
return signal;
}
@@ -2761,7 +2806,14 @@ export function HostPage({
}
if (captured) {
if (selection.kind === "browser") {
- hostAudioRef.current = new HostAudio(captured, setMicrophoneEnabled, selection.source ?? "browser");
+ hostAudioRef.current = new HostAudio(captured, setMicrophoneEnabled, selection.source ?? "browser", available => {
+ if (!isCurrentShare(generation, shareGeneration)) return;
+ audioAvailableRef.current = available;
+ signalRef.current?.setAudioAvailable(available);
+ const source = hostAudioRef.current?.sourceStream;
+ if (source) setDetails(captureDetails(source));
+ });
+ audioAvailableRef.current = hostAudioRef.current.audioAvailable;
if (selection.source === "camera") setCameraDevice(selection.deviceId ?? "");
}
streamRef.current = captured;
@@ -3735,21 +3787,12 @@ export function HostPage({
/>
) : null}
</StageTv>
- <div className="lr-host-share-controls lr-media-controls" role="group" aria-label={t("host.shareControls")}>
- {phase === "live" ? <>
+ <HostShareControls
+ actions={phase === "live" ? <>
<HostMicrophone enabled={microphoneEnabled} pending={microphonePending}
unavailable={nativeActive && !nativeClientRef.current?.health.nativeMedia.microphone} paused={sharingPaused} disabled={switchingSource || changingQuality}
volume={microphoneVolume}
onToggle={() => void changeMicrophone(!microphoneEnabled, microphoneDevices[nativeActive ? "native" : "browser"])} />
- <Btn
- icon={sharingPaused ? "play" : "pause"}
- cap={sharingPaused ? "host.resume" : "host.pause"}
- title={sharingPaused ? "host.resume" : "host.pause"}
- hint={sharingPaused ? "hint-resume" : "hint-pause"}
- draw="host-share-toggle"
- disabled={switchingSource || changingQuality || microphonePending}
- onClick={toggleSharingPause}
- />
<Btn
id="host-switch-source"
icon="switchSource"
@@ -3760,7 +3803,26 @@ export function HostPage({
onClick={() => void switchSource()}
/>
</> : null}
- <Btn
+ remote={nativeActive && remoteControlState && <HostRemoteControl
+ mode={remoteControlState.mode}
+ platform={remoteControlState.platform}
+ disabled={sharingPaused || switchingSource}
+ requests={remoteControlState.requests.map(request => {
+ return { ...request, name: viewers.find(viewer => viewer.peerId === request.peerId)?.label ?? t("common.name.viewerDefault") };
+ })}
+ onPolicy={async (mode, password) => {
+ const client = nativeClientRef.current;
+ const shareId = nativeShareGenerationRef.current;
+ if (!client || !shareId) throw new Error("Native share is unavailable");
+ await client.setRemoteControlPolicy(shareId, mode, password);
+ }}
+ onDecide={async (id, allow) => {
+ const client = nativeClientRef.current;
+ const shareId = nativeShareGenerationRef.current;
+ if (!client || !shareId) throw new Error("Native share is unavailable");
+ await client.setRemoteControl(shareId, id, allow);
+ }} />}
+ settings={<Btn
icon="sliders"
busy={changingQuality}
cap="host.settings.button"
@@ -3771,8 +3833,17 @@ export function HostPage({
expanded={showAdvanced}
controls="host-advanced-door"
onClick={() => setShowAdvanced((current) => !current)}
- />
- {phase === "live" ? (
+ />}
+ pause={phase === "live" && <Btn
+ icon={sharingPaused ? "play" : "pause"}
+ cap={sharingPaused ? "host.resume" : "host.pause"}
+ title={sharingPaused ? "host.resume" : "host.pause"}
+ hint={sharingPaused ? "hint-resume" : "hint-pause"}
+ draw="host-share-toggle"
+ disabled={switchingSource || changingQuality || microphonePending}
+ onClick={toggleSharingPause}
+ />}
+ ending={phase === "live" ? (
<Btn
id="host-stop-share"
icon="stop"
@@ -3793,7 +3864,7 @@ export function HostPage({
onClick={() => endSharing({ key: "host.startCancelled" })}
/>
) : null}
- </div>
+ />
<div className="lr-stage-notices" role="status" aria-live="polite">
{details?.hasSourceAudio === false && stream ? (
<Pill icon="speakerOff" label={t("host.noAudio")} comic="no-audio" tone="off" />
@@ -3815,6 +3886,7 @@ export function HostPage({
maxAudioBitrate: screenAudioBitrate(advancedQualityRef.current.maxAudioBitrate),
})} />
}
+ pictureSummary={<PictureSettingsSummary value={advancedQuality} />}
picture={<>
<ResolutionControl value={advancedQuality.resolution} limits={videoLimits}
disabled={phase === "starting" || switchingSource}
@@ -3826,11 +3898,25 @@ export function HostPage({
<PicturePreferenceControl value={advancedQuality.degradationPreference}
disabled={phase === "starting" || switchingSource}
onChange={degradationPreference => changeAdvancedQuality({ degradationPreference })} />
+ <div className="lr-door-group">
+ <span className="lr-door-glyph"><Glyph name="puzzle" size={19} /><Cap k="host.advanced.codec" /></span>
+ <div className="lr-row-group" role="group" aria-label={t("host.advanced.codec")}>
+ {(["vp8", "auto", "h264"] as const).map(mode => (
+ <Chip key={mode} selected={displayedVideoCodecMode === mode}
+ disabled={phase === "starting" || phase === "live"}
+ title={mode === "auto"
+ ? resolvedVideoCodec
+ ? `${t("host.advanced.codec.auto")} · ${resolvedVideoCodec.toUpperCase()}`
+ : `${t("host.advanced.codec.auto")} · ${t("host.advanced.codec.autoHint")}`
+ : `${mode.toUpperCase()} · ${t(mode === "vp8" ? "host.advanced.codec.vp8Hint" : "host.advanced.codec.h264Hint")}`}
+ hint="hint-codec" onClick={() => changeVideoCodecMode(mode)}>
+ {mode === "auto" && !vis ? t("host.advanced.codec.auto") : mode.toUpperCase()}
+ </Chip>
+ ))}
+ </div>
+ </div>
</>}
audio={<>
- <AudioBitrateControl value={screenAudioBitrate(advancedQuality.maxAudioBitrate)}
- max={audioBitrateCeiling} disabled={phase === "starting" || switchingSource}
- onChange={changeMaxAudioBitrate} />
{phase === "live" && nativeActive && nativeSourceSelectionRef.current?.target.kind === "display" &&
nativeClientRef.current?.health.nativeMedia.microphone && nativeClientRef.current.health.nativeMedia.processAudioExclusion ? (
<div className="lr-door-group lr-source-audio-settings">
@@ -3867,89 +3953,48 @@ export function HostPage({
onVoiceProcessing={enabled => void changeMicrophone(microphoneEnabled, microphoneDevices.browser, enabled)}
/>
) : null}
+ <AudioBitrateControl value={screenAudioBitrate(advancedQuality.maxAudioBitrate)}
+ max={audioBitrateCeiling} disabled={phase === "starting" || switchingSource}
+ onChange={changeMaxAudioBitrate} />
</>}
- technical={<>
- <div className="lr-door-group">
- <span
- className="lr-door-glyph"
- >
- <Glyph name="branch" size={19} />
- <Cap k="host.advanced.route" />
- </span>
- <div className="lr-row-group">
- {sfuOnly ? <SwitchItem checked disabled locked
- onChange={() => {}}
- label={t("host.advanced.route.sfuOnly")}
- note={t("host.advanced.route.sfuOnlyHint")}
- hint="hint-route-sfu"
- /> : <>
- <SwitchItem
- checked={routePolicy.topologyOptimization}
- disabled={phase === "starting" || phase === "live"}
- onChange={(checked) =>
- changeRoutePolicy({ topologyOptimization: checked })
- }
- label={t("host.advanced.route.topo")}
- note={t("host.advanced.route.topoHint")}
- hint="hint-topology"
- />
- <SwitchItem
- checked={routePolicy.peerOnly}
- disabled={
- !sfuAvailable || phase === "starting" || phase === "live"
- }
- locked={!sfuAvailable}
- onChange={(checked) =>
- changeRoutePolicy({ peerOnly: checked })
- }
- label={t("host.advanced.route.peerOnly")}
- note={t(
- sfuAvailable
- ? "host.advanced.route.peerOnlyHint"
- : "host.advanced.route.peerOnlyRequired",
- )}
- hint={sfuAvailable ? "hint-route-p2p" : "hint-route-p2p-required"}
- />
- </>}
- </div>
- </div>
- <div className="lr-door-group">
- <span
- className="lr-door-glyph"
- >
- <Glyph name="puzzle" size={19} />
- <Cap k="host.advanced.codec" />
- </span>
- <div
- className="lr-row-group"
- role="group"
- aria-label={t("host.advanced.codec")}
- >
- {(["vp8", "auto", "h264"] as const).map((mode) => (
- <Chip
- key={mode}
- selected={displayedVideoCodecMode === mode}
- disabled={phase === "starting" || phase === "live"}
- title={
- mode === "auto"
- ? resolvedVideoCodec
- ? `${t("host.advanced.codec.auto")} · ${resolvedVideoCodec.toUpperCase()}`
- : `${t("host.advanced.codec.auto")} · ${t("host.advanced.codec.autoHint")}`
- : `${mode.toUpperCase()} · ${t(
- mode === "vp8"
- ? "host.advanced.codec.vp8Hint"
- : "host.advanced.codec.h264Hint",
- )}`
- }
- hint="hint-codec"
- onClick={() => changeVideoCodecMode(mode)}
- >
- {mode.toUpperCase()}
- </Chip>
- ))}
- </div>
+ connection={
+ <div className="lr-row-group" role="group" aria-label={t("host.advanced.route")}>
+ {sfuOnly ? <SwitchItem checked disabled locked
+ onChange={() => {}}
+ label={t("host.advanced.route.sfuOnly")}
+ note={t("host.advanced.route.sfuOnlyHint")}
+ hint="hint-route-sfu"
+ /> : <>
+ <SwitchItem
+ checked={routePolicy.topologyOptimization}
+ disabled={phase === "starting" || phase === "live"}
+ onChange={(checked) =>
+ changeRoutePolicy({ topologyOptimization: checked })
+ }
+ label={t("host.advanced.route.topo")}
+ note={t("host.advanced.route.topoHint")}
+ hint="hint-topology"
+ />
+ <SwitchItem
+ checked={routePolicy.peerOnly}
+ disabled={
+ !sfuAvailable || phase === "starting" || phase === "live"
+ }
+ locked={!sfuAvailable}
+ onChange={(checked) =>
+ changeRoutePolicy({ peerOnly: checked })
+ }
+ label={t("host.advanced.route.peerOnly")}
+ note={t(
+ sfuAvailable
+ ? "host.advanced.route.peerOnlyHint"
+ : "host.advanced.route.peerOnlyRequired",
+ )}
+ hint={sfuAvailable ? "hint-route-p2p" : "hint-route-p2p-required"}
+ />
+ </>}
</div>
- </>}
+ }
/>
<RoomInteractions session={room ? interactionSession : null}
view="host"
@@ -4178,7 +4223,6 @@ export function HostPage({
className="lr-toggle"
role="group"
aria-label={t("host.policy")}
- data-selected={activeCodeEntryPolicy}
>
<Tooltip kind="hint-admission-code"
text={vis ? undefined : `${t("host.policy.open")} · ${t("host.policy.openHint")}`}>
diff --git a/src/client/pages/PlaybackPreviewPage.tsx b/src/client/pages/PlaybackPreviewPage.tsx
index b8c28544..90ddd23d 100644
--- a/src/client/pages/PlaybackPreviewPage.tsx
+++ b/src/client/pages/PlaybackPreviewPage.tsx
@@ -1,25 +1,29 @@
import { useEffect, useRef, useState } from "react";
+import type { VideoFit } from "../media/video-geometry";
import { AppHeader } from "../components/living/Header";
import { PlaybackControls } from "../components/living/PlaybackControls";
-import { StageTv } from "../components/living/Stage";
+import { StageOverlay, StageTv } from "../components/living/Stage";
+import { StatusIndicator } from "../components/living/StatusIndicator";
+import { STATUS_CATALOG } from "../ui/media-status";
import { useCopy } from "../ui/copy";
function testMedia(withAudio: boolean) {
const canvas = document.createElement("canvas");
canvas.width = 640;
- canvas.height = 360;
+ // A 4:3 picture makes contain, crop and stretch visible in the 16:9 player.
+ canvas.height = 480;
const paint = canvas.getContext("2d")!;
const started = performance.now();
let animation = 0;
function draw(now: number) {
const seconds = (now - started) / 1000;
paint.fillStyle = "#172c3b";
- paint.fillRect(0, 0, 640, 360);
+ paint.fillRect(0, 0, 640, 480);
paint.fillStyle = "#29475b";
- paint.fillRect(0, 260, 640, 100);
+ paint.fillRect(0, 340, 640, 140);
paint.fillStyle = "#9de8bf";
paint.beginPath();
- paint.arc(320 + Math.sin(seconds) * 190, 180, 26, 0, Math.PI * 2);
+ paint.arc(320 + Math.sin(seconds) * 190, 240, 26, 0, Math.PI * 2);
paint.fill();
paint.fillStyle = "#dfe8f2";
paint.font = "24px monospace";
@@ -29,10 +33,11 @@ function testMedia(withAudio: boolean) {
draw(started);
const stream = canvas.captureStream(30);
let audio: AudioContext | undefined;
+ let gain: GainNode | undefined;
if (withAudio) {
audio = new AudioContext();
const tone = audio.createOscillator();
- const gain = audio.createGain();
+ gain = audio.createGain();
const destination = audio.createMediaStreamDestination();
tone.frequency.value = 220;
gain.gain.value = 0.02;
@@ -43,6 +48,7 @@ function testMedia(withAudio: boolean) {
return {
stream,
audio,
+ setAudioInput(available: boolean) { if (gain) gain.gain.value = available ? 0.02 : 0; },
stop() {
cancelAnimationFrame(animation);
stream.getTracks().forEach((track) => track.stop());
@@ -52,13 +58,17 @@ function testMedia(withAudio: boolean) {
}
export function PlaybackPreviewPage() {
- const { lang } = useCopy();
+ const { lang, t } = useCopy();
const english = lang === "en";
const videoRef = useRef<HTMLVideoElement>(null);
const mediaRef = useRef<ReturnType<typeof testMedia> | null>(null);
const [stream, setStream] = useState<MediaStream | null>(null);
const [theaterMode, setTheaterMode] = useState(false);
+ const [pictureFit, setPictureFit] = useState<VideoFit>("contain");
+ const [viewerRoute, setViewerRoute] = useState<"auto" | "p2p" | "sfu">("auto");
const [error, setError] = useState("");
+ const [waiting, setWaiting] = useState(true);
+ const [audioAvailable, setAudioAvailable] = useState(false);
const hasAudio = Boolean(stream?.getAudioTracks().length);
function play() {
@@ -74,7 +84,9 @@ export function PlaybackPreviewPage() {
const media = testMedia(withAudio);
mediaRef.current = media;
setError("");
+ setWaiting(false);
setStream(media.stream);
+ setAudioAvailable(withAudio);
if (media.audio) void media.audio.resume().catch((cause: unknown) => setError(String(cause)));
}
@@ -107,20 +119,31 @@ export function PlaybackPreviewPage() {
<div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
<button className="lr-btn" type="button" onClick={() => start(false)}>
{english ? "Start picture only" : "开启无声测试画面"}</button>
+ <button className="lr-btn" type="button" aria-pressed={waiting} onClick={() => setWaiting(value => !value)}>
+ {english ? "Connection overlay" : "连接遮罩"}</button>
<button className="lr-btn" type="button" disabled={!stream} onClick={() => start(!hasAudio)}>
{hasAudio ? (english ? "Remove audio track" : "移除音轨") : (english ? "Add quiet test tone" : "加入轻音量测试音")}</button>
<button className="lr-btn" type="button" disabled={!stream} onClick={() => start(hasAudio)}>
{english ? "Rebind new stream" : "重新绑定新流"}</button>
+ <button className="lr-btn" type="button" disabled={!hasAudio} onClick={() => {
+ mediaRef.current?.setAudioInput(!audioAvailable);
+ setAudioAvailable(!audioAvailable);
+ }}>{audioAvailable ? (english ? "Stop audio input, keep track" : "关闭声音输入,保留音轨")
+ : (english ? "Restore audio input" : "恢复声音输入")}</button>
</div>
{error ? <p role="alert">{error}</p> : null}
</header> : null}
<div className="lr-scene">
- <StageTv live={Boolean(stream)} label={english ? "Local test picture" : "本机测试画面"}>
- <video ref={videoRef} playsInline tabIndex={0} inert={!stream}
+ <StageTv live={Boolean(stream)} label={english ? "Local test picture" : "本机测试画面"}
+ indicator={<StatusIndicator status={waiting ? STATUS_CATALOG.joining : stream ? STATUS_CATALOG.connected : STATUS_CATALOG.idle} />}>
+ <video ref={videoRef} playsInline tabIndex={0} inert={!stream} style={{ objectFit: pictureFit }}
aria-label={english ? "Local test video" : "本机测试视频"} />
- <PlaybackControls videoRef={videoRef} stream={stream}
+ {waiting && <StageOverlay dim waiting icon={STATUS_CATALOG.joining.icon} message={t(STATUS_CATALOG.joining.labelKey)} comic={STATUS_CATALOG.joining.comic} />}
+ <PlaybackControls videoRef={videoRef} stream={stream} audioAvailable={audioAvailable}
+ settings={{ pictureFit, setPictureFit, route: { preference: viewerRoute, onChange: setViewerRoute,
+ sfuAvailable: true, sfuOnly: false, peerOnly: false, disabled: false, rejected: false } }}
audioTrackKey={stream?.getAudioTracks().map((track) => track.id).join(",")}
- canPlay={Boolean(stream)} theaterMode={theaterMode} onPlay={play}
+ canPlay={Boolean(stream) && !waiting} theaterMode={theaterMode} onPlay={play}
onToggleTheater={() => setTheaterMode((value) => !value)}
onReconnect={() => start(hasAudio)} reconnectAvailable={Boolean(stream)} />
</StageTv>
diff --git a/src/client/pages/StatusPreviewPage.tsx b/src/client/pages/StatusPreviewPage.tsx
index e62ea20a..0e0c445a 100644
--- a/src/client/pages/StatusPreviewPage.tsx
+++ b/src/client/pages/StatusPreviewPage.tsx
@@ -19,6 +19,7 @@ import { locales, type TitleFrameKey } from "../locales";
import { composeDocumentTitle, useDocumentTitle } from "../ui/document-title";
import { HOST_STATUS_SCENARIOS, STATUS_SCENARIOS } from "./status-preview-scenarios";
import "./status-preview.css";
+import { usePreviewAnchor } from "./use-preview-anchor";
function StatusMark({ status }: { status: StatusDescriptor }) {
const { t, vis } = useCopy();
@@ -31,6 +32,7 @@ function StatusMark({ status }: { status: StatusDescriptor }) {
}
export function StatusPreviewPage() {
+ usePreviewAnchor();
const { lang, vis, t, titleFrames } = useCopy();
const [selected, setSelected] = useState("playing");
const [reducedMotion, setReducedMotion] = useState(false);
diff --git a/src/client/pages/TooltipPreviewPage.tsx b/src/client/pages/TooltipPreviewPage.tsx
index 5c9dbd54..79073948 100644
--- a/src/client/pages/TooltipPreviewPage.tsx
+++ b/src/client/pages/TooltipPreviewPage.tsx
@@ -11,6 +11,7 @@ import { useCopy, type CopyKey } from "../ui/copy";
import { replaySvgAnimations } from "../ui/animation";
import { MetricCells } from "../components/living/Metrics";
import { EMPTY_METRICS } from "../types";
+import { usePreviewAnchor } from "./use-preview-anchor";
const EXAMPLES: { label: string; kind: HintKind | ComicKind; tone: ComicTone; motion: ComicMotion; text: CopyKey }[] = [
{ label: "说明 / Neutral", kind: "hint-volume", tone: "off", motion: "demo", text: "playback.volume" },
@@ -56,6 +57,7 @@ function PreviewCard({ kind, tone, motion, label, text }: {
}
export function TooltipPreviewPage() {
+ usePreviewAnchor();
const { t, lang } = useCopy();
const en = lang === "en";
const [reducedMotion, setReducedMotion] = useState(false);
@@ -71,11 +73,13 @@ export function TooltipPreviewPage() {
</header>
<nav className="cp-nav" aria-label={en ? "Preview sections" : "预览目录"}>
<a href="#button-preview">{en ? "Buttons" : "按钮"}</a><a href="#option-preview">{en ? "Options" : "选择与开关"}</a>
+ <a href="#sharing-preview">{t("host.advanced")}</a>
<a href="#input-preview">{en ? "Inputs" : "输入与房间号"}</a><a href="#feedback-preview">{en ? "Feedback" : "反馈"}</a>
<a href="#people-preview">{en ? "People & connections" : "人物、沙发与连接图"}</a><a href="#source-preview">{en ? "Source picker" : "画面选择"}</a>
<a href="#playback-preview">{en ? "Playback" : "播放栏"}</a><a href="#comic-preview">{en ? "Tooltips & comics" : "提示与漫画"}</a>
<a href="#launcher-preview">{en ? "App launcher" : "模式选择"}</a>
<a href="#interaction-preview">{en ? "Chat & reactions" : "聊天与互动"}</a>
+ <a href="#hint-remote-control">{en ? "Remote control" : "远程控制"}</a>
<a href="#hint-admission-code">{en ? "Room entry" : "房间准入"}</a>
<a href="#metrics-preview">{en ? "Metrics" : "连接数据"}</a>
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index 57cbf0f9..9de845de 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -1,4 +1,5 @@
import { PawnSvg } from "../components/living/Pawn";
+import type { VideoFit } from "../media/video-geometry";
import {
useEffect,
useMemo,
@@ -17,6 +18,7 @@ import {
type PreparedRouteCandidate,
type ServerMessage,
type RoutePolicy,
+ type ViewerRoutePreference,
} from "../../shared/protocol";
import {
viewerReconnectRoute,
@@ -25,7 +27,7 @@ import {
import { AppHeader, LedStrip } from "../components/living/Header";
import type { CouchEntry } from "../components/living/Couch";
import { RoomInteractions } from "../components/living/RoomInteractions";
-import { RoomChatOverlay, RoomChatToggle } from "../components/living/RoomChatOverlay";
+import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";
import type { RoomInteractionSession } from "../lib/room-interactions";
import { getRuntimeCapabilities } from "../lib/api";
import { participantColor } from "../components/living/participant-color";
@@ -41,6 +43,8 @@ import {
import { StatusIndicator } from "../components/living/StatusIndicator";
import { Tooltip } from "../components/living/Tooltip";
import { PlaybackControls } from "../components/living/PlaybackControls";
+import { RemoteControl } from "../components/living/RemoteControl";
+import { InputRoute } from "../remote-control/input-route";
import { useTheaterMode } from "../components/living/use-theater-mode";
import { LoadingStatus } from "../components/living/WaitingStatus";
import {
@@ -63,6 +67,7 @@ import { deriveViewerStatus, deriveParticipantStatus } from "../ui/media-status"
import { clearViewerGrant, getStableClientId } from "../lib/session";
import { createOpaqueId } from "../lib/opaque-id";
import { SignalingClient } from "../lib/signaling";
+import { readRoomPreferences, saveRoomPreferences } from "../lib/room-preferences";
import { labelParticipantSnapshot } from "../lib/viewer-presence";
import {
P2pQualityProbe,
@@ -188,6 +193,8 @@ export function ViewerPage({
null,
);
const [peerSnapshot, setPeerSnapshot] = useState<PeerSnapshot | null>(null);
+ const [, refreshInput] = useState(0);
+ const inputRoute = useMemo(() => new InputRoute(() => refreshInput(value => value + 1)), []);
const [sfuUpstream, setSfuUpstream] = useState<SfuUpstreamState | null>(null);
const [assignedRoute, setAssignedRoute] = useState<{
revision: number;
@@ -202,6 +209,7 @@ export function ViewerPage({
const [showConnectionDetails, setShowConnectionDetails] = useState(false);
const [showTopology, setShowTopology] = useState(false);
const [theaterMode, setTheaterMode] = useTheaterMode();
+ const [audioAvailable, setAudioAvailable] = useState<boolean | null>(null);
const [hasCustomDisplayName, setHasCustomDisplayName] = useState(
() => readStoredDisplayName() !== null,
);
@@ -264,6 +272,13 @@ export function ViewerPage({
const viewerSfuRouteRef = useRef<ViewerSfuRoute | null>(null);
const signalRef = useRef<SignalingClient | null>(null);
const [interactionSession, setInteractionSession] = useState<RoomInteractionSession | null>(null);
+ const [pictureFit, setPictureFit] = useState<VideoFit>(() => readRoomPreferences().pictureFit);
+ const [routeOptions, setRouteOptions] = useState<{ sfu: boolean; sfuOnly: boolean } | null>(null);
+ const [routePreference, setRoutePreference] = useState<ViewerRoutePreference>("auto");
+ const [routePreferencePending, setRoutePreferencePending] = useState(false);
+ const [routePreferenceRejected, setRoutePreferenceRejected] = useState(false);
+ const [peerOnly, setPeerOnly] = useState(false);
+ useEffect(() => { if (signalStatus !== "connected") setRoutePreferencePending(false); }, [signalStatus]);
const presentationStateRef = useRef(presentationState);
presentationStateRef.current = presentationState;
function dispatchPresentation(action: ViewerPresentationAction): void {
@@ -606,8 +621,18 @@ export function ViewerPage({
},
);
setInteractionSession(null);
+ setRouteOptions(null);
+ setAudioAvailable(null);
void getRuntimeCapabilities().then(capabilities => {
- if (active && capabilities.roomInteractions) setInteractionSession(signal.enableRoomInteractions());
+ if (active && capabilities.audioPresence) signal.enableAudioPresence();
+ if (active && capabilities.roomInteractions) setInteractionSession(signal.enableRoomInteractions(capabilities.roomReactionIds));
+ if (active && capabilities.remoteInput) inputRoute.enable(identity => signal.send({ type: "subscribe-remote-input", ...identity }));
+ if (active && capabilities.viewerRouteSelection) {
+ const saved = readRoomPreferences().routePreference;
+ const allowed = saved === "sfu" ? capabilities.sfu : saved !== "p2p" || !capabilities.sfuOnly;
+ signal.enableViewerRouteSelection(allowed ? saved : "auto");
+ setRouteOptions({ sfu: capabilities.sfu, sfuOnly: capabilities.sfuOnly === true });
+ }
}).catch(() => { /* Optional room data never blocks viewing. */ });
signalRef.current = signal;
const qualityEvidenceReporter = new ViewerQualityEvidenceReporter(
@@ -772,6 +797,7 @@ export function ViewerPage({
currentIceConfig,
currentQualitySettings,
{
+ onInputChannel: (channel, connection) => inputRoute.attachChild(channel, connection),
sendSignal: (targetPeerId, payload) =>
active
? signal.send({
@@ -939,6 +965,7 @@ export function ViewerPage({
}
let route: ViewerSfuRoute;
route = new ViewerSfuRoute(currentPeerId!, {
+ onInputChanged: () => refreshInput(value => value + 1),
activatePeer: async (assignment, revision) => {
if (!active || viewerSfuRoute !== route) {
return;
@@ -1474,7 +1501,14 @@ export function ViewerPage({
message: ServerMessage,
authorityToken: number,
): Promise<void> {
+ if (message.type === "viewer-route-preference") {
+ setRoutePreference(message.preference);
+ setRoutePreferencePending(false);
+ setRoutePreferenceRejected(!message.accepted);
+ return;
+ }
if (message.type === "authenticated") {
+ inputRoute.reauthenticate();
dispatchPresentation({ type: "access", access: "ready" });
setViewerPasswordDraft("");
setViewerPasswordError(null);
@@ -1490,6 +1524,7 @@ export function ViewerPage({
viewerAuthorizationGeneration =
message.viewerAuthorizationGeneration;
currentRoutePolicy = message.routePolicy;
+ setPeerOnly(message.routePolicy.peerOnly);
const nextRouteRevision = message.routeRevision;
if (nextRouteRevision !== currentRouteRevision) {
relayChildEvidenceStore.clear();
@@ -1660,6 +1695,7 @@ export function ViewerPage({
) {
currentShareGeneration = message.shareGeneration;
currentRoutePolicy = message.routePolicy;
+ setPeerOnly(message.routePolicy.peerOnly);
}
return;
}
@@ -1729,6 +1765,10 @@ export function ViewerPage({
);
return;
}
+ if (message.type === "audio-presence") {
+ setAudioAvailable(message.available);
+ return;
+ }
if (message.type === "host-status") {
currentHostOnline = message.online;
if (currentHostPaused !== message.paused && message.paused) {
@@ -1755,6 +1795,7 @@ export function ViewerPage({
return;
}
if (message.type === "sharing-stopped") {
+ setAudioAvailable(null);
invalidatePresentedMedia();
currentRouteAssignment = null;
currentRouteConnectionId = null;
@@ -1828,6 +1869,7 @@ export function ViewerPage({
}
relayChildEvidenceStore.clear();
signal.stop();
+ inputRoute.dispose();
clearParticipantPresence();
if (signalRef.current === signal) {
signalRef.current = null;
@@ -1849,6 +1891,10 @@ export function ViewerPage({
};
}, [roomId, viewerGrant, viewerPasswordAttempt]);
+ useEffect(() => {
+ inputRoute.setUpstream(peerRef.current?.getRemoteInput?.() ?? viewerSfuRouteRef.current?.getRemoteInput() ?? null);
+ });
+
useEffect(() => {
const video = videoRef.current;
if (!video || !remoteMedia) {
@@ -2194,6 +2240,7 @@ export function ViewerPage({
>
<video
ref={videoRef}
+ style={{ objectFit: pictureFit }}
autoPlay
tabIndex={0}
inert={!remoteMedia}
@@ -2214,10 +2261,31 @@ export function ViewerPage({
onEnded={invalidateQualityPresentation}
/>
<PlaybackControls
- extraActions={<RoomChatToggle session={interactionSession} />}
+ overlayAction={<RoomChatToggle session={interactionSession} />}
+ overlaySettings={interactionSession && <RoomChatOverlaySettings session={interactionSession} />}
+ remoteActions={<RemoteControl channel={inputRoute.current} videoRef={videoRef}
+ pictureFit={pictureFit}
+ available={presentation.overlay === "none" && presentation.hasCurrentFrame} />}
+ settings={{ pictureFit, setPictureFit: fit => {
+ setPictureFit(fit); saveRoomPreferences({ pictureFit: fit });
+ },
+ route: routeOptions ? {
+ preference: routePreference, sfuAvailable: routeOptions.sfu && !peerOnly,
+ sfuOnly: routeOptions.sfuOnly, peerOnly,
+ disabled: signalStatus !== "connected" || routePreferencePending,
+ rejected: routePreferenceRejected,
+ onChange: preference => {
+ if (signalRef.current?.setViewerRoutePreference(preference)) {
+ saveRoomPreferences({ routePreference: preference });
+ setRoutePreferencePending(true); setRoutePreferenceRejected(false);
+ }
+ },
+ } : undefined,
+ }}
videoRef={videoRef}
stream={remoteMedia?.stream ?? null}
audioTrackKey={remoteMedia?.audioTrackKey}
+ audioAvailable={audioAvailable}
theaterMode={theaterMode}
onToggleTheater={() => setTheaterMode((current) => !current)}
onReconnect={retryConnection}
diff --git a/src/client/pages/controls-preview.css b/src/client/pages/controls-preview.css
index e4b8f7ce..b233b40e 100644
--- a/src/client/pages/controls-preview.css
+++ b/src/client/pages/controls-preview.css
@@ -1,7 +1,9 @@
.cp-nav { display: flex; flex-wrap: wrap; gap: 8px 18px; margin: 20px 0 28px; }
.cp-nav a { color: var(--ink); font-size: 13px; text-underline-offset: 5px; }
.cp-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
-.cp-card { min-width: 0; padding: 24px; border: 1px solid var(--control-edge); border-radius: 24px; background: var(--paper); }
+.cp-card { min-width: 0; padding: 24px; border: 1px solid var(--control-edge); border-radius: 24px; background: var(--paper); scroll-margin-top: 24px; }
+.cp-sharing-preview { grid-column: 1 / -1; }
+.cp-sharing-preview > header { justify-content: center; }
.cp-card > header, .cp-section-head { display: flex; align-items: baseline; gap: 12px; }
.cp-card > header h2, .cp-section-head h2 { margin: 0; font-size: 19px; }
.cp-number { font: 600 11px var(--mono); color: var(--ink); }
@@ -30,6 +32,7 @@
@media (max-width: 850px) { .cp-grid { grid-template-columns: 1fr; } }
@media (max-width: 480px) {
.cp-card { padding: 18px; }
+ .cp-sharing-preview { padding-inline: 0; border-inline: 0; }
.cp-section-head h2, .cp-card > header h2 { font-size: 17px; }
.cp-sync { gap: 16px; }
.cp-people-room { padding-inline: 0; }
diff --git a/src/client/pages/use-preview-anchor.ts b/src/client/pages/use-preview-anchor.ts
new file mode 100644
index 00000000..ad554491
--- /dev/null
+++ b/src/client/pages/use-preview-anchor.ts
@@ -0,0 +1,8 @@
+import { useLayoutEffect } from "react";
+
+export function usePreviewAnchor() {
+ useLayoutEffect(() => {
+ // Native fragment navigation runs before a lazy preview has mounted.
+ document.getElementById(window.location.hash.slice(1))?.scrollIntoView();
+ }, []);
+}
diff --git a/src/client/remote-control/input-route.ts b/src/client/remote-control/input-route.ts
new file mode 100644
index 00000000..33136ac5
--- /dev/null
+++ b/src/client/remote-control/input-route.ts
@@ -0,0 +1,181 @@
+export const INPUT_CHANNEL = "piik-remote-input-prototype-v1";
+export type InputIdentity = { endpointId: string; secret: string };
+type Packet = { id?: string; epoch?: string; data?: string; closed?: boolean; ready?: boolean };
+export type InputTransport = Pick<RTCDataChannel, "readyState" | "bufferedAmount" | "send" | "close" | "addEventListener" | "removeEventListener">;
+
+function packet(data: unknown): Packet | null {
+ if (typeof data !== "string" || data.length > 6144) return null;
+ try {
+ const p = JSON.parse(data) as Packet;
+ return p && (typeof p.ready === "boolean" || typeof p.id === "string" && /^[0-9a-f]{32}$/.test(p.id) &&
+ typeof p.epoch === "string" && /^[0-9a-f]{32}$/.test(p.epoch) && (p.closed === true || typeof p.data === "string")) ? p : null;
+ } catch { return null; }
+}
+function send(channel: RTCDataChannel | null, p: Packet): void {
+ if (channel?.readyState !== "open") return;
+ if (channel.bufferedAmount > 8192) { channel.close(); return; }
+ try { channel.send(JSON.stringify(p)); } catch { channel.close(); }
+}
+
+// One small adapter follows the committed media input and existing relay edges.
+// It selects no route and keeps neither permissions nor input history.
+export class InputRoute {
+ private up: RTCDataChannel | null = null;
+ private ready = false;
+ private endpoint: EncryptedInput | null = null;
+ private identity: InputIdentity | null = null;
+ private counter = { sent: 0n };
+ private register: ((identity: InputIdentity) => boolean) | null = null;
+ private children = new Map<RTCDataChannel, Map<string, string>>();
+ constructor(private readonly changed: () => void) {}
+ get current(): InputTransport | null { return this.endpoint; }
+
+ enable(register: (identity: InputIdentity) => boolean): void {
+ this.register = register;
+ this.reauthenticate();
+ }
+ reauthenticate(): void {
+ this.retireEndpoint();
+ this.identity = null;
+ this.counter = { sent: 0n };
+ this.refreshEndpoint();
+ }
+ setUpstream(channel: RTCDataChannel | null): void {
+ if (this.up === channel) return;
+ if (this.up) {
+ this.up.removeEventListener("message", this.received);
+ this.up.removeEventListener("close", this.lost);
+ this.up.removeEventListener("open", this.opened);
+ for (const ids of this.children.values()) {
+ for (const [id, epoch] of ids) send(this.up, { id, epoch, closed: true });
+ ids.clear();
+ }
+ }
+ this.retireEndpoint();
+ this.ready = false;
+ this.up = channel;
+ this.broadcast({ ready: false });
+ channel?.addEventListener("message", this.received);
+ channel?.addEventListener("close", this.lost);
+ channel?.addEventListener("open", this.opened);
+ if (channel?.readyState === "open") this.opened();
+ }
+ private readonly opened = (): void => send(this.up, { ready: true });
+ private readonly lost = (): void => { this.ready = false; this.retireEndpoint(); this.broadcast({ ready: false }); };
+ private readonly received = (event: MessageEvent): void => {
+ const p = packet(event.data); if (!p) return;
+ if (p.ready !== undefined && p.id) {
+ if (p.ready && p.id === this.identity?.endpointId) this.endpoint?.send(JSON.stringify({ type: "sync" }));
+ } else if (p.ready !== undefined) {
+ this.ready = p.ready;
+ if (!p.ready) this.retireEndpoint(); else this.refreshEndpoint();
+ } else if (p.id === this.identity?.endpointId && p.epoch === this.endpoint?.epoch && p.data) this.endpoint?.receive(p.data);
+ this.broadcast(p);
+ };
+ private broadcast(p: Packet): void { for (const child of this.children.keys()) send(child, p); }
+ private refreshEndpoint(): void {
+ if (this.endpoint || !this.ready || !this.register || !crypto.subtle) return;
+ if (!this.identity) {
+ const identity = { endpointId: crypto.randomUUID().replaceAll("-", ""),
+ secret: Array.from(crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, "0")).join("") };
+ if (!this.register(identity)) return;
+ this.identity = identity;
+ }
+ this.endpoint = new EncryptedInput(this.identity, this.counter, p => send(this.up, p));
+ this.changed();
+ }
+ private retireEndpoint(): void {
+ this.endpoint?.close();
+ this.endpoint = null;
+ this.changed();
+ }
+ attachChild(channel: RTCDataChannel, connection: RTCPeerConnection): void {
+ const ids = new Map<string, string>();
+ this.children.set(channel, ids);
+ connection.addEventListener("connectionstatechange", () => {
+ if (!this.children.has(channel)) return;
+ if (connection.connectionState === "disconnected" || connection.connectionState === "failed" || connection.connectionState === "closed") {
+ for (const [id, epoch] of ids) send(this.up, { id, epoch, closed: true });
+ ids.clear();
+ }
+ });
+ channel.addEventListener("open", () => send(channel, { ready: this.ready }));
+ channel.addEventListener("message", event => {
+ const p = packet(event.data); if (!p || !this.children.has(channel)) return;
+ if (p.ready !== undefined) { send(channel, { ready: this.ready }); return; }
+ if (!this.ready || !p.id || !p.epoch) return;
+ if (p.closed) { if (ids.get(p.id) === p.epoch) ids.delete(p.id); }
+ else { if (!ids.has(p.id) && ids.size >= 20) return; ids.set(p.id, p.epoch); }
+ send(this.up, p);
+ });
+ channel.addEventListener("close", () => {
+ if (!this.children.delete(channel)) return;
+ for (const [id, epoch] of ids) send(this.up, { id, epoch, closed: true });
+ });
+ if (channel.readyState === "open") send(channel, { ready: this.ready });
+ }
+ dispose(): void {
+ this.setUpstream(null);
+ this.identity = null;
+ this.register = null;
+ for (const child of this.children.keys()) child.close();
+ this.children.clear();
+ }
+}
+
+// Keys arrive over authenticated room signaling. An intermediate Viewer/SFU
+// transports ciphertext and cannot impersonate the approved controller.
+class EncryptedInput extends EventTarget implements InputTransport {
+ readonly epoch = crypto.randomUUID().replaceAll("-", "");
+ readyState: RTCDataChannelState = "open";
+ bufferedAmount = 0;
+ private received = 0n;
+ private readonly key: Promise<CryptoKey>;
+ private outbound = Promise.resolve();
+ private inbound = Promise.resolve();
+ private incomingBytes = 0;
+ constructor(private readonly identity: InputIdentity, private readonly counter: { sent: bigint }, private readonly transmit: (packet: Packet) => void) {
+ super();
+ this.key = crypto.subtle.importKey("raw", Uint8Array.from(identity.secret.match(/../g)!, b => parseInt(b, 16)), "AES-GCM", false, ["encrypt", "decrypt"]);
+ }
+ send(data: string | Blob | ArrayBuffer | ArrayBufferView): void {
+ if (this.readyState !== "open" || typeof data !== "string") return;
+ const plain = new TextEncoder().encode(data);
+ this.bufferedAmount += plain.length;
+ this.outbound = this.outbound.then(async () => {
+ if (this.readyState !== "open") return;
+ const header = new Uint8Array(20);
+ new DataView(header.buffer).setBigUint64(0, ++this.counter.sent);
+ crypto.getRandomValues(header.subarray(8));
+ const aad = new Uint8Array(41); aad.set(header.subarray(0, 8), 1); aad.set(new TextEncoder().encode(this.epoch), 9);
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: header.subarray(8), additionalData: aad }, await this.key, plain));
+ if (this.readyState !== "open") return;
+ const bytes = new Uint8Array(header.length + encrypted.length);
+ bytes.set(header); bytes.set(encrypted, header.length);
+ this.transmit({ id: this.identity.endpointId, epoch: this.epoch, data: btoa(String.fromCharCode(...bytes)) });
+ }).catch(() => this.close()).finally(() => { this.bufferedAmount -= plain.length; });
+ }
+ receive(data: string): void {
+ if (this.incomingBytes + data.length > 8192) { this.close(); return; }
+ this.incomingBytes += data.length;
+ this.inbound = this.inbound.then(async () => {
+ if (this.readyState !== "open") return;
+ const bytes = Uint8Array.from(atob(data), c => c.charCodeAt(0));
+ if (bytes.length < 36) return;
+ const sequence = new DataView(bytes.buffer).getBigUint64(0);
+ if (sequence <= this.received) return;
+ const aad = new Uint8Array(41); aad[0] = 1; aad.set(bytes.subarray(0, 8), 1); aad.set(new TextEncoder().encode(this.epoch), 9);
+ const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(8, 20), additionalData: aad }, await this.key, bytes.slice(20));
+ if (this.readyState !== "open") return;
+ this.received = sequence;
+ this.dispatchEvent(new MessageEvent("message", { data: new TextDecoder().decode(plain) }));
+ }).catch(() => { /* Unauthenticated relay data has no input meaning. */ })
+ .finally(() => { this.incomingBytes -= data.length; });
+ }
+ close(): void {
+ if (this.readyState === "closed") return;
+ this.readyState = "closed";
+ this.transmit({ id: this.identity.endpointId, epoch: this.epoch, closed: true });
+ this.dispatchEvent(new Event("close"));
+ }
+}
diff --git a/src/client/remote-control/input-session.ts b/src/client/remote-control/input-session.ts
new file mode 100644
index 00000000..afe92bd4
--- /dev/null
+++ b/src/client/remote-control/input-session.ts
@@ -0,0 +1,167 @@
+import type { InputTransport } from "./input-route";
+import { videoPictureSize } from "../media/video-geometry";
+import { remoteInputStateSchema, type RemoteInputState } from "./protocol";
+export type { RemoteInputState } from "./protocol";
+export type RemoteInputEvent =
+ | { type: "move"; x: number; y: number }
+ | { type: "relative"; dx: number; dy: number }
+ | { type: "key"; code: string; down: boolean }
+ | { type: "text"; text: string }
+ | { type: "button"; button: number; down: boolean }
+ | { type: "wheel"; delta: number }
+ | { type: "reset" };
+
+type PointerInput = Extract<RemoteInputEvent, { type: "move" | "relative" }>;
+
+// Owns input intent and its exact Host grant. DOM capture and media routing
+// consume this session; neither can revive an old approval after cancellation.
+export class RemoteInputSession {
+ state: RemoteInputState | null = null;
+ private intent: string | null = null;
+ private disposed = false;
+ private pointer: PointerInput | null = null;
+ private pointerTimer: ReturnType<typeof setTimeout> | null = null;
+ private wheelFraction = 0;
+
+ constructor(private readonly channel: InputTransport, private readonly changed: (state: RemoteInputState | null) => void) {
+ channel.addEventListener("message", this.message);
+ channel.addEventListener("close", this.closed);
+ this.send({ type: "sync" });
+ }
+
+ private set(state: RemoteInputState | null): void {
+ this.clearPointer();
+ this.wheelFraction = 0;
+ this.state = state;
+ this.changed(state);
+ }
+
+ private clearPointer(): void {
+ if (this.pointerTimer !== null) clearTimeout(this.pointerTimer);
+ this.pointerTimer = null;
+ this.pointer = null;
+ }
+
+ private readonly flushPointer = (): void => {
+ const pointer = this.pointer;
+ this.clearPointer();
+ if (pointer) this.sendInput(pointer);
+ };
+
+ private readonly message = (event: MessageEvent): void => {
+ if (this.disposed || typeof event.data !== "string" || event.data.length > 1024) return;
+ let decoded: unknown;
+ try { decoded = JSON.parse(event.data); } catch { return; }
+ const parsed = remoteInputStateSchema.safeParse(decoded);
+ if (!parsed.success) return;
+ const state = parsed.data;
+ // Source availability is authoritative for every request. Pause/off may
+ // reach us before the Host receives our new intent; it still ends it.
+ if (state.state === "unavailable") this.intent = null;
+ if (this.intent !== null && state.intent !== this.intent) return;
+ if (this.intent === null && (state.state === "active" || state.state === "suspended" || state.state === "pending")) {
+ this.send({ type: "release", intent: state.intent });
+ return;
+ }
+ if (state.state !== "pending" && state.state !== "active" && state.state !== "suspended") this.intent = null;
+ this.set(state);
+ };
+
+ private readonly closed = (): void => { this.intent = null; this.set(null); };
+
+ private send(event: object): boolean {
+ if (this.disposed || this.channel.readyState !== "open") return false;
+ try {
+ // A stalled input queue must not replay seconds of old actions later.
+ if (this.channel.bufferedAmount > 8192) throw new Error("input queue stalled");
+ this.channel.send(JSON.stringify(event));
+ return true;
+ } catch {
+ this.intent = null;
+ this.set(this.state && { ...this.state, state: "failed", grant: undefined });
+ this.channel.close();
+ return false;
+ }
+ }
+
+ request(password?: string): void {
+ const state = this.state;
+ if (!state) return;
+ this.intent = crypto.randomUUID().replaceAll("-", "");
+ if (this.send({ type: "request", intent: this.intent, ...(password !== undefined ? { password } : {}) }))
+ this.set({ state: "pending", mode: state.mode, platform: state.platform, intent: this.intent });
+ }
+
+ release(): void {
+ if (this.intent === null || !this.state) {
+ if (this.state?.reason) this.set({ ...this.state, reason: undefined });
+ return;
+ }
+ const intent = this.intent;
+ const state = this.state;
+ this.intent = null;
+ if (this.send({ type: "release", intent })) this.set({ state: "ready", mode: state.mode, platform: state.platform });
+ }
+
+ input(event: RemoteInputEvent): void {
+ if (event.type === "move" || event.type === "relative") {
+ if (this.state?.state !== "active") return;
+ // Absolute samples replace one another; relative samples accumulate.
+ // Flush before a button/key transition to preserve drag and game input order.
+ if (this.pointer && this.pointer.type !== event.type) this.flushPointer();
+ this.pointer = event.type === "relative" && this.pointer?.type === "relative"
+ ? { type: "relative", dx: this.pointer.dx + event.dx, dy: this.pointer.dy + event.dy }
+ : event;
+ // Bound motion batching independently of rendering: a slow picture must
+ // not slow input too. The timer exists only while motion is pending.
+ if (this.pointerTimer === null) this.pointerTimer = setTimeout(this.flushPointer, 4);
+ return;
+ }
+ if (event.type === "reset") { this.clearPointer(); this.wheelFraction = 0; }
+ else this.flushPointer();
+ this.sendInput(event);
+ }
+
+ scroll(deltaY: number, deltaMode: number): void {
+ if (this.state?.state !== "active") return;
+ // Normalize browser pixel/line/page units to wheel ticks (120 per notch).
+ // Common defaults: 100 px or 3 lines per notch; retain precision-pad fractions.
+ this.wheelFraction -= deltaY * (deltaMode === 1 ? 40 : deltaMode === 2 ? 120 : 1.2);
+ const delta = Math.trunc(this.wheelFraction);
+ this.wheelFraction -= delta;
+ if (delta) this.input({ type: "wheel", delta: Math.max(-1200, Math.min(1200, delta)) });
+ }
+
+ private sendInput(event: RemoteInputEvent): void {
+ const state = this.state;
+ if (!this.intent || !state?.grant || state.intent !== this.intent ||
+ (state.state !== "active" && !(event.type === "reset" && state.state === "suspended"))) return;
+ this.send({ ...event, grant: state.grant });
+ }
+
+ dispose(): void {
+ this.release();
+ this.clearPointer();
+ this.disposed = true;
+ this.channel.removeEventListener("message", this.message);
+ this.channel.removeEventListener("close", this.closed);
+ }
+}
+
+// The input surface can include letterboxing. Its bars are not clickable
+// picture pixels; use the same local fit as Viewer playback, including cropping.
+export function pictureRect(video: HTMLVideoElement): { left: number; top: number; width: number; height: number } | null {
+ if (!video.videoWidth || !video.videoHeight) return null;
+ const rect = video.getBoundingClientRect();
+ const { width, height } = videoPictureSize(video, rect.width, rect.height);
+ if (!width || !height) return null;
+ return { left: rect.left + (rect.width - width) / 2, top: rect.top + (rect.height - height) / 2, width, height };
+}
+
+export function picturePoint(video: HTMLVideoElement, clientX: number, clientY: number): { x: number; y: number } | null {
+ const rect = pictureRect(video);
+ if (!rect) return null;
+ const x = (clientX - rect.left) / rect.width;
+ const y = (clientY - rect.top) / rect.height;
+ return x >= 0 && x <= 1 && y >= 0 && y <= 1 ? { x, y } : null;
+}
diff --git a/src/client/remote-control/keyboard.ts b/src/client/remote-control/keyboard.ts
new file mode 100644
index 00000000..a5f0a7a1
--- /dev/null
+++ b/src/client/remote-control/keyboard.ts
@@ -0,0 +1,45 @@
+import type { RemoteInputEvent } from "./input-session";
+
+// Virtual keys share the physical-key path. Each contact owns its chord until
+// release; another finger must not release a modifier that is still in use.
+export class RemoteKeyboardPresses {
+ private held = new Map<number, { codes: readonly string[]; timer?: ReturnType<typeof setTimeout> }>();
+
+ constructor(private readonly input: (event: RemoteInputEvent) => void) {}
+
+ down(id: number, codes: readonly string[], repeating = true): void {
+ this.up(id);
+ for (const code of codes) {
+ if (!this.pressed(code)) this.input({ type: "key", code, down: true });
+ }
+ const repeat = () => {
+ const press = this.held.get(id);
+ if (!press) return;
+ this.input({ type: "key", code: codes[codes.length - 1], down: true });
+ press.timer = setTimeout(repeat, 50);
+ };
+ this.held.set(id, { codes, timer: repeating ? setTimeout(repeat, 400) : undefined });
+ }
+
+ up(id: number): void {
+ const press = this.held.get(id);
+ if (!press) return;
+ clearTimeout(press.timer);
+ this.held.delete(id);
+ for (const code of [...press.codes].reverse()) {
+ if (!this.pressed(code)) this.input({ type: "key", code, down: false });
+ }
+ }
+
+ tap(codes: readonly string[]): void {
+ this.down(-1, codes); this.up(-1);
+ }
+
+ reset(): void {
+ for (const id of this.held.keys()) this.up(id);
+ }
+
+ private pressed(code: string): boolean {
+ return [...this.held.values()].some(press => press.codes.includes(code));
+ }
+}
diff --git a/src/client/remote-control/protocol.ts b/src/client/remote-control/protocol.ts
new file mode 100644
index 00000000..ab2d9887
--- /dev/null
+++ b/src/client/remote-control/protocol.ts
@@ -0,0 +1,19 @@
+import { z } from "zod";
+
+// A text submission still fits one encrypted input packet and the existing queue.
+export const REMOTE_TEXT_BYTES = 2048;
+
+export const remoteControlModeSchema = z.enum(["off", "ask", "room", "password"]);
+export type RemoteControlMode = z.infer<typeof remoteControlModeSchema>;
+export const remoteInputPlatformSchema = z.enum(["windows", "darwin", "linux"]);
+export type RemoteInputPlatform = z.infer<typeof remoteInputPlatformSchema>;
+
+export const remoteInputStateSchema = z.object({
+ state: z.enum(["ready", "unavailable", "pending", "active", "suspended", "failed"]),
+ mode: remoteControlModeSchema,
+ platform: remoteInputPlatformSchema,
+ grant: z.string().regex(/^[0-9a-f]{64}$/).optional(),
+ intent: z.string().regex(/^[0-9a-f]{32}$/).optional(),
+ reason: z.enum(["password", "retry", "busy"]).optional(),
+}).strict();
+export type RemoteInputState = z.infer<typeof remoteInputStateSchema>;
diff --git a/src/client/remote-control/touchpad.ts b/src/client/remote-control/touchpad.ts
new file mode 100644
index 00000000..6cad2cad
--- /dev/null
+++ b/src/client/remote-control/touchpad.ts
@@ -0,0 +1,141 @@
+import type { RemoteInputEvent } from "./input-session";
+import type { RemoteViewport } from "./viewport";
+
+type Point = { x: number; y: number };
+type Contact = Point & { start: Point };
+
+// Gesture lifetime belongs to the current input grant. Pointer coordinates
+// belong to the source picture; the local viewport supplies its visible bounds.
+export class RemoteTouchpad {
+ position: Point = { x: 0.5, y: 0.5 };
+ private contacts = new Map<number, Contact>();
+ private hold: ReturnType<typeof setTimeout> | null = null;
+ private fingers = 0;
+ private moved = false;
+ private dragging = false;
+ private started = 0;
+ private pair: { center: Point; distance: number } | null = null;
+ private gesture: "pending" | "scroll" | "view" = "pending";
+ private frame: number | null = null;
+
+ constructor(
+ private readonly picture: () => { width: number; height: number } | null,
+ private readonly input: (event: RemoteInputEvent) => void,
+ private readonly scroll: (deltaY: number) => void,
+ private readonly changed: (position: Point) => void,
+ private readonly viewport: Pick<RemoteViewport, "scale" | "transform" | "visiblePosition">,
+ ) {}
+
+ down(id: number, x: number, y: number): void {
+ if (!this.contacts.size) {
+ this.started = performance.now();
+ this.fingers = 0;
+ this.moved = false;
+ this.gesture = "pending";
+ this.changed(this.position);
+ }
+ this.contacts.set(id, { x, y, start: { x, y } });
+ this.fingers = Math.max(this.fingers, this.contacts.size);
+ this.clearHold();
+ if (this.fingers === 1) {
+ this.hold = setTimeout(() => {
+ this.hold = null;
+ this.dragging = true;
+ this.input({ type: "move", ...this.position });
+ this.input({ type: "button", button: 0, down: true });
+ }, 500);
+ } else {
+ this.endDrag();
+ this.pair = this.pairGeometry();
+ }
+ }
+
+ move(id: number, x: number, y: number): void {
+ const contact = this.contacts.get(id);
+ if (!contact) return;
+ if (this.fingers > 1) {
+ contact.x = x; contact.y = y;
+ // A native touch packet produces one pointer event per finger. Decide
+ // pinch versus parallel movement after both arrive, not halfway through.
+ if (this.frame === null) this.frame = requestAnimationFrame(() => this.movePair());
+ return;
+ }
+ const dx = x - contact.x, dy = y - contact.y;
+ if (Math.hypot(x - contact.start.x, y - contact.start.y) > 8) {
+ this.moved = true;
+ this.clearHold();
+ }
+ if (!this.moved && !this.dragging) return;
+ // Keep the initial displacement while deciding tap versus motion. Updating
+ // the origin before this threshold loses the start of every small swipe.
+ contact.x = x; contact.y = y;
+ const picture = this.picture();
+ if (!picture?.width || !picture.height) return;
+ this.position = this.viewport.visiblePosition({
+ x: Math.max(0, Math.min(1, this.position.x + dx / picture.width)),
+ y: Math.max(0, Math.min(1, this.position.y + dy / picture.height)),
+ });
+ this.input({ type: "move", ...this.position });
+ this.changed(this.position);
+ }
+
+ private pairGeometry(): { center: Point; distance: number } | null {
+ if (this.fingers !== 2 || this.contacts.size !== 2) return null;
+ const [a, b] = [...this.contacts.values()];
+ return { center: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, distance: Math.max(1, Math.hypot(b.x - a.x, b.y - a.y)) };
+ }
+
+ private movePair(): void {
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
+ this.frame = null;
+ const next = this.pairGeometry(), previous = this.pair;
+ if (!next || !previous) return;
+ if (this.gesture === "pending") {
+ const pinch = Math.abs(next.distance - previous.distance) > Math.max(8, previous.distance * .08);
+ const pan = Math.hypot(next.center.x - previous.center.x, next.center.y - previous.center.y) > 8;
+ if (!pinch && !pan) return;
+ this.gesture = pinch || this.viewport.scale > 1 ? "view" : "scroll";
+ this.moved = true;
+ }
+ if (this.gesture === "view") this.viewport.transform(previous.center, next.center, next.distance / previous.distance);
+ else this.scroll(previous.center.y - next.center.y);
+ this.pair = next;
+ }
+
+ up(id: number): void {
+ this.movePair();
+ if (!this.contacts.delete(id)) return;
+ this.clearHold();
+ if (this.contacts.size) return;
+ if (!this.moved && !this.dragging && performance.now() - this.started < 500 && this.fingers <= 2) {
+ const button = this.fingers === 2 ? 2 : 0;
+ this.input({ type: "move", ...this.position });
+ this.input({ type: "button", button, down: true });
+ this.input({ type: "button", button, down: false });
+ }
+ this.endDrag();
+ }
+
+ private clearHold(): void {
+ if (this.hold !== null) clearTimeout(this.hold);
+ this.hold = null;
+ }
+
+ private endDrag(): void {
+ if (this.dragging) this.input({ type: "button", button: 0, down: false });
+ this.dragging = false;
+ }
+
+ cancel(id: number): void {
+ if (this.contacts.has(id)) this.reset();
+ }
+
+ reset(): void {
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
+ this.frame = null;
+ this.pair = null;
+ this.clearHold();
+ this.endDrag();
+ this.contacts.clear();
+ }
+}
diff --git a/src/client/remote-control/viewport.ts b/src/client/remote-control/viewport.ts
new file mode 100644
index 00000000..4d7cbfe7
--- /dev/null
+++ b/src/client/remote-control/viewport.ts
@@ -0,0 +1,69 @@
+import { pictureRect } from "./input-session";
+import { videoPictureSize } from "../media/video-geometry";
+
+type Point = { x: number; y: number };
+
+// Local picture magnification only. The input owner still uses pictureRect's
+// transformed video geometry; neither capture nor the remote desktop is resized.
+export class RemoteViewport {
+ scale = 1;
+ private offset: Point = { x: 0, y: 0 };
+
+ constructor(
+ private readonly video: HTMLVideoElement,
+ private readonly surface: HTMLElement,
+ private readonly changed: (zoomed: boolean) => void,
+ ) {}
+
+ transform(from: Point, to: Point, ratio: number): void {
+ const rect = this.surface.getBoundingClientRect();
+ const next = Math.max(1, Math.min(4, this.scale * ratio));
+ const factor = next / this.scale;
+ const center = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
+ this.offset = {
+ x: to.x - center.x - (from.x - center.x - this.offset.x) * factor,
+ y: to.y - center.y - (from.y - center.y - this.offset.y) * factor,
+ };
+ this.scale = next;
+ this.refresh();
+ }
+
+ refresh(): void {
+ const { videoWidth, videoHeight, style } = this.video;
+ const { width, height } = this.surface.getBoundingClientRect();
+ if (!videoWidth || !videoHeight || !width || !height) return;
+ const picture = videoPictureSize(this.video, width, height);
+ const limitX = Math.max(0, (picture.width * this.scale - width) / 2);
+ const limitY = Math.max(0, (picture.height * this.scale - height) / 2);
+ const x = this.offset.x = Math.max(-limitX, Math.min(limitX, this.offset.x));
+ const y = this.offset.y = Math.max(-limitY, Math.min(limitY, this.offset.y));
+ style.transform = this.scale > 1 ? `translate(${x}px, ${y}px) scale(${this.scale})` : "";
+ // Clip to the original video cell, including when a keyboard occupies the
+ // next grid cell. Inverse-transform its edges into the video's local space.
+ const insets = [height / 2 - (height / 2 + y) / this.scale, width / 2 - (width / 2 - x) / this.scale,
+ height / 2 - (height / 2 - y) / this.scale, width / 2 - (width / 2 + x) / this.scale];
+ style.clipPath = this.scale > 1 ? `inset(${insets.map(value => `${value}px`).join(" ")})` : "";
+ this.changed(this.scale > 1);
+ }
+
+ visiblePosition(position: Point): Point {
+ const picture = pictureRect(this.video), rect = this.surface.getBoundingClientRect();
+ if (!picture) return position;
+ // Keep the local touch cursor in view while panning. No remote input is
+ // emitted until the user next moves or clicks, at this visible position.
+ return {
+ x: Math.max(0, Math.min(1, Math.max((rect.left - picture.left) / picture.width,
+ Math.min((rect.right - picture.left) / picture.width, position.x)))),
+ y: Math.max(0, Math.min(1, Math.max((rect.top - picture.top) / picture.height,
+ Math.min((rect.bottom - picture.top) / picture.height, position.y)))),
+ };
+ }
+
+ reset(): void {
+ this.scale = 1;
+ this.offset = { x: 0, y: 0 };
+ this.video.style.transform = "";
+ this.video.style.clipPath = "";
+ this.changed(false);
+ }
+}
diff --git a/src/client/sfu/subscriber.ts b/src/client/sfu/subscriber.ts
index 85bf51b5..88383658 100644
--- a/src/client/sfu/subscriber.ts
+++ b/src/client/sfu/subscriber.ts
@@ -1,4 +1,5 @@
import type { SfuSignalMessage } from "../../shared/protocol";
+import { RemoteInputChannel } from "../webrtc/remote-input-channel";
import type { ConnectionMetrics } from "../types";
import { debugRtcFailure, debugRtcStats } from "../lib/debug-webrtc";
import {
@@ -12,6 +13,7 @@ import { observeDecodedFrameProof } from "../media/decoded-frame-proof";
import { SfuPeer, type SfuConnectionConfig } from "./peer";
interface SubscriberEvents {
+ onInputChanged?: () => void;
send: (message: SfuSignalMessage) => boolean;
onStream: (stream: MediaStream | null) => void;
onVideoAvailability?: (available: boolean) => void;
@@ -28,6 +30,8 @@ interface SubscribedTrack {
}
export class SfuSubscriber {
+ private readonly remoteInput = new RemoteInputChannel(() => this.events.onInputChanged?.());
+ getRemoteInput(): RTCDataChannel | null { return this.remoteInput.current; }
private peer: SfuPeer | null = null;
private video: SubscribedTrack | null = null;
private audio: SubscribedTrack | null = null;
@@ -59,6 +63,7 @@ export class SfuSubscriber {
} else if (state === "disconnected") this.reconnect();
},
});
+ this.remoteInput.attach(this.peer.pc);
return true;
}
@@ -131,6 +136,7 @@ export class SfuSubscriber {
async disconnect(): Promise<void> {
if (this.closed) return;
this.closed = true;
+ this.remoteInput.dispose();
this.active = false;
const peer = this.peer;
this.peer = null;
diff --git a/src/client/styles.css b/src/client/styles.css
index 00b4c139..fe20d922 100644
--- a/src/client/styles.css
+++ b/src/client/styles.css
@@ -1,3 +1,4 @@
+@import "./ui/palette.css";
@import "./components/living/pawn.css";
@import "./components/living/brand-mark.css";
@import "./components/living/language-control.css";
@@ -13,11 +14,6 @@
:root {
color-scheme: light;
- --wall: #e9f2ee;
- --wall-2: #dcebe4;
- --ink: #22303e;
- --paper: #ffffff;
- --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));
/* Fixed warm upholstery; shade changes define the cushions and arms. */
--couch: #e9ad63;
--couch-dark: #cd8845;
@@ -29,9 +25,6 @@
--pawn-5: #e2698f;
--pawn-6: #4e9c74;
--pawn-7: #a978bd;
- --pawn-8: #5f7dd8;
- --action: #2f6fed;
- --action-deep: #2058c9;
--live: #2fa66a;
--warn: #d98e04;
--danger: #d64541;
@@ -40,13 +33,11 @@
--route-pending: var(--action);
--lcd: #1d2b22;
--lcd-digits: #9de8bf;
- --stage: #101a2c;
- --frame: #22303e;
+ --stage: #17191c;
+ --frame: #283445;
+ --frame-highlight: #3e4b5b;
--radius: 16px;
--control-radius: 18px;
- --control-edge: color-mix(in srgb, var(--ink) 62%, var(--paper));
- --control-hover: var(--wall-2);
- --control-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 13%, transparent);
--spring: cubic-bezier(.3, 1.45, .45, 1);
--font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", "PingFang SC",
"Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
@@ -55,14 +46,8 @@
html[data-theme="dark"] {
color-scheme: dark;
- --wall: #141e29;
- --wall-2: #0e1620;
- --ink: #dde8f3;
- --paper: #22303e;
- --control-hover: #2b3d4f;
- --frame: #0a111a;
- --action: #4a84f2;
- --action-deep: #3a70d8;
+ --frame: #1d2633;
+ --stage: #141517;
--live: #3fb97a;
--warn: #e8a33d;
--danger: #e25a52;
@@ -89,6 +74,7 @@ body {
button, input, select { font: inherit; color: inherit; }
button { cursor: pointer; touch-action: manipulation; }
button:disabled { cursor: not-allowed; opacity: 0.4; }
+input[type="checkbox"]:not(:disabled) { cursor: pointer; }
h1, h2, h3, p, dl, dd, dt { margin: 0; }
ul { margin: 0; padding: 0; list-style: none; }
@@ -171,7 +157,7 @@ ul { margin: 0; padding: 0; list-style: none; }
/* Extra locales share one menu after the familiar shortcuts. */
.lr-lang-more > span { display: inline-flex; align-items: center; gap: 2px; pointer-events: none; }
.lr-lang-more .lr-glyph:last-child { transition: transform 180ms var(--spring); }
-.lr-header-controls:has(.lr-language-menu:popover-open) .lr-lang-more .lr-glyph:last-child { transform: rotate(180deg); }
+.lr-header-controls:has(.lr-language-menu:is(:popover-open, .\:popover-open)) .lr-lang-more .lr-glyph:last-child { transform: rotate(180deg); }
.lr-language-menu {
position: fixed;
inset: auto;
@@ -188,7 +174,7 @@ ul { margin: 0; padding: 0; list-style: none; }
font: 600 14px/1.4 var(--font);
transform-origin: top right;
}
-.lr-language-menu:popover-open { animation: lr-language-open 180ms var(--spring); }
+.lr-language-menu:is(:popover-open, .\:popover-open) { animation: lr-language-open 180ms var(--spring); }
.lr-language-menu.is-above { transform-origin: bottom right; --language-offset: 5px; }
@keyframes lr-language-open { from { opacity: 0; transform: translateY(var(--language-offset, -5px)) scale(.97); } }
.lr-language-menu button {
@@ -208,10 +194,10 @@ ul { margin: 0; padding: 0; list-style: none; }
transition: background-color 140ms ease, color 140ms ease, transform 180ms var(--spring);
}
.lr-language-menu button + button { margin-top: 4px; }
-.lr-language-menu button:is(:hover, :focus-visible) { background: var(--wall-2); transform: translateX(2px); }
+.lr-language-menu button:is(:hover, :focus-visible) { background: var(--wall-2); transform: translateY(-1px); }
.lr-language-menu button:focus-visible { outline-offset: -3px; }
-.lr-language-menu button:active { transform: scale(.98); }
-.lr-language-menu button[aria-checked="true"] { background: var(--ink); color: var(--paper); }
+.lr-language-menu button:active { transform: var(--control-press-transform); transition-duration: 80ms; }
+.lr-language-menu button[aria-checked="true"] { background: var(--control-selected); color: var(--control-selected-ink); box-shadow: inset 0 0 0 2px var(--action); }
.lr-language-mark {
display: grid;
place-items: center;
@@ -233,6 +219,9 @@ ul { margin: 0; padding: 0; list-style: none; }
overflow-y: visible untouched. Open panels are edge-aligned via
is-start/is-end, so nothing visible is cut in practice. */
.lr-app { min-height: 100dvh; display: flex; flex-direction: column; overflow-x: clip; }
+.lr-app-shell { min-height: 100dvh; display: flex; flex-direction: column; }
+.lr-app-shell > .lr-app { flex: 1; min-height: 0; }
+.lr-web-version { padding: 8px 16px 16px; color: var(--muted); font-size: 11.5px; text-align: center; }
.lr-room {
flex: 1;
width: min(1180px, 100%);
@@ -282,7 +271,8 @@ body.lr-theater-open .lr-top { visibility: hidden; }
padding: 12px 12px 0;
border: 3px solid var(--frame);
border-radius: 26px 26px 20px 20px;
- background: var(--frame);
+ background: linear-gradient(155deg, var(--frame-highlight), var(--frame) 75%);
+ box-shadow: inset 0 1px 0 rgb(255 255 255 / .16), 0 2px 0 var(--surface-shade), 0 18px 35px color-mix(in srgb, var(--surface-shade) 58%, transparent);
transition: width 240ms ease-out;
}
.lr-tv-screen {
@@ -320,9 +310,18 @@ body.lr-theater-open .lr-top { visibility: hidden; }
}
/* TV overlays */
+.lr-tv-screen:has(> .lr-tv-overlay.is-dim)::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ pointer-events: none;
+ background: color-mix(in srgb, var(--stage) 62%, transparent);
+}
.lr-tv-overlay {
position: absolute;
inset: 0;
+ z-index: 2;
display: grid;
place-content: center;
justify-items: center;
@@ -333,7 +332,6 @@ body.lr-theater-open .lr-top { visibility: hidden; }
color: #dfe8f2;
text-align: center;
}
-.lr-tv-overlay.is-dim { background: rgba(10, 16, 28, .62); }
.lr-tv-overlay.is-passive { pointer-events: none; }
.lr-tv-status-content { display: flex; flex-direction: column; align-items: center; gap: 14px; }
.lr-tv-progress { display: inline-flex; align-items: center; gap: 6px; }
@@ -349,7 +347,6 @@ body.lr-theater-open .lr-top { visibility: hidden; }
.lr-tooltip-preview-card code, .lr-tooltip-preview-card small { font-size: .75rem; overflow-wrap: anywhere; opacity: .7; }
.lr-tooltip-preview-actions { display: flex; gap: 4px; }
.lr-tooltip-preview-trigger { width: 36px; height: 36px; padding: 0; border: 1px solid var(--wall-2); border-radius: 999px; background: transparent; color: var(--ink); }
-.lr-tooltip-preview-card { --comic-repeat: infinite; }
.lr-tooltip-preview-art { min-height: 106px; display: grid; place-items: center; overflow: hidden; }
.lr-tooltip-preview-art svg { max-width: 100%; height: auto; }
.lr-tv-overlay.has-comic {
@@ -383,18 +380,18 @@ body.lr-theater-open .lr-top { visibility: hidden; }
border-radius: 50%;
color: #fff;
background: rgba(255, 255, 255, .07);
- transition: transform 180ms var(--spring), background 160ms ease;
+ transition: var(--control-motion), background 160ms ease;
}
-.lr-tv-big:hover { transform: scale(1.05); }
-.lr-tv-big:active { transform: scale(.94); }
-.lr-tv-big.is-action { border-color: var(--action); background: var(--action); cursor: pointer; }
-.lr-tv-big.is-action:hover { background: var(--action-deep); }
+.lr-tv-big:is(button, .is-action):is(:hover, :focus-visible):not(:disabled) { transform: var(--control-hover-transform); }
+.lr-tv-big:is(button, .is-action):active:not(:disabled) { transform: var(--control-press-transform); transition-duration: 80ms; }
+.lr-tv-big.is-action { border-color: var(--primary); background: var(--primary); color: var(--primary-ink); cursor: pointer; }
+.lr-tv-big.is-action:is(:hover, :focus-visible) { border-color: color-mix(in srgb, var(--primary) 88%, #000); background: color-mix(in srgb, var(--primary) 88%, #000); }
.lr-tv-big.is-ripple::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
- box-shadow: 0 0 0 22px rgba(47, 111, 237, .45);
+ box-shadow: 0 0 0 22px color-mix(in srgb, var(--primary) 45%, transparent);
opacity: 0;
pointer-events: none;
transform: scale(.66);
@@ -421,7 +418,8 @@ body.lr-theater-open .lr-top { visibility: hidden; }
place-content: stretch;
justify-items: stretch;
overflow: hidden;
- background: rgba(10, 16, 28, .92);
+ background: linear-gradient(155deg, color-mix(in srgb, var(--wall) 88%, var(--paper)), var(--wall));
+ color: var(--ink);
text-align: left;
}
.lr-source-picker-panel {
@@ -446,13 +444,16 @@ body.lr-theater-open .lr-top { visibility: hidden; }
display: grid;
flex: 0 0 auto;
place-items: center;
- color: #fff;
+ color: var(--ink);
}
.lr-source-picker-mark {
width: 42px;
height: 42px;
- border: 2px solid rgba(223, 232, 242, .72);
+ border: 2px solid var(--action);
border-radius: 50%;
+ background: var(--control-selected);
+ color: var(--control-selected-ink);
+ box-shadow: 0 2px 0 var(--surface-shade);
}
.lr-source-picker-copy,
.lr-source-option-copy {
@@ -465,7 +466,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
.lr-source-picker-copy small,
.lr-source-option-copy small,
.lr-source-picker-status {
- color: #9aa8bb;
+ color: var(--muted);
font-size: 11.5px;
}
.lr-source-picker-refresh,
@@ -475,52 +476,38 @@ body.lr-theater-open .lr-top { visibility: hidden; }
height: 38px;
flex: 0 0 auto;
place-items: center;
- border: 2px solid rgba(223, 232, 242, .62);
+ border: 2px solid var(--control-edge);
border-radius: 50%;
- background: transparent;
- color: #dfe8f2;
- transition: transform 140ms var(--spring), background 120ms ease;
+ background: var(--paper);
+ box-shadow: var(--control-shadow);
+ color: var(--ink);
+ transition: var(--control-motion), background 120ms ease;
}
.lr-source-picker-refresh { margin-left: auto; }
.lr-source-picker-head > .lr-comic-tip-wrap:has(> .lr-source-picker-refresh) { margin-left: auto; }
.lr-source-picker-refresh:is(:hover, :focus-visible):not(:disabled),
-.lr-source-picker-close:is(:hover, :focus-visible):not(:disabled) { background: rgba(255, 255, 255, .1); }
+.lr-source-picker-close:is(:hover, :focus-visible):not(:disabled) { background: var(--control-hover); transform: var(--control-hover-transform); }
.lr-source-picker-refresh:active:not(:disabled),
-.lr-source-picker-close:active:not(:disabled) { transform: scale(.92); }
-.lr-source-picker-tabs {
+.lr-source-picker-close:active:not(:disabled) { transform: var(--control-press-transform); box-shadow: none; transition-duration: 80ms; }
+.lr-source-picker-tabs.lr-toggle {
display: grid;
- gap: 4px;
- padding: 4px;
- border: 1px solid rgba(223, 232, 242, .24);
- border-radius: 16px;
- background: rgba(0, 0, 0, .12);
}
.lr-source-picker-tabs > span { min-width: 0; }
-.lr-source-picker-tabs button {
- display: flex;
+.lr-source-picker-tabs.lr-toggle button {
width: 100%;
+ height: auto;
min-height: 44px;
- align-items: center;
- justify-content: center;
gap: 7px;
padding: 8px 4px;
- border: 0;
- border-radius: 12px;
- background: transparent;
- color: #9aa8bb;
font-size: 12px;
font-weight: 700;
- transition: color 120ms ease, background 120ms ease;
}
.lr-source-picker-tabs button svg { flex: 0 0 auto; }
+.lr-source-picker-tabs button > span { word-break: keep-all; }
@media (max-width: 520px) {
- .lr-source-picker-tabs button { flex-direction: column; gap: 3px; padding-inline: 0; font-size: 11px; }
-}
-.lr-source-picker-tabs button:is(:hover, :focus-visible):not(:disabled):not([aria-selected="true"]) { background: rgba(255, 255, 255, .1); }
-.lr-source-picker-tabs button[aria-selected="true"] {
- background: #dfe8f2;
- color: #22303e;
+ .lr-source-picker-tabs.lr-toggle button { flex-direction: column; gap: 3px; padding-inline: 0; font-size: 11px; }
}
+.lr-source-picker-tabs button:is(:hover, :focus-visible):not(:disabled):not([aria-selected="true"]) { background: var(--control-hover); }
.lr-source-picker-body {
display: flex;
min-height: 0;
@@ -528,6 +515,8 @@ body.lr-theater-open .lr-top { visibility: hidden; }
gap: 10px;
overflow-y: auto;
scrollbar-gutter: stable;
+ padding: 8px;
+ margin: -8px;
}
.lr-source-picker-body > [role="status"] { text-align: center; }
.lr-source-app-connection { display: flex; justify-content: flex-end; margin-top: 12px; }
@@ -550,20 +539,22 @@ body.lr-theater-open .lr-top { visibility: hidden; }
align-items: center;
gap: 10px;
padding: 9px 12px;
- border: 2px solid rgba(223, 232, 242, .62);
- border-radius: 12px;
- background: rgba(255, 255, 255, .06);
- color: #dfe8f2;
+ border: 2px solid var(--control-edge);
+ border-radius: var(--control-radius);
+ background: var(--surface-glaze) var(--paper);
+ box-shadow: var(--control-shadow);
+ color: var(--ink);
text-align: left;
- transition: transform 150ms var(--spring), border-color 120ms ease, background 120ms ease;
+ transition: var(--control-motion), border-color 120ms ease, background 120ms ease;
}
.lr-source-option:is(:hover, :focus-visible):not(:disabled) {
border-color: var(--action);
- background: rgba(47, 111, 237, .2);
- transform: translateY(-2px);
+ background: var(--control-hover);
+ transform: var(--control-hover-transform);
+ box-shadow: inset 0 0 0 1px var(--action), var(--control-shadow);
}
-.lr-source-option:active:not(:disabled) { transform: scale(.98); }
-.lr-source-option[aria-current="true"] { border-color: #dfe8f2; background: rgba(223, 232, 242, .18); }
+.lr-source-option:active:not(:disabled) { transform: var(--control-press-transform); box-shadow: none; transition-duration: 80ms; }
+.lr-source-option[aria-current="true"] { border-color: var(--action); background: var(--control-selected); color: var(--control-selected-ink); }
.lr-source-option:not(.is-browser) {
display: grid;
align-items: stretch;
@@ -590,7 +581,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
width: 38px;
height: 38px;
border-radius: 8px;
- background: rgba(255, 255, 255, .1);
+ background: var(--wall-2);
}
.lr-source-option-preview {
grid-template: minmax(0, 1fr) / minmax(0, 1fr);
@@ -598,14 +589,14 @@ body.lr-theater-open .lr-top { visibility: hidden; }
height: 144px;
overflow: hidden;
border-radius: 8px;
- background: rgba(255, 255, 255, .1);
+ background: var(--wall-2);
}
.lr-source-option-preview img {
display: block;
width: 100%;
height: 100%;
object-fit: contain;
- background: #0a101c;
+ background: var(--wall-2);
}
.lr-source-option-copy { flex: 1; }
.lr-source-option-copy strong {
@@ -642,7 +633,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
align-items: center;
justify-content: flex-end;
gap: 9px;
- color: #dfe8f2;
+ color: var(--ink);
font-size: 12px;
font-weight: 650;
}
@@ -650,28 +641,24 @@ body.lr-theater-open .lr-top { visibility: hidden; }
.lr-source-exclusion[open] { flex-basis: 100%; }
.lr-source-exclusion summary {
display: flex; align-items: center; gap: 7px; min-height: 38px; padding: 0 8px;
- color: #dfe8f2; font-size: 12px; font-weight: 650; cursor: pointer; border-radius: 12px;
+ color: var(--ink); font-size: 12px; font-weight: 650; cursor: pointer; border-radius: 12px;
transition: background-color 140ms ease;
}
.lr-source-exclusion summary::-webkit-details-marker { display: none; }
.lr-source-exclusion summary span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lr-source-exclusion summary svg { flex-shrink: 0; }
.lr-source-exclusion[open] summary > svg:last-child { transform: rotate(180deg); }
-.lr-source-exclusion summary:is(:hover, :focus-visible) { background: rgba(255, 255, 255, .1); }
+.lr-source-exclusion summary:is(:hover, :focus-visible) { background: var(--control-hover); }
.lr-source-picker-option .lr-switch {
width: 50px;
height: 30px;
- border-color: rgba(223, 232, 242, .72);
- background: rgba(255, 255, 255, .06);
}
.lr-source-picker-option .lr-switch::after {
width: 20px;
height: 20px;
- background: #dfe8f2;
}
.lr-source-picker-option .lr-switch[aria-checked="true"]::after {
transform: translateX(20px);
- background: #fff;
}
/* static noise while connecting */
@@ -794,7 +781,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
inset: 45px 0 auto;
display: grid;
place-items: center;
- color: #6f8579;
+ color: var(--muted);
opacity: .85;
}
@@ -846,8 +833,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
flex-wrap: nowrap;
font-size: 13px;
}
-.lr-viewer-host-slot svg { flex: 0 0 auto; color: #53676a; }
-html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }
+.lr-viewer-host-slot svg { flex: 0 0 auto; color: var(--muted); }
.lr-viewer-host-slot b {
min-width: 0;
overflow: hidden;
@@ -893,7 +879,7 @@ html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }
.lr-invite-field > .lr-row-group { flex: none; width: auto; }
.lr-spacer { flex: 1; }
.lr-divider { width: 2.5px; align-self: stretch; border-radius: 2px; background: var(--wall-2); }
-.lr-row.is-sub .lr-divider { background: #c3d4cb; }
+.lr-row.is-sub .lr-divider { background: var(--line); }
.lr-field-cap { opacity: .68; font-size: 12px; font-weight: 600; }
.lr-invite-url {
width: 100%;
@@ -914,7 +900,6 @@ html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }
text-align: left;
user-select: text;
}
-html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #33465c; }
/* Touch only: the compact mono URL would auto-zoom iOS on focus under 16px,
and the zoom never returns. Pointer devices keep the dense line. */
/* LCD room code */
@@ -968,16 +953,16 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
overflow: auto; overscroll-behavior: contain;
}
.lr-app-connect-help p { margin: 12px 0; font-size: 13px; line-height: 1.6; }
-.lr-app-connect-help:popover-open { animation: lr-language-open 180ms var(--spring); }
+.lr-app-connect-help:is(:popover-open, .\:popover-open) { animation: lr-language-open 180ms var(--spring); }
.lr-app-connect-help.is-above { --language-offset: 5px; }
.lr-app-connect-head { display: flex; align-items: flex-start; gap: 8px; }
.lr-app-connect-close { flex: 0 0 auto; width: 32px; height: 32px; min-width: 32px; padding: 0; }
-.lr-app-connect-scene { width: min(220px, 100%); aspect-ratio: 10 / 3; margin-inline: auto; --comic-repeat: infinite; }
+.lr-app-connect-scene { width: min(220px, 100%); aspect-ratio: 10 / 3; margin-inline: auto; }
.lr-app-connect-scene > svg { width: 100% !important; }
.lr-app-connect-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
.lr-app-connect-actions .lr-btn { min-height: 40px; }
.lr-app-connect-help .lr-app-connect-optional { color: var(--muted); font-size: 12px; margin-bottom: 0; }
-@media (prefers-reduced-motion: reduce) { .lr-app-connect-help:popover-open { animation: none; } }
+@media (prefers-reduced-motion: reduce) { .lr-app-connect-help:is(:popover-open, .\:popover-open) { animation: none; } }
.lr-cap { font-size: 12.5px; font-weight: 600; color: inherit; white-space: nowrap; }
/* Sharing and local playback have distinct owners, but one control grammar. */
@@ -1011,12 +996,13 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
/* Selection keeps the same press/release transition. A separate transform
animation would jump away from the held pose when the selection changes. */
.lr-chip, .lr-tile {
- transition: transform 180ms var(--spring), background-color 140ms ease, color 140ms ease, border-color 140ms ease, box-shadow 140ms ease;
+ transition: var(--control-motion), background-color 140ms ease, color 140ms ease, border-color 140ms ease, box-shadow 140ms ease;
}
-:is(.lr-chip, .lr-tile):is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):where(:not(.is-selected)) { background: var(--wall-2); transform: translateY(-2px); }
-:is(.lr-chip, .lr-tile):active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.97); box-shadow: none; }
-:is(.lr-chip, .lr-tile).is-selected { background: var(--ink); color: var(--paper); }
-.lr-chip.is-selected { border-color: var(--ink); }
+:is(.lr-chip, .lr-tile):is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: var(--control-hover-transform); }
+:is(.lr-chip, .lr-tile):is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):where(:not(.is-selected)) { background: var(--control-hover); }
+:is(.lr-chip, .lr-tile):active:not(:disabled):not([aria-disabled="true"]) { transform: var(--control-press-transform); box-shadow: none; transition-duration: 80ms; }
+:is(.lr-chip, .lr-tile).is-selected { background: var(--control-selected); color: var(--control-selected-ink); border-color: var(--action); box-shadow: inset 0 0 0 1px var(--action), var(--control-shadow); }
+:is(.lr-chip, .lr-tile).is-selected:active:not(:disabled) { box-shadow: inset 0 0 0 1px var(--action); }
.lr-chip .lr-cap { font-family: var(--font); letter-spacing: 0; }
.lr-chip small { margin-left: 5px; font-size: 10.5px; opacity: .6; }
.lr-chip .lr-audio-rate {
@@ -1036,8 +1022,10 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
}
@keyframes lr-pop { 50% { transform: scale(1.06); } }
-/* Equal columns keep the admission thumb aligned across translated captions. */
+/* Equal segments keep the shared thumb aligned across translated captions. */
.lr-toggle {
+ --lr-segments: 2;
+ --lr-selected-index: 0;
position: relative;
display: inline-grid;
grid-auto-flow: column;
@@ -1053,12 +1041,14 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
top: 4px; bottom: 4px; left: 4px;
border-radius: 999px;
background: var(--ink);
+ box-shadow: inset 0 0 0 2px var(--action);
+ width: calc((100% - 8px) / var(--lr-segments));
+ transform: translateX(calc(var(--lr-selected-index) * 100%));
transition: transform 260ms var(--spring);
pointer-events: none;
}
-.lr-toggle::before { width: calc(50% - 4px); }
-.lr-toggle:not([data-selected])::before { opacity: 0; }
-.lr-toggle[data-selected="private"]::before { transform: translateX(100%); }
+.lr-toggle:not(:has(.is-selected))::before { opacity: 0; }
+.lr-toggle:has(> :nth-child(2).is-selected, > :nth-child(2) .is-selected) { --lr-selected-index: 1; }
.lr-toggle button {
position: relative;
z-index: 1;
@@ -1071,13 +1061,14 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
border: 0;
border-radius: 999px;
background: transparent;
- /* 68% ink clears AA on both themes (light 4.89:1, dark 5.89:1) while the
- selected option keeps its stronger contrast. */
+ font-weight: 600;
+ /* Inactive text stays readable; the selected option gains full contrast. */
color: color-mix(in srgb, var(--ink) 68%, var(--paper));
- transition: color 180ms ease;
+ transition: color 180ms ease, transform 180ms var(--spring);
}
.lr-toggle button.is-selected { color: var(--paper); }
-.lr-toggle button:active { transform: scale(.94); }
+.lr-toggle button:is(:hover, :focus-visible):not(:disabled) { transform: translateY(-1px); }
+.lr-toggle button:active { transform: var(--control-press-transform); transition-duration: 80ms; }
/* The wrapper owns each half in both language modes. */
.lr-toggle > .lr-comic-tip-wrap { flex: 1; justify-content: center; }
.lr-toggle > .lr-comic-tip-wrap > button { width: 100%; }
@@ -1103,8 +1094,8 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
transition: transform 280ms var(--spring), background 200ms ease;
}
.lr-switch:active::after { transform: scaleX(1.18); }
-.lr-switch[aria-checked="true"] { background: var(--live); border-color: var(--live); }
-.lr-switch[aria-checked="true"]::after { transform: translateX(24px); background: #fff; }
+.lr-switch[aria-checked="true"] { background: var(--action-deep); border-color: var(--action-deep); }
+.lr-switch[aria-checked="true"]::after { transform: translateX(24px); background: var(--action-ink); }
.lr-switch[aria-checked="true"]:active::after { transform: translateX(24px) scaleX(1.18); }
/* sliders */
@@ -1126,8 +1117,8 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334
color: var(--ink);
box-shadow: var(--control-shadow);
}
-.lr-tiles .lr-tile small { max-width: 100%; font-family: var(--mono); font-size: 11px; letter-spacing: .02em; color: #5d7086; text-wrap: balance; overflow-wrap: normal; }
-.lr-tiles .lr-tile.is-selected small { color: var(--paper); opacity: .75; }
+.lr-tiles .lr-tile small { max-width: 100%; font-family: var(--mono); font-size: 11px; letter-spacing: .02em; color: var(--muted); text-wrap: balance; overflow-wrap: normal; }
+.lr-tiles .lr-tile.is-selected small { color: var(--control-selected-ink); }
/* text inputs */
.lr-input {
@@ -1283,11 +1274,10 @@ html[data-theme="dark"] .lr-pill.is-good { background: #14291d; }
font-weight: 700;
letter-spacing: .02em;
}
-.lr-meter-cell svg { color: #53676a; }
-html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
+.lr-meter-cell svg { color: var(--muted); }
.lr-meter-text { display: grid; line-height: 1.18; }
.lr-meter-text small { font-size: 9.5px; font-weight: 600; color: var(--muted); }
-.lr-meter-tag { display: inline-flex; align-items: center; padding: 9px 2px 9px 0; color: #53676a; }
+.lr-meter-tag { display: inline-flex; align-items: center; padding: 9px 2px 9px 0; color: var(--muted); }
.lr-meter-tag .lr-cap { margin-left: 6px; font-size: 12px; }
.lr-metrics-more { min-width: 40px; height: 40px; padding: 0 10px; }
.lr-metrics-more svg { transition: transform 160ms ease; }
@@ -1314,10 +1304,10 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
border-radius: 12px;
background: var(--paper);
color: var(--ink);
- transition: transform 120ms var(--spring), background 120ms ease;
+ transition: var(--control-motion), background 120ms ease;
}
-.lr-pawn-detail-close:hover { background: var(--wall-2); }
-.lr-pawn-detail-close:active { transform: scale(.9); }
+.lr-pawn-detail-close:is(:hover, :focus-visible) { background: var(--wall-2); transform: var(--control-hover-transform); }
+.lr-pawn-detail-close:active { transform: var(--control-press-transform); transition-duration: 80ms; }
/* ---------- topology tree ---------- */
@@ -1485,7 +1475,7 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
display: grid;
gap: 16px;
padding: 16px;
- border: 2.5px dashed #9db3a7;
+ border: 2.5px dashed var(--control-edge);
border-radius: var(--radius);
}
.lr-door { display: grid; }
@@ -1529,21 +1519,21 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
.lr-client-launch-title { font-size: 36px; line-height: 1.1; letter-spacing: -.04em; }
.lr-client-launch-title small { margin-left: 6px; color: var(--muted); font-size: 15px; letter-spacing: 0; font-weight: 650; }
.lr-client-brand-dot { color: #e77d38; }
-.lr-client-standby { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; width: 100%; padding: 12px 20px 16px; border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 22px; background: var(--paper); }
+.lr-client-standby { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; width: 100%; padding: 12px 20px 16px; border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 22px; background: var(--surface-glaze) var(--paper); box-shadow: var(--control-shadow); }
.lr-client-standby-state { display: inline-flex; align-items: center; gap: 9px; }
.lr-client-standby strong { font-size: 14px; }
.lr-client-standby p { margin: 0; color: var(--muted); font-size: 12px; line-height: 1.65; }
-.lr-client-connect-guide > summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 40px; border-radius: 8px; cursor: pointer; list-style: none; }
+.lr-client-connect-guide > summary { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; min-height: 40px; border-radius: 8px; cursor: pointer; list-style: none; }
.lr-client-connect-guide > summary::-webkit-details-marker { display: none; }
-.lr-client-connect-toggle { display: inline-flex; align-items: center; gap: 5px; color: var(--muted); font-size: 12px; }
+.lr-client-connect-toggle { display: inline-flex; align-items: center; gap: 5px; margin-inline-start: auto; color: var(--muted); font-size: 12px; }
.lr-client-connect-guide > summary:is(:hover, :focus-visible) .lr-client-connect-toggle { color: var(--ink); }
.lr-client-connect-toggle > svg:last-child { transition: transform 180ms var(--spring); }
.lr-client-connect-guide[open] .lr-client-connect-toggle > svg:last-child { transform: rotate(180deg); }
.lr-client-connect-steps { padding: 4px 0 8px; }
-.lr-client-approved-site { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; min-width: 0; }
-.lr-client-approved-site a { display: flex; flex: 1; align-items: baseline; gap: 4px; min-width: 0; overflow-wrap: anywhere; color: var(--ink); font: 12px/1.6 var(--mono); text-underline-offset: 3px; }
+.lr-client-approved-site { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
+.lr-client-approved-site a { display: flex; flex: 1 1 auto; align-items: baseline; gap: 4px; min-width: 0; overflow-wrap: anywhere; color: var(--ink); font: 12px/1.6 var(--mono); text-underline-offset: 3px; }
.lr-client-approved-site a > span { flex: none; }
-.lr-client-site-actions { display: flex; flex: none; align-items: center; gap: 8px; }
+.lr-client-site-actions { display: flex; flex: none; align-items: center; gap: 8px; margin-inline-start: auto; }
.lr-client-approved-site .lr-btn { min-width: 32px; width: 32px; height: 32px; padding: 0; }
.lr-client-launch-section { justify-self: start; margin: 5px 0 -8px; font-size: 13px; font-weight: 700; color: var(--muted); }
.lr-client-approval {
@@ -1565,6 +1555,10 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
.lr-client-approval-origin > strong { flex: 1; min-width: 0; font-weight: 650; }
.lr-client-approval-origin > .lr-client-approval-check { color: var(--live); }
.lr-client-approval p.lr-client-approval-replace { padding-top: 12px; border-top: 1px solid color-mix(in srgb, var(--ink) 15%, transparent); font-size: 12px; }
+.lr-client-approval-startup { display: flex; align-items: center; gap: 8px; min-height: 40px; font-size: 13px; line-height: 1.5; cursor: pointer; }
+.lr-client-approval-startup input { width: 18px; height: 18px; margin: 0 2px 0 0; flex: none; accent-color: var(--action); }
+.lr-client-approval-startup > svg { flex: none; }
+.lr-client-approval-startup:has(:disabled) { opacity: .5; cursor: default; }
.lr-client-approval-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.lr-client-approval-actions > :only-child { grid-column: 1 / -1; }
.lr-client-approval-actions > .lr-comic-tip-wrap { min-width: 0; }
@@ -1572,15 +1566,15 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
.lr-client-footer { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 8px clamp(16px, 4vw, 44px) 16px; color: var(--muted); font-size: 11.5px; }
.lr-client-footer .lr-btn { min-width: 44px; height: 36px; padding: 0 10px; border-color: transparent; background: transparent; box-shadow: none; color: inherit; font-size: 12px; text-decoration: none; }
.lr-client-version { overflow-wrap: anywhere; text-align: right; }
-.lr-client-project-links { display: flex; justify-content: center; flex-wrap: wrap; gap: 0 20px; }
-.lr-client-project-links a { display: inline-flex; align-items: center; gap: 4px; min-height: 36px; color: inherit; text-underline-offset: 3px; }
-.lr-client-project-links a:is(:hover, :focus-visible) { color: var(--ink); }
.lr-client-launch-status { color: var(--ink); font-size: 14px; font-weight: 650; }
+.lr-client-launch-technical { width: 100%; min-width: 0; color: var(--muted); font-size: 13px; text-align: start; }
+.lr-client-launch-technical > summary { width: fit-content; cursor: pointer; }
+.lr-client-launch-technical > summary:focus-visible { outline: 2px solid var(--action); outline-offset: 4px; border-radius: 3px; }
.lr-client-launch-detail { max-width: 100%; overflow-wrap: anywhere; white-space: pre-wrap; font: 13px/1.6 var(--mono); }
.lr-client-release { display: grid; justify-items: center; gap: 6px; max-width: 100%; }
-.lr-client-release .lr-client-project-links { flex-direction: column; align-items: center; gap: 4px; font-size: 12.5px; }
-.lr-client-release-links { display: flex; justify-content: center; flex-wrap: wrap; gap: 4px 20px; }
-.lr-client-release-warning { max-width: 42ch; color: var(--muted); font-size: 12px; line-height: 1.6; text-align: center; }
+.lr-client-release-mirror { display: inline-flex; align-items: center; gap: 4px; min-height: 28px; color: var(--muted); font-size: 12px; text-underline-offset: 3px; }
+.lr-client-release-mirror:is(:hover, :focus-visible) { color: var(--ink); }
+.lr-client-release-warning { max-width: 42ch; color: var(--muted); font-size: 12px; line-height: 1.6; text-align: center; text-underline-offset: 3px; }
.lr-client-update {
gap: 7px;
min-width: 0;
@@ -1681,7 +1675,7 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
font-weight: 700;
transition: border-color 120ms ease, transform 160ms var(--spring), box-shadow 160ms ease;
}
-.lr-dial.is-active { border-color: var(--action); transform: translateY(-4px); box-shadow: 0 6px 0 -2px rgba(47, 111, 237, .2); }
+.lr-dial.is-active { border-color: var(--action); transform: translateY(-4px); box-shadow: 0 6px 0 -2px color-mix(in srgb, var(--action) 20%, transparent); }
.lr-dial.is-filled { background: var(--ink); color: var(--paper); animation: lr-pop .18s ease; }
.lr-dials-wrap input {
position: absolute;
@@ -1694,16 +1688,15 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }
display: grid;
width: 68px; height: 68px;
place-items: center;
- border: 3px solid var(--action);
+ border: 3px solid var(--primary);
border-radius: 50%;
- background: var(--action);
- color: #fff;
- transition: transform 140ms var(--spring), background 160ms ease;
+ background: var(--primary);
+ color: var(--primary-ink);
+ transition: var(--control-motion), background 160ms ease;
}
-.lr-join-go:hover:not(:disabled) { background: var(--action-deep); transform: scale(1.05); }
-.lr-join-go:active:not(:disabled) { transform: scale(.92); }
-.lr-join-go:disabled { background: var(--wall-2); border-color: transparent; color: #9db3a7; opacity: 1; }
-html[data-theme="dark"] .lr-join-go:disabled { background: #1a2634; color: #48607a; }
+.lr-join-go:is(:hover, :focus-visible):not(:disabled) { border-color: color-mix(in srgb, var(--primary) 88%, #000); background: color-mix(in srgb, var(--primary) 88%, #000); transform: var(--control-hover-transform); }
+.lr-join-go:active:not(:disabled) { transform: var(--control-press-transform); transition-duration: 80ms; }
+.lr-join-go:disabled { background: var(--wall-2); border-color: transparent; color: var(--muted); opacity: 1; }
.lr-access-text {
display: grid;
@@ -1762,23 +1755,6 @@ html[data-theme="dark"] .lr-join-go:disabled { background: #1a2634; color: #4860
.lr-spin { animation: lr-rotate .9s linear infinite; }
@keyframes lr-rotate { to { transform: rotate(360deg); } }
-/* ---------- dark theme refinements ---------- */
-
-html[data-theme="dark"] .lr-btn.is-on { background: var(--ink); color: #22303e; }
-html[data-theme="dark"] .lr-btn.is-danger:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: #3d2626; }
-html[data-theme="dark"] .lr-chip:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-selected),
-html[data-theme="dark"] .lr-tile:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-selected) { background: #2b3d4f; }
-html[data-theme="dark"] .lr-chip.is-selected,
-html[data-theme="dark"] .lr-tile.is-selected { background: var(--ink); color: #22303e; }
-html[data-theme="dark"] .lr-row.is-sub { background: #1a2634; }
-html[data-theme="dark"] .lr-meter-cell { background: #1a2634; }
-html[data-theme="dark"] .lr-meter-tag { color: #7d92a8; }
-html[data-theme="dark"] .lr-door-body { border-color: #33465c; }
-html[data-theme="dark"] .lr-pawn-name { background: #0e1620; box-shadow: none; }
-html[data-theme="dark"] .lr-couch-empty { color: #54708c; }
-html[data-theme="dark"] .lr-switch { background: #0e1620; }
-html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
-
/* ---------- responsive ---------- */
@media (max-width: 640px) {
@@ -1869,14 +1845,15 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-stage-notices:empty { display: none; }
.lr-sharing-settings { width: min(820px, 100%); margin: 0 auto; container: sharing-settings / inline-size; }
.lr-sharing-panel {
- margin-top: 14px; padding: 24px; background: var(--paper);
- border: 1px solid var(--control-edge); border-radius: 24px; box-shadow: var(--control-shadow);
+ margin-top: 14px; padding: 24px; background: var(--surface-glaze) var(--paper);
+ border: 1px solid var(--control-edge); border-radius: 24px; box-shadow: var(--panel-shadow);
animation: lr-sharing-enter 180ms ease-out;
}
.lr-sharing-section { display: grid; align-content: start; gap: 20px; min-width: 0; }
-.lr-sharing-section + .lr-sharing-section { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--wall-2); }
-.lr-sharing-section h2 { display: flex; align-items: center; gap: 8px; font-size: 16px; }
-.lr-sharing-section h2 .lr-cap { font-size: inherit; }
+.lr-sharing-section[hidden] { display: none; }
+.lr-sharing-tabs { display: grid; width: fit-content; margin: 0 auto 22px; }
+.lr-sharing-tabs > button { min-width: 112px; gap: 8px; }
+.lr-sharing-section:focus-visible { outline: 2px solid var(--action); outline-offset: 5px; border-radius: 12px; }
.lr-sharing-section .lr-door-group { gap: 8px; }
.lr-sharing-section .lr-door-glyph .lr-cap { white-space: normal; }
.lr-sharing-limits { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; }
@@ -1893,6 +1870,7 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-sharing-audio-controls { display: grid; gap: 20px; min-width: 0; }
.lr-sharing-audio-controls:has(> .lr-source-audio-settings):has(> .lr-microphone-settings) { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.lr-sharing-audio-controls > .lr-audio-quality { grid-column: 1 / -1; }
+.lr-sharing-audio-controls > .lr-audio-quality:not(:first-child) { padding-top: 18px; border-top: 1px solid var(--wall-2); }
.lr-sharing-panel .lr-microphone-settings { max-width: none; }
.lr-sharing-panel input[type="range"] { appearance: none; background: transparent; }
.lr-sharing-panel input[type="range"]:disabled { opacity: .55; cursor: default; }
@@ -1902,22 +1880,30 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-sharing-panel input[type="range"]::-moz-range-thumb { width: 14px; height: 14px; border: 3px solid var(--paper); border-radius: 50%; background: var(--action); box-shadow: 0 0 0 1px var(--action); transition: transform 180ms var(--spring); }
.lr-sharing-panel input[type="range"]:is(:hover, :focus-visible):not(:disabled)::-webkit-slider-thumb { transform: scale(1.1); }
.lr-sharing-panel input[type="range"]:is(:hover, :focus-visible):not(:disabled)::-moz-range-thumb { transform: scale(1.1); }
-.lr-sharing-technical { margin-top: 20px; padding-top: 12px; border-top: 1px solid var(--wall-2); }
-.lr-sharing-technical > summary { padding: 10px 8px; border-radius: 12px; color: var(--muted); cursor: pointer; font-size: 12px; transition: color 140ms ease, background-color 140ms ease; }
-.lr-sharing-technical > summary:is(:hover, :focus-visible) { color: var(--ink); background: var(--control-hover); }
-.lr-sharing-technical > summary > svg { vertical-align: middle; margin-inline-end: 6px; }
-.lr-sharing-technical > div { display: grid; gap: 18px; padding-top: 16px; }
-.lr-sharing-technical .lr-row-group:has(.lr-switch-item) { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
-.lr-sharing-technical .lr-switch-item .lr-cap { white-space: normal; }
+.lr-sharing-connection { margin-top: 20px; padding-top: 12px; border-top: 1px solid var(--wall-2); }
+:is(.lr-sharing-picture-details, .lr-sharing-connection) > summary { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 12px; padding: 10px 8px; border-radius: 12px; color: var(--muted); cursor: pointer; list-style: none; font-size: 12px; transition: color 140ms ease, background-color 140ms ease; }
+:is(.lr-sharing-picture-details, .lr-sharing-connection) > summary::-webkit-details-marker { display: none; }
+:is(.lr-sharing-picture-details, .lr-sharing-connection) > summary:is(:hover, :focus-visible) { color: var(--ink); background: var(--control-hover); }
+:is(.lr-sharing-picture-details, .lr-sharing-connection) > summary > span:first-child { display: inline-flex; align-items: center; gap: 6px; }
+.lr-sharing-chevron { grid-column: -2; transition: transform 180ms ease; }
+details[open] > summary > .lr-sharing-chevron { transform: rotate(180deg); }
+.lr-sharing-picture-summary { display: flex; justify-content: end; flex-wrap: wrap; gap: 4px 12px; font: 11px/1.5 var(--mono); font-variant-numeric: tabular-nums; }
+.lr-sharing-picture-summary > span { white-space: nowrap; }
+:is(.lr-sharing-picture-details, .lr-sharing-connection) > div { display: grid; gap: 20px; padding-top: 16px; }
+.lr-sharing-connection .lr-row-group:has(.lr-switch-item) { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
+.lr-sharing-connection .lr-switch-item .lr-cap { white-space: normal; }
@keyframes lr-sharing-enter { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }
-@media (prefers-reduced-motion: reduce) { .lr-sharing-panel { animation: none; } }
+@media (prefers-reduced-motion: reduce) { .lr-sharing-panel { animation: none; } .lr-sharing-chevron { transition: none; } }
@container sharing-settings (max-width: 600px) {
.lr-sharing-panel { padding: 16px; border-radius: 20px; }
.lr-sharing-limits, .lr-sharing-audio-controls:has(> .lr-source-audio-settings):has(> .lr-microphone-settings),
- .lr-sharing-technical .lr-row-group:has(.lr-switch-item) { grid-template-columns: 1fr; gap: 20px; }
+ .lr-sharing-connection .lr-row-group:has(.lr-switch-item) { grid-template-columns: 1fr; gap: 20px; }
.lr-sharing-section .lr-tiles { gap: 8px; }
.lr-sharing-section .lr-tile { padding: 10px 4px; }
.lr-sharing-section .lr-tile strong { font-size: 12px; }
+ .lr-sharing-picture-details > summary { grid-template-columns: minmax(0, 1fr) auto; gap: 6px 12px; }
+ .lr-sharing-picture-details .lr-sharing-chevron { grid-column: 2; grid-row: 1; }
+ .lr-sharing-picture-summary { grid-column: 1 / -1; grid-row: 2; justify-content: start; }
.lr-resolution-controls > .lr-row-group { gap: 5px; }
.lr-resolution-controls .lr-chip { padding-inline: 3px; font-size: 12px; letter-spacing: 0; }
}
@@ -1929,13 +1915,17 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
@container sharing-settings (max-width: 340px) {
.lr-sharing-section .lr-tile small { max-width: 8ch; min-height: 2.8em; line-height: 1.4; }
}
+.lr-host-controls { width: 100%; margin-top: 12px; container: host-controls / inline-size; }
.lr-host-share-controls {
- display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 4px;
- width: fit-content; max-width: 100%; margin: 12px auto 0; padding: 6px;
- background: var(--paper); color: var(--ink); border: 1px solid var(--control-edge);
+ display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px;
+ width: fit-content; max-width: 100%; margin: 0 auto; padding: 6px; color: var(--ink);
+ background: var(--surface-glaze) var(--paper); border: 1px solid var(--control-edge);
border-radius: 20px; box-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 8%, transparent);
}
-.lr-host-share-controls > .lr-comic-tip-wrap:has(#host-stop-share) { margin-inline-start: 4px; padding-inline-start: 8px; border-inline-start: 1px solid var(--control-edge); }
+.lr-host-action-dock, .lr-host-tool-dock { display: flex; align-items: center; gap: 4px; }
+.lr-host-action-dock + .lr-host-tool-dock { padding-inline-start: 8px; border-inline-start: 1px solid var(--control-edge); }
+.lr-host-control-group { display: flex; align-items: center; gap: 4px; }
+.lr-host-control-group + .lr-host-control-group { padding-inline-start: 4px; }
.lr-microphone-settings { min-width: 0; max-width: 440px; gap: 6px; }
.lr-microphone-settings .lr-capture-device { padding: 0; }
.lr-source-audio-settings .lr-capture-device { padding: 0; }
@@ -1961,13 +1951,20 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }
.lr-capture-device select:disabled { opacity: .55; cursor: default; }
.lr-capture-device small, .lr-microphone-settings > small { color: var(--muted); font-size: 11px; line-height: 1.5; }
.lr-source-picker-body > .lr-capture-device { margin-bottom: 10px; }
-.lr-source-picker .lr-capture-device :is(label, small) { color: #9aa8bb; }
-@media (max-width: 580px) {
- .lr-host-share-controls { gap: 2px; }
+@container host-controls (max-width: 920px) {
+ .lr-host-share-controls { gap: 4px; }
+ .lr-host-action-dock, .lr-host-tool-dock { gap: 2px; }
+ .lr-host-action-dock + .lr-host-tool-dock { padding-inline-start: 4px; }
+ .lr-host-control-group { gap: 2px; }
+ .lr-host-control-group + .lr-host-control-group { padding-inline-start: 4px; }
.lr-host-share-controls .lr-btn { width: 44px; padding: 0; }
.lr-host-share-controls .lr-cap { display: none; }
- .lr-host-share-controls .lr-btn[aria-controls] { width: auto; min-width: 44px; height: auto; min-height: 44px; grid-auto-flow: row; gap: 2px; padding: 4px 8px; }
- .lr-host-share-controls .lr-btn[aria-controls] .lr-cap { display: inline; max-width: 9ch; white-space: normal; font-size: 11px; line-height: 1.3; text-align: center; }
+}
+@container host-controls (max-width: 340px) {
+ .lr-host-share-controls { gap: 4px; padding: 4px; }
+ .lr-host-action-dock, .lr-host-tool-dock { gap: 0; }
+ .lr-host-control-group { gap: 0; }
+ .lr-host-control-group + .lr-host-control-group { padding-inline-start: 2px; }
}
.lr-room.is-theater .lr-stage-notices {
position: absolute;
@@ -2229,8 +2226,6 @@ svg[data-comic-motion="still"] .lr-person-eyes > ellipse {
html[data-theme="dark"] .lr-pill { color: #e8a33d; }
html[data-theme="dark"] .lr-pill.is-bad { color: #e88a85; }
html[data-theme="dark"] .lr-pill.is-good { color: #63c78a; }
-/* Dark-mode preset tiles: lift the unselected caption off the tile fill. */
-html[data-theme="dark"] .lr-tiles .lr-tile:not(.is-selected) small { color: #8ba0b4; }
@media (max-width: 640px) {
/* Pawn drill-down: the shared .lr-row column stack breaks this card —
diff --git a/src/client/ui/icons.tsx b/src/client/ui/icons.tsx
index 4e5ac25b..8c5cbba2 100644
--- a/src/client/ui/icons.tsx
+++ b/src/client/ui/icons.tsx
@@ -10,6 +10,11 @@ import { useEffect, useRef, type ReactNode } from "react";
import { bindSvgReplayOnPointerEnter } from "./animation";
const PATHS = {
+ fitContain: { body: (<><rect pathLength={1} x="2" y="3" width="20" height="18" rx="2"/><path pathLength={1} d="M2 7h20M2 17h20m-15-5h10"/></>) },
+ fitCover: { body: (<><rect pathLength={1} x="2" y="3" width="20" height="18" rx="2"/><path pathLength={1} d="M7 3v18M17 3v18m-7-9h4"/></>) },
+ fitStretch: { body: (<><rect pathLength={1} x="2" y="3" width="20" height="18" rx="2"/><path pathLength={1} d="M6 12h12M9 9l-3 3 3 3m6-6 3 3-3 3"/></>) },
+ keyboard: { body: (<><rect pathLength={1} x="2" y="5" width="20" height="14" rx="3"/><path pathLength={1} d="M6 9h.01M10 9h.01M14 9h.01M18 9h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M7 16h10"/></>) },
+ mouse: { body: (<><rect pathLength={1} x="6" y="2" width="12" height="20" rx="6"/><path pathLength={1} d="M12 2v7M6 10h12"/></>) },
star: { body: <path pathLength={1} d="m12 3 2.8 5.7 6.3.9-4.5 4.4 1.1 6.3-5.7-3-5.7 3 1.1-6.3L3.1 9.6l6.3-.9Z" /> },
textSize: { body: (<><path pathLength={1} d="m2 18 4-9 4 9m-6.5-3h5M12 18l5-13 5 13m-8-4h6"/></>) },
opacity: { body: (<><circle pathLength={1} cx="12" cy="12" r="9"/><path pathLength={1} d="M12 3a9 9 0 0 1 0 18Z" fill="currentColor" opacity=".4"/></>) },
@@ -45,7 +50,6 @@ const PATHS = {
network: { body: (<><rect pathLength={1} x="9" y="2" width="6" height="6" rx="1.5"/><rect pathLength={1} x="2" y="16" width="6" height="6" rx="1.5"/><rect pathLength={1} x="16" y="16" width="6" height="6" rx="1.5"/><path pathLength={1} d="M12 8v3.5M12 11.5 5.5 16M12 11.5l6.5 4.5"/></>) },
chevron: { body: (<><path pathLength={1} d="m6 9 6 6 6-6"/></>) },
grip: { body: (<><path pathLength={1} d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" strokeWidth="3"/></>) },
- move: { body: (<><path pathLength={1} d="M12 3v18M3 12h18M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3"/></>) },
loader: { body: (<><path pathLength={1} d="M21 12a9 9 0 1 1-6.22-8.56"/></>) },
alert: { body: (<><path pathLength={1} d="M12 3.5 2.8 19.5a1 1 0 0 0 .87 1.5h16.66a1 1 0 0 0 .87-1.5L12 3.5Z"/><path pathLength={1} d="M12 10v4.5"/><path pathLength={1} d="M12 17.8h.01"/></>) },
wifiOff: { body: (<><path pathLength={1} d="m2 2 20 20"/><path pathLength={1} d="M8.5 16.5a5 5 0 0 1 7 0"/><path pathLength={1} d="M5 12.9a11 11 0 0 1 3.1-2.2M15.9 11.4a11 11 0 0 1 3.1 1.5"/><path pathLength={1} d="M1.5 8.8A16 16 0 0 1 8 5.4m8 .2a16 16 0 0 1 6.5 3.2"/><path pathLength={1} d="M12 20h.01"/></>) },
diff --git a/src/client/ui/palette.css b/src/client/ui/palette.css
new file mode 100644
index 00000000..3ba9215d
--- /dev/null
+++ b/src/client/ui/palette.css
@@ -0,0 +1,53 @@
+/* Shared surfaces for the App, website and documentation. Illustrations and
+ semantic status colours keep their own roles. Theme selection stays local. */
+:root {
+ --wall: #f3f5f8;
+ --wall-2: #e5eaf2;
+ --paper: #fffefb;
+ --ink: #29374a;
+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));
+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));
+ /* Primary actions keep their identity; selection/focus follows the theme. */
+ --primary: #2765ce;
+ --primary-ink: #fff;
+ --action: #3478e5;
+ --action-deep: var(--primary);
+ --action-ink: var(--primary-ink);
+ --action-text: #2055b2;
+ --control-hover: #eef3ff;
+ --control-selected: #e5efff;
+ --control-selected-ink: #214c9b;
+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));
+ --surface-rim: rgb(255 255 255 / .95);
+ --surface-shade: rgb(36 53 78 / .18);
+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));
+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);
+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);
+ --piik-dark-wall: #242a34;
+ --piik-dark-wall-2: #2c3543;
+ --piik-dark-paper: #354153;
+ --piik-dark-ink: #f6f3eb;
+ --piik-dark-action: #f6f3eb;
+ --piik-dark-action-ink: #29374a;
+ --piik-dark-action-text: var(--piik-dark-action);
+ --piik-dark-hover: #414f67;
+ --piik-dark-selected: var(--piik-dark-action);
+ --piik-dark-selected-ink: var(--piik-dark-action-ink);
+}
+:root[data-theme="dark"], :root.dark {
+ --wall: var(--piik-dark-wall);
+ --wall-2: var(--piik-dark-wall-2);
+ --paper: var(--piik-dark-paper);
+ --ink: var(--piik-dark-ink);
+ --action: var(--piik-dark-action);
+ --action-deep: var(--piik-dark-action);
+ --action-ink: var(--piik-dark-action-ink);
+ --action-text: var(--piik-dark-action-text);
+ --control-hover: var(--piik-dark-hover);
+ --control-selected: var(--piik-dark-selected);
+ --control-selected-ink: var(--piik-dark-selected-ink);
+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));
+ --surface-rim: rgb(222 234 255 / .12);
+ --surface-shade: rgb(6 12 22 / .38);
+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));
+}
diff --git a/src/client/ui/panel-window.ts b/src/client/ui/panel-window.ts
index cccdd194..44f0b5ca 100644
--- a/src/client/ui/panel-window.ts
+++ b/src/client/ui/panel-window.ts
@@ -1,24 +1,64 @@
-import { createContext, useContext } from "react";
+import { createContext, useContext, useLayoutEffect, useRef, useState } from "react";
// Geometry, focus and visibility follow the document displaying a surface.
// Its React tree and domain state continue to belong to the original page.
export const SurfaceDocument = createContext<Document | null>(null);
export const useSurfaceDocument = () => useContext(SurfaceDocument) ?? (typeof document === "undefined" ? null : document);
-type PictureInPicture = { requestWindow(options: { width: number; height: number }): Promise<Window> };
+type PictureInPicture = { requestWindow(options: { width: number; height: number; preferInitialWindowPlacement: boolean }): Promise<Window> };
export function panelWindowAPI(view: Window | null) {
return view && view === view.top && view.isSecureContext
? (view as Window & { documentPictureInPicture?: PictureInPicture }).documentPictureInPicture
: undefined;
}
+/** One portal target survives adoption; the containing room owns its retirement. */
+export function usePanelWindow(enabled: boolean, onDocument?: (owner: Document) => void) {
+ const [container] = useState(() => {
+ if (!enabled || typeof document === "undefined") return null;
+ const node = document.createElement("div");
+ node.style.display = "contents";
+ return node;
+ });
+ const slot = useRef<HTMLSpanElement>(null);
+ const lifetime = useRef<AbortController | null>(null);
+ const [surfaceDocument, setSurfaceDocument] = useState<Document | null>(null);
+ const [opening, setOpening] = useState(false);
+ const [failed, setFailed] = useState(false);
+ useLayoutEffect(() => {
+ if (!container || !slot.current) return;
+ slot.current.append(container);
+ return () => { lifetime.current?.abort(); container.remove(); };
+ }, [container]);
+ async function open() {
+ if (!container || opening) return;
+ const controller = new AbortController();
+ lifetime.current = controller;
+ setOpening(true); setFailed(false);
+ try {
+ await openPanelWindow(container, controller.signal, owner => {
+ setSurfaceDocument(owner); onDocument?.(owner);
+ });
+ } catch { if (!controller.signal.aborted) setFailed(true); }
+ finally { if (!controller.signal.aborted) setOpening(false); }
+ }
+ function close() {
+ lifetime.current?.abort();
+ setOpening(false); setFailed(false);
+ }
+ return { container, slot, surfaceDocument, opening, failed, open, close,
+ detached: Boolean(surfaceDocument && surfaceDocument !== document) };
+}
+
/** Adopt one stable portal, then return it on close. No second React root/session. */
export async function openPanelWindow(container: HTMLElement, signal: AbortSignal, onDocument: (document: Document) => void) {
const home = container.ownerDocument;
const parent = container.parentElement;
const api = panelWindowAPI(home.defaultView);
if (!api || !parent || signal.aborted) return;
- const pip = await api.requestWindow({ width: 360, height: 480 });
+ // The portal wrapper uses display: contents; its child owns visible geometry.
+ const { width, height } = container.firstElementChild!.getBoundingClientRect();
+ const pip = await api.requestWindow({ width: Math.round(width), height: Math.round(height), preferInitialWindowPlacement: true });
// Room retirement can beat the browser's permission/window creation work.
if (signal.aborted || !container.isConnected) { pip.close(); return; }
let returned = false;
diff --git a/src/client/ui/popover-polyfill.ts b/src/client/ui/popover-polyfill.ts
new file mode 100644
index 00000000..f25c0ece
--- /dev/null
+++ b/src/client/ui/popover-polyfill.ts
@@ -0,0 +1,14 @@
+import "@oddbird/popover-polyfill";
+
+// Native Escape dismissal follows event dispatch; the polyfill closes auto
+// popovers in its document listener. Mark that key as consumed before outer
+// panels/theater handle it, without taking over the polyfill's dismissal.
+const dismissals = new WeakSet<KeyboardEvent>();
+document.addEventListener("keydown", event => {
+ if (event.key !== "Escape" || !document.querySelector('[popover="auto"]:popover-open')) return;
+ if (event.isComposing) event.preventDefault();
+ else dismissals.add(event);
+}, true);
+document.addEventListener("keydown", event => {
+ if (dismissals.has(event)) event.preventDefault();
+});
diff --git a/src/client/ui/tab-navigation.ts b/src/client/ui/tab-navigation.ts
new file mode 100644
index 00000000..5760c335
--- /dev/null
+++ b/src/client/ui/tab-navigation.ts
@@ -0,0 +1,17 @@
+import type { KeyboardEvent } from "react";
+
+// Small, immediately available content pages share automatic tab activation.
+// Selection and panel lifetime stay with the component that owns the content.
+export function navigateTabs(event: KeyboardEvent<HTMLElement>): void {
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
+ const tabs = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]:not(:disabled)'));
+ const current = tabs.indexOf(event.target as HTMLButtonElement);
+ if (current < 0) return;
+ const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1
+ : event.key === "ArrowRight" ? (current + 1) % tabs.length
+ : event.key === "ArrowLeft" ? (current + tabs.length - 1) % tabs.length : -1;
+ if (next < 0) return;
+ event.preventDefault();
+ tabs[next].focus();
+ tabs[next].click();
+}
diff --git a/src/client/ui/visual-kinds.ts b/src/client/ui/visual-kinds.ts
index beace820..df741dbf 100644
--- a/src/client/ui/visual-kinds.ts
+++ b/src/client/ui/visual-kinds.ts
@@ -105,6 +105,9 @@ export type Set4Kind =
| "hint-client-site";
export type PlaybackHintKind =
+ | "hint-fit-contain"
+ | "hint-fit-cover"
+ | "hint-fit-fill"
| "hint-local-play"
| "hint-local-pause"
| "hint-volume"
@@ -144,14 +147,23 @@ export type MetricHintKind = `hint-metric-${
}`;
export type InteractionHintKind =
+ | "hint-reaction-picker"
| "hint-chat-open"
| "hint-chat-send"
| "hint-chat-settings"
| "hint-chat-export"
- | "hint-chat-detach"
+ | "hint-window-detach"
| "hint-chat-overlay-show"
| "hint-chat-overlay-hide";
+export type RemoteHintKind =
+ | "hint-remote-keyboard"
+ | "hint-key-combination"
+ | "hint-remote-control"
+ | "hint-remote-stop"
+ | "hint-remote-mouse-lock"
+ | "hint-remote-mouse-release";
+
export type HintKind =
| Set1Kind
| Set2Kind
@@ -161,6 +173,7 @@ export type HintKind =
| PlaybackHintKind
| MetricHintKind
| InteractionHintKind
+ | RemoteHintKind
| ControlHintKind;
export type ComicTheme = "stage" | "paper";
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index 057ac02a..e21bc8ca 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -1,4 +1,5 @@
import type { CopyKey } from "../ui/copy";
+import { INPUT_CHANNEL } from "../remote-control/input-route";
import type { IceConfig, SignalPayload } from "../../shared/protocol";
import { createOpaqueId } from "../lib/opaque-id";
import { waitForConnectionOperation } from "./connection-operation";
@@ -52,6 +53,7 @@ type PeerIceConfig = Pick<RTCConfiguration, "iceServers"> & {
export interface HostPeerEvents {
sendSignal: (peerId: string, payload: SignalPayload) => boolean;
onUpdate: (snapshot: PeerSnapshot) => void;
+ onInputChannel?: (channel: RTCDataChannel, connection: RTCPeerConnection) => void;
}
/** Common lifecycle contract for Browser and native Host direct edges. */
@@ -144,6 +146,7 @@ export class HostPeer {
iceConfig.natPredictionStunUrls,
),
});
+ if (events.onInputChannel) events.onInputChannel(this.connection.createDataChannel(INPUT_CHANNEL), this.connection);
} catch (error) {
stopSenderVideoTrack(this.senderVideoTrack);
throw error;
diff --git a/src/client/webrtc/remote-input-channel.ts b/src/client/webrtc/remote-input-channel.ts
new file mode 100644
index 00000000..7104e3bf
--- /dev/null
+++ b/src/client/webrtc/remote-input-channel.ts
@@ -0,0 +1,42 @@
+import { INPUT_CHANNEL } from "../remote-control/input-route";
+// Both Browser reception and the App's local playback bridge announce the
+// same optional capability. Their media owner still owns the PeerConnection.
+export class RemoteInputChannel {
+ private channel: RTCDataChannel | null = null;
+ private connection: RTCPeerConnection | null = null;
+ get current(): RTCDataChannel | null {
+ return this.connection?.connectionState === "connected" && this.channel?.readyState === "open" ? this.channel : null;
+ }
+
+ constructor(private readonly changed: () => void) {}
+
+ attach(connection: RTCPeerConnection): void {
+ this.dispose();
+ this.connection = connection;
+ connection.addEventListener("connectionstatechange", () => { if (this.connection === connection) this.changed(); });
+ connection.addEventListener("datachannel", ({ channel }) => {
+ if (this.connection !== connection || channel.label !== INPUT_CHANNEL || this.channel) {
+ channel.close();
+ return;
+ }
+ this.channel = channel;
+ channel.addEventListener("open", () => {
+ if (this.channel === channel) this.changed();
+ });
+ channel.addEventListener("close", () => {
+ if (this.channel === channel) {
+ this.channel = null;
+ this.changed();
+ }
+ });
+ if (channel.readyState === "open") this.changed();
+ });
+ }
+
+ dispose(): void {
+ this.connection = null;
+ const channel = this.channel;
+ this.channel = null;
+ channel?.close();
+ }
+}
diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.ts
index dfa55576..0bbda6dd 100644
--- a/src/client/webrtc/viewer-peer.ts
+++ b/src/client/webrtc/viewer-peer.ts
@@ -1,4 +1,5 @@
import type { CopyKey } from "../ui/copy";
+import { RemoteInputChannel } from "./remote-input-channel";
import type { IceConfig, SignalPayload } from "../../shared/protocol";
import { debugError } from "../lib/debug";
import { observeDebugConnection } from "../lib/debug-webrtc";
@@ -68,6 +69,7 @@ export function createViewerRecoveryBudget(): ViewerRecoveryBudget {
}
export interface ViewerMediaPeer {
+ getRemoteInput?(): RTCDataChannel | null;
acceptSignal(parentPeerId: string, payload: SignalPayload): Promise<void>;
updateIceConfig(iceConfig: IceConfig): void;
requestRecovery(rebuild?: boolean): boolean;
@@ -85,6 +87,8 @@ export interface ViewerMediaPeer {
}
export class ViewerPeer implements ViewerMediaPeer {
+ private readonly remoteInput = new RemoteInputChannel(() => this.emit());
+ getRemoteInput(): RTCDataChannel | null { return this.remoteInput.current; }
private connection: RTCPeerConnection | null = null;
private connectionLifetime: AbortController | null = null;
private connectionId: string | null = null;
@@ -300,6 +304,7 @@ export class ViewerPeer implements ViewerMediaPeer {
),
);
this.connection = connection;
+ this.remoteInput.attach(connection);
this.connectionLifetime = new AbortController();
this.localIceCandidates = localIceCandidates;
this.snapshot = {
@@ -729,6 +734,7 @@ export class ViewerPeer implements ViewerMediaPeer {
}
private disposeConnection(): void {
+ this.remoteInput.dispose();
this.clearDisconnectTimer();
this.clearInitialConnectionTimer();
this.clearRecoveryTimer();
diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.ts
index ff8fa84e..929f6e29 100644
--- a/src/client/webrtc/viewer-relay.ts
+++ b/src/client/webrtc/viewer-relay.ts
@@ -21,6 +21,7 @@ import {
import { preferredVideoCodecForTrack } from "./video-codec-preflight";
export interface ViewerRelayEvents {
+ onInputChannel?: (channel: RTCDataChannel, connection: RTCPeerConnection) => void;
sendSignal: (peerId: string, payload: SignalPayload) => boolean;
onUpdate?: (snapshot: PeerSnapshot | null) => void;
onSenderUpdate?: (snapshot: PeerSnapshot, revision: number | null) => void;
@@ -540,6 +541,7 @@ export class ViewerRelay {
): HostMediaPeer {
let peer: HostMediaPeer;
const peerEvents: HostPeerEvents = {
+ onInputChannel: this.events.onInputChannel,
sendSignal: (targetPeerId, payload) =>
!this.disposed &&
(this.peers.get(childPeerId) === peer ||
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index b070100e..c1caa47e 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -222,6 +222,8 @@ export const routePolicySchema = z
})
.strict();
export type RoutePolicy = z.infer<typeof routePolicySchema>;
+export const viewerRoutePreferenceSchema = z.enum(["auto", "p2p", "sfu"]);
+export type ViewerRoutePreference = z.infer<typeof viewerRoutePreferenceSchema>;
export const DEFAULT_ROUTE_POLICY = {
peerOnly: false,
topologyOptimization: true,
@@ -233,7 +235,11 @@ export const runtimeCapabilitiesSchema = z.object({
sfuOnly: z.boolean().optional(),
natPrediction: z.boolean().default(false),
roomInteractions: z.boolean().default(false),
+ roomReactionIds: z.array(z.string().max(32).regex(/^[a-z][a-z0-9-]*$/)).max(64).optional(),
hostRoomSession: z.boolean().default(false),
+ remoteInput: z.boolean().default(false),
+ viewerRouteSelection: z.boolean().default(false),
+ audioPresence: z.boolean().default(false),
});
export type RuntimeCapabilities = z.infer<typeof runtimeCapabilitiesSchema>;
@@ -863,6 +869,7 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
clientId: opaqueIdSchema,
viewerGrant: viewerGrantSchema.optional(),
viewerPassword: viewerPasswordSchema.optional(),
+ routePreference: viewerRoutePreferenceSchema.optional(),
displayName: displayNameSchema.optional(),
viewerPresence: z.literal(true).optional(),
})
@@ -876,6 +883,11 @@ const signalingChallengeSequenceSchema = z
.max(Number.MAX_SAFE_INTEGER);
export const clientMessageSchema = z.union([
+ z.object({ type: z.literal("set-viewer-route-preference"), preference: viewerRoutePreferenceSchema }).strict(),
+ z.object({ type: z.literal("subscribe-audio-presence") }).strict(),
+ z.object({ type: z.literal("set-audio-presence"), shareGeneration: opaqueIdSchema, available: z.boolean() }).strict(),
+ z.object({ type: z.literal("subscribe-remote-input"), endpointId: z.string().regex(/^[0-9a-f]{32}$/).optional(),
+ secret: z.string().regex(/^[0-9a-f]{64}$/).optional() }).strict(),
z.object({ type: z.literal("subscribe-room-interactions") }).strict(),
z.object({ type: z.literal("send-room-interaction"), requestId: opaqueIdSchema,
payload: interactionPayloadSchema }).strict(),
@@ -1053,6 +1065,10 @@ const authenticatedMessageSchema = z.union([
]);
export const serverMessageSchema = z.union([
+ z.object({ type: z.literal("viewer-route-preference"), preference: viewerRoutePreferenceSchema, accepted: z.boolean() }).strict(),
+ z.object({ type: z.literal("audio-presence"), available: z.boolean().nullable() }).strict(),
+ z.object({ type: z.literal("remote-input-peers"), peers: z.array(z.object({ peerId: opaqueIdSchema,
+ endpointId: z.string().regex(/^[0-9a-f]{32}$/), secret: z.string().regex(/^[0-9a-f]{64}$/) }).strict()).max(20) }).strict(),
z.object({ type: z.literal("room-interactions-ready"), serverTime: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER) }).strict(),
z.object({ type: z.literal("room-interaction-rejected"), requestId: opaqueIdSchema,
reason: z.enum(["rate-limited", "target-unavailable", "not-subscribed", "busy"]) }).strict(),
diff --git a/src/shared/room-interactions.ts b/src/shared/room-interactions.ts
index f0131fca..29966b8f 100644
--- a/src/shared/room-interactions.ts
+++ b/src/shared/room-interactions.ts
@@ -2,12 +2,16 @@
export const MAX_CHAT_CODE_POINTS = 280;
export const INTERACTION_INTERVAL_MS = 800;
export const REACTION_DURATION_MS = 2400;
-export const REACTION_IDS = ["wave", "heart", "clap", "laugh", "wow", "party", "fire", "eyes", "star", "sleep", "tomato", "poop"] as const;
+export const REACTION_IDS = ["thumbsup", "thumbsdown", "laugh", "clown", "eyeroll", "eyes", "wow", "wave", "heart", "clap", "party", "fire", "star", "sleep", "tomato", "poop"] as const;
export type ReactionId = typeof REACTION_IDS[number];
+// Published 2.1 Servers predate the optional reaction command registry.
+export const BASELINE_REACTION_IDS: readonly ReactionId[] = ["wave", "heart", "clap", "laugh", "wow", "party", "fire", "eyes", "star", "sleep", "tomato", "poop"];
export const isThrow = (reaction: string) => reaction === "tomato" || reaction === "poop";
export const REACTION_GLYPHS: Record<ReactionId, string> = {
wave: "👋", heart: "❤️", clap: "👏", laugh: "😂", wow: "🤯", party: "🎉",
fire: "🔥", eyes: "👀", star: "⭐", sleep: "😴", tomato: "🍅", poop: "💩",
+ clown: "🤡", eyeroll: "🙄",
+ thumbsup: "👍", thumbsdown: "👎",
};
const forbiddenText = /[\p{Cc}\p{Zl}\p{Zp}\u061c\u200b\u200e\u200f\u202a-\u202e\u2060\u2066-\u2069\ufeff\uD800-\uDFFF]/u;
diff --git a/tests/app-assembly.test.ts b/tests/app-assembly.test.ts
index 635e4be0..04ed91a6 100644
--- a/tests/app-assembly.test.ts
+++ b/tests/app-assembly.test.ts
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
@@ -9,7 +9,7 @@ const source = vi.hoisted(() => ({
}));
// Exercise the actual assembler and final export. Only external build tools,
-// Git observations and platform/license generation are replaced by the fixture.
+// Git observations and license generation are replaced by the fixture.
vi.mock("node:child_process", async (original) => ({
...await original<typeof import("node:child_process")>(),
execFileSync: (_command: string, args: string[]) => {
@@ -26,9 +26,14 @@ vi.mock("node:child_process", async (original) => ({
writeFileSync(join(args[args.indexOf("-C") + 1]!, "REVISION"), `${source.revision}\n`);
} else if (args[0] === "build") {
const executable = Buffer.alloc(64);
- executable.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]);
- executable.writeUInt16LE(source.finalState === "wrong-architecture"
- ? (source.machine === 0x3e ? 0xb7 : 0x3e) : source.machine, 18);
+ if (source.machine > 0xffff) {
+ executable.set([0xcf, 0xfa, 0xed, 0xfe]);
+ executable.writeUInt32LE(source.machine, 4);
+ } else {
+ executable.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]);
+ executable.writeUInt16LE(source.finalState === "wrong-architecture"
+ ? (source.machine === 0x3e ? 0xb7 : 0x3e) : source.machine, 18);
+ }
writeFileSync(args[args.indexOf("-o") + 1]!, executable);
source.built = true;
if (source.finalState === "output-created") {
@@ -51,7 +56,6 @@ vi.mock("node:fs", async (original) => {
return fs.cpSync(...args);
} };
});
-vi.mock("../scripts/app-icons.mjs", () => ({ writeAppPlatformAssets: () => ({}) }));
vi.mock("../scripts/package-licenses.mjs", () => ({ writeAppLicenseNotices: () => undefined }));
describe.each(["linux-amd64", "linux-arm64"])("App package source identity (%s)", (target) => {
@@ -109,3 +113,51 @@ describe.each(["linux-amd64", "linux-arm64"])("App package source identity (%s)"
}
});
});
+
+it("assembles a macOS bundle that retains its executable and helpers when moved alone", async () => {
+ const root = mkdtempSync(join(tmpdir(), "piik-mac-bundle-"));
+ const output = join(root, "archive");
+ const descriptor = join(root, "server.release.json");
+ const artifact = Buffer.from("fixture server archive");
+ const previousArguments = process.argv;
+ const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
+ const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
+ source.built = false;
+ source.finalState = "clean";
+ source.output = output;
+ source.machine = 0x0100000c;
+ try {
+ // The external Go build is a Mach-O fixture; test package assembly on any runner.
+ Object.defineProperty(process, "platform", { ...platform, value: "darwin" });
+ const helper = Buffer.alloc(64);
+ helper.set([0xcf, 0xfa, 0xed, 0xfe]);
+ helper.writeUInt32LE(source.machine, 4);
+ writeFileSync(join(root, "helper"), helper);
+ writeFileSync(join(root, "server.tar.gz"), artifact);
+ writeFileSync(descriptor, JSON.stringify({
+ schema: 2, version: "development", revision: source.revision,
+ artifact: "server.tar.gz", artifactSha256: createHash("sha256").update(artifact).digest("hex"),
+ }));
+ process.argv = [process.execPath, "assemble-app.mjs", descriptor, output, "--target", "darwin-arm64",
+ "--capture", join(root, "helper"), "--tunnel", join(root, "helper")];
+ vi.resetModules();
+ await import("../scripts/assemble-app.mjs");
+ const relocated = join(root, "Moved Piik.app");
+ renameSync(join(output, "Piik App.app"), relocated);
+ const contents = join(relocated, "Contents");
+ const plist = readFileSync(join(contents, "Info.plist"), "utf8");
+ const entry = plist.match(/<key>CFBundleExecutable<\/key><string>([^<]+)<\/string>/)![1]!;
+ const executable = join(contents, "MacOS", entry);
+ expect(readFileSync(executable).subarray(0, 4)).toEqual(helper.subarray(0, 4));
+ for (const path of ["runtime/native/piik-capture", "runtime/tunnel/cloudflared"]) {
+ expect(readFileSync(join(contents, "MacOS", path))).toEqual(helper);
+ }
+ expect(readFileSync(join(contents, "MacOS", "REVISION"), "ascii").trim()).toBe(source.revision);
+ expect(existsSync(join(output, "piik-app"))).toBe(false);
+ } finally {
+ Object.defineProperty(process, "platform", platform);
+ process.argv = previousArguments;
+ stdout.mockRestore();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/tests/app-launcher-recovery.test.ts b/tests/app-launcher-recovery.test.ts
index 91c22115..d18c7852 100644
--- a/tests/app-launcher-recovery.test.ts
+++ b/tests/app-launcher-recovery.test.ts
@@ -34,13 +34,13 @@ const saved = {
revision: "test", version: "development", debug: false,
lan: { addresses: [{ address: "192.0.2.1", name: "LAN" }], selected: "192.0.2.1" },
};
-const response = (state: typeof saved & { detail?: string } = saved) => ({ ok: true, json: async () => state });
+const response = (state: typeof saved & { detail?: string } = saved) => ({ ok: true, status: 200, json: async () => state });
function mount(fetch: ReturnType<typeof vi.fn>) {
const state: Record<string, unknown> = {};
const setters = Object.fromEntries([
"Mode", "LocalAccessPassword", "Lan", "Version", "Target", "Starting", "Site", "StartupSite",
- "AppDebug", "Debug", "Error", "Loading", "Update",
+ "AppDebug", "Debug", "Error", "Loading", "Update", "RemoteControlPrototype",
"SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload",
].map(name => [`set${name}`, vi.fn((value: unknown) => {
state[name] = typeof value === "function" ? value(state[name]) : value;
@@ -61,7 +61,7 @@ function mount(fetch: ReturnType<typeof vi.fn>) {
return nextTimer;
},
clearTimeout: (id: number) => timers.delete(id),
- }) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site"): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };
+ }) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site", starAfterApproval?: boolean): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };
return { state, setters, ...actions, checkReleaseUpdate, focus: () => window.dispatchEvent(new Event("focus")),
retry: () => {
expect(timers.size).toBe(1);
@@ -73,6 +73,28 @@ function mount(fetch: ReturnType<typeof vi.fn>) {
}
describe("App launcher state recovery", () => {
+ it.each([true, false])("keeps approval pending until the optional startup preference settles (saved: %s)", async (savedStartup) => {
+ const nextSite = "https://next.example";
+ let finishStartup!: (value: ReturnType<typeof response>) => void;
+ const fetch = vi.fn(async () => response());
+ const page = mount(fetch);
+ await settle();
+ fetch.mockResolvedValueOnce(response({ ...saved, site: nextSite }))
+ .mockImplementationOnce(() => new Promise(resolve => { finishStartup = resolve; }));
+ const approval = page.changeSite(nextSite, "site", true);
+ await settle();
+ expect(page.state).toMatchObject({ Site: nextSite, StartupSite: "", SiteBusy: true });
+ expect(fetch.mock.calls[2]).toEqual(["/api/client-launcher/startup-site", expect.objectContaining({
+ body: JSON.stringify({ site: nextSite, expectedSite: nextSite }),
+ })]);
+ finishStartup({ ...response({ ...saved, site: nextSite, startupSite: savedStartup ? nextSite : "" }),
+ ok: savedStartup, status: savedStartup ? 200 : 503 });
+ await approval;
+ expect(page.state).toMatchObject({ Site: nextSite, SiteBusy: false,
+ StartupSite: savedStartup ? nextSite : "", SiteError: savedStartup ? undefined : "client.connect.saveFailed" });
+ page.cleanup();
+ });
+
it("restores saved choices after a failed first read, then preserves unsaved edits on focus", async () => {
const fetch = vi.fn(async () => response()).mockRejectedValueOnce(new Error("unavailable"));
const page = mount(fetch);
diff --git a/tests/archive-tool.test.ts b/tests/archive-tool.test.ts
index 05d45827..44bf547c 100644
--- a/tests/archive-tool.test.ts
+++ b/tests/archive-tool.test.ts
@@ -15,7 +15,7 @@ describe("App ZIP distribution", () => {
const archive = join(root, "Piik App.zip");
const files = {
"piik-app": "#!/bin/sh\nexit 0\n",
- "Piik App.app/Contents/MacOS/launcher": "#!/bin/sh\nexit 0\n",
+ "Piik App.app/Contents/MacOS/piik-app": "#!/bin/sh\nexit 0\n",
"runtime/.native/画面.txt": "Native capture\n",
".release-metadata": "Hidden metadata\n",
};
@@ -24,7 +24,7 @@ describe("App ZIP distribution", () => {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content);
}
- const executables = ["piik-app", "Piik App.app/Contents/MacOS/launcher"];
+ const executables = ["piik-app", "Piik App.app/Contents/MacOS/piik-app"];
for (const name of executables) chmodSync(join(source, name), 0o755);
createZip(source, archive);
expect(readFileSync(archive).subarray(0, 4)).toEqual(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index 0b05b1e9..737c38ea 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -1317,7 +1317,7 @@ describe("client signaling recovery policy", () => {
signal.stop();
});
- it("enables negotiated room data after authentication without replacing signaling or exposing it to media handlers", () => {
+ it.each([false, true])("negotiates room reactions without replacing signaling (initial discovery: %s)", initial => {
vi.useFakeTimers();
const sockets: FakeWebSocket[] = [];
class FakeWebSocket extends EventTarget {
@@ -1334,7 +1334,7 @@ describe("client signaling recovery policy", () => {
const onMessage = vi.fn();
const signal = new SignalingClient({ roomId: "1234", role: "viewer", clientId: "viewer-client" }, {
onMessage, onStatus: vi.fn(), onTerminated: vi.fn(), onAccessRequired: vi.fn(),
- });
+ }, undefined, initial ? { roomInteractions: true, roomReactionIds: ["heart"] } : {});
const receive = (body: object) => {
const event = new Event("message");
Object.defineProperty(event, "data", { value: JSON.stringify(body) });
@@ -1347,10 +1347,13 @@ describe("client signaling recovery policy", () => {
iceConfig: { iceServers: [], natPredictionStunUrls: [] }, codeEntryPolicy: "open",
viewerAuthorizationGeneration: "viewer_generation_12345678", ...routeAuthenticated(),
});
- expect(signal.interactions).toBeNull();
- expect(sockets[0].send).toHaveBeenCalledTimes(1);
- const data = signal.enableRoomInteractions()!;
+ if (initial) expect(signal.interactions?.getSnapshot().reactionIds).toEqual(["heart"]);
+ else expect(signal.interactions).toBeNull();
+ expect(sockets[0].send).toHaveBeenCalledTimes(initial ? 2 : 1);
+ const data = signal.enableRoomInteractions(["heart", "thumbsup", "future-effect"])!;
+ expect(data.getSnapshot().reactionIds).toEqual(["thumbsup", "heart"]);
expect(sockets[0].send).toHaveBeenLastCalledWith(JSON.stringify({ type: "subscribe-room-interactions" }));
+ expect(sockets[0].send).toHaveBeenCalledTimes(2);
receive({ type: "room-interactions-ready", serverTime: Date.now() });
expect(data.getSnapshot().ready).toBe(true);
expect(sockets).toHaveLength(1);
diff --git a/tests/fixtures/wire-samples.json b/tests/fixtures/wire-samples.json
index 788694d0..78892bd6 100644
--- a/tests/fixtures/wire-samples.json
+++ b/tests/fixtures/wire-samples.json
@@ -43,6 +43,24 @@
"interactionIntervalMs": 800
},
"clientMessages": [
+ {
+ "name": "viewer-route-selection",
+ "schema": "client",
+ "json": "{\"type\":\"set-viewer-route-preference\",\"preference\":\"sfu\"}",
+ "valid": true
+ },
+ {
+ "name": "viewer-route-unknown-choice",
+ "schema": "client",
+ "json": "{\"type\":\"set-viewer-route-preference\",\"preference\":\"tcp\"}",
+ "valid": false
+ },
+ {
+ "name": "viewer-route-no-choice",
+ "schema": "client",
+ "json": "{\"type\":\"set-viewer-route-preference\"}",
+ "valid": false
+ },
{
"name": "signal-punch-stable-mapping",
"schema": "client",
@@ -1069,6 +1087,30 @@
"json": "{\"type\":\"send-room-interaction\",\"requestId\":\"request_12345678\",\"payload\":{\"kind\":\"reaction\",\"reaction\":\"wave\"}}",
"valid": true
},
+ {
+ "name": "room-reaction-clown-targeted",
+ "schema": "client",
+ "json": "{\"type\":\"send-room-interaction\",\"requestId\":\"request_12345678\",\"payload\":{\"kind\":\"reaction\",\"reaction\":\"clown\",\"targetPeerId\":\"viewer_12345678\"}}",
+ "valid": true
+ },
+ {
+ "name": "room-reaction-eyeroll-untargeted",
+ "schema": "client",
+ "json": "{\"type\":\"send-room-interaction\",\"requestId\":\"request_12345678\",\"payload\":{\"kind\":\"reaction\",\"reaction\":\"eyeroll\"}}",
+ "valid": true
+ },
+ {
+ "name": "room-reaction-thumbsup-targeted",
+ "schema": "client",
+ "json": "{\"type\":\"send-room-interaction\",\"requestId\":\"request_12345678\",\"payload\":{\"kind\":\"reaction\",\"reaction\":\"thumbsup\",\"targetPeerId\":\"viewer_12345678\"}}",
+ "valid": true
+ },
+ {
+ "name": "room-reaction-thumbsdown-untargeted",
+ "schema": "client",
+ "json": "{\"type\":\"send-room-interaction\",\"requestId\":\"request_12345678\",\"payload\":{\"kind\":\"reaction\",\"reaction\":\"thumbsdown\"}}",
+ "valid": true
+ },
{
"name": "numeric-audio-6000",
"schema": "client",
@@ -1293,6 +1335,14 @@
}
],
"serverMessages": [
+ {
+ "name": "viewer-route-selection-accepted",
+ "json": "{\"type\":\"viewer-route-preference\",\"preference\":\"sfu\",\"accepted\":true}"
+ },
+ {
+ "name": "viewer-route-selection-rejected",
+ "json": "{\"type\":\"viewer-route-preference\",\"preference\":\"auto\",\"accepted\":false}"
+ },
{
"name": "room-interaction-future-reaction",
"json": "{\"type\":\"room-interaction\",\"id\":\"event_12345678\",\"requestId\":\"request_12345678\",\"occurredAt\":1700000000010,\"sender\":{\"peerId\":\"peer_12345678\",\"role\":\"host\",\"displayName\":\"Piik friend\"},\"payload\":{\"kind\":\"reaction\",\"reaction\":\"future-effect\",\"targetPeerId\":\"target_12345678\"}}"
diff --git a/tests/host-audio.test.ts b/tests/host-audio.test.ts
index 4112bdee..95b7697e 100644
--- a/tests/host-audio.test.ts
+++ b/tests/host-audio.test.ts
@@ -2,11 +2,11 @@ import { afterEach, expect, test, vi } from "vitest";
import { HostAudio } from "../src/client/media/host-audio";
import { captureBrowserSource, QUALITY_PROFILES } from "../src/client/media/quality";
-class Track {
+class Track extends EventTarget {
enabled = true;
readyState = "live";
onended: (() => void) | null = null;
- constructor(readonly kind: string) {}
+ constructor(readonly kind: string) { super(); }
stop = vi.fn(() => { this.readyState = "ended"; });
}
class Stream {
@@ -45,6 +45,38 @@ function setup() {
}
afterEach(() => vi.unstubAllGlobals());
+test("input availability follows source and microphone independently of the retained mixer track", async () => {
+ const { getUserMedia } = setup();
+ const source = new Track("audio"), microphone = new Track("audio");
+ const changed = vi.fn();
+ const audio = new HostAudio(media(new Track("video"), source), vi.fn(), "browser", changed);
+ expect(audio.audioAvailable).toBe(true);
+ source.stop();
+ source.dispatchEvent(new Event("ended"));
+ expect(changed).toHaveBeenLastCalledWith(false);
+ getUserMedia.mockResolvedValue(media(microphone));
+ const mixed = (await audio.toggleMicrophone())!;
+ expect(changed).toHaveBeenLastCalledWith(true); // Microphone only.
+ const replaced = audio.attach(media(new Track("video")));
+ expect(replaced.getAudioTracks()).toEqual(mixed.getAudioTracks());
+ expect(changed).toHaveBeenLastCalledWith(true); // Source switch keeps the microphone.
+ await audio.toggleMicrophone();
+ expect(changed).toHaveBeenLastCalledWith(false);
+ expect(mixed.getAudioTracks()[0].readyState).toBe("live");
+ await audio.toggleMicrophone();
+ microphone.stop(); microphone.onended!();
+ expect(changed).toHaveBeenLastCalledWith(false);
+ const next = new Track("audio");
+ audio.attach(media(new Track("video"), next));
+ expect(changed).toHaveBeenLastCalledWith(true);
+ next.enabled = false; // Share pause does not change input availability.
+ expect(audio.audioAvailable).toBe(true);
+ audio.dispose();
+ changed.mockClear();
+ next.dispatchEvent(new Event("ended"));
+ expect(changed).not.toHaveBeenCalled();
+});
+
test("camera is a bounded video source and never implicitly requests a microphone", async () => {
const { getUserMedia } = setup();
const video = new Track("video");
diff --git a/tests/host-quality-ownership.test.ts b/tests/host-quality-ownership.test.ts
index d02366cc..99e37ba8 100644
--- a/tests/host-quality-ownership.test.ts
+++ b/tests/host-quality-ownership.test.ts
@@ -11,6 +11,7 @@ import { NativeSenderPeer } from "../src/client/native/native-sender-peer";
import { NativeCompatibilityError, NativeRequestError } from "../src/client/native/client";
import { nativeCaptureTargetKey } from "../src/client/native/capture-selection";
import { NativeMediaBridgeError } from "../src/client/native/media-bridge";
+import { InputRoute } from "../src/client/remote-control/input-route";
import { reconcileBoundedMediaChildren } from "../src/client/webrtc/media-assignment";
import { debugError, debugEvent, debugOperation } from "../src/client/lib/debug";
import { ApiError } from "../src/client/lib/api";
@@ -96,18 +97,20 @@ function fixture(launchedByClient = true) {
appQualityPreferenceRef: ref<{ save: (quality: QualitySettings) => void } | null>(null),
qualityPreferenceEditedRef: ref(false), pendingAppQualityPreferenceRef: ref<QualitySettings | null>(null),
activeGenerationRef: ref<number | null>(1), streamRef: ref<typeof stream | null>(stream), sourceSwitchRef: ref<object | null>(null),
- nativeSourceAudioRef: ref<boolean | undefined>(undefined), setMicrophoneEnabled: vi.fn(),
+ nativeSourceAudioRef: ref<boolean | undefined>(undefined), audioAvailableRef: ref(false), setMicrophoneEnabled: vi.fn(),
microphoneVoiceProcessing: true, setMicrophoneVoiceProcessing: vi.fn(),
nativeSourceSelectionRef: ref<Record<string, unknown> | null>(null), nativeCaptureTargetKey,
nativeModeRef: ref(false), nativeClientRef: ref<typeof client | null>(client), nativeShareGenerationRef: ref<string | null>("share"),
hostAudioRef: ref<{ sourceStream: MediaStream } | null>(null),
nativeMediaIngressRef: ref<ReturnType<typeof ingress> | null>(null), nativeMediaBridgeRef: ref(null),
+ nativeInputRoute: new InputRoute(() => {}),
nativeEventCleanupRef: ref(null), nativeShareCleanupRef: ref(Promise.resolve()),
peersRef: ref(new Map([["viewer", peer]])), hostProvisionalChildRef: ref(null), hostSfuRouteRef: ref(route),
- signalRef: ref({ setHostQualitySettings: vi.fn(), send: vi.fn() }),
+ signalRef: ref({ setHostQualitySettings: vi.fn(), setAudioAvailable: vi.fn(), send: vi.fn() }),
setQualitySettings: vi.fn(), setAdvancedQuality: vi.fn(), setChangingQuality: vi.fn(), savePreferredQuality: vi.fn(),
setNoticeValue: vi.fn(), setNoticeError: vi.fn(), readableError: hostActionErrorNotice,
- setDetails: vi.fn(), setNativeActive: vi.fn(),
+ setDetails: vi.fn(), setNativeActive: vi.fn(), setRemoteControlState: vi.fn(),
+ remoteInputPeersRef: ref([]), getRuntimeCapabilities: vi.fn(async () => ({ remoteInput: false })),
applyCaptureProfile: vi.fn(async (_stream: unknown, profile: QualitySettings) => { physical = profile; }),
captureDetails: () => ({}),
qualitySettingsEqual, qualityResolutionEqual, videoQualitySettingsEqual, screenAudioBitrate, qualitySettingsLabel,
@@ -232,6 +235,8 @@ describe("Host room ownership", () => {
interactions = {};
stop = vi.fn();
stopSharing = vi.fn();
+ setAudioAvailable = vi.fn();
+ enableRoomInteractions = vi.fn(() => this.interactions);
constructor(public identity: { roomId: string; token: string; roomOnly?: true; shareGeneration?: string },
public events: {
onMessage(message: unknown): void;
@@ -246,7 +251,7 @@ describe("Host room ownership", () => {
Object.assign(current.signalRef, { current: null });
current.generationRef.current = 1;
Object.assign(current.context, {
- SignalingClient: Signal, hostRoomSessionAvailable: true, roomInteractionsAvailable: true,
+ SignalingClient: Signal, hostRoomSessionAvailable: true, roomInteractionsAvailable: true, roomReactionIds: undefined,
visRef: ref(false), hostClientIdRef: ref(null), displayNameRef: ref("Host"),
getStableClientId: () => "host-client", defaultHostDisplayName: () => "Host", readDisplayName: () => "Host",
setDisplayName: vi.fn(), setDisplayNameDraft: vi.fn(), setDisplayNameError: vi.fn(),
@@ -1292,7 +1297,7 @@ describe("Host quality ownership", () => {
const setResolvedVideoCodec = vi.fn();
Object.assign(current.context, {
phase: "idle", captureBrowserSource: async () => captured,
- HostAudio: class {}, setStream: vi.fn(), watchCaptureEnd: vi.fn(),
+ HostAudio: class { audioAvailable = false; }, setStream: vi.fn(), watchCaptureEnd: vi.fn(),
resolveStreamVideoCodec, startBrowserNativeIngress, setResolvedVideoCodec,
});
current.disposeResources.mockImplementation(() => {
diff --git a/tests/native-client.test.ts b/tests/native-client.test.ts
index 3f234279..8884795d 100644
--- a/tests/native-client.test.ts
+++ b/tests/native-client.test.ts
@@ -32,6 +32,15 @@ describe("native App private wire", () => {
nativeMedia: { video: true, hardwareH264: true },
};
+ it("requires the controlled App platform in remote-control state", () => {
+ const event = { version: NATIVE_CLIENT_PROTOCOL, type: "remote-control-state", shareId: "share_123456", mode: "off", requests: [] };
+ expect(nativeEventSchema.safeParse(event).success).toBe(false);
+ for (const platform of ["windows", "darwin", "linux"]) {
+ expect(nativeEventSchema.parse({ ...event, platform })).toMatchObject({ platform });
+ }
+ expect(nativeEventSchema.safeParse({ ...event, platform: "unknown" }).success).toBe(false);
+ });
+
it.each(["prompt", "denied"])("background App preferences do not request local access when permission is %s", async (state) => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue({ state }) } });
@@ -531,7 +540,7 @@ describe("native App private wire", () => {
]) expect(nativeHealthSchema.safeParse({ ...health, ...invalid }).success).toBe(false);
});
- it.each([undefined, false, true])("gates capture-border commands on advertised support: %s", async (supported) => {
+ it.each([undefined, false, true])("gates optional capture commands on advertised support: %s", async (supported) => {
const requests: Record<string, unknown>[] = [];
class CaptureSocket extends EventTarget {
static readonly OPEN = 1;
@@ -561,7 +570,7 @@ describe("native App private wire", () => {
vi.stubGlobal("WebSocket", CaptureSocket);
vi.stubGlobal("window", { setTimeout, clearTimeout });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
- ...health, nativeMedia: { ...health.nativeMedia, captureBorderControl: supported },
+ ...health, nativeMedia: { ...health.nativeMedia, captureBorderControl: supported, remoteInput: supported },
}))));
const client = await NativeClient.connect();
expect(client).not.toBeNull();
@@ -578,6 +587,7 @@ describe("native App private wire", () => {
const extension = supported ? { showCaptureBorder: showCaptureBorder ?? false } : {};
expect(requests.at(-2)).toEqual({
version: NATIVE_CLIENT_PROTOCOL, id: expect.any(String), type: "start-share", ...input, ...extension,
+ ...(supported ? { remoteInput: true } : {}),
});
expect(requests.at(-1)).toEqual({
version: NATIVE_CLIENT_PROTOCOL, id: expect.any(String), type: "replace-share-source",
diff --git a/tests/panel-window.test.ts b/tests/panel-window.test.ts
index 4671da2c..024a2903 100644
--- a/tests/panel-window.test.ts
+++ b/tests/panel-window.test.ts
@@ -6,16 +6,18 @@ function setup() {
const requestWindow = vi.fn(() => new Promise<Window>(resolve => { finish = resolve; }));
const view = { isSecureContext: true, documentPictureInPicture: { requestWindow } } as unknown as Window;
Object.defineProperty(view, "top", { value: view });
- const container = { ownerDocument: { defaultView: view }, parentElement: {}, isConnected: true } as HTMLElement;
+ const container = { ownerDocument: { defaultView: view }, parentElement: {}, isConnected: true,
+ firstElementChild: { getBoundingClientRect: () => ({ width: 304, height: 346 }) } } as unknown as HTMLElement;
return { container, view, requestWindow, finish: (window: Window) => finish(window) };
}
test("a room retired while the browser opens PiP closes the late window without moving its UI", async () => {
- const { container, finish } = setup();
+ const { container, finish, requestWindow } = setup();
const controller = new AbortController();
const changed = vi.fn();
const close = vi.fn();
const opening = openPanelWindow(container, controller.signal, changed);
+ expect(requestWindow).toHaveBeenCalledWith({ width: 304, height: 346, preferInitialWindowPlacement: true });
controller.abort();
finish({ close } as unknown as Window);
await opening;
diff --git a/tests/participant-color.test.ts b/tests/participant-color.test.ts
new file mode 100644
index 00000000..09298e58
--- /dev/null
+++ b/tests/participant-color.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { participantColor } from "../src/client/components/living/participant-color";
+
+describe("participant identity colours", () => {
+ it("separates identities that collided in the eight-colour palette, independently of roster order", () => {
+ const ids = [
+ "00000000-0000-4000-8000-000000000000",
+ "00000000-0000-4000-8000-000000000008",
+ "00000000-0000-4000-8000-000000000011",
+ ];
+ const colours = ids.map(participantColor);
+ expect(new Set(colours).size).toBe(ids.length);
+ const hues = colours.map(colour => Number(colour.slice(colour.lastIndexOf(" ") + 1, -1))).sort((a, b) => a - b);
+ expect(Math.min(hues[1]! - hues[0]!, hues[2]! - hues[1]!)).toBeGreaterThan(15);
+ expect(ids.toReversed().map(participantColor)).toEqual(colours.toReversed());
+ });
+});
diff --git a/tests/playback-gestures.test.ts b/tests/playback-gestures.test.ts
index 86edc27c..5047f896 100644
--- a/tests/playback-gestures.test.ts
+++ b/tests/playback-gestures.test.ts
@@ -1,87 +1,23 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { expect, it, vi } from "vitest";
import { bindPlaybackGestures } from "../src/client/components/living/playback-gestures";
-function picture() {
+it("reserves picture gestures for desktop double-click fullscreen and removes them on disposal", () => {
const screen = new EventTarget();
- const video = Object.assign(new EventTarget(), {
- parentElement: screen,
- srcObject: {} as object | null,
- });
- const playback = vi.fn();
+ const video = Object.assign(new EventTarget(), { parentElement: screen });
const fullscreen = vi.fn();
- const dispose = bindPlaybackGestures(video as unknown as HTMLVideoElement, playback, fullscreen);
- const pointer = (pointerType = "mouse") => screen.dispatchEvent(Object.assign(new Event("pointerdown"), { pointerType }));
- const click = (detail = 1, button = 0) => video.dispatchEvent(Object.assign(new Event("click"), { detail, button }));
- const doubleClick = () => video.dispatchEvent(Object.assign(new Event("dblclick"), { detail: 2, button: 0 }));
- return { screen, video, playback, fullscreen, dispose, pointer, click, doubleClick };
-}
+ const dispose = bindPlaybackGestures(video as unknown as HTMLVideoElement, fullscreen);
+ const pointer = (pointerType: string) => screen.dispatchEvent(Object.assign(new Event("pointerdown"), { pointerType }));
+ const doubleClick = () => video.dispatchEvent(Object.assign(new Event("dblclick"), { button: 0 }));
-afterEach(() => vi.useRealTimers());
-
-describe("Viewer picture gestures", () => {
- it("waits for a single click and gives double-click fullscreen priority without changing playback", () => {
- vi.useFakeTimers();
- const view = picture();
- view.pointer();
- view.click();
- vi.advanceTimersByTime(499);
- expect(view.playback).not.toHaveBeenCalled();
- vi.advanceTimersByTime(1);
- expect(view.playback).toHaveBeenCalledOnce();
-
- view.playback.mockClear();
- view.pointer();
- view.click();
- vi.advanceTimersByTime(300);
- view.pointer();
- // The second press cancels the single even if its release comes later.
- vi.advanceTimersByTime(300);
- view.click(2);
- view.doubleClick();
- vi.runAllTimers();
- expect(view.playback).not.toHaveBeenCalled();
- expect(view.fullscreen).toHaveBeenCalledOnce();
- view.dispose();
- });
-
- it("retires pending clicks after another action, playback change, media replacement or unmount", () => {
- vi.useFakeTimers();
- const view = picture();
- for (const [target, event] of [
- [view.screen, "pointerdown"], [view.screen, "keydown"], [view.screen, "pointercancel"],
- [view.video, "play"], [view.video, "pause"], [view.video, "emptied"],
- ] as const) {
- view.click();
- target.dispatchEvent(new Event(event));
- vi.runAllTimers();
- }
- view.click();
- view.video.srcObject = {};
- vi.runAllTimers();
- view.click();
- view.dispose();
- vi.runAllTimers();
- view.click();
- view.doubleClick();
- vi.runAllTimers();
- expect(view.playback).not.toHaveBeenCalled();
- expect(view.fullscreen).not.toHaveBeenCalled();
- });
-
- it("leaves touch taps, control-bar clicks, auxiliary buttons and keyboard-generated clicks alone", () => {
- vi.useFakeTimers();
- const view = picture();
- view.pointer("touch");
- view.click();
- view.doubleClick();
- view.pointer();
- view.screen.dispatchEvent(Object.assign(new Event("click"), { detail: 1, button: 0 }));
- view.screen.dispatchEvent(Object.assign(new Event("dblclick"), { detail: 2, button: 0 }));
- view.click(1, 2);
- view.click(0);
- vi.runAllTimers();
- expect(view.playback).not.toHaveBeenCalled();
- expect(view.fullscreen).not.toHaveBeenCalled();
- view.dispose();
- });
+ pointer("touch"); doubleClick();
+ pointer("mouse");
+ video.dispatchEvent(new Event("click"));
+ screen.dispatchEvent(Object.assign(new Event("dblclick"), { button: 0 }));
+ const consumed = Object.assign(new Event("dblclick", { cancelable: true }), { button: 0 });
+ consumed.preventDefault(); video.dispatchEvent(consumed);
+ expect(fullscreen).not.toHaveBeenCalled();
+ doubleClick();
+ expect(fullscreen).toHaveBeenCalledOnce();
+ dispose(); doubleClick();
+ expect(fullscreen).toHaveBeenCalledOnce();
});
diff --git a/tests/project-link.test.ts b/tests/project-link.test.ts
new file mode 100644
index 00000000..79602eab
--- /dev/null
+++ b/tests/project-link.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, expect, it, vi } from "vitest";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ vi.resetModules();
+});
+
+it.each(["available", "http-error", "unreachable", "timeout"])(
+ "keeps the optional website probe shared and bounded: %s", async outcome => {
+ vi.useFakeTimers();
+ const fetchImpl = vi.fn(async (_url: string, options: RequestInit) => {
+ if (outcome === "unreachable") throw new TypeError("Failed to fetch");
+ if (outcome === "timeout") return new Promise<Response>((_resolve, reject) => {
+ options.signal!.addEventListener("abort", () => reject(options.signal!.reason), { once: true });
+ });
+ return new Response(null, { status: outcome === "available" ? 200 : 503 });
+ });
+ vi.stubGlobal("fetch", fetchImpl);
+ const { projectWebsiteAvailable } = await import("../src/client/lib/use-project-link");
+ const first = projectWebsiteAvailable();
+ expect(projectWebsiteAvailable()).toBe(first);
+ if (outcome === "timeout") await vi.advanceTimersByTimeAsync(3_000);
+ expect(await first).toBe(outcome === "available");
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ expect(fetchImpl.mock.calls[0]![1]).toMatchObject({
+ method: "HEAD", credentials: "omit", referrerPolicy: "no-referrer",
+ });
+ expect(vi.getTimerCount()).toBe(0);
+ },
+);
diff --git a/tests/protocol-fixture.test.ts b/tests/protocol-fixture.test.ts
index 25754c5e..1e34a61d 100644
--- a/tests/protocol-fixture.test.ts
+++ b/tests/protocol-fixture.test.ts
@@ -135,6 +135,7 @@ describe("shared wire fixture", () => {
"client:set-display-name",
"client:set-quality-settings",
"client:set-sharing-paused",
+ "client:set-viewer-route-preference",
"client:sfu-publisher-quality-evidence",
"client:sfu-signal",
"client:signal",
@@ -190,6 +191,7 @@ describe("shared wire fixture", () => {
"viewer-grant-revoked",
"viewer-presence",
"viewer-quality-evidence",
+ "viewer-route-preference",
]);
});
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index c1e15cd8..b8fe6285 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -28,6 +28,17 @@ const token = "a".repeat(43);
const roomId = "1234";
const viewerGrant = `${"b".repeat(21)}g`;
+it("keeps audio availability nullable for older Hosts and generation-scoped for updates", () => {
+ expect(clientMessageSchema.safeParse({ type: "subscribe-audio-presence" }).success).toBe(true);
+ for (const available of [false, true, null]) {
+ expect(serverMessageSchema.safeParse({ type: "audio-presence", available }).success).toBe(true);
+ expect(clientMessageSchema.safeParse({ type: "set-audio-presence", shareGeneration: "audio_share_generation", available }).success)
+ .toBe(available !== null);
+ }
+ expect(serverMessageSchema.safeParse({ type: "audio-presence" }).success).toBe(false);
+ expect(clientMessageSchema.safeParse({ type: "set-audio-presence", shareGeneration: "bad", available: true }).success).toBe(false);
+});
+
it("accepts bounded future reaction events while keeping commands and known prop targets strict", () => {
const event = { type: "room-interaction", id: "event_future_1234", requestId: "request_future_1234", occurredAt: 1,
sender: { peerId: "sender_peer_1234", role: "viewer", displayName: "Friend" },
@@ -56,20 +67,24 @@ const qualitySettings = {
describe("runtime capabilities", () => {
it("defaults missing capabilities off and ignores unknown descriptors", () => {
- expect(runtimeCapabilitiesSchema.parse({})).toEqual({ sfu: false, natPrediction: false, roomInteractions: false, hostRoomSession: false });
+ expect(runtimeCapabilitiesSchema.parse({})).toEqual({ sfu: false, natPrediction: false, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false });
expect(runtimeCapabilitiesSchema.parse({ sfu: true, extra: { enabled: true } }))
- .toEqual({ sfu: true, natPrediction: false, roomInteractions: false, hostRoomSession: false });
+ .toEqual({ sfu: true, natPrediction: false, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false });
expect(runtimeCapabilitiesSchema.parse({ natPrediction: true, SFU: true }))
- .toEqual({ sfu: false, natPrediction: true, roomInteractions: false, hostRoomSession: false });
+ .toEqual({ sfu: false, natPrediction: true, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false });
expect(runtimeCapabilitiesSchema.parse({ sfu: true, natPrediction: true }))
- .toEqual({ sfu: true, natPrediction: true, roomInteractions: false, hostRoomSession: false });
+ .toEqual({ sfu: true, natPrediction: true, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false });
expect(runtimeCapabilitiesSchema.parse({ sfu: true, sfuOnly: true }).sfuOnly).toBe(true);
-
+ expect(runtimeCapabilitiesSchema.parse({ roomReactionIds: ["heart", "future-effect"] }).roomReactionIds)
+ .toEqual(["heart", "future-effect"]);
+ expect(runtimeCapabilitiesSchema.parse({ roomReactionIds: [] }).roomReactionIds).toEqual([]);
});
it("rejects malformed known capabilities and non-object responses", () => {
for (const value of [null, [], true, { sfu: null }, { sfu: "true" },
{ natPrediction: null }, { natPrediction: 1 }, { sfuOnly: null }, { sfuOnly: "true" },
+ { roomReactionIds: null }, { roomReactionIds: "heart" }, { roomReactionIds: ["bad id"] },
+ { roomReactionIds: [true] }, { roomReactionIds: [""] },
]) {
expect(runtimeCapabilitiesSchema.safeParse(value).success).toBe(false);
}
diff --git a/tests/quality-controls.test.ts b/tests/quality-controls.test.ts
index d817a3da..7ef3087e 100644
--- a/tests/quality-controls.test.ts
+++ b/tests/quality-controls.test.ts
@@ -43,7 +43,7 @@ function editor() {
},
});
const blur = (relatedTarget: unknown = null) => result.props.onBlur({ currentTarget: container, relatedTarget });
- const press = (value: string) => key({ key: value, currentTarget: { blur: () => blur() },
+ const press = (value: string) => key({ key: value, nativeEvent: { isComposing: false }, currentTarget: { blur: () => blur() },
preventDefault() {}, stopPropagation() {} });
return { input, inside, onChange, choose, blur, press, setInvalid };
}
diff --git a/tests/remote-input.test.ts b/tests/remote-input.test.ts
new file mode 100644
index 00000000..57fbd1fe
--- /dev/null
+++ b/tests/remote-input.test.ts
@@ -0,0 +1,210 @@
+import { expect, it, vi } from "vitest";
+import { RemoteInputSession, picturePoint } from "../src/client/remote-control/input-session";
+import { InputRoute, type InputIdentity } from "../src/client/remote-control/input-route";
+import { remoteInputStateSchema } from "../src/client/remote-control/protocol";
+
+class Channel extends EventTarget {
+ readyState = "open";
+ bufferedAmount = 0;
+ sent: Record<string, unknown>[] = [];
+ send(value: string) { this.sent.push(JSON.parse(value)); }
+ close() { this.readyState = "closed"; this.dispatchEvent(new Event("close")); }
+ receive(value: object) { this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(value) })); }
+}
+
+it.each(["windows", "darwin", "linux"] as const)("keeps the Host platform in local request state (%s)", platform => {
+ const channel = new Channel();
+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});
+ session.request();
+ expect(channel.sent).toEqual([{ type: "sync" }]);
+ expect(remoteInputStateSchema.safeParse({ mode: "ask", state: "ready" }).success).toBe(false);
+ expect(remoteInputStateSchema.safeParse({ mode: "ask", state: "ready", platform: "unknown" }).success).toBe(false);
+ channel.receive({ mode: "ask", state: "ready", platform });
+ session.request();
+ expect(session.state).toMatchObject({ state: "pending", platform });
+ session.release();
+ expect(session.state).toMatchObject({ state: "ready", platform });
+ session.dispose();
+});
+
+it("reuses the authenticated identity across media routes and syncs after delayed key installation", async () => {
+ const registered: InputIdentity[] = [];
+ const route = new InputRoute(() => {});
+ route.enable(identity => { registered.push(identity); return true; });
+ const first = new Channel();
+ route.setUpstream(first as unknown as RTCDataChannel);
+ first.receive({ ready: true });
+ const oldEndpoint = route.current!;
+ const session = new RemoteInputSession(oldEndpoint, () => {});
+ await vi.waitFor(() => expect(first.sent.filter(p => p.data)).toHaveLength(1));
+ const oldPacket = first.sent.find(p => p.data)!;
+ expect(oldPacket.data).not.toContain("sync");
+ first.receive({ id: registered[0].endpointId, ready: true });
+ await vi.waitFor(() => expect(first.sent.filter(p => p.data)).toHaveLength(2));
+ session.dispose();
+ const next = new Channel();
+ route.setUpstream(next as unknown as RTCDataChannel);
+ expect(oldEndpoint.readyState).toBe("closed");
+ next.receive({ ready: true });
+ const nextSession = new RemoteInputSession(route.current!, () => {});
+ await vi.waitFor(() => expect(next.sent.filter(p => p.data)).toHaveLength(1));
+ const newPacket = next.sent.find(p => p.data)!;
+ expect(registered).toHaveLength(1);
+ expect(newPacket.id).toBe(oldPacket.id);
+ expect(newPacket.epoch).not.toBe(oldPacket.epoch);
+ const sequence = (p: Record<string, unknown>) => new DataView(Uint8Array.from(atob(p.data as string), c => c.charCodeAt(0)).buffer).getBigUint64(0);
+ expect(sequence(newPacket)).toBeGreaterThan(sequence(oldPacket));
+ nextSession.dispose();
+ route.dispose();
+});
+
+it("binds input to the current request and retires cancelled or replaced grants", () => {
+ const channel = new Channel();
+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});
+ const grant = "a".repeat(64);
+ channel.receive({ platform: "windows", mode: "ask", state: "ready" });
+ session.request();
+ const first = channel.sent.at(-1)?.intent;
+ session.release();
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent: first, grant });
+ expect(session.state?.state).toBe("ready");
+ expect(channel.sent.at(-1)).toEqual({ type: "release", intent: first });
+ session.request();
+ const second = channel.sent.at(-1)?.intent;
+ channel.receive({ platform: "windows", mode: "ask", state: "ready", intent: first });
+ expect(session.state?.state).toBe("pending");
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent: second, grant });
+ session.input({ type: "key", code: "KeyW", down: true });
+ expect(channel.sent.at(-1)).toEqual({ type: "key", code: "KeyW", down: true, grant });
+ channel.receive({ platform: "windows", mode: "ask", state: "suspended", intent: second, grant });
+ const count = channel.sent.length;
+ session.input({ type: "key", code: "KeyD", down: true });
+ expect(channel.sent).toHaveLength(count);
+ session.input({ type: "reset" });
+ expect(channel.sent.at(-1)).toEqual({ type: "reset", grant });
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent: second, grant });
+ session.dispose();
+ expect(channel.sent.at(-1)).toEqual({ type: "release", intent: second });
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent: second, grant });
+ session.input({ type: "key", code: "KeyW", down: true });
+ expect(channel.sent.at(-1)).toEqual({ type: "release", intent: second });
+ expect(channel.readyState).toBe("open"); // Media owns the channel lifetime.
+});
+
+it("maps only visible picture pixels when playback has letterboxing", () => {
+ const video = { videoWidth: 1920, videoHeight: 1080,
+ style: { objectFit: "contain" },
+ getBoundingClientRect: () => ({ left: 100, top: 50, width: 800, height: 600 }),
+ } as HTMLVideoElement;
+ expect(picturePoint(video, 500, 350)).toEqual({ x: 0.5, y: 0.5 });
+ expect(picturePoint(video, 500, 60)).toBeNull();
+ expect(picturePoint(video, 901, 350)).toBeNull();
+ video.style.objectFit = "cover";
+ expect(picturePoint(video, 500, 350)).toEqual({ x: 0.5, y: 0.5 });
+ // Filling this 4:3 player crops the 16:9 picture, it does not stretch input.
+ expect(picturePoint(video, 100, 50)?.x).toBeCloseTo(0.125);
+ expect(picturePoint(video, 900, 650)?.x).toBeCloseTo(0.875);
+ video.style.objectFit = "fill";
+ expect(picturePoint(video, 100, 50)).toEqual({ x: 0, y: 0 });
+ expect(picturePoint(video, 900, 650)).toEqual({ x: 1, y: 1 });
+ expect(picturePoint(video, 300, 500)).toEqual({ x: 0.25, y: 0.75 });
+});
+
+it("ends a pending request when its source becomes unavailable, even before the request reaches the Host", () => {
+ const channel = new Channel();
+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});
+ channel.receive({ platform: "windows", mode: "ask", state: "ready" });
+ session.request();
+ // Source pause/off can be announced before the Host has seen this intent.
+ // It still invalidates the whole endpoint, not just an older request.
+ channel.receive({ platform: "windows", mode: "ask", state: "unavailable" });
+ expect(session.state?.state).toBe("unavailable");
+ channel.receive({ platform: "windows", mode: "ask", state: "ready" });
+ session.request();
+ channel.receive({ platform: "windows", mode: "off", state: "unavailable", intent: "a".repeat(32) });
+ expect(session.state?.mode).toBe("off");
+ session.dispose();
+});
+
+it("sends a control password only in the request and follows the App policy after cancellation", () => {
+ const channel = new Channel();
+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});
+ channel.receive({ platform: "windows", state: "ready", mode: "password" });
+ session.request("temporary-secret");
+ const intent = channel.sent.at(-1)?.intent;
+ expect(channel.sent.at(-1)).toMatchObject({ type: "request", password: "temporary-secret" });
+ channel.receive({ platform: "windows", state: "ready", mode: "password", reason: "password", intent });
+ expect(session.state?.reason).toBe("password");
+ session.release();
+ expect(session.state?.reason).toBeUndefined();
+ expect(session.state?.mode).toBe("password");
+ session.request("temporary-secret");
+ const nextIntent = channel.sent.at(-1)?.intent;
+ channel.receive({ platform: "windows", state: "active", mode: "password", intent: nextIntent, grant: "a".repeat(64) });
+ session.release();
+ expect(session.state?.mode).toBe("password");
+ expect(channel.sent.at(-1)).toEqual({ type: "release", intent: nextIntent });
+ channel.receive({ platform: "windows", state: "ready", mode: "ask", intent: nextIntent });
+ expect(session.state?.mode).toBe("ask");
+ session.dispose();
+});
+
+it("preserves wheel magnitude and fractions across browser units, only within the current grant", () => {
+ const channel = new Channel();
+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});
+ channel.receive({ platform: "windows", mode: "ask", state: "ready" });
+ session.request();
+ const intent = channel.sent.at(-1)?.intent;
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent, grant: "c".repeat(64) });
+ session.scroll(100, 0);
+ session.scroll(3, 1);
+ session.scroll(1, 2);
+ expect(channel.sent.slice(-3).map(event => event.delta)).toEqual([-120, -120, -120]);
+ const count = channel.sent.length;
+ for (let i = 0; i < 4; i++) session.scroll(0.25, 0);
+ expect(channel.sent).toHaveLength(count + 1);
+ expect(channel.sent.at(-1)?.delta).toBe(-1);
+ session.scroll(-10_000, 0);
+ expect(channel.sent.at(-1)?.delta).toBe(1200);
+ channel.receive({ platform: "windows", mode: "ask", state: "suspended", intent, grant: "c".repeat(64) });
+ const suspendedCount = channel.sent.length;
+ session.scroll(100, 0);
+ expect(channel.sent).toHaveLength(suspendedCount);
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent, grant: "c".repeat(64) });
+ session.scroll(0.75, 0);
+ expect(channel.sent).toHaveLength(suspendedCount);
+ session.dispose();
+});
+
+it("flushes coalesced motion before buttons and discards it when control ends", () => {
+ vi.useFakeTimers();
+ const channel = new Channel();
+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});
+ const grant = "b".repeat(64);
+ try {
+ channel.receive({ platform: "windows", mode: "ask", state: "ready" });
+ session.request();
+ const intent = channel.sent.at(-1)?.intent;
+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent, grant });
+ session.input({ type: "move", x: 0.2, y: 0.3 });
+ session.input({ type: "move", x: 0.7, y: 0.8 });
+ session.input({ type: "button", button: 0, down: false });
+ expect(channel.sent.slice(-2)).toEqual([
+ { type: "move", x: 0.7, y: 0.8, grant },
+ { type: "button", button: 0, down: false, grant },
+ ]);
+ expect(vi.getTimerCount()).toBe(0);
+ session.input({ type: "relative", dx: 3, dy: -2 });
+ session.input({ type: "relative", dx: 4, dy: 5 });
+ vi.advanceTimersByTime(4); // Input does not depend on a rendered frame.
+ expect(channel.sent.at(-1)).toEqual({ type: "relative", dx: 7, dy: 3, grant });
+ session.input({ type: "move", x: 0.9, y: 0.1 });
+ const count = channel.sent.length;
+ channel.receive({ platform: "windows", mode: "ask", state: "ready", intent });
+ expect(vi.getTimerCount()).toBe(0);
+ expect(channel.sent).toHaveLength(count);
+ } finally {
+ session.dispose();
+ vi.useRealTimers();
+ }
+});
diff --git a/tests/remote-keyboard.test.ts b/tests/remote-keyboard.test.ts
new file mode 100644
index 00000000..c977d879
--- /dev/null
+++ b/tests/remote-keyboard.test.ts
@@ -0,0 +1,53 @@
+import { expect, it, vi } from "vitest";
+import { RemoteKeyboardPresses } from "../src/client/remote-control/keyboard";
+import type { RemoteInputEvent } from "../src/client/remote-control/input-session";
+
+it("keeps a selected modifier across keys without repeating it and releases it on reset", () => {
+ vi.useFakeTimers();
+ try {
+ const events: RemoteInputEvent[] = [];
+ const keyboard = new RemoteKeyboardPresses(event => events.push(event));
+ keyboard.down(-2, ["ControlLeft"], false);
+ keyboard.tap(["ControlLeft", "KeyC"]);
+ keyboard.tap(["ControlLeft", "KeyV"]);
+ vi.advanceTimersByTime(1000);
+ expect(events).toEqual([
+ { type: "key", code: "ControlLeft", down: true },
+ { type: "key", code: "KeyC", down: true }, { type: "key", code: "KeyC", down: false },
+ { type: "key", code: "KeyV", down: true }, { type: "key", code: "KeyV", down: false },
+ ]);
+ keyboard.reset();
+ expect(events.at(-1)).toEqual({ type: "key", code: "ControlLeft", down: false });
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { vi.useRealTimers(); }
+});
+
+it("holds and repeats virtual chords, shares modifiers, and releases every contact on retirement", () => {
+ vi.useFakeTimers();
+ try {
+ const events: RemoteInputEvent[] = [];
+ const keyboard = new RemoteKeyboardPresses(event => events.push(event));
+ keyboard.down(1, ["ControlLeft", "KeyA"]);
+ keyboard.down(2, ["ControlLeft", "KeyC"]);
+ keyboard.up(1);
+ expect(events).toEqual([
+ { type: "key", code: "ControlLeft", down: true }, { type: "key", code: "KeyA", down: true },
+ { type: "key", code: "KeyC", down: true }, { type: "key", code: "KeyA", down: false },
+ ]);
+ vi.advanceTimersByTime(450);
+ expect(events.slice(-2)).toEqual(Array(2).fill({ type: "key", code: "KeyC", down: true }));
+ keyboard.reset(); keyboard.up(2);
+ expect(events.slice(-2)).toEqual([
+ { type: "key", code: "KeyC", down: false }, { type: "key", code: "ControlLeft", down: false },
+ ]);
+ const count = events.length;
+ vi.advanceTimersByTime(1000);
+ expect(events).toHaveLength(count);
+ keyboard.tap(["MetaLeft", "Space"]);
+ expect(events.slice(-4)).toEqual([
+ { type: "key", code: "MetaLeft", down: true }, { type: "key", code: "Space", down: true },
+ { type: "key", code: "Space", down: false }, { type: "key", code: "MetaLeft", down: false },
+ ]);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { vi.useRealTimers(); }
+});
diff --git a/tests/remote-touchpad.test.ts b/tests/remote-touchpad.test.ts
new file mode 100644
index 00000000..56aee4ae
--- /dev/null
+++ b/tests/remote-touchpad.test.ts
@@ -0,0 +1,88 @@
+import { expect, it, vi } from "vitest";
+import { RemoteTouchpad } from "../src/client/remote-control/touchpad";
+import type { RemoteInputEvent } from "../src/client/remote-control/input-session";
+
+it("keeps taps, dragging, two-finger gestures and grant retirement distinct", () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
+ try {
+ const events: RemoteInputEvent[] = [], scroll: number[] = [];
+ vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 16));
+ vi.stubGlobal("cancelAnimationFrame", clearTimeout);
+ const touchpad = new RemoteTouchpad(() => ({ width: 200, height: 100 }),
+ event => events.push(event), delta => scroll.push(delta), () => {}, { scale: 1, transform: () => {}, visiblePosition: position => position });
+ touchpad.down(1, 20, 20); touchpad.up(1);
+ expect(events).toEqual([{ type: "move", x: .5, y: .5 },
+ { type: "button", button: 0, down: true }, { type: "button", button: 0, down: false }]);
+ events.length = 0;
+ touchpad.down(1, 20, 20);
+ touchpad.move(1, 24, 22); // Below the tap threshold: retain, don't lose motion.
+ touchpad.move(1, 26, 23);
+ touchpad.move(1, 70, 45); touchpad.up(1);
+ expect(events.at(-1)).toEqual({ type: "move", x: .75, y: .75 });
+ expect(events.some(event => event.type === "button")).toBe(false);
+
+ events.length = 0;
+ touchpad.down(1, 20, 20); vi.advanceTimersByTime(500); touchpad.move(1, 500, 45);
+ expect(touchpad.position).toEqual({ x: 1, y: 1 });
+ touchpad.reset(); touchpad.up(1); vi.advanceTimersByTime(1000);
+ expect(events.filter(event => event.type === "button")).toEqual([
+ { type: "button", button: 0, down: true }, { type: "button", button: 0, down: false },
+ ]);
+
+ events.length = 0;
+ touchpad.down(1, 20, 20); touchpad.down(2, 40, 20); touchpad.up(2);
+ touchpad.cancel(2); // Normal pointer-up also emits lostpointercapture.
+ touchpad.up(1);
+ expect(events.slice(-2)).toEqual([
+ { type: "button", button: 2, down: true }, { type: "button", button: 2, down: false },
+ ]);
+ events.length = 0;
+ touchpad.down(1, 20, 20); touchpad.down(2, 40, 20);
+ touchpad.move(1, 20, 50); touchpad.move(2, 40, 50);
+ touchpad.up(1); touchpad.move(2, 40, 80); touchpad.up(2);
+ expect(scroll.reduce((sum, delta) => sum + delta, 0)).toBe(-30);
+ expect(events.some(event => event.type === "button")).toBe(false);
+
+ touchpad.down(1, 20, 20); touchpad.reset(); vi.advanceTimersByTime(600);
+ expect(events.some(event => event.type === "button")).toBe(false);
+ } finally { vi.useRealTimers(); vi.unstubAllGlobals(); }
+});
+
+it("keeps pinch/pan local and never turns the remaining finger into a remote click", () => {
+ vi.useFakeTimers();
+ vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 16));
+ vi.stubGlobal("cancelAnimationFrame", clearTimeout);
+ try {
+ const input = vi.fn(), scroll = vi.fn(), transform = vi.fn();
+ const viewport = { scale: 1, transform, visiblePosition: (position: { x: number; y: number }) => position };
+ const pad = new RemoteTouchpad(() => ({ width: 200, height: 100 }), input, scroll, () => {}, viewport);
+ pad.down(1, 40, 50); pad.down(2, 160, 50);
+ input.mockClear();
+ pad.move(1, 10, 50); pad.move(2, 190, 50);
+ vi.advanceTimersByTime(16);
+ expect(transform).toHaveBeenLastCalledWith({ x: 100, y: 50 }, { x: 100, y: 50 }, 1.5);
+ pad.up(1); pad.move(2, 180, 60); pad.up(2);
+ expect(input).not.toHaveBeenCalled();
+ expect(scroll).not.toHaveBeenCalled();
+
+ viewport.scale = 1.5;
+ pad.down(1, 40, 50); pad.down(2, 160, 50);
+ pad.move(1, 60, 70); pad.move(2, 180, 70);
+ vi.advanceTimersByTime(16);
+ expect(transform).toHaveBeenLastCalledWith({ x: 100, y: 50 }, { x: 120, y: 70 }, 1);
+ expect(scroll).not.toHaveBeenCalled();
+ pad.up(1); pad.up(2);
+
+ // A zoomed two-finger tap remains a right-click, and cancellation discards
+ // pending local movement instead of replaying it after the grant ends.
+ pad.down(1, 40, 50); pad.down(2, 160, 50);
+ pad.up(1); pad.up(2);
+ expect(input.mock.calls.slice(-2)).toEqual([
+ [{ type: "button", button: 2, down: true }], [{ type: "button", button: 2, down: false }],
+ ]);
+ pad.down(1, 40, 50); pad.down(2, 160, 50);
+ pad.move(1, 10, 50); transform.mockClear(); pad.reset();
+ vi.advanceTimersByTime(600);
+ expect(transform).not.toHaveBeenCalled();
+ } finally { vi.useRealTimers(); vi.unstubAllGlobals(); }
+});
diff --git a/tests/room-interactions.test.ts b/tests/room-interactions.test.ts
index 54490a8f..b46448c3 100644
--- a/tests/room-interactions.test.ts
+++ b/tests/room-interactions.test.ts
@@ -1,6 +1,6 @@
import { afterEach, expect, test, vi } from "vitest";
import { CHAT_HISTORY_LIMIT, CHAT_OVERLAY_DURATION_MS, RoomInteractionSession, type RoomInteraction } from "../src/client/lib/room-interactions";
-import { normalizeChatText } from "../src/shared/room-interactions";
+import { REACTION_IDS, normalizeChatText } from "../src/shared/room-interactions";
import { formatChatTranscript } from "../src/client/lib/room-chat-export";
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
@@ -15,6 +15,26 @@ function setup() {
const message = (id: string): RoomInteraction => ({ type: "room-interaction", id, requestId: "request_1234", occurredAt: Date.now(),
sender: { peerId: "other_peer_1234", role: "viewer", displayName: "朋友" }, payload: { kind: "chat", text: "Hello" } });
+test.each([
+ { advertised: undefined, expected: ["laugh", "eyes", "wow", "wave", "heart", "clap", "party", "fire", "star", "sleep", "tomato", "poop"] },
+ { advertised: ["heart", "thumbsup", "future-effect"], expected: ["thumbsup", "heart"] },
+ { advertised: [], expected: [] },
+])("sends only known Server-supported reactions: $advertised", ({ advertised, expected }) => {
+ const send = vi.fn(() => true);
+ const session = new RoomInteractionSession(send, Date.now, advertised);
+ session.authenticated("self_peer_1234");
+ session.receive({ type: "room-interactions-ready", serverTime: Date.now() });
+ expect(session.getSnapshot().reactionIds).toEqual(expected);
+ for (const reaction of REACTION_IDS.filter(id => !expected.includes(id))) {
+ expect(session.send({ kind: "reaction", reaction, targetPeerId: "other_peer_1234" })).toBe(false);
+ }
+ expect(send).toHaveBeenCalledTimes(1); // Unsupported commands never reach signaling.
+ expect(session.send(advertised?.includes("thumbsup")
+ ? { kind: "reaction", reaction: "thumbsup" }
+ : { kind: "chat", text: "Still here" })).toBe(true);
+ session.close();
+});
+
test("appearance is local, preserves a running flight, survives re-admission and resets with the room", () => {
const { session, send } = setup();
session.receive({ type: "room-interactions-ready", serverTime: Date.now() });
diff --git a/tests/room-preferences.test.ts b/tests/room-preferences.test.ts
new file mode 100644
index 00000000..0a31943d
--- /dev/null
+++ b/tests/room-preferences.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { readRoomPreferences, saveRoomPreferences } from "../src/client/lib/room-preferences";
+import { RoomInteractionSession } from "../src/client/lib/room-interactions";
+
+afterEach(() => vi.unstubAllGlobals());
+
+function storage() {
+ const values = new Map<string, string>();
+ vi.stubGlobal("window", { localStorage: {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => values.set(key, value),
+ } });
+ return values;
+}
+
+it("keeps independent room-tool choices across reads without storing private runtime fields", () => {
+ const values = storage();
+ saveRoomPreferences({ pictureFit: "cover", routePreference: "p2p", keyboardPage: "text", combineKeys: true });
+ saveRoomPreferences({ interactionEffects: false, remoteControlMode: "password" });
+ expect(readRoomPreferences()).toMatchObject({ pictureFit: "cover", routePreference: "p2p", keyboardPage: "text",
+ combineKeys: true, interactionEffects: false, remoteControlMode: "password" });
+
+ // Storage accepts only the preference contract, even if a caller supplies a
+ // room snapshot with credentials, text or actual held input by mistake.
+ saveRoomPreferences(Object.assign({ overlayEnabled: true }, {
+ password: "private", grant: "private", text: "private", modifiers: ["ControlLeft"], controller: "other-peer",
+ }));
+ const saved = JSON.parse([...values.values()][0]);
+ expect(saved.overlayEnabled).toBe(true);
+ expect(saved.remoteControlMode).toBe("password");
+ for (const field of ["password", "grant", "text", "modifiers", "controller"]) expect(saved).not.toHaveProperty(field);
+ expect([...values.values()][0]).not.toContain("private");
+ expect(readRoomPreferences().pictureFit).toBe("cover");
+});
+
+it("rejects malformed saved data and invalid patches while retaining useful defaults", () => {
+ const values = storage();
+ const defaults = readRoomPreferences();
+ saveRoomPreferences({ remoteControlMode: "room" });
+ const [key] = [...values.keys()];
+ saveRoomPreferences(JSON.parse('{"remoteControlMode":"off"}'));
+ expect(readRoomPreferences().remoteControlMode).toBe("room");
+ for (const raw of ["{", "null", JSON.stringify({ overlayAppearance: { scale: 100, opacity: 0 } })]) {
+ values.set(key, raw);
+ expect(readRoomPreferences()).toEqual(defaults);
+ }
+});
+
+it("restores overlay choices in a new room without restoring messages or room authority", () => {
+ storage();
+ const first = new RoomInteractionSession(() => true);
+ first.setOverlayEnabled(true);
+ first.setOverlayAppearance({ scale: 100, opacity: -1 });
+ first.close();
+ const next = new RoomInteractionSession(() => true);
+ expect(next.getSnapshot()).toMatchObject({ overlayEnabled: true, overlayAppearance: { scale: 1.3, opacity: .4 },
+ ready: false, peerId: null, messages: [], overlayMessages: [], reactions: [], pending: null });
+ next.close();
+});
+
+it("keeps room tools working when Browser storage is unavailable", () => {
+ vi.stubGlobal("window", { get localStorage() { throw new Error("storage denied"); } });
+ expect(readRoomPreferences()).toMatchObject({ pictureFit: "contain", routePreference: "auto", remoteControlMode: "ask" });
+ expect(() => saveRoomPreferences({ keyboardPage: "symbols" })).not.toThrow();
+ const session = new RoomInteractionSession(() => true);
+ session.setOverlayEnabled(true);
+ session.setOverlayAppearance({ scale: 1.2, opacity: .5 });
+ expect(session.getSnapshot()).toMatchObject({ overlayEnabled: true, overlayAppearance: { scale: 1.2, opacity: .5 } });
+ session.close();
+});
diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.ts
index 7ef8e919..c50a4477 100644
--- a/tests/sfu-client.test.ts
+++ b/tests/sfu-client.test.ts
@@ -95,7 +95,7 @@ class FakeSender {
}
}
-class FakePc {
+class FakePc extends EventTarget {
static instances: FakePc[] = [];
onicecandidate: ((event: { candidate: unknown }) => void) | null = null;
onconnectionstatechange: (() => void) | null = null;
@@ -148,6 +148,7 @@ class FakePc {
async (_candidate: RTCIceCandidateInit) => undefined,
);
constructor(readonly configuration: RTCConfiguration) {
+ super();
FakePc.instances.push(this);
}
addTransceiver(track: FakeTrack | string, options: RTCRtpTransceiverInit) {
@@ -164,6 +165,7 @@ class FakePc {
state(state: RTCPeerConnectionState): void {
this.connectionState = state;
this.onconnectionstatechange?.();
+ this.dispatchEvent(new Event("connectionstatechange"));
}
}
diff --git a/tests/signaling-admission.test.ts b/tests/signaling-admission.test.ts
index 2fe5e8a6..df7ade79 100644
--- a/tests/signaling-admission.test.ts
+++ b/tests/signaling-admission.test.ts
@@ -38,6 +38,72 @@ function fixture(role: "host" | "viewer" = "host") {
}
describe("room authentication and site admission", () => {
+ it("opts into audio presence after discovery and replays subscriptions and Host intent on reconnect", async () => {
+ const wire = JSON.parse(readFileSync(new URL("./fixtures/wire-samples.json", import.meta.url), "utf8"));
+ const auth = (role: string) => JSON.parse(wire.serverMessages.find(
+ (sample: { name: string }) => sample.name === `authenticated-${role}-minimal`).json);
+ const viewer = fixture("viewer");
+ viewer.sockets[0]!.receive(auth("viewer"));
+ expect(viewer.sockets[0]!.send.mock.calls.some(([raw]) => JSON.parse(raw).type === "subscribe-audio-presence")).toBe(false);
+ viewer.signal.enableAudioPresence();
+ expect(viewer.sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "subscribe-audio-presence" }));
+ viewer.sockets[0]!.dispatchEvent(Object.assign(new Event("close"), { code: 1006 }));
+ await vi.advanceTimersByTimeAsync(800);
+ viewer.sockets[1]!.dispatchEvent(new Event("open"));
+ viewer.sockets[1]!.receive(auth("viewer"));
+ expect(viewer.sockets[1]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "subscribe-audio-presence" }));
+ viewer.signal.stop();
+
+ const host = fixture();
+ host.signal.setAudioAvailable(false);
+ const authenticated = { ...auth("host"), shareGeneration: "share_generation_12345678" };
+ host.sockets[0]!.receive(authenticated);
+ expect(host.sockets[0]!.send.mock.calls.some(([raw]) => JSON.parse(raw).type === "set-audio-presence")).toBe(false);
+ host.signal.enableAudioPresence();
+ host.signal.setAudioAvailable(true);
+ const intent = { type: "set-audio-presence", shareGeneration: authenticated.shareGeneration, available: true };
+ expect(host.sockets[0]!.send).toHaveBeenLastCalledWith(JSON.stringify(intent));
+ host.sockets[0]!.dispatchEvent(Object.assign(new Event("close"), { code: 1006 }));
+ host.signal.setAudioAvailable(false);
+ await vi.advanceTimersByTimeAsync(800);
+ host.sockets[1]!.dispatchEvent(new Event("open"));
+ host.sockets[1]!.receive(authenticated);
+ expect(host.sockets[1]!.send).toHaveBeenCalledWith(JSON.stringify({ ...intent, available: false }));
+ host.signal.stopSharing(authenticated.shareGeneration);
+ host.signal.startSharing("next_audio_generation", authenticated.qualitySettings, DEFAULT_ROUTE_POLICY);
+ host.signal.setAudioAvailable(true);
+ const next = { ...intent, shareGeneration: "next_audio_generation" };
+ expect(host.sockets[1]!.send).not.toHaveBeenCalledWith(JSON.stringify(next));
+ host.sockets[1]!.receive({ type: "sharing-started", shareGeneration: "next_audio_generation",
+ routePolicy: DEFAULT_ROUTE_POLICY, routeRevision: authenticated.routeRevision,
+ routeAssignment: authenticated.routeAssignment, qualitySettings: authenticated.qualitySettings, paused: false });
+ expect(host.sockets[1]!.send).toHaveBeenCalledWith(JSON.stringify(next));
+ host.signal.stop();
+ });
+
+ it("restores Viewer route preference after discovery and reconnects with the acknowledged choice", async () => {
+ const { signal, sockets, events } = fixture("viewer");
+ const wire = JSON.parse(readFileSync(new URL("./fixtures/wire-samples.json", import.meta.url), "utf8"));
+ const authenticated = JSON.parse(wire.serverMessages.find(
+ (sample: { name: string }) => sample.name === "authenticated-viewer-minimal").json);
+ expect(JSON.parse(sockets[0]!.send.mock.calls[0]![0])).not.toHaveProperty("routePreference");
+ expect(signal.setViewerRoutePreference("sfu")).toBe(false);
+ // Capability discovery finishes after authenticate went onto the wire.
+ signal.enableViewerRouteSelection("sfu");
+ sockets[0]!.receive(authenticated);
+ expect(sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "set-viewer-route-preference", preference: "sfu" }));
+ expect(signal.setViewerRoutePreference("p2p")).toBe(true);
+ sockets[0]!.receive({ type: "viewer-route-preference", preference: "p2p", accepted: true });
+ expect(signal.setViewerRoutePreference("sfu")).toBe(true);
+ sockets[0]!.receive({ type: "viewer-route-preference", preference: "p2p", accepted: false });
+ sockets[0]!.dispatchEvent(Object.assign(new Event("close"), { code: 1006 }));
+ await vi.advanceTimersByTimeAsync(800);
+ sockets[1]!.dispatchEvent(new Event("open"));
+ expect(JSON.parse(sockets[1]!.send.mock.calls[0]![0])).toMatchObject({ type: "authenticate", routePreference: "p2p" });
+ expect(events.onTerminated).not.toHaveBeenCalled();
+ signal.stop();
+ });
+
it("skips an unknown reaction without interrupting chat, media messages or a pending send", () => {
const { signal, sockets, events } = fixture();
const interactions = signal.interactions!;