Compare commits

..
3 Commits
  • fix(app): clarify site entry and update guidance (#458)
    ## Problem and outcome / 问题与结果
    
    The App's update notice lacked a separate release-note link and any distinction
    for a new major release. Site entry also required users to supply the URL scheme.
    This maintenance phase keeps direct manual downloads, adds concise major-upgrade
    guidance in the App and Server log, and accepts bare Site domains through the
    existing App normalizer. Explicit HTTP/HTTPS origins retain their meaning.
    
    The shared launcher preview and accessibility copy follow the same behavior.
    Website brand baselines are aligned; source-map-js is updated to 1.2.2 in both
    build lockfiles. Windows capture self-tests now retain the first worker exception
    and report the failing phase and output progress without changing deadlines or
    production capture behavior. The Magicsock assessment remains documentation only.
    
    ## Release notes
    
    ### 中文
    
    这是一次维护更新,重点改善 Piik App 的站点连接和版本更新体验。现有设置和连接协议保持兼容。
    
    - **站点地址填写更省事:** 可以直接输入域名,App 自动补全 HTTPS;粘贴完整 HTTP/HTTPS 网址也可直接使用。
    - **更新入口更清晰:** 更新按钮继续下载对应平台的程序包,“版本说明”可单独打开查看;两项操作分排居中。
    - **大版本升级有提示:** 今后检测到新的大版本时,App 会显示简短升级提醒,Server 也会在日志中提示查看不兼容改动。
    - 修正启动页的读屏提示,并对齐官网标志中的小电视与 Piik 字样。
    
    ### English
    
    This maintenance update makes Piik App's Site entry and update notices easier to use. Existing settings and connection protocols remain compatible.
    
    - **Easier Site entry:** Enter a domain and the App adds HTTPS, or paste a complete HTTP/HTTPS address.
    - **Clearer update actions:** The update button still downloads the matching platform package. Release notes open separately, with both actions centered on their own rows.
    - **Major-upgrade guidance:** When a newer major release becomes available, the App shows a short upgrade notice and the Server log directs operators to its breaking changes.
    - Corrected launcher screen-reader text and aligned the website's television mark with the Piik wordmark.
    
    ## Verification / 验证
    
    - `npm run check`: 81 test files / 1,378 tests passed; type checking and production Web build passed.
    - `npm run build:website`: homepage, film and bilingual documentation build passed.
    - Launcher browser checks: ordinary/major updates, GitHub/Gitee metadata fallback,
      exact package/release links, no download during detection, missing-package page
      fallback, Chinese/English/visual modes, light/dark themes, 320–1440px layouts and
      scoped accessibility checks passed. Network metadata is simulated in these checks.
    - Bare domain, complete HTTPS and explicit HTTP inputs reached the launch request;
      App configuration and launcher tests passed, including normalization and invalid
      origins. Go vet passed for the affected packages.
    - Repository hygiene and documentation checks passed; existing documentation-length
      and Web bundle-size warnings remain.
    - `npm run check:go`: Go tests, formatting, vet, registered non-Darwin target
      builds, Windows native build, deterministic capture regressions, probe and source
      enumeration passed. Darwin cgo builds were skipped on this Windows runner as designed.
    
    ## Impact / 影响
    
    Maintenance release: v1.9.2. No public wire or storage change: Browser/server v23,
    Native control v9, capture v7 and SQLite schema 2 are unchanged. No media, route,
    room-authority or automatic-installation behavior changes. Site origin validation
    remains strict; a missing scheme defaults to HTTPS without network probing or
    silent HTTP fallback. Configs written by this version still contain complete origins.
    
    Historical installed Apps retain their released update behavior. Future major
    upgrades still need release-specific compatibility instructions. Physical macOS/Linux
    capture and reporter-dependent issues remain outside this maintenance change.
  • docs(website): improve screen sharing discoverability (#457)
    Add descriptive English and Chinese homepage titles and summaries, and introduce private screen sharing, live streaming with friends, and self-hosting naturally in both READMEs. Keep the visible slogan, layout and download behavior. Set the homepage's canonical URL and record the search-copy boundary in the existing public-introduction guide.
    
    The Demo operations example now includes its accepted one-hour empty-room setting.
    
    Validation: website build, documentation and repository checks passed; browser checks covered language switching, metadata, 360px and 1440px layouts and existing Latest download links. The release planner reports `publish: false`; this is a website/documentation update with no App or Server release.
  • fix(rooms): reclaim empty rooms on public sites (#456)
    Public sites can exhaust the four-digit room-code pool because retained room authority has no default expiry. Add an opt-in empty-room timeout and reclaim the oldest eligible empty room when capacity is exhausted. Connected Hosts and Viewers retain their rooms through sharing, pause and idle chat; the existing reconnect grace protects early reclamation.
    
    The default remains disabled, including App Local and the internal deployment. The public Demo will use `ROOM_EMPTY_TIMEOUT_SECONDS=3600`. Retirement reuses the storage-first deletion and signaling cleanup owners; no protocol or SQLite schema changes are required.
    
    Validation: Web type-check, 81 test files / 1372 tests and production build; Go core tests, formatting, vet and target builds; documentation/project hygiene; access-privacy gate; live server expiry/occupied-room check. Regression coverage includes all 9000 codes, restart, stale credentials, reconnects, revocation and atomic storage failure. Native device behavior is unchanged; physical macOS/Linux acceptance retains its documented limits.
    
    ## Release notes
    
    ### 中文
    
    这是一次面向公共站点的维护更新,解决长期保留的空房间占满房间号的问题。
    
    - 管理员可配置空房间回收时长;号码用满时,优先回收过期空房间,再按创建顺序回收符合条件的空房间。在线分享、暂停和聊天均会保留。
    - 房间号确实已用满时,界面会显示更明确的提示。
    - 自动回收默认关闭。公共站点可设置 `ROOM_EMPTY_TIMEOUT_SECONDS=3600`,在房间连续无人在线一小时后回收;未配置的站点保持原有行为。
    
    ### English
    
    This maintenance release helps public sites avoid exhausting room codes through indefinitely retained empty rooms.
    
    - Operators can configure an empty-room timeout. When all codes are in use, allocation reclaims expired empty rooms first, then the oldest eligible empty room. Connected sharing, paused sessions and chat remain protected.
    - Capacity errors now provide clearer guidance when no room code is available.
    - Automatic reclamation is disabled by default. Public sites can set `ROOM_EMPTY_TIMEOUT_SECONDS=3600` to retire rooms after one continuous hour with no connected participants. Unconfigured sites retain their existing behavior.
61 changed files with 1046 additions and 154 deletions

No files matched your search

+4
View File
@@ -16,6 +16,10 @@ SITE_ACCESS_PASSWORD=
# should use an access-restricted absolute path outside the release directory,
# preserving the existing database and its writable parent across updates.
ROOM_DATABASE_PATH=
# Optional empty-room recycling. 0 keeps rooms indefinitely (default).
# 3600 expires rooms after an hour with no authenticated participants; when
# all codes are used, the oldest empty room may be reclaimed earlier.
ROOM_EMPTY_TIMEOUT_SECONDS=0
# Viewers per room, excluding the Host. Valid range: 1..20; default: 20.
MAX_VIEWERS_PER_ROOM=20
# Bounded standard-WebRTC relay/SFU controller is active for every room.
+4 -3
View File
@@ -15,9 +15,10 @@
</p>
<p align="center">English · <a href="./README.zh-CN.md">简体中文</a></p>
Piik is a free, open-source screen sharing tool for games, movie nights,
drawings and photos. Choose what to share and send an invitation. Your friends
watch in their browsers.
Piik is a free, open-source screen sharing tool for private live streams with
friends: games, movie nights, drawings and photos. Choose what to share and send
an invitation. Your friends watch in their browsers. You can also self-host Piik
on your own server.
<details open>
<summary>A little room · Show / hide animation</summary>
+2 -2
View File
@@ -15,8 +15,8 @@
</p>
<p align="center"><a href="./README.md">English</a> · 简体中文</p>
Piik 是一个免费开源的屏幕共享工具,适合游戏围观、一起看电影、展示绘画或分享照片。
选择画面,把邀请链接发给朋友,对方用浏览器即可观看。
Piik 是一个免费开源的私密屏幕共享工具,适合游戏直播、一起看电影、展示绘画或分享照片。
选择画面,把邀请链接发给朋友,对方用浏览器即可观看。也支持自部署,搭建自己的 Piik 站点。
<details open>
<summary>客厅小剧场 · 展开 / 收起动画</summary>
+4 -2
View File
@@ -35,8 +35,10 @@ publication are separate steps in [deployment](../../docs/deployment.md).
covers saved preferences and custom paths.
- The `--site`, `--local`, and `--link` flags select a mode for CI and development.
- The default launcher checks official releases after it opens, using GitHub
first and Gitee if GitHub is unavailable. It opens the matching platform ZIP
when available, falling back to the release page. It does not install or replace the App.
first and Gitee if GitHub is unavailable. Click the update button to download
the matching platform ZIP, or open the release page when no package matches.
**Release notes** opens separately; a new major version includes an upgrade
warning. The App does not install or replace itself.
Local rooms last for this App run and work on a reachable LAN. **Public invite**
uses the packaged Cloudflare Tunnel helper to expose that same room service at a
+2 -1
View File
@@ -29,7 +29,8 @@ Apple 芯片或 Intel Mac,以及 macOS 13 或更新版本。构建程序包与
[App 配置](../../docs/standards/configuration.md#piik-app-configuration)。
- `--site`、`--local` 和 `--link` 用于在 CI 或开发时直接选择模式。
- 默认启动页打开后会检查官方发布,优先使用 GitHub,GitHub 不可用时使用 Gitee。
有对应平台的 ZIP 时直接打开下载地址,否则打开发布页。App 不会自行安装或替换程序。
点击更新按钮下载对应平台的 ZIP,没有匹配包时打开发布页。
**版本说明** 可单独查看;发现新的大版本时会显示升级提示。App 不会自行安装或替换程序。
本地房间仅在本次 App 运行期间有效,适用于设备间可互相访问的局域网。
**公网邀请** 通过程序包中的 Cloudflare Tunnel 辅助程序,为同一个房间服务提供临时 HTTPS 地址。
+7 -1
View File
@@ -126,7 +126,13 @@ func logReleaseNotice(logger *slog.Logger, result releaseResult) {
if result.CurrentVersion != nil {
current = *result.CurrentVersion
}
logger.Info(message, "event", "release-check", "status", result.Status,
level := slog.LevelInfo
if result.Status == statusUpdateAvailable && semver.IsValid(current) &&
semver.Major(*result.LatestVersion) != semver.Major(current) {
level = slog.LevelWarn
message = "A new major Piik release is available; review breaking changes in the release notes before upgrading"
}
logger.Log(context.Background(), level, message, "event", "release-check", "status", result.Status,
"currentVersion", current, "latestVersion", *result.LatestVersion, "releaseUrl", *result.ReleaseURL)
}
+22
View File
@@ -51,6 +51,28 @@ func TestReleaseNoticeUsesOperatorLogsOnlyForAvailableChoices(t *testing.T) {
}
}
func TestReleaseNoticeWarnsAboutANewerMajorWithoutChangingCheckerStatus(t *testing.T) {
for _, current := range []string{"v1.9.1", "v2.0.0-rc.1", "development"} {
t.Run(current, func(t *testing.T) {
var output bytes.Buffer
version, page := "v2.0.0", releaseURLPrefix+"v2.0.0"
logReleaseNotice(slog.New(slog.NewJSONHandler(&output, nil)), releaseResult{
Status: statusUpdateAvailable, CurrentVersion: &current, LatestVersion: &version, ReleaseURL: &page,
})
var entry map[string]any
if err := json.Unmarshal(output.Bytes(), &entry); err != nil {
t.Fatal(err)
}
warning := current == "v1.9.1"
if (entry["level"] == "WARN") != warning ||
strings.Contains(entry["msg"].(string), "breaking changes") != warning ||
entry["status"] != statusUpdateAvailable || entry["releaseUrl"] != page {
t.Fatalf("incorrect major release notice: %v", entry)
}
})
}
}
func TestParseReleaseMetadataAcceptsOnlyTheStrictReleaseIdentity(t *testing.T) {
tagged := func(version, page string) string {
return `{"tag_name":"` + version + `","html_url":"` + page + `"}`
+3
View File
@@ -4,6 +4,9 @@ STUN_URLS=stun:share.example.com:3478
MAX_VIEWERS_PER_ROOM=20
# Empty means the site opens without a site password. Room access is separate.
SITE_ACCESS_PASSWORD=
# Optional for public sites: reclaim empty rooms after an hour, or earlier
# under room-code pressure. Unset/0 preserves room authority indefinitely.
# ROOM_EMPTY_TIMEOUT_SECONDS=3600
# Optional automatic media fallback: set BOTH values and allow UDP 7882.
# SFU_UDP_PORT=7882
@@ -28,11 +28,15 @@ Every room owns:
- a monotonically increasing Viewer authorization generation;
- `open | private` code entry and optional salted scrypt password material.
Room authority has no time limit. Stop, disconnect and inactivity do not change
it. Explicit replacement or deletion invalidates its credentials and releases
the code; grant rotation or revocation retires the invitation independently.
There is no lease, renewal, expiry timer or replacement garbage collector.
The existing 9,000-code bound remains; a full store rejects new rooms.
Room authority has no time limit by default. Explicit replacement or deletion
invalidates its credentials and releases the code; grant rotation or revocation
retires the invitation independently. Public sites may opt into the
[empty-room retention policy](../standards/rooms-access.md#optional-empty-room-retention)
to keep abandoned allocations from exhausting the 9,000-code space. Occupancy,
including idle chat, protects a room; the existing signaling heartbeat owns
expiry and normal retirement owns cleanup. There is no client lease or renewal.
The allocation bound remains; a full store rejects creation when no empty room
is reclaimable.
Site-access cookies retain their separate 24-hour rolling idle lifetime.
### Lightweight And Stable Storage
@@ -126,8 +130,10 @@ returns `ROOM_ACCESS_DENIED`.
- Both modes pass the same creation, ownership, admission, password,
rotate/revoke, replacement and 9,000-code-capacity behavior.
- Inactivity cannot invalidate room authority. Stable restart preserves it
exactly and restores no participant or media authority.
- Default inactivity cannot invalidate room authority. Opt-in retention only
retires empty rooms, commits storage first and cleans up all transient effects.
Stable restart preserves authority, restarts the empty interval and restores
no participant or media authority.
- A surviving Host and Viewer can reauthenticate after restart, receive fresh
sessions/routes, and recommit media; an old revoked grant stays revoked.
- Replacement never returns the old code, never partially retires the old room,
@@ -142,4 +148,5 @@ returns `ROOM_ACCESS_DENIED`.
- [`modernc.org/sqlite` driver](https://pkg.go.dev/modernc.org/sqlite)
- [SQLite transactional guarantees](https://www.sqlite.org/transactional.html)
- [SQLite locking mode](https://sqlite.org/pragma.html#pragma_locking_mode)
- [LiveKit room lifecycle timeouts](https://docs.livekit.io/reference/other/roomservice-api/)
- [LiveKit reconnect behavior](https://docs.livekit.io/intro/basics/connect/#network-changes-and-reconnection)
+7 -3
View File
@@ -76,6 +76,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.
| Filename contains | Platform |
| --- | --- |
| `windows-amd64` | Windows x64 |
@@ -101,9 +105,9 @@ See the [App guide](../../cmd/piik-app/README.md) for package and runtime detail
For Local room and Public invite, expand **Site passphrase** to set an optional
access passphrase.
For **Connect to Site**, enter the full site address, such as
`https://demo.piik.tv`, then choose **Open Piik**. Enter the site's passphrase
on the page that opens if asked.
For **Connect to Site**, enter a domain such as `demo.piik.tv` or paste the full
site address, then choose **Open Piik**. HTTPS is added when omitted; for an HTTP
site, include `http://`. Enter the site's passphrase on the page that opens if asked.
After opening the site through the App once, the same browser remembers that
entry. Keep the App running with that site configured and you can visit the
address directly. **Start sharing** opens the selector; choose **Apps / Windows**
+5 -1
View File
@@ -69,6 +69,9 @@ App 的本地房间和临时公网邀请会随本次 App 退出而结束。
然后选定要分享的画面与声音。
5. 复制房间邀请发给朋友。分享期间保持 App 和分享标签页打开。
启动页提示更新时,可点击 **版本说明** 查看 GitHub 或 Gitee 上的详情。
跨大版本更新会显示兼容性提醒;替换 App 前,请先阅读升级说明。
| 文件名包含 | 适用平台 |
| --- | --- |
| `windows-amd64` | Windows x64 |
@@ -92,7 +95,8 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)
本地房间和公网邀请可展开 **站点口令** 设置可选的访问口令。
使用 **连接站点** 时,填写完整地址,例如 `https://demo.piik.tv`,然后点击 **进入 Piik**。
使用 **连接站点** 时,输入域名(例如 `demo.piik.tv`)或粘贴完整网址,然后点击 **进入 Piik**。
省略前缀时自动使用 HTTPS;HTTP 站点请填写 `http://`。
如果站点要求访问口令,在打开的站点页面输入。通过 App 打开过一次后,同一浏览器会记住这个入口。
保持 App 运行并使用该站点配置,之后就能直接访问网址。点击 **开始分享**,
在选择器里选 **程序 / 窗口** 或 **屏幕**,即可使用 App 采集。
+2 -1
View File
@@ -12,8 +12,9 @@ collect a diagnostic report if the problem persists.
| App startup fails, or no page opens automatically | Read the reason on the page and in the terminal. If the App is still running, copy its address into your browser. See [App diagnostics](../../cmd/piik-app/README.md#diagnostics) to collect a report; if Local mode lists several addresses, choose an adapter and IP on the launch page. |
| Public invitation fails to start, or a link shows 1033 | Check the host's App and current link using [public invitation troubleshooting](#public-invitation-fails-or-shows-1033). |
| Local invitation will not open | Check that both devices are on the same network and can reach each other. Guest Wi-Fi or firewall rules can block local access. |
| Room code says the room does not exist | Codes work only on the site where the room was created. Open the host's full invitation link; see [joining a room](./getting-started.md#join-a-friends-room). |
| Room code says the room does not exist | Open the host's current full invitation link. Codes work only on their original site; a site with empty-room recycling may also have reclaimed it. The host can create a new room; see [joining a room](./getting-started.md#join-a-friends-room). |
| Cannot create a room (403) | On a self-hosted site, ask the administrator to check the [allowed site address](#room-creation-returns-403). |
| All room codes are in use | Retry later or use another Piik site. Administrators can enable [empty-room retention](../operations/self-hosting.md#1-configure-and-start-piik) to reclaim unused codes. This is separate from the per-room Viewer limit. |
| No screen picker | Allow the browser or App to record the screen when the OS asks. Browser capture needs HTTPS or `localhost`; try sharing from a desktop computer. |
| No App windows or screens listed | Check the message in the source picker, then follow [App source troubleshooting](#app-windows-or-screens-are-missing). **Browser** → **Choose what to share** opens the browser's screen, window or tab chooser. |
| Sharing fails after selecting a source | Click the error icon below the TV for details and guidance, then follow [sharing startup checks](#sharing-does-not-start-after-source-selection). |
+2 -1
View File
@@ -12,8 +12,9 @@
| App 启动失败,或没有自动打开网页 | 查看页面和终端中的原因;App 仍在运行时可复制终端中的地址打开。按 [App 运行与诊断说明](../../cmd/piik-app/README.zh-CN.md#诊断)收集报告;本地模式提示多个地址时,在启动页选择网卡和 IP。 |
| 公网邀请创建失败,或打开链接出现 1033 | 按[公网邀请排查](#公网邀请创建失败或出现-1033)检查房主 App 和当前链接。 |
| 本地邀请打不开 | 确认两台设备在同一网络且可以互相访问。访客 Wi-Fi 或防火墙规则可能阻止本地连接。 |
| 输入房间号后提示房间不存在 | 房间号只在创建它的站点有效。优先打开房主发送的完整邀请链接,参阅[加入房间](./getting-started.zh-CN.md#加入朋友的房间)。 |
| 输入房间号后提示房间不存在 | 先打开房主最新的完整邀请链接。房间号只在原站点有效;站点开启空房间回收时,旧房间也可能已被回收,由房主重新创建即可。参阅[加入房间](./getting-started.zh-CN.md#加入朋友的房间)。 |
| 无法创建房间 (403) | 自建站点请联系管理员检查[允许访问的站点地址](#创建房间返回-403)。 |
| 站点房间号已用满 | 稍后重试或使用其他 Piik 站点;管理员可配置[空房间回收](../operations/self-hosting.zh-CN.md#1-配置并启动-piik)。这与单个房间的观众人数上限不同。 |
| 没有屏幕选择弹窗 | 按系统提示允许浏览器或 App 录制屏幕。浏览器采集需要 HTTPS 或 `localhost`,请在电脑上尝试分享。 |
| App 的窗口或屏幕列表为空 | 先查看选源器中的提示,再按 [App 来源排查](#app-找不到窗口或屏幕) 操作;也可以选 **浏览器** → **选择画面**,在浏览器弹窗中选择屏幕、窗口或标签页。 |
| 选源后提示分享失败 | 点击电视下方的错误图标查看原因和排查入口,按[分享启动排查](#选源后无法开始分享)逐步对照。 |
+6
View File
@@ -100,6 +100,12 @@ cause [403 when creating a room](../guide/troubleshooting.md#room-creation-retur
resources. See [room capacity](../standards/configuration.md#room-capacity)
for defaults and the difference from App rooms.
For a public site, optionally set `ROOM_EMPTY_TIMEOUT_SECONDS=3600` and restart.
Rooms with nobody connected are reclaimed after an hour; if all room codes are
used, the oldest empty room can be reclaimed earlier. Occupied rooms keep working.
Reclaimed rooms need new invitations. Unset or `0` keeps the default indefinite
retention; see [room retention](../standards/configuration.md#room-retention).
### 2. Enable HTTPS
Use your existing HTTPS reverse proxy to forward to `127.0.0.1:8787` with
+5
View File
@@ -92,6 +92,11 @@ SITE_ACCESS_PASSWORD=
人数越多,对网络和转发资源的需求也可能增加。默认值及 App 房间的区别见
[人数限制](../standards/configuration.md#room-capacity)。
公开站点可选设 `ROOM_EMPTY_TIMEOUT_SECONDS=3600`,重启后,无人在线的房间会在空置一小时后
回收;房间号用满时,会提前回收最早创建的空房间,仍有人在线的房间不受影响。
被回收的房间需要重新创建并发送邀请。不设置或设为 `0` 则保持默认的长期保留行为,
详见[房间保留策略](../standards/configuration.md#room-retention)。
### 2. 配置 HTTPS
如果已有 HTTPS 反向代理,将请求转发到 `127.0.0.1:8787`,并启用 WebSocket 支持。
+1
View File
@@ -37,6 +37,7 @@ PUBLIC_BASE_URL=https://demo.piik.tv
ALLOWED_ORIGINS=https://demo.piik.tv
SITE_ACCESS_PASSWORD=
ROOM_DATABASE_PATH=/var/lib/piik/rooms.sqlite
ROOM_EMPTY_TIMEOUT_SECONDS=3600
MAX_VIEWERS_PER_ROOM=20
STUN_URLS=stun:stun.piik.tv:3478
NAT_PREDICTION_ENABLED=true
+5 -4
View File
@@ -1,6 +1,6 @@
# Project Memory
Last updated: 2026-10-01
Last updated: 2026-10-06
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
@@ -60,9 +60,10 @@ implementation and routine UI detail.
- Rooms use random four-digit codes, exact Host ownership, room-scoped Viewer
invitations and independent `open | private` code entry. Room authority ends
through explicit replacement/deletion, with separate invitation rotation or
revocation. Hosted defaults to SQLite, with explicit process-memory opt-out;
App Local remains process-only. Site access has a separate 24-hour idle
through replacement/deletion, with separate invitation rotation or revocation.
Hosted operators may opt into empty-room expiry and capacity reclamation;
the default retains rooms indefinitely. Hosted defaults to SQLite, with explicit
process-memory opt-out; App Local remains process-only. Site access has a separate 24-hour idle
cookie lifetime within one service run. Production persists SQLite room
authority; live participants, routes, and media remain process-only.
- Media is automatic and distributed. Ordinary peers are STUN-only and prefer
@@ -202,6 +202,42 @@ for recoverable edge disconnects. Piik's four-start acquisition limit is not a
four-reconnect limit after readiness. Restarting the Quick Tunnel process would
allocate a new public address rather than repair the old invitation.
## Major-Upgrade Delivery Assessment
Reviewed 2026-10-06 against released update checkers and simulated v2.0.0
metadata. The v1.0.0 checker opens a provider's release page; v1.1.0 and v1.9.1
choose a matching ZIP on both GitHub and the Gitee fallback. Detection does not
download or install anything: the user must click. These clients have no
major-upgrade warning. The bounded replay used the released source, not the
current candidate's checker.
The legacy checkers accept exact provider release/asset URLs; release metadata
cannot redirect them to `piik.tv`. A valid GitHub API response wins without
checking whether its page or attachment is reachable. Gitee fallback selects
the highest stable version itself, so keeping GitHub's Latest on a transition
release does not constrain both discovery paths. Publishing a transition
release first cannot guarantee that every installed client receives it.
[Sparkle](https://sparkle-project.org/documentation/publishing/#major-upgrades)
separates major-upgrade presentation from installation and supports
[website downloads](https://sparkle-project.org/documentation/publishing/#downloading-from-a-web-site).
Its [feature-upgrade guidance](https://sparkle-project.org/documentation/publishing/#upgrading-to-newer-features)
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.
The evidence supports direct manual downloads with an optional release-note
link and inline major-upgrade guidance. The accepted behavior belongs to
[versioning](../standards/versioning.md#major-upgrade-guidance). Historical
clients still follow their released behavior; a notice cannot substitute for
actual App/Site compatibility checks. The scope of a future 2.0 break remains
undecided.
## Remaining Gates
- Run the exact clean-revision package on macOS; Linux amd64 is proved.
+5 -2
View File
@@ -13,7 +13,9 @@ code-entry policy and password verifier. It is not a generic
store for future features.
Hosted defaults to SQLite over the same RoomStore contract. Process-only mode
remains an explicit composition; neither mode needs time-based room expiry.
remains an explicit composition. Persistence is independent of the optional
[empty-room retention policy](../standards/rooms-access.md#optional-empty-room-retention):
the default keeps authority indefinitely; public sites may reclaim abandoned codes.
## Stored Authority
@@ -92,7 +94,8 @@ compatibility path. The completed cutover is retained in Git; current
2. Stable restart preserves code, token/grant validation, password, policy,
generation while restoring zero participants or media state.
3. A grant revoked before restart remains revoked afterward.
4. Presence and elapsed time do not mutate durable authority.
4. Default presence and elapsed time do not mutate durable authority; opt-in
retention retires only empty rooms and resets the empty interval on restart.
5. Explicit deletion/replacement releases codes; the allocation bound is unchanged.
6. Corrupt/mismatched/multiply owned state fails before accepting traffic.
7. Surviving Host/Viewer tabs reauthenticate and rebuild a fresh route; no test
+44
View File
@@ -317,6 +317,50 @@ still needs room-authorized key/endpoint exchange, MTU/resource limits and mixed
Browser/Native behavior. The nested probe module and full evidence stay on that
isolated branch; production dependencies and routing remain unchanged.
### Integration Cost And Recovery Controls
The 2026-10-06 assessment retains the probes on `spike/magicsock-assessment`
at `fea0587f`, based on current main. These nested Go modules are outside Piik's
build and dependency graph. Repeated local Tailcat bootstrap, peer denial,
revocation and synthetic SRTP media checks passed; the raw magicsock direct-path
matrix again found the same reachable classes as fresh Pion ICE. Retired shared
mapping-cache reproductions remain causal controls, not the current baseline.
[Tailcat](https://github.com/tailscale/tailcat/blob/b4dc28e8aa8936f0a90a41ad8293a64e3d6b645f/README.md)
provides a supported Go reuse lead: magicsock plus WireGuard, with DERP bootstrap
and relay fallback. Its Browser path at that pin is relay-only. In the isolated
Linux kernel NAT comparison on 2026-10-05, both stacks connected directly through
ordinary/ordinary and open/hard gateways in either direction. Neither delivered
fresh direct payloads through ordinary/hard, hard/ordinary, hard/hard or blocked
UDP pairs within the observation window. Tailcat delivered those cases while
the fixture relay remained available. This demonstrates relay coverage, not
an additional P2P reachability class or a field success rate.
Replacing one gateway mapping without notifying endpoints separated recovery
from initial reachability. Neither established direct path delivered within
20 seconds with the relay closed. Fresh Pion discovery/exchange recovered in
about 0.6 seconds after it was started. Tailcat recovered delivery in about
6.5 seconds through its retained relay; closing it immediately lost delivery
again. Keeping traffic and discovery alive for 45 seconds allowed subsequent
direct delivery after relay closure. Both gateway directions were checked.
These timings have different detection/setup boundaries and are not a Piik
startup or playback benchmark.
The raw Bind adapter also has a composition cost: it consumes unwrapped STUN
payloads, and its discovery retry can outlive Pion's initial check budget.
Dropping the first discovery packet in each direction reproduced that failure;
increasing only the fixture's ICE budget recovered media. The ordinary Pion
loss control recovered without that override. Do not adopt packet prefixes,
diagnostic Ping polling or wider product deadlines as integration shortcuts.
Current recommendation: keep the transport isolated. Go reuse is feasible, but
new key authorization/revocation, underlay readiness, packet-size limits and
relay operation have no demonstrated direct-coverage benefit sufficient for
product integration. A future trial needs matched networks with a repeatable
benefit, separate direct/relayed/first-media results, and current room/route
ownership. IPv6, gateway mapping, Piik prediction, physical routers, decoded
playback and mixed Browser/Native fanout remain outside this comparison.
## Native Mapping Cache And Retry Lifetimes
Pion ICE `v4.4.0` caches a shared socket's STUN mapping by destination for 25
+17 -2
View File
@@ -27,6 +27,7 @@ service secret store or an untracked access-restricted environment file.
| `ALLOWED_ORIGINS` | Unset or empty follows `PUBLIC_BASE_URL`. A non-empty comma-separated list replaces that default; include every trusted browser origin (scheme, host and port). Wildcard is invalid. |
| `SITE_ACCESS_PASSWORD` | Optional in every environment. Unset or empty allows entry without a site password. A configured value is matched exactly, including spaces and Unicode; there are no password length or character rules. General HTTP request limits still apply. Room ownership and Viewer admission remain independent. |
| `ROOM_DATABASE_PATH` | Hosted defaults to `rooms.sqlite` in its working directory when unset or blank. An explicit absolute file path selects another SQLite file; `:memory:` opts into process-memory room authority. App Local remains in memory. |
| `ROOM_EMPTY_TIMEOUT_SECONDS` | Integer `0..31536000`, default `0` (disabled). Positive values enable empty-room expiry and oldest-empty reclamation under allocation pressure. Apply at Server startup; App Local retains its process-only lifecycle. |
| `MAX_VIEWERS_PER_ROOM` | `1..20`, default `20`; excludes the Host. |
| `ENDPOINT_MEDIA_COPY_CAPACITY` | Shared endpoint steady-copy cap `1..3`, default `2`. |
| `STUN_URLS` | Comma-separated advertised `stun:` discovery URLs; at least one is required in production. These are not local bind addresses and may use an unproxied DNS name separate from the Web origin. |
@@ -47,6 +48,15 @@ so increasing it in source requires a compatibility and capacity review. More
Viewers can add relay hops, routing wait and total media load. The setting does
not increase the per-endpoint copy cap or guarantee available bandwidth.
### Room retention
Public sites can use `ROOM_EMPTY_TIMEOUT_SECONDS=3600` to release unused codes.
Only rooms without authenticated participants expire; watching, paused sharing
and idle chat are protected. When all codes are used, the oldest empty room may
be reclaimed before the hour. Expired rooms and invitations must be recreated.
The default `0` preserves existing indefinite-room behavior. The complete
lifecycle and restart semantics belong to [rooms/access](./rooms-access.md#optional-empty-room-retention).
### Media fallback
Automatic SFU fallback runs inside the Hosted process when `SFU_UDP_PORT` is set:
@@ -79,9 +89,9 @@ The SQLite parent directory must exist and be writable. The systemd template
sets `/var/lib/piik/rooms.sqlite` under its managed state directory; the
container image sets `/home/nonroot/rooms.sqlite` under its writable data
directory. Keep the existing database path and data across application updates.
Room authority has no idle expiry; the separate site-access cookie keeps its
Room authority has no idle expiry by default; the separate site-access cookie keeps its
24-hour idle lifetime within one service run. Restarting the App or Server
requires site-password entry again; saved rooms and invitation grants are unaffected.
requires site-password entry again; saved rooms and invitation grants are restored.
Removed access, room TTL/lease, endpoint-tier, room-rollout, and TURN variables fail
startup even when blank. A present `NODE_ENV` fails the same way, so a stale
@@ -101,6 +111,11 @@ schema field. The user settings are:
| `site` | Saved Piik Site origin. The launcher or `--site` updates it. |
| `localAccessPassword` | Empty by default. Optional password for the App's Local room authority, with the same exact-match behavior as `SITE_ACCESS_PASSWORD`. It is separate from a hosted site's password. |
Site input in the launcher and `--site` defaults to HTTPS when the scheme is
omitted; explicit HTTP or HTTPS is preserved. The App saves the normalized origin
and still rejects credentials, room paths, queries and fragments. It does not
probe protocols or downgrade a failed HTTPS connection to HTTP.
The launcher remembers the last mode confirmed with the launch button. This
optional preference lives beside the configuration as `client.json.mode` (or
`<custom-config-path>.mode`); removing it restores the initial selection without
+6
View File
@@ -36,6 +36,12 @@ of the FAQ and the footer in the selected language. Keep these steps in one
reader guide; App references link to it rather than maintaining a second copy.
Do not duplicate troubleshooting steps on the homepage.
Search titles, descriptions and repository topics describe the actual product:
private screen sharing, watching together and optional self-hosting. Use natural
Chinese and English phrases in the relevant introduction; preserve the brand
line in the visible headline. Follow [Google's title guidance](https://developers.google.com/search/docs/appearance/title-link):
avoid keyword lists, unrelated product names and unsupported performance claims.
## Presentation
Keep three presentation responsibilities distinct:
+33 -5
View File
@@ -20,17 +20,45 @@ the storage decision; implementation detail belongs in code and tests.
but duplicated-tab exclusion is not guaranteed. Closing the tab releases its
claim; losing Host authority clears that tab without erasing another tab's
resume hint.
- Room identity and credentials do not expire with inactivity. The exact Host
token resumes the room until explicit replacement or deletion. Grant rotation
or revocation ends an invitation without changing the room code. No presence
event renews or shortens room authority.
- Room identity and credentials have no inactivity expiry by default. The exact
Host token resumes the room until explicit replacement or deletion, including
the optional empty-room policy below. Grant rotation or revocation ends an
invitation without changing the room code.
- The Host may replace its room code. Replacement atomically creates a different
room and invalidates the old ownership, invitations, password, sessions,
routes, and media resources. It ends an active share and stops its capture
tracks; it does not migrate or automatically restart capture.
- A locally remembered preferred code is only a request. The server remains the
authority and allocates another code when that code is unavailable. The store
remains bounded by 9,000 codes; it rejects new rooms when full.
remains bounded by 9,000 codes; full allocation rejects new rooms when no
empty room may be reclaimed under the deployment's retention policy.
### Optional empty-room retention
Hosted operators may enable `ROOM_EMPTY_TIMEOUT_SECONDS`; `0` (default) preserves
indefinite authority. A positive value retires a room after that many seconds
continuously without any authenticated Host or Viewer. Never-joined rooms start
empty at creation. Sharing, pausing and idle chat do not change this rule; failed
authentication and HTTP access do not renew it. The existing heartbeat performs
expiry checks, normally every 30 seconds.
With retention enabled, allocation first reclaims expired empty rooms; if none
are available, it may retire the earliest-created empty room before the timeout,
including when replacing a room code. Early reclamation observes the existing
20-second reconnect grace after creation, restore or the last departure. Occupied rooms
are never candidates; a replacement cannot reclaim its own old room before the
replacement commits. If all rooms are occupied, creation still returns capacity
exhaustion. Expiry and pressure retirement use the same storage-first deletion
and signaling cleanup as explicit abandonment; recycled codes never retain old
credentials, share generations or reconnect timers.
The empty interval is process-local. Restored rooms receive a fresh interval so
surviving pages can reconnect; allocation pressure can still reclaim them while
empty. SQLite restores the insertion order of retained rows. This policy adds
no room lease, client renewal, wire field or persisted presence. Deletion ends
both ownership and invitations; ordinary missing-room/invalid-credential handling
applies. [Configuration](./configuration.md#room-retention) owns deployment values.
Disabling retention stops future reclamation; it cannot restore retired authority.
## Admission Paths
+23
View File
@@ -122,6 +122,29 @@ notice. Unknown SHA is not inferred from a branch name in GitHub metadata.
The publisher records a full SHA in `target_commitish` and verifies actual tag
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.
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.
Older installed Apps cannot acquire new warning UI from release metadata.
Their historical download behavior is accepted; do not split release feeds or
force a stepping-stone release solely to make advisory presentation identical.
Before a major release, put bilingual upgrade guidance near the top of its
release notes and on the website download entry. Name the actual incompatible
App/Site combinations, required upgrade order, interruptions and any persistent
data implications. Do not assume everyone installed the preceding minor/patch.
Verify the oldest relevant public App/page and the last preceding-major release
against the candidate: actual mismatches must fail clearly at their owning
contract. Keep historical packages available through GitHub releases. A major
preparation change does not itself authorize a wire bump, migration or release.
## Automatic Publication
Before a product-changing merge or manual run that can publish, present the
+7 -7
View File
@@ -12,7 +12,7 @@ and Git/PRs own completed history.
[Versioning](./standards/versioning.md#public-compatibility-promise) owns
compatibility between published Web/App/Server versions.
- Hosted Server defaults to SQLite schema 2. Room authority has no inactivity
expiry; explicit replacement/deletion or grant rotation/revocation ends the
expiry by default; replacement/deletion or grant rotation/revocation ends the
corresponding authority. Explicit memory mode and App Local end rooms at
process exit. Site access retains its separate 24-hour idle lifetime within
one service run; service restart requires site-password entry again.
@@ -54,12 +54,12 @@ Release artifacts and operator deployment records own delivery completion;
## Current Work
The public baseline retains Browser/server v23, Native control v9, capture v7
and the 1440p ceiling. The compatible maintenance phase combines sharing-failure
guidance and bilingual troubleshooting with source-list, codec admission,
minimized-capture and gateway-mapping repairs. Live audio-exclusion controls
reuse the source/mixer owner; website controls retain shared motion and cache
identity. 4K and resolution/capability expansion are not planned for this phase.
The public baseline retains Browser/server v23, Native control v9, capture v7,
SQLite schema 2 and the 1440p ceiling. Hosted empty-room retention and capacity
guidance preserve indefinite retention by default. The accepted Demo policy is
one hour without authenticated participants; the private deployment retains the
default. Operator records own activation, database and postflight evidence.
4K and resolution/capability expansion are not planned for this phase.
Native Magicsock remains a separate experiment, outside product integration.
Immutable release artifacts own delivery completion; [TODO](./todo.md#now) owns
remaining work.
+11 -5
View File
@@ -7,11 +7,8 @@ history. A parked idea is not implementation authority.
## Now
- [ ] **Assess Native Magicsock transport.** Compare the isolated Go transport
with the repaired Pion baseline under the [NAT evidence boundary](#next-p2p-connection-and-feedback-evidence).
Establish a measured benefit, supported paths, resource/authority bounds and
compatibility cost before accepting product integration. Experiments do not
establish a connectivity gain or authorize publication.
No active implementation work. Deferred proposals and evidence-dependent reports
remain below; release delivery is tracked by the pipeline and deployment records.
## Held By Owner
@@ -41,6 +38,11 @@ history. A parked idea is not implementation authority.
These proposals remain deferred beyond the accepted interaction phase.
- [ ] **Native Magicsock integration.** The [isolated comparison](./research/nat-traversal.md#integration-cost-and-recovery-controls)
establishes Go feasibility and relay-assisted recovery, but no additional
direct-reachability class in its tested matrix. Keep product transport unchanged.
Reopen integration only for a repeatable benefit on matched networks that
justifies the extra identity, readiness, packet-size and relay responsibilities.
- [ ] **Managed Demo hosting.** Evaluate cost and public UDP support before any
migration. The assessment remains outside the current product release; keep
the existing P2P-only Demo deployment until a provider and operating boundary
@@ -61,6 +63,10 @@ These proposals remain deferred beyond the accepted interaction phase.
These reports remain unmatched. A local repair or successful test is not proof
of a reporter's cause; research owns the completed experiments and their limits.
- [ ] **Intermittent native capture self-test failure.** The worker check now
records its phase, original exception and per-output progress. A local pass
does not explain the earlier CI failure; use the next failed run's diagnostics
before changing deadlines or worker behavior.
- [ ] **macOS and Linux physical capture.** Complete the remaining capture/audio
checks in [verification status](./verification-status.md#device-evidence-boundary),
including an Intel Mac with a usable hardware H.264 encoder, an ARM64 Linux
+3
View File
@@ -103,6 +103,9 @@ func NormalizeSite(value string) (string, error) {
if value == "" {
return "", nil
}
if !strings.Contains(value, "://") {
value = "https://" + value
}
parsed, err := url.Parse(value)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") ||
parsed.Host == "" || parsed.User != nil ||
+16
View File
@@ -143,6 +143,14 @@ func TestSaveDoesNotModifyPreviousFileInPlace(t *testing.T) {
func TestNormalizeSiteAcceptsOnlyAPlainWebOrigin(t *testing.T) {
for value, want := range map[string]string{
"": "",
" \t ": "",
"share.example": "https://share.example",
" Share.Example:443/ ": "https://share.example",
"share.example:8443": "https://share.example:8443",
"[::1]:8443": "https://[::1]:8443",
"bücher.example": "https://xn--bcher-kva.example",
" HTTPS://Share.Example/ ": "https://share.example",
"https://share.example": "https://share.example",
"https://Share.Example:443/": "https://share.example",
"http://Share.Example:80": "http://share.example",
@@ -158,6 +166,14 @@ func TestNormalizeSiteAcceptsOnlyAPlainWebOrigin(t *testing.T) {
}
}
for _, value := range []string{
"https://https://share.example",
"share.example/r/9527",
"share.example?mode=host",
"share.example#credential",
"user:pass@share.example",
"share.example:65536",
"ftp://share.example",
"javascript:alert(1)",
"file:///tmp/app",
"https://user:pass@share.example",
"https://share.example/room",
+21
View File
@@ -251,12 +251,33 @@ func TestLauncherRequiresTheEmbeddedBrowserBuild(t *testing.T) {
}
}
func TestLauncherNormalizesSiteSelection(t *testing.T) {
for input, want := range map[string]string{
" Share.Example:443/ ": "https://share.example",
"https://Share.Example/": "https://share.example",
"http://192.168.1.4:8787/": "http://192.168.1.4:8787",
} {
t.Run(input, func(t *testing.T) {
payload, err := json.Marshal(Selection{Mode: ModeSite, Language: "en", Site: input})
if err != nil {
t.Fatal(err)
}
selection, err := decodeSelection(bytes.NewReader(payload))
if err != nil || selection.Site != want {
t.Fatalf("site selection = %+v, %v; want %q", selection, err, want)
}
})
}
}
func TestLauncherRejectsInvalidSelections(t *testing.T) {
for name, payload := range map[string]string{
"unknown": `{"mode":"other","language":"en"}`,
"local-site": `{"mode":"local","language":"en","site":"https://share.example"}`,
"missing-site": `{"mode":"site","language":"en"}`,
"site-path": `{"mode":"site","language":"en","site":"https://share.example/path"}`,
"bare-site-path": `{"mode":"site","language":"en","site":"share.example/path"}`,
"site-credentials": `{"mode":"site","language":"en","site":"user:pass@share.example"}`,
"site-password": `{"mode":"site","language":"en","site":"https://share.example","localAccessPassword":"valid-pass"}`,
"unknown-field": `{"mode":"local","language":"en","extra":true}`,
"password-type": `{"mode":"local","language":"en","localAccessPassword":123}`,
+2
View File
@@ -169,6 +169,7 @@ func New(options Options) (*Server, error) {
AuthenticationTimeoutMs: options.AuthenticationTimeoutMs,
ViewerDisconnectGraceMs: options.ViewerDisconnectGraceMs,
HeartbeatIntervalMs: options.HeartbeatIntervalMs,
RoomEmptyTimeoutMs: int64(configuration.RoomEmptyTimeoutSeconds) * 1_000,
MaxConnections: options.MaxSignalConnections,
MaxUnauthenticatedConnections: options.MaxUnauthenticatedSignalConnections,
AfterFunc: options.AfterFunc,
@@ -204,6 +205,7 @@ func newRoomStore(options Options) (*room.Store, error) {
MaxRooms: room.Capacity,
MaxViewersPerRoom: options.Config.MaxViewersPerRoom,
Database: database,
Now: options.Now,
})
}
+25
View File
@@ -1265,6 +1265,31 @@ func TestRoomCreationReturnsServiceUnavailableAtTheGlobalRoomBound(t *testing.T)
expect(http.StatusServiceUnavailable, `{"error":"Room capacity reached"}`)
}
func TestConfiguredEmptyRoomExpiryRunsFromTheOwnedHeartbeat(t *testing.T) {
var now atomic.Int64
configuration := testConfig(t)
configuration.SiteAccessPassword = ""
configuration.RoomEmptyTimeoutSeconds = 3600
ticks := make(chan func(), 2)
server := start(t, Options{
Config: configuration, Now: now.Load,
AfterFunc: func(_ time.Duration, callback func()) func() bool {
ticks <- callback
return func() bool { return true }
},
})
created := server.createRoom(roomRequest{}).expectStatus(http.StatusCreated).room()
now.Store(3_599_999)
(<-ticks)()
request := accessRequest{roomID: created.RoomID, hostToken: created.HostToken,
body: `{"action":"set-code-entry-policy","policy":"private"}`}
server.updateRoomAccess(request).expectStatus(http.StatusOK)
now.Store(3_600_000)
(<-ticks)()
server.updateRoomAccess(request).expectStatus(http.StatusNotFound)
server.createRoom(roomRequest{}).expectStatus(http.StatusCreated)
}
// --- server HTTP listener and health --------------------------------------
func TestServesAnExplicitStaticFrontendIndependentlyOfTheEnvironment(t *testing.T) {
+11 -2
View File
@@ -57,8 +57,8 @@ var removedEnvironmentVariables = []struct{ name, reason string }{
{"PEER_ASSISTED_MEDIA", "peer-assisted media is always enabled"},
{"HOST_ADMISSION_PASSWORD", "use SITE_ACCESS_PASSWORD"},
{"MAX_PEER_RELAY_DOWNSTREAM_EDGES", "use ENDPOINT_MEDIA_COPY_CAPACITY"},
{"ROOM_TTL_SECONDS", "rooms do not expire"},
{"ROOM_LEASE_SECONDS", "rooms do not expire"},
{"ROOM_TTL_SECONDS", "use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"ROOM_LEASE_SECONDS", "use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"ACCESS_PASSWORD", "use SITE_ACCESS_PASSWORD"},
{"NODE_ENV", "use PIIK_ENV"},
}
@@ -82,6 +82,7 @@ type Config struct {
AllowedOrigins map[string]struct{}
SiteAccessPassword string
RoomDatabasePath string
RoomEmptyTimeoutSeconds int
MaxViewersPerRoom int
EndpointMediaCopyCapacity int
SFU *SFUConfig
@@ -144,6 +145,13 @@ func Load(env map[string]string) (Config, error) {
if err != nil {
return Config{}, err
}
roomEmptyTimeout := 0
if value := strings.TrimSpace(env["ROOM_EMPTY_TIMEOUT_SECONDS"]); value != "" {
roomEmptyTimeout, err = strconv.Atoi(value)
if err != nil || roomEmptyTimeout < 0 || roomEmptyTimeout > 31_536_000 {
return Config{}, errors.New("ROOM_EMPTY_TIMEOUT_SECONDS must be an integer between 0 and 31536000")
}
}
stunURLs, err := parseStunURLList(env["STUN_URLS"], "STUN_URLS")
if err != nil {
return Config{}, err
@@ -201,6 +209,7 @@ func Load(env map[string]string) (Config, error) {
AllowedOrigins: allowedOrigins,
SiteAccessPassword: siteAccessPassword,
RoomDatabasePath: roomDatabasePath,
RoomEmptyTimeoutSeconds: roomEmptyTimeout,
MaxViewersPerRoom: int(maxViewersPerRoom),
EndpointMediaCopyCapacity: int(endpointMediaCopyCapacity),
SFU: sfu,
+3 -3
View File
@@ -496,11 +496,11 @@ func TestLoadRejects(t *testing.T) {
{"removed peer-assisted toggle", map[string]string{"PEER_ASSISTED_MEDIA": "true"},
"PEER_ASSISTED_MEDIA is no longer supported; peer-assisted media is always enabled"},
{"removed room TTL", map[string]string{"ROOM_TTL_SECONDS": ""},
"ROOM_TTL_SECONDS is no longer supported; rooms do not expire"},
"ROOM_TTL_SECONDS is no longer supported; use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"removed room lease", map[string]string{"ROOM_LEASE_SECONDS": "86400"},
"ROOM_LEASE_SECONDS is no longer supported; rooms do not expire"},
"ROOM_LEASE_SECONDS is no longer supported; use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"blank removed room lease", map[string]string{"ROOM_LEASE_SECONDS": ""},
"ROOM_LEASE_SECONDS is no longer supported; rooms do not expire"},
"ROOM_LEASE_SECONDS is no longer supported; use ROOM_EMPTY_TIMEOUT_SECONDS for empty-room retention"},
{"removed access password", map[string]string{"ACCESS_PASSWORD": "legacy-password"},
"ACCESS_PASSWORD is no longer supported; use SITE_ACCESS_PASSWORD"},
{"blank access password", map[string]string{"ACCESS_PASSWORD": ""},
+21
View File
@@ -0,0 +1,21 @@
package config
import "testing"
func TestRoomEmptyTimeoutConfiguration(t *testing.T) {
for _, value := range []string{"", "0", "3600", "31536000"} {
cfg, err := Load(map[string]string{"ROOM_EMPTY_TIMEOUT_SECONDS": value})
if err != nil {
t.Fatalf("value %q: %v", value, err)
}
if value == "3600" && cfg.RoomEmptyTimeoutSeconds != 3600 ||
(value == "" || value == "0") && cfg.RoomEmptyTimeoutSeconds != 0 {
t.Fatalf("value %q: timeout=%d", value, cfg.RoomEmptyTimeoutSeconds)
}
}
for _, value := range []string{"-1", "1.5", "31536001", "NaN", "Infinity"} {
if _, err := Load(map[string]string{"ROOM_EMPTY_TIMEOUT_SECONDS": value}); err == nil {
t.Fatalf("accepted invalid timeout %q", value)
}
}
}
+19 -10
View File
@@ -48,6 +48,9 @@ const roomSchema = `
PRAGMA user_version = 2;
`
// The current schema only inserts/deletes rooms; updates retain rowid. Reading
// its insertion order keeps oldest-empty allocation stable across restarts,
// without persisting presence or adding a creation-time schema migration.
const selectStoredRooms = `SELECT
room_id,
host_token_digest,
@@ -56,7 +59,7 @@ const selectStoredRooms = `SELECT
code_entry_policy,
viewer_password_material
FROM rooms
ORDER BY room_id`
ORDER BY rowid`
const insertStoredRoom = `INSERT INTO rooms (
room_id,
@@ -264,17 +267,23 @@ func (d *Database) SetViewerGrant(
})
}
// DeleteRoom is deleteRoom.
func (d *Database) DeleteRoom(roomID string, hostTokenDigest []byte) error {
if err := assertRoomIdentity(roomID, hostTokenDigest); err != nil {
return err
}
return d.transaction(func() error {
changes, err := d.exec(deleteRoomStatement, roomID, hostTokenDigest)
if err != nil {
func (d *Database) deleteRooms(rooms []StoredRoomAuthority) error {
for _, room := range rooms {
if err := assertRoomIdentity(room.RoomID, room.HostTokenDigest); err != nil {
return err
}
return assertSingleChange(changes, "delete")
}
return d.transaction(func() error {
for _, room := range rooms {
changes, err := d.exec(deleteRoomStatement, room.RoomID, room.HostTokenDigest)
if err != nil {
return err
}
if err := assertSingleChange(changes, "delete"); err != nil {
return err
}
}
return nil
})
}
+1 -1
View File
@@ -531,7 +531,7 @@ func TestRejectsInvalidAuthorityArguments(t *testing.T) {
return d.InsertRoom(room)
}, "Viewer password material must contain 48 bytes"},
{"identity", func(d *Database) error {
return d.DeleteRoom("123", make([]byte, 32))
return d.deleteRooms([]StoredRoomAuthority{{RoomID: "123", HostTokenDigest: make([]byte, 32)}})
}, "Room ID is invalid"},
{"update policy", func(d *Database) error {
return d.SetCodeEntryPolicy("1234", make([]byte, 32), "public")
+31
View File
@@ -0,0 +1,31 @@
package room
// ExpireEmptyRooms commits storage retirement before returning effect cleanup.
func (s *Store) ExpireEmptyRooms(beforeMs int64) ([]ClosedRoom, error) {
return s.abandonRooms(s.EmptyRoomIDs(beforeMs))
}
// EmptyRoomIDs returns empty rooms in creation order, including never-joined
// rooms. A connected Host or Viewer protects an idle chat room just like a share.
// Callers retire candidates synchronously under the same signaling lock.
func (s *Store) EmptyRoomIDs(beforeMs int64) []string {
var ids []string
for id, room := range s.rooms.All() {
if room.emptySinceMs <= beforeMs && !roomOccupied(room) {
ids = append(ids, id)
}
}
return ids
}
func roomOccupied(room *Room) bool {
if room.host != nil && room.host.sessionID != "" {
return true
}
for _, viewer := range room.viewers.All() {
if viewer.sessionID != "" {
return true
}
}
return false
}
+129
View File
@@ -0,0 +1,129 @@
package room
import (
"reflect"
"testing"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
func TestEmptyRoomRetentionUsesAuthenticatedPresence(t *testing.T) {
var now int64
store := newStore(t, Options{Now: func() int64 { return now }})
created := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")
if ids := store.EmptyRoomIDs(0); !reflect.DeepEqual(ids, []string{created.RoomID}) {
t.Fatalf("never-joined room = %v", ids)
}
host := mustConnect(t, store, hostInput(created.RoomID, created.HostToken))
viewer := mustConnect(t, store, viewerInput(created.RoomID, "viewer-session", created.ViewerGrant))
now = 3_600_000
if closed, err := store.ExpireEmptyRooms(now); err != nil || len(closed) != 0 {
t.Fatalf("occupied room retired: %v %v", closed, err)
}
_, _ = store.DisconnectParticipant(created.RoomID, host.PeerID, "host-session")
if len(store.EmptyRoomIDs(now)) != 0 {
t.Fatal("a Viewer without a Host must protect the room")
}
_, _ = store.DisconnectParticipant(created.RoomID, viewer.PeerID, "viewer-session")
if len(store.EmptyRoomIDs(now-1)) != 0 {
t.Fatal("empty interval began before the last departure")
}
// Reconnect/replacement and a late old-session close must not retire the
// current participant, or let failed admission renew an empty room.
now += 10
mustConnect(t, store, hostInput(created.RoomID, created.HostToken, "new-session"))
_, _ = store.DisconnectParticipant(created.RoomID, host.PeerID, "host-session")
if len(store.EmptyRoomIDs(now)) != 0 {
t.Fatal("stale disconnect made the new session empty")
}
_, _ = store.DisconnectParticipant(created.RoomID, host.PeerID, "new-session")
lastDeparture := now
now += 100
_, err := store.ConnectParticipant(hostInput(created.RoomID, "wrong-token"))
expectCode(t, err, CodeInvalidToken)
store.RemoveDisconnectedViewer(created.RoomID, viewer.PeerID)
closed, err := store.ExpireEmptyRooms(lastDeparture)
if err != nil || len(closed) != 1 || len(closed[0].SessionIDs) != 0 || store.Size() != 0 {
t.Fatalf("empty retirement = %v %v, size=%d", closed, err, store.Size())
}
reused := createRoom(t, store, protocol.CodeEntryOpen, "", created.RoomID)
_, err = store.ConnectParticipant(viewerInput(reused.RoomID, "old-invite", created.ViewerGrant))
expectCode(t, err, CodeInvalidToken)
}
func TestRevokingLastConnectedViewerStartsEmptyInterval(t *testing.T) {
var now int64
store := newStore(t, Options{Now: func() int64 { return now }})
created := createRoom(t, store, protocol.CodeEntryOpen, "", "4321")
mustConnect(t, store, viewerInput(created.RoomID, "viewer-session", created.ViewerGrant))
now = 100
if _, err := store.SetViewerGrant(created.RoomID, "revoke", created.HostToken); err != nil {
t.Fatal(err)
}
if len(store.EmptyRoomIDs(99)) != 0 || len(store.EmptyRoomIDs(100)) != 1 {
t.Fatal("revocation did not start the empty interval")
}
now = 200
if _, err := store.SetViewerGrant(created.RoomID, "rotate", created.HostToken); err != nil {
t.Fatal(err)
}
if len(store.EmptyRoomIDs(100)) != 1 {
t.Fatal("changing credentials on an already empty room renewed it")
}
}
func TestRestorePreservesCreationOrderAndRestartsEmptyInterval(t *testing.T) {
path := databasePath(t)
var now int64
options := Options{Now: func() int64 { return now }}
first := stableStore(t, path, options)
older := createRoom(t, first, protocol.CodeEntryOpen, "", "9000")
now++
createRoom(t, first, protocol.CodeEntryOpen, "", "1000")
_, err := first.SetCodeEntryPolicy(older.RoomID, protocol.CodeEntryPrivate, older.HostToken)
if err != nil {
t.Fatal(err)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
now = 7_200_000
restored := stableStore(t, path, options)
if len(restored.EmptyRoomIDs(now-1)) != 0 {
t.Fatal("restart must allow participants to reconnect")
}
if ids := restored.EmptyRoomIDs(now); !reflect.DeepEqual(ids, []string{"9000", "1000"}) {
t.Fatalf("restored creation order = %v", ids)
}
closed, err := restored.ExpireEmptyRooms(now)
if err != nil || len(closed) != 2 {
t.Fatalf("expire = %v %v", closed, err)
}
if err := restored.Close(); err != nil {
t.Fatal(err)
}
if next := stableStore(t, path, options); next.Size() != 0 {
t.Fatal("expired authority survived restart")
}
}
func TestExpiryStorageFailureDoesNotPartiallyRetireRooms(t *testing.T) {
store := stableStore(t, databasePath(t), Options{Now: func() int64 { return 0 }})
createRoom(t, store, protocol.CodeEntryOpen, "", "9000")
createRoom(t, store, protocol.CodeEntryOpen, "", "1000")
// Fail the second deletion, after the first executed inside the transaction.
_, err := store.database.exec(`CREATE TEMP TRIGGER fail_retirement BEFORE DELETE ON rooms
WHEN OLD.room_id = '1000' BEGIN SELECT RAISE(ABORT, 'injected write failure'); END`)
if err != nil {
t.Fatal(err)
}
free := len(store.freeRoomCodes)
if closed, err := store.ExpireEmptyRooms(0); err == nil || len(closed) != 0 {
t.Fatalf("expiry unexpectedly succeeded: %v %v", closed, err)
}
rows, err := store.database.readStoredRooms()
if err != nil || len(rows) != 2 || store.Size() != 2 || len(store.freeRoomCodes) != free {
t.Fatalf("failed batch changed authority: rows=%d, rooms=%d, free=%d, error=%v", len(rows), store.Size(), len(store.freeRoomCodes), err)
}
}
+48 -21
View File
@@ -12,6 +12,7 @@ import (
"math"
"slices"
"strconv"
"time"
"github.com/TNTcraftHIM/Piik/internal/server/ordered"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
@@ -77,6 +78,9 @@ type Room struct {
viewerAuthorizationGeneration string
codeEntryPolicy protocol.CodeEntryPolicy
host *participant
// Process-local: restored rooms receive a fresh reconnect window. Only the
// last authenticated departure updates this; failed admission cannot renew it.
emptySinceMs int64
// ordering: JS Map insertion order decides viewer presence order, the
// closed-session list and the router's participant order.
viewers ordered.Map[string, *participant]
@@ -175,6 +179,7 @@ type Options struct {
MaxViewersPerRoom int
Database *Database
Random func(size int) []byte
Now func() int64
}
// Store is RoomStore. See the package comment for the locking contract.
@@ -183,6 +188,7 @@ type Store struct {
rooms ordered.Map[string, *Room]
freeRoomCodes []string
random func(size int) []byte
now func() int64
database *Database
initialized bool
maxRooms int
@@ -207,6 +213,7 @@ func New(options Options) (*Store, error) {
store := &Store{
freeRoomCodes: make([]string, Capacity),
random: options.Random,
now: options.Now,
database: options.Database,
initialized: options.Database == nil,
maxRooms: options.MaxRooms,
@@ -219,6 +226,9 @@ func New(options Options) (*Store, error) {
if store.random == nil {
store.random = cryptoRandom
}
if store.now == nil {
store.now = func() int64 { return time.Now().UnixMilli() }
}
return store, nil
}
@@ -284,6 +294,7 @@ func (s *Store) restore() error {
viewerPasswordMaterial: bytes.Clone(stored.ViewerPasswordMaterial),
viewerAuthorizationGeneration: stored.ViewerAuthorizationGeneration,
codeEntryPolicy: stored.CodeEntryPolicy,
emptySinceMs: s.now(),
})
}
available := s.freeRoomCodes[:0]
@@ -538,12 +549,16 @@ func (s *Store) SetViewerGrant(
}
room.viewerGrantDigest = viewerGrantDigest
room.viewerAuthorizationGeneration = generation
wasOccupied := roomOccupied(room)
// ordering: delete during iteration, which a JS Map allows.
for clientID, viewer := range room.viewers.All() {
if viewer.admittedBy == admittedByGrant {
room.viewers.Delete(clientID)
}
}
if wasOccupied && !roomOccupied(room) {
room.emptySinceMs = s.now()
}
return ViewerGrantUpdate{
ViewerGrant: viewerGrant,
ViewerAuthorizationGeneration: room.viewerAuthorizationGeneration,
@@ -681,6 +696,9 @@ func (s *Store) DisconnectParticipant(
return nil, nil
}
room.host.sessionID = ""
if !roomOccupied(room) {
room.emptySinceMs = s.now()
}
return &DisconnectedParticipant{
RoomID: roomID, Role: protocol.RoleHost, PeerID: peerID}, nil
}
@@ -690,6 +708,9 @@ func (s *Store) DisconnectParticipant(
return nil, nil
}
viewer.sessionID = ""
if !roomOccupied(room) {
room.emptySinceMs = s.now()
}
return &DisconnectedParticipant{
RoomID: roomID, Role: protocol.RoleViewer, PeerID: peerID}, nil
}
@@ -761,41 +782,46 @@ func (s *Store) GetConnectedViewers(roomID string) []ConnectedPeer {
// AbandonRoom is abandonRoom; it returns nil where the TypeScript returned
// undefined.
func (s *Store) AbandonRoom(roomID string) (*ClosedRoom, error) {
closed, err := s.abandonRooms([]string{roomID})
if err != nil || len(closed) == 0 {
return nil, err
}
return &closed[0], nil
}
// Retire a batch atomically before releasing codes. One SQLite transaction
// avoids thousands of fsyncs under the signaling lock after a restart.
func (s *Store) abandonRooms(roomIDs []string) ([]ClosedRoom, error) {
if err := s.ensureInitialized(); err != nil {
return nil, err
}
room, ok := s.rooms.Get(roomID)
if !ok {
var authorities []StoredRoomAuthority
var closed []ClosedRoom
for _, roomID := range roomIDs {
if room, ok := s.rooms.Get(roomID); ok {
authorities = append(authorities, StoredRoomAuthority{RoomID: roomID, HostTokenDigest: room.hostTokenDigest})
closed = append(closed, ClosedRoom{RoomID: roomID, SessionIDs: connectedSessionIDs(room)})
}
}
if len(closed) == 0 {
return nil, nil
}
sessionIDs := connectedSessionIDs(room)
err := s.writeDatabase(func() error {
return s.database.DeleteRoom(roomID, room.hostTokenDigest)
return s.database.deleteRooms(authorities)
})
if err != nil {
return nil, err
}
s.rooms.Delete(roomID)
s.releaseRoomCode(roomID)
return &ClosedRoom{RoomID: roomID, SessionIDs: sessionIDs}, nil
for _, room := range closed {
s.rooms.Delete(room.RoomID)
s.releaseRoomCode(room.RoomID)
}
return closed, nil
}
// AbandonAllRooms is abandonAllRooms, in room insertion order.
func (s *Store) AbandonAllRooms() ([]ClosedRoom, error) {
if err := s.ensureInitialized(); err != nil {
return nil, err
}
var closedRooms []ClosedRoom
for _, roomID := range s.rooms.Keys() {
closed, err := s.AbandonRoom(roomID)
if err != nil {
return nil, err
}
if closed != nil {
closedRooms = append(closedRooms, *closed)
}
}
return closedRooms, nil
return s.abandonRooms(s.rooms.Keys())
}
func (s *Store) connectHost(
@@ -1004,6 +1030,7 @@ func (s *Store) newRoom(
viewerPasswordMaterial: material,
viewerAuthorizationGeneration: generation,
codeEntryPolicy: policy,
emptySinceMs: s.now(),
}
return room, CreatedRoom{
RoomID: roomID,
+45
View File
@@ -0,0 +1,45 @@
package signal
import (
"errors"
"fmt"
"github.com/TNTcraftHIM/Piik/internal/server/room"
)
// Capacity reclamation and scheduled expiry use the normal room retirement
// owner, so grace timers, route state and share generations cannot outlive a
// recycled code. All selection and retirement happen under Server.mu.
func (s *Server) roomCapacityCandidate(err error, exceptRoomID string) string {
var roomError *room.Error
if s.roomEmptyTimeoutMs <= 0 || !errors.As(err, &roomError) || roomError.Code != room.CodeRoomLimit {
return ""
}
now := s.now()
// A recently vacated old room should not be displaced while another empty
// room has already expired but is waiting for the next heartbeat sweep.
// Reuse the admission/reconnect window for early reclamation as well: a
// new room's HTTP response must reach its Host before its code can be reused.
for _, before := range []int64{now - s.roomEmptyTimeoutMs, now - int64(s.viewerDisconnectGraceMs)} {
for _, id := range s.store.EmptyRoomIDs(before) {
if id != exceptRoomID {
return id
}
}
}
return ""
}
func (s *Server) expireEmptyRooms() {
if s.roomEmptyTimeoutMs <= 0 {
return
}
closed, err := s.store.ExpireEmptyRooms(s.now() - s.roomEmptyTimeoutMs)
if err != nil {
s.logger.Error("Could not expire empty rooms", "errorType", fmt.Sprintf("%T", err))
return
}
for _, room := range closed {
s.closeRoom(room)
}
}
+188
View File
@@ -0,0 +1,188 @@
package signal
import (
"errors"
"testing"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/TNTcraftHIM/Piik/internal/server/room"
)
func TestRoomCapacityReclaimsOldestEmptyRoomOnlyWhenEnabled(t *testing.T) {
for _, enabled := range []bool{false, true} {
t.Run(map[bool]string{false: "default-retention", true: "empty-reclamation"}[enabled], func(t *testing.T) {
store, err := room.New(room.Options{MaxRooms: 2, MaxViewersPerRoom: 2, Now: func() int64 { return 0 }})
if err != nil {
t.Fatal(err)
}
timeout := int64(0)
if enabled {
timeout = 3_600_000
}
h := startHarness(t, harnessOptions{store: store, now: func() int64 { return 51 }, roomEmptyTimeoutMs: timeout})
second, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, "")
if err != nil {
t.Fatal(err)
}
created, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, h.room.RoomID)
if !enabled {
var limit *room.Error
if !errors.As(err, &limit) || limit.Code != room.CodeRoomLimit {
t.Fatalf("default capacity result = %v", err)
}
return
}
if err != nil || created.RoomID != h.room.RoomID || created.HostToken == h.room.HostToken {
t.Fatalf("reclaim oldest empty = %v %v", created.RoomID, err)
}
h.locked(func() {
if _, err := store.HostManagedRoom(second.RoomID, second.HostToken); err != nil {
t.Fatal("newer empty room was retired")
}
})
host := openClient(t, h)
authenticate(t, host, created, protocol.RoleHost, "idle-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
viewer := openClient(t, h)
authenticate(t, viewer, second, protocol.RoleViewer, "waiting-viewer", 1, "", presenceOptions{})
_, err = h.server.CreateRoom(protocol.CodeEntryOpen, nil, "")
var limit *room.Error
if !errors.As(err, &limit) || limit.Code != room.CodeRoomLimit {
t.Fatalf("occupied rooms must not be evicted: %v", err)
}
})
}
}
func TestEmptyExpiryCleansShareAndReconnectState(t *testing.T) {
clock := &clock{}
store, err := room.New(room.Options{MaxRooms: 2, MaxViewersPerRoom: 2, Now: clock.now})
if err != nil {
t.Fatal(err)
}
h := startHarness(t, harnessOptions{store: store, now: clock.now, roomEmptyTimeoutMs: 3_600_000, viewerDisconnectGraceMs: 20_000})
host := openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "retention-host", 1, "", presenceOptions{roomSession: true})
host.ignore("route-update")
viewer := openClient(t, h)
authenticate(t, viewer, h.room, protocol.RoleViewer, "retention-viewer", 1, "", presenceOptions{})
viewer.ignore("route-update")
clock.advance(7_200_000)
h.locked(func() {
h.server.expireEmptyRooms()
if store.Size() != 1 {
t.Fatal("connected room expired")
}
})
h.closeClient(viewer)
h.closeClient(host)
h.locked(func() {
if len(h.server.viewerGraceTimers) != 1 || len(h.server.shares) != 1 {
t.Fatal("test did not retain reconnect/share state")
}
})
clock.advance(3_599_999)
h.locked(func() {
h.server.expireEmptyRooms()
if store.Size() != 1 {
t.Fatal("room expired before an hour empty")
}
})
clock.advance(1)
h.locked(func() {
h.server.expireEmptyRooms()
if store.Size() != 0 || len(h.server.shares) != 0 || len(h.server.viewerGraceTimers) != 0 {
t.Fatal("expired room left authority or effects behind")
}
})
created, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, h.room.RoomID)
if err != nil {
t.Fatal(err)
}
newHost := openClient(t, h)
authenticate(t, newHost, created, protocol.RoleHost, "new-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
}
func TestRoomCapacityPrefersExpiredRoomOverRecentlyVacatedOlderRoom(t *testing.T) {
clock := &clock{}
store, err := room.New(room.Options{MaxRooms: 2, MaxViewersPerRoom: 2, Now: clock.now})
if err != nil {
t.Fatal(err)
}
h := startHarness(t, harnessOptions{store: store, now: clock.now, roomEmptyTimeoutMs: 3_600_000})
host := openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "retention-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
clock.advance(10)
newer := h.createRoom(protocol.CodeEntryOpen, "")
clock.advance(3_600_000)
h.closeClient(host)
clock.advance(100)
created, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, newer.RoomID)
if err != nil || created.RoomID != newer.RoomID {
t.Fatalf("expired room not reclaimed first: %s %v", created.RoomID, err)
}
h.locked(func() {
if _, err := store.HostManagedRoom(h.room.RoomID, h.room.HostToken); err != nil {
t.Fatal("recent departure lost its room before an already-expired room")
}
})
}
func TestRoomReplacementAtAll9000CodesReclaimsAnotherEmptyRoom(t *testing.T) {
store, err := room.New(room.Options{MaxRooms: room.Capacity, MaxViewersPerRoom: 2, Now: func() int64 { return 0 }})
if err != nil {
t.Fatal(err)
}
oldest := createStoreRoom(t, store, protocol.CodeEntryOpen, "")
second := createStoreRoom(t, store, protocol.CodeEntryOpen, "")
for store.Size() < room.Capacity {
createStoreRoom(t, store, protocol.CodeEntryOpen, "")
}
h := startHarness(t, harnessOptions{store: store, room: &oldest, now: func() int64 { return 51 }, roomEmptyTimeoutMs: 3_600_000})
if _, err := h.server.ReplaceRoom(oldest.RoomID, "wrong-token", protocol.CodeEntryOpen, nil); err == nil {
t.Fatal("invalid ownership replaced a room")
}
if h.storeSize() != room.Capacity {
t.Fatal("rejected replacement evicted another room")
}
replacement, err := h.server.ReplaceRoom(oldest.RoomID, oldest.HostToken, protocol.CodeEntryOpen, nil)
if err != nil || replacement.RoomID != second.RoomID || replacement.HostToken == second.HostToken {
t.Fatalf("replacement did not reclaim the next oldest empty room: %s %v", replacement.RoomID, err)
}
if h.storeSize() != room.Capacity-1 {
t.Fatal("replacement left incorrect room capacity")
}
h.locked(func() {
if _, err := store.HostManagedRoom(oldest.RoomID, oldest.HostToken); err == nil {
t.Fatal("old replacement authority survived")
}
})
}
func TestCapacityReclamationProtectsCreationAndReconnectWindow(t *testing.T) {
clock := &clock{}
store, err := room.New(room.Options{MaxRooms: 1, MaxViewersPerRoom: 1, Now: clock.now})
if err != nil {
t.Fatal(err)
}
h := startHarness(t, harnessOptions{store: store, now: clock.now, roomEmptyTimeoutMs: 3_600_000, viewerDisconnectGraceMs: 20_000})
assertProtected := func() {
t.Helper()
_, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, "")
var limit *room.Error
if !errors.As(err, &limit) || limit.Code != room.CodeRoomLimit {
t.Fatalf("creation/reconnect window lost its room: %v", err)
}
}
clock.advance(19_999)
assertProtected()
host := openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "retention-host", 1, "", presenceOptions{roomSession: true, roomOnly: true})
h.closeClient(host)
clock.advance(19_999)
assertProtected()
clock.advance(1)
if _, err := h.server.CreateRoom(protocol.CodeEntryOpen, nil, ""); err != nil {
t.Fatalf("reclamation after reconnect window: %v", err)
}
assertProtected()
}
+27 -6
View File
@@ -85,10 +85,13 @@ type Options struct {
SiteAccessAtUpgrade func(*http.Request) bool
PublicBaseURL *url.URL
// Now returns Unix milliseconds; nil uses the wall clock.
Now func() int64
AuthenticationTimeoutMs int
ViewerDisconnectGraceMs int
HeartbeatIntervalMs int
Now func() int64
AuthenticationTimeoutMs int
ViewerDisconnectGraceMs int
HeartbeatIntervalMs int
// Zero retains room authority indefinitely. Otherwise empty rooms expire
// and allocation pressure may reclaim the oldest empty room early.
RoomEmptyTimeoutMs int64
MaxConnections int
MaxUnauthenticatedConnections int
// AfterFunc is the timer factory; nil uses time.AfterFunc.
@@ -178,6 +181,7 @@ type Server struct {
authenticationTimeoutMs int
viewerDisconnectGraceMs int
heartbeatIntervalMs int
roomEmptyTimeoutMs int64
maxConnections int
maxUnauthenticatedConnections int
@@ -235,6 +239,7 @@ func New(options Options) (*Server, error) {
authenticationTimeoutMs: orDefault(options.AuthenticationTimeoutMs, defaultAuthenticationTimeoutMs),
viewerDisconnectGraceMs: orDefault(options.ViewerDisconnectGraceMs, defaultViewerDisconnectGraceMs),
heartbeatIntervalMs: orDefault(options.HeartbeatIntervalMs, defaultHeartbeatIntervalMs),
roomEmptyTimeoutMs: options.RoomEmptyTimeoutMs,
maxConnections: orDefault(options.MaxConnections, defaultMaxSignalConnections),
maxUnauthenticatedConnections: orDefault(options.MaxUnauthenticatedConnections, defaultMaxUnauthenticatedConnections),
sessionsByID: map[string]*session{},
@@ -599,6 +604,13 @@ func (s *Server) ReplaceRoom(
}
material, derived := s.deriveViewerPasswordMaterial(roomID, hostToken, roomPassword, current)
replacement, err := s.store.ReplaceRoom(roomID, hostToken, codeEntryPolicy, material, derived, current)
if derived == nil {
if candidate := s.roomCapacityCandidate(err, roomID); candidate != "" {
if err = s.abandonRoom(candidate); err == nil {
replacement, err = s.store.ReplaceRoom(roomID, hostToken, codeEntryPolicy, material, derived, current)
}
}
}
if err != nil {
return room.CreatedRoom{}, err
}
@@ -615,7 +627,7 @@ func (s *Server) CreateRoom(
) (room.CreatedRoom, error) {
s.mu.Lock()
defer s.mu.Unlock()
if err := s.store.BeginCreateRoom(); err != nil {
if err := s.store.BeginCreateRoom(); err != nil && s.roomCapacityCandidate(err, "") == "" {
return room.CreatedRoom{}, err
}
var material []byte
@@ -627,7 +639,15 @@ func (s *Server) CreateRoom(
material, derived = s.store.DeriveViewerPasswordMaterial(*roomPassword, nil)
}()
}
return s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID)
created, err := s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID)
if derived == nil {
if candidate := s.roomCapacityCandidate(err, ""); candidate != "" {
if err = s.abandonRoom(candidate); err == nil {
created, err = s.store.CreateRoom(codeEntryPolicy, material, derived, preferredRoomID)
}
}
}
return created, err
}
// armHeartbeat is the heartbeat setInterval: each tick re-arms the
@@ -641,6 +661,7 @@ func (s *Server) armHeartbeat() {
return
}
pings := s.heartbeat()
s.expireEmptyRooms()
s.armHeartbeat()
s.mu.Unlock()
for _, sess := range pings {
+2
View File
@@ -248,6 +248,7 @@ func TestPersistentRoomSessionReconnectStaysMediaIdle(t *testing.T) {
type harnessOptions struct {
authenticationTimeoutMs int
viewerDisconnectGraceMs int
roomEmptyTimeoutMs int64
maxViewersPerRoom int
maxSignalConnections int
maxUnauthenticatedSignalConnections int
@@ -353,6 +354,7 @@ func startHarness(t *testing.T, options harnessOptions) *harness {
AuthenticationTimeoutMs: orValue(options.authenticationTimeoutMs, 500),
ViewerDisconnectGraceMs: orValue(options.viewerDisconnectGraceMs, 50),
HeartbeatIntervalMs: 60_000,
RoomEmptyTimeoutMs: options.roomEmptyTimeoutMs,
MaxConnections: options.maxSignalConnections,
MaxUnauthenticatedConnections: options.maxUnauthenticatedSignalConnections,
AfterFunc: options.afterFunc,
@@ -8,6 +8,8 @@
#include <array>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <exception>
#include <future>
#include <thread>
#include <vector>
@@ -62,6 +64,7 @@ void CheckWorkers() {
std::mutex mutex;
std::condition_variable changed;
std::exception_ptr failure;
size_t failed_layer = 0;
std::promise<void> entered, release;
auto entered_future = entered.get_future();
auto released = release.get_future().share();
@@ -99,7 +102,10 @@ void CheckWorkers() {
}
} catch (...) {
std::lock_guard<std::mutex> lock(mutex);
failure = std::current_exception();
if (!failure) {
failure = std::current_exception();
failed_layer = layer;
}
changed.notify_one();
}
});
@@ -108,28 +114,45 @@ void CheckWorkers() {
auto input = std::make_shared<Input>(Input{index});
for (auto& mailbox : mailboxes) mailbox.Submit(input);
};
auto wait = [&](auto predicate) {
auto wait = [&](const char* phase, auto predicate) {
std::unique_lock<std::mutex> lock(mutex);
const bool ready = changed.wait_for(lock, std::chrono::seconds(2), [&]() { return failure || predicate(); });
if (!ready || failure) {
std::fprintf(stderr, "capture_control: phase=%s result=%s\n", phase,
failure ? "worker-exception" : "timeout");
if (failure) {
try { std::rethrow_exception(failure); }
catch (const std::exception& error) {
std::fprintf(stderr, " layer=%zu error=%s\n", failed_layer, error.what());
} catch (...) {
std::fprintf(stderr, " layer=%zu error=non-standard-exception\n", failed_layer);
}
}
for (size_t layer = 0; layer < workers.size(); ++layer) {
std::fprintf(stderr, " layer=%zu last=%u count=%u retired=%u\n",
layer, last[layer], count[layer], retired[layer]);
}
std::fflush(stderr);
}
assert(ready && !failure);
};
submit(1);
assert(entered_future.wait_for(std::chrono::seconds(2)) == std::future_status::ready);
for (uint32_t index = 2; index <= 4; ++index) submit(index);
wait([&]() { return last[1] == 4 && last[2] == 4; });
wait("independent-outputs", [&]() { return last[1] == 4 && last[2] == 4; });
mailboxes[0].RequestKeyFrame();
release.set_value();
wait([&]() { return last[0] == 4; });
wait("pending-recovery", [&]() { return last[0] == 4; });
assert(count[0] == 2 && recovery[0]); // New request survived the older keyframe; pending 2/3 were replaced.
mailboxes[1].SetActive(false);
mailboxes[2].SetActive(false);
submit(5);
wait([&]() { return last[0] == 5 && retired[1] == 1 && retired[2] == 1; });
wait("output-retirement", [&]() { return last[0] == 5 && retired[1] == 1 && retired[2] == 1; });
assert(last[1] == 4 && last[2] == 4);
mailboxes[0].SetBitrate(30'000);
for (auto& mailbox : mailboxes) { mailbox.SetActive(true); mailbox.RequestKeyFrame(); }
submit(6);
wait([&]() { return last[0] == 6 && last[1] == 6 && last[2] == 6; });
wait("output-reactivation", [&]() { return last[0] == 6 && last[1] == 6 && last[2] == 6; });
assert(recovery[0] && recovery[1] && recovery[2]);
const auto stopped = std::chrono::steady_clock::now();
for (auto& mailbox : mailboxes) mailbox.Stop();
+3 -3
View File
@@ -1589,9 +1589,9 @@
"license": "ISC"
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
+3
View File
@@ -1,5 +1,8 @@
.identity { display:flex; gap:11px; align-items:center; text-decoration:none; font-size:32px; font-weight:800; letter-spacing:-.065em; line-height:1; color:inherit; }
.identity .mascot { width:37px; height:37px; overflow:visible; }
/* Align the feet with the wordmark baseline, allowing for the SVG's bottom inset. */
.identity[data-brand],.footer-identity { align-items:baseline; }
.identity[data-brand] .mascot,.footer-identity > svg { translate:0 .1em; }
.identity-dot { color:#e4572e; }
.identity .mascot-face,.identity .mascot-eye-open,.identity .mascot-sparkles { transform-box:fill-box; transform-origin:center; }
@media (prefers-reduced-motion:no-preference) {
+3 -3
View File
@@ -2329,9 +2329,9 @@
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
+5 -4
View File
@@ -6,10 +6,11 @@
<meta name="color-scheme" content="light dark" />
<meta
name="description"
content="Share the good stuff. Piik is free screen sharing for games, movie nights, drawings and photos. Invite up to 20 friends to watch in their browsers."
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" />
<title>Piik — Share the good stuff.</title>
<title>Piik — Free, open-source screen sharing</title>
<link rel="canonical" href="https://piik.tv/" />
<link rel="icon" href="./assets/favicon.svg" type="image/svg+xml" />
<link rel="stylesheet" href="./styles.css" />
<link rel="stylesheet" href="./assets/brand.css" />
@@ -839,10 +840,10 @@
</h2>
<p>
<span lang="en"
>Run a Piik site on a Linux server or NAS with your own domain.
>Self-host Piik on a Linux server or NAS with your own domain.
Server packages support x64 and ARM64; Docker selects the matching architecture automatically.</span
><span lang="zh-CN"
>在 Linux 服务器或 NAS 上,用自己的域名搭一个长期可用的 Piik 站点。
>在 Linux 服务器或 NAS 上自部署 Piik,用自己的域名和朋友共享屏幕。
服务端程序支持 x64 和 ARM64,Docker 镜像会自动选择对应架构。</span
>
</p>
+2 -2
View File
@@ -88,8 +88,8 @@ const copy = {
image: roomIllustration.alt,
},
'zh-CN': {
title: 'Piik — 来,看点好康的。',
description: '游戏、绘画、电影、照片。Piik 是免费开源的屏幕共享工具,邀请最多 20 位朋友用浏览器观看。',
title: 'Piik — 免费开源的屏幕共享',
description: 'Piik 是免费开源的私密屏幕共享工具,适合游戏直播、一起看电影、展示绘画和照片。支持自部署站点,邀请最多 20 位朋友通过浏览器观看。',
themes: { system: '跟随系统', light: '浅色', dark: '深色' },
image: '戴着小金冠的房主分享 RPG 游戏、绘画、旅行照片和动画电影,三位朋友坐在沙发上观看。',
},
+1 -1
View File
@@ -203,7 +203,7 @@ details p { max-width: 610px; padding: 0 24px 23px 0; color: var(--muted); font-
.docs-links p { margin: 0; font-size: 13px; }
.project-note .docs-note { margin-bottom: 0; font-size: 12px; }
.site-footer { display: flex; align-items: center; flex-wrap: wrap; column-gap: 20px; padding-block: 48px 29px; }
.footer-identity { display: flex; align-items: center; gap: 8px; font-size: 21px; font-weight: 750; letter-spacing: -.035em; }
.footer-identity { display: flex; gap: 8px; font-size: 21px; font-weight: 750; letter-spacing: -.035em; }
.footer-identity svg { width: 28px; height: 28px; }
.footer-identity p { color: var(--muted); margin-left: 12px; font-size: 11px; font-weight: 400; letter-spacing: 0; }
.footer-links { display: flex; flex-wrap: wrap; gap: 24px; margin-left: auto; font-size: 12px; }
@@ -0,0 +1,37 @@
import { useId } from "react";
import type { ReleaseUpdateNotice } from "../../lib/release-update";
import { useCopy, type CopyKey } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
import { Tooltip } from "./Tooltip";
const labels: Record<ReleaseUpdateNotice["kind"], CopyKey> = {
"update-available": "client.update.available",
"major-update": "client.update.major",
"different-build": "client.update.differentBuild",
"official-release": "client.update.official",
};
export function AppReleaseNotice({ update }: { update: ReleaseUpdateNotice }) {
const { vis, t } = useCopy();
const warningId = useId();
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>
<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>
</div>
{major && <p id={warningId} className={vis ? "visually-hidden" : "lr-client-release-warning"}>
{t("client.update.majorHint")}
</p>}
</div>;
}
+11 -6
View File
@@ -166,12 +166,15 @@ export function LauncherForm({
{mode === "site" ? (
<label className="lr-input lr-client-site">
<Glyph name="link" size={18} />
{/* The App normalizes bare domains; type="url" would block submission first. */}
<input
type="url"
type="text"
value={site}
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
inputMode="url"
placeholder="https://piik.example.com"
placeholder="piik.example.com"
aria-label={t("client.launch.siteAddress")}
onChange={(event) => {
onSiteChange(event.target.value);
@@ -209,11 +212,13 @@ export function LauncherForm({
(mode === "local" && lan !== undefined && !lan.selected)}
/>
<div className="lr-client-about">
{version && <p className="lr-client-version" aria-label={t("client.launch.version", { version })}>
{vis ? version : t("client.launch.version", { version })}
{version && <p className="lr-client-version">
<span className={vis ? "visually-hidden" : undefined}>{t("client.launch.version", { version })}</span>
{vis && <span aria-hidden="true">{version}</span>}
</p>}
<p aria-label={vis ? t("client.launch.credit") : undefined}>
{vis ? "MIT · TNTcraft" : t("client.launch.credit")}
<p>
<span className={vis ? "visually-hidden" : undefined}>{t("client.launch.credit")}</span>
{vis && <span aria-hidden="true">MIT · TNTcraft</span>}
</p>
<div className="lr-client-project-links">
<a href="https://piik.tv/" target="_blank" rel="noopener noreferrer" aria-label={t("client.launch.website")}>
+7 -5
View File
@@ -32,11 +32,13 @@ async function responseBody(response: Response): Promise<unknown> {
} catch {
throw new ApiError(say("host.err.serverError"), response.status);
}
if (
response.status === 403 && body && typeof body === "object" &&
"error" in body && body.error === "Origin not allowed"
) {
throw new ApiError(say("api.originNotAllowed"), response.status);
if (body && typeof body === "object" && "error" in body) {
if (response.status === 403 && body.error === "Origin not allowed") {
throw new ApiError(say("api.originNotAllowed"), response.status);
}
if (response.status === 503 && body.error === "Room capacity reached") {
throw new ApiError(say("host.err.roomCapacity"), response.status);
}
}
return body;
}
+8 -4
View File
@@ -1,4 +1,4 @@
import { compare, valid } from "semver";
import { compare, major, valid } from "semver";
export const DEFAULT_RELEASE_API_URL =
"https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest";
@@ -14,10 +14,11 @@ interface PublishedRelease {
version: string;
revision: string | null;
url: string;
releaseURL: string;
publishedAt?: string;
}
export interface ReleaseUpdateNotice extends PublishedRelease {
kind: "update-available" | "different-build" | "official-release";
kind: "update-available" | "major-update" | "different-build" | "official-release";
}
export function normalizeReleaseRevision(value: unknown): string | null {
@@ -61,6 +62,7 @@ export function parseReleaseMetadata(value: unknown, packageTarget?: string): Pu
// GitHub permits a branch here; only our publisher's full SHA is provenance.
revision: normalizeReleaseRevision(release.target_commitish),
url: RELEASE_PAGE + version,
releaseURL: RELEASE_PAGE + version,
...(Number.isFinite(publishedTime) ? { publishedAt: new Date(publishedTime).toISOString() } : {}),
};
return { ...normalized, url: packageDownloadURL(normalized, release.assets, packageTarget) };
@@ -78,7 +80,8 @@ export function parseMirrorReleaseMetadata(value: unknown, packageTarget?: strin
target_commitish: sources[0][1],
});
if (!normalized) return null;
const mirror = { ...normalized, url: MIRROR_RELEASE_PAGE + normalized.version };
const mirror = { ...normalized, url: MIRROR_RELEASE_PAGE + normalized.version,
releaseURL: MIRROR_RELEASE_PAGE + normalized.version };
return { ...mirror, url: packageDownloadURL(mirror, release.assets, packageTarget) };
}
@@ -90,7 +93,8 @@ export function releaseUpdateNotice(
const revision = normalizeReleaseRevision(current.revision);
if (version) {
const order = compare(latest.version, version);
if (order > 0) return { ...latest, kind: "update-available" };
if (order > 0) return { ...latest,
kind: major(latest.version) > major(version) ? "major-update" : "update-available" };
if (order === 0 && revision && latest.revision && revision !== latest.revision) {
return { ...latest, kind: "different-build" };
}
+4
View File
@@ -79,6 +79,9 @@ export const en: Record<CopyKey, string> = {
"client.launch.debugHint": "Record App and browser diagnostics for this launch. Press D in the terminal to export App logs.",
"client.launch.loadFailed": "Could not read launcher settings; reload to retry",
"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.differentBuild": "This build differs from the official release",
"client.update.official": "An official Piik release is available",
@@ -523,6 +526,7 @@ export const en: Record<CopyKey, string> = {
"host.err.forbidden": "Action unavailable",
"host.err.serverError": "Service temporarily unavailable; try again later",
"host.err.createRoomStatus": "Cannot create a room right now ({status})",
"host.err.roomCapacity": "All room codes are in use. Try again later or use another Piik site.",
"host.err.replaceRoomStatus": "Cannot change rooms right now ({status})",
"host.err.updateRoomStatus": "Cannot update room settings right now ({status})",
"host.capture.cancelled": "Screen selection cancelled or not permitted",
+4
View File
@@ -79,6 +79,9 @@ export const zh = {
"client.launch.debugHint": "本次启动记录 App 和网页诊断。App 日志可在终端按 D 导出。",
"client.launch.loadFailed": "无法读取启动设置,请刷新页面重试",
"client.update.available": "发现新的 Piik 版本",
"client.update.major": "发现新的 Piik 大版本",
"client.update.majorHint": "此更新含不兼容改动。升级前请查看版本说明。",
"client.update.notes": "版本说明",
"client.update.differentBuild": "当前构建与官方发行版不同",
"client.update.official": "可获取 Piik 正式发行版",
@@ -523,6 +526,7 @@ export const zh = {
"host.err.forbidden": "当前操作不可用",
"host.err.serverError": "服务暂时不可用,请稍后重试",
"host.err.createRoomStatus": "当前无法创建房间 ({status})",
"host.err.roomCapacity": "站点房间号已用满,请稍后重试或使用其他 Piik 站点。",
"host.err.replaceRoomStatus": "当前无法更换房间 ({status})",
"host.err.updateRoomStatus": "当前无法更新房间设置 ({status})",
"host.capture.cancelled": "屏幕选择已取消或没有共享权限",
+3 -25
View File
@@ -3,12 +3,11 @@ import { z } from "zod";
import { BrandMark } from "../components/living/BrandMark";
import { LoadingStatus } from "../components/living/WaitingStatus";
import { Tooltip } from "../components/living/Tooltip";
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 { Glyph } from "../ui/icons";
import { hasCopyPreference, useCopy, type CopyKey } from "../ui/copy";
import { hasCopyPreference, useCopy } from "../ui/copy";
import { consoleLanguage } from "../locales";
import { currentThemePreference } from "../ui/theme";
import { clientLaunchURL, type ClientLaunchPresentation } from "../lib/session";
@@ -124,27 +123,6 @@ export function AppLauncherPage() {
}
}
const updateKey: CopyKey =
update?.kind === "different-build"
? "client.update.differentBuild"
: update?.kind === "official-release"
? "client.update.official"
: "client.update.available";
const updateText = update ? `${t(updateKey)} · ${update.version}` : "";
const updateLink = update ? (
<a
className="lr-btn lr-client-update"
href={update.url}
target="_blank"
rel="noopener noreferrer"
aria-label={updateText}
>
<Glyph name="arrowUp" size={17} />
<span className={vis ? "visually-hidden" : undefined}>{updateText}</span>
{vis && <span aria-hidden="true">{update.version}</span>}
</a>
) : null;
return (
<div className="lr-app">
<AppHeader homeHref="/client" diagnosticControl={appDebug === undefined ? null : (
@@ -189,7 +167,7 @@ export function AppLauncherPage() {
lan={lan && { ...lan, onChange: (selected) => setLan({ ...lan, selected }) }}
onSubmit={launch}
>
{update && updateLink && <Tooltip kind="update-available" text={vis ? update.version : updateText}>{updateLink}</Tooltip>}
{update && <AppReleaseNotice update={update} />}
</LauncherForm>
)}
</main>
+16 -2
View File
@@ -16,6 +16,7 @@ import { REACTION_IDS, type ReactionId } from "../../shared/room-interactions";
import { PlaybackControls } from "../components/living/PlaybackControls";
import { SharingSettings } from "../components/living/SharingSettings";
import { LauncherForm, type AppMode } from "../components/living/LauncherForm";
import { AppReleaseNotice } from "../components/living/AppReleaseNotice";
import { useTheaterMode } from "../components/living/use-theater-mode";
import { QualityPresets } from "../components/living/QualityPresets";
@@ -57,6 +58,9 @@ export function ControlsPreview() {
const [microphoneDevice, setMicrophoneDevice] = useState("");
const [sharingSettings, setSharingSettings] = useState(false);
const [launchMode, setLaunchMode] = useState<AppMode>("link");
const [majorUpdate, setMajorUpdate] = useState(true);
const releaseVersion = majorUpdate ? "v2.0.0" : "v1.1.0";
const releaseURL = `https://github.com/TNTcraftHIM/Piik/releases/tag/${releaseVersion}`;
const [launchSite, setLaunchSite] = useState("");
const [launchPassword, setLaunchPassword] = useState("");
const [launchLan, setLaunchLan] = useState("192.0.2.10");
@@ -233,15 +237,25 @@ export function ControlsPreview() {
</section>
<section id="launcher-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">08</span><h2>{t("client.launch.title")}</h2></header>
<div className="cp-tools">
<button className="lr-btn" type="button" aria-pressed={majorUpdate} onClick={() => setMajorUpdate(value => !value)}>
{en ? "Preview major update" : "预览跨大版本更新"}
</button>
</div>
<div className="lr-client-launch">
<LauncherForm version="development" mode={launchMode} onModeChange={setLaunchMode}
<LauncherForm version="v1.0.0" mode={launchMode} onModeChange={setLaunchMode}
site={launchSite} onSiteChange={setLaunchSite}
lan={{ selected: launchLan, onChange: setLaunchLan, addresses: [
{ address: "192.0.2.10", name: "Wi-Fi" },
{ address: "192.0.2.20", name: "vEthernet (Example Virtual Network Adapter with a Long Name)" },
] }}
localAccessPassword={launchPassword} onLocalAccessPasswordChange={setLaunchPassword}
onSubmit={event => event.preventDefault()} />
onSubmit={event => event.preventDefault()}>
<AppReleaseNotice update={{ kind: majorUpdate ? "major-update" : "update-available",
version: releaseVersion, revision: null,
url: `https://github.com/TNTcraftHIM/Piik/releases/download/${releaseVersion}/piik-app-windows-amd64.zip`,
releaseURL }} />
</LauncherForm>
</div>
</section>
<section id="interaction-preview" className="cp-section">
+3
View File
@@ -1506,6 +1506,9 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }
.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-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-warning { max-width: 42ch; color: var(--muted); font-size: 12px; line-height: 1.6; text-align: center; }
.lr-client-update {
gap: 7px;
min-width: 0;
+19
View File
@@ -740,6 +740,25 @@ describe("client session identity", () => {
});
describe("site access API", () => {
it.each(["zh", "en"] as const)("explains room capacity across creation and replacement in %s", async (lang) => {
setCopy({ lang, vis: false });
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockImplementation(async () =>
new Response(JSON.stringify({ error: "Room capacity reached" }), { status: 503 }),
));
for (const request of [
() => createRoom("open", null),
() => replaceOwnedRoom("4321", "host-token", "open", null),
]) {
await expect(request()).rejects.toMatchObject({ status: 503, message: say("host.err.roomCapacity") });
}
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockResolvedValue(
new Response(JSON.stringify({ error: "Room creation unavailable" }), { status: 503 }),
));
await expect(createRoom("open", null)).rejects.toMatchObject({
status: 503, message: say("host.err.createRoomStatus", { status: "503" }),
});
});
it.each(["zh", "en"] as const)("explains rejected origins across write APIs in %s", async (lang) => {
setCopy({ lang, vis: false });
vi.stubGlobal("fetch", vi.fn<typeof fetch>().mockImplementation(async () =>
+19 -3
View File
@@ -34,6 +34,7 @@ describe("App release update notice", () => {
const fetchImpl = vi.fn<typeof fetch>(async () => Response.json({ ...release, assets }));
await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision }, { fetchImpl, packageTarget }))
.resolves.toMatchObject({ kind: "update-available", version: release.tag_name,
releaseURL: release.html_url,
url: assets.find(asset => asset.name === `piik-app-${packageTarget}.zip`)!.browser_download_url });
expect(fetchImpl).toHaveBeenCalledTimes(1);
expect(String(fetchImpl.mock.calls[0][0])).toBe(DEFAULT_RELEASE_API_URL);
@@ -73,7 +74,8 @@ describe("App release update notice", () => {
const fetchImpl = vi.fn<typeof fetch>(async (input) => String(input) === DEFAULT_RELEASE_API_URL
? new Response(null, { status: 503 }) : Response.json([mirrored]));
await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision },
{ fetchImpl, packageTarget })).resolves.toMatchObject({ url: mirrorAsset.browser_download_url });
{ fetchImpl, packageTarget })).resolves.toMatchObject({ url: mirrorAsset.browser_download_url,
releaseURL: `https://gitee.com/TNTcraftHIM/Piik/releases/tag/${release.tag_name}` });
expect(fetchImpl).toHaveBeenCalledTimes(2);
for (const assets of [[], [mirrorAsset, mirrorAsset],
[{ ...mirrorAsset, browser_download_url: mirrorAsset.browser_download_url.replace("gitee.com", "evil.example") }],
@@ -92,7 +94,7 @@ describe("App release update notice", () => {
});
await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision }, { fetchImpl }))
.resolves.toEqual({ version: "v1.2.0", revision: latestRevision,
url: release.html_url, kind: "update-available" });
url: release.html_url, releaseURL: release.html_url, kind: "update-available" });
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
@@ -109,10 +111,23 @@ describe("App release update notice", () => {
["development", currentRevision, null, null],
])("compares %s by release precedence, using SHA only to identify builds", (version, revision, remoteRevision, expected) => {
expect(releaseUpdateNotice({ version, revision }, {
version: "v1.2.0", revision: remoteRevision, url: release.html_url,
version: "v1.2.0", revision: remoteRevision, url: release.html_url, releaseURL: release.html_url,
})?.kind ?? null).toBe(expected);
});
it.each([
["v1.9.1", "major-update"],
["v0.9.0", "major-update"],
["v2.0.0-rc.1", "update-available"],
["v2.0.0", "different-build"],
["v3.0.0", null],
["development", "official-release"],
])("warns for a newer major without inferring compatibility from an unknown build: %s", (version, kind) => {
const latest = parseReleaseMetadata({ ...release, tag_name: "v2.0.0",
html_url: "https://github.com/TNTcraftHIM/Piik/releases/tag/v2.0.0" })!;
expect(releaseUpdateNotice({ version, revision: currentRevision }, latest)?.kind ?? null).toBe(kind);
});
it("does not turn branch names, prereleases or malformed metadata into release identity", async () => {
expect(parseReleaseMetadata({ ...release, target_commitish: "main" })?.revision).toBeNull();
for (const changed of [
@@ -142,6 +157,7 @@ describe("App release update notice", () => {
await expect(checkReleaseUpdate(current, { fetchImpl })).resolves.toEqual({
kind: "update-available", version: "v1.10.0", revision: latestRevision,
url: "https://gitee.com/TNTcraftHIM/Piik/releases/tag/v1.10.0",
releaseURL: "https://gitee.com/TNTcraftHIM/Piik/releases/tag/v1.10.0",
});
await expect(checkReleaseUpdate({ ...current, version: "v2.0.0" }, { fetchImpl })).resolves.toBeNull();
});