Compare commits

..
Author SHA1 Message Date
Alex SouthwellandSAPHID 241f538f99 Bump version to 0.4.17 (#153)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 08:43:00 +00:00
Alex SouthwellandSAPHID 21dacfcbe7 Distinguish unreadable panel discovery from an empty list (#152)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 08:34:56 +00:00
Alex SouthwellandSAPHID eb181d8996 Add opt-in desktop low-battery comfort alerts (#150)
* Add opt-in desktop low-battery comfort alerts

* Fix desktop battery alert test harness and Windows encoding

---------

Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 08:22:56 +00:00
Alex SouthwellandSAPHID 827ddcf14f Clarify desktop installation and first headset connection (#151)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 08:08:47 +00:00
Alex SouthwellandSAPHID 7c3894e630 docs: record real Frame clip Export button check (#149)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 08:04:06 +00:00
Alex SouthwellandSAPHID 040581a4c7 Bump Frame Control to 0.4.16 (#148)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 07:42:37 +00:00
Alex SouthwellandSAPHID 17f6d52717 Document real Steam clip export verification (#147)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 07:34:34 +00:00
Alex SouthwellandSAPHID b4e80cab0a Escape power report CSV metadata for spreadsheets (#146)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 07:28:26 +00:00
Alex SouthwellandSAPHID b98e3e496f Bump Frame Control to 0.4.15 (#145)
Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 07:08:23 +00:00
Alex SouthwellandSAPHID a148e02d39 Add bounded read-only power and heat reports to desktop Tools (#144)
* Add bounded desktop power and heat observations with offline downloads

* Fix desktop power tests on Python 3.9

---------

Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 06:58:19 +00:00
Alex SouthwellandSAPHID 0fb9174c23 Fix Return to Game Mode detection in full Plasma (#143)
* Fix Frame session detection for full Plasma Desktop Mode

* Document real Frame Desktop Mode return verification

---------

Co-authored-by: SAPHID <saphid@users.noreply.github.com>
2026-10-24 06:46:17 +00:00
33 changed files with 1556 additions and 121 deletions

No files matched your search

+23
View File
@@ -2,6 +2,29 @@
## Unreleased
- Distinguish an unreadable gamescope panel list from a confirmed empty list in
Desktop Capture and Control (issue #73). Failed discovery now asks users to
check SteamVR and report the exact message and SteamOS version, rather than
claiming no panel is open. This does not establish a new capture fix.
- Add an opt-in desktop low-battery alert without starting a family session.
Existing status reads confirm low charge and drain; recovery hysteresis and a
ten-minute cooldown limit repeat alerts. Off on page open/headset switch;
pauses with hidden-page status refreshes. No extra polling or headset changes.
- Clarify first-time desktop downloads, installation and opening on the website
and README, including CPU choices, unsigned-app warnings, pairing fallback
and the source-only iOS build. Keep section navigation available on mobile.
- Treat headset aliases and other CSV metadata as plain text in power and heat
exports, so spreadsheet formula prefixes cannot run when a report is opened.
- Add desktop Tools → Power & heat report: bounded read-only one/five-minute
observations with progress, stop and HTML/JSON/CSV downloads. Received samples
survive stop, disconnect and headset switch, labeled incomplete and tied to the
original headset. Shared sampler/report modules ship with the app; no power or
thermal controls are added. Download before replacing a report or quitting.
- Fix Return to Game Mode misidentifying full Plasma Desktop Mode when its VR
overlay also runs gamescope (issue #142). Session targets now determine the
mode; conflicting or incomplete evidence stays unknown. Use SteamOS's
+60 -29
View File
@@ -7,9 +7,9 @@
**Manage your Valve Steam Frame from your computer.**<br>
See what the headset sees, install games and Android apps, move files and text across, and check battery and status, all over SSH.
[![Latest release](https://img.shields.io/github/v/release/saphid/steam-frame?label=release&color=1a9fff)](https://github.com/saphid/steam-frame/releases/latest)
[![Latest release](https://img.shields.io/github/v/release/saphid/frame-control?label=release&color=1a9fff)](https://github.com/saphid/frame-control/releases/latest)
[![Platforms](https://img.shields.io/badge/macOS%20%7C%20Windows%20%7C%20Linux-2a475e?label=runs%20on)](#install)
[![Checks](https://img.shields.io/github/actions/workflow/status/saphid/steam-frame/checks.yml?branch=main&label=checks)](https://github.com/saphid/steam-frame/actions/workflows/checks.yml)
[![Checks](https://img.shields.io/github/actions/workflow/status/saphid/frame-control/checks.yml?branch=main&label=checks)](https://github.com/saphid/frame-control/actions/workflows/checks.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-66c0f4)](LICENSE)
[**Website**](https://frame-control.pages.dev) · [**Download**](#install) · [Trailer](#trailer) · [Features](#features) · [Set up the headset](#set-up-the-headset) · [Feedback](#feedback) · [Docs](#going-further)
@@ -19,7 +19,7 @@ See what the headset sees, install games and Android apps, move files and text a
<img src="docs/img/frame-control.png" alt="Frame Control's Games tab: installed games, sideloaded titles, and your Steam library with Frame ratings" width="900">
<a id="trailer"></a>
<a href="https://github.com/saphid/steam-frame/releases/download/trailer/frame-control-trailer.mp4"><img src="docs/img/trailer.jpg" alt="Watch the Frame Control trailer" width="900"></a>
<a href="https://github.com/saphid/frame-control/releases/download/trailer/frame-control-trailer.mp4"><img src="docs/img/trailer.jpg" alt="Watch the Frame Control trailer" width="900"></a>
<sub>The trailer: 66 seconds, with sound. Downloads the MP4 from the trailer release.</sub>
@@ -116,17 +116,30 @@ already ships (sideloading a game copies Valve's own devkit scripts to
## Install
**Install Frame Control on your computer, not on the headset.** The website is
for downloads and instructions; it does not connect to your Frame in a browser.
Choose the operating system and processor of the computer you will use.
| | Download | Needs |
|---|---|---|
| **macOS** (Apple Silicon) | [Frame-Control-mac-arm64.dmg](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-mac-arm64.dmg) | Nothing extra |
| **Windows** 10 / 11 (x64) | [Frame-Control-Setup-x64.exe](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-Setup-x64.exe) · [portable .zip](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-win-x64.zip) | Nothing extra |
| **Linux** (x64) | [AppImage](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-linux-x86_64.AppImage) · [.deb](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-linux-amd64.deb) | `ssh` (most desktops have it) |
| **Linux** (arm64) | [AppImage](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-linux-arm64.AppImage) · [.deb](https://github.com/saphid/steam-frame/releases/latest/download/Frame-Control-linux-arm64.deb) | `ssh`, and `adb` for Android apps (`sudo apt install adb`) |
| **macOS** (Apple Silicon) | [Frame-Control-mac-arm64.dmg](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-mac-arm64.dmg) | Nothing extra |
| **Windows** 10 / 11 (x64) | [Frame-Control-Setup-x64.exe](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-Setup-x64.exe) · [portable .zip](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-win-x64.zip) | OpenSSH Client (normally installed) |
| **Linux** (x64) | [AppImage](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-x86_64.AppImage) · [.deb](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-amd64.deb) | `ssh` (most desktops have it) |
| **Linux** (arm64) | [AppImage](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-arm64.AppImage) · [.deb](https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-arm64.deb) | `ssh`, and `adb` for Android apps (`sudo apt install adb`) |
**iPhone and iPad:** the same features from your phone, with nothing to install on
a computer. Build it from [`ios/`](ios) in Xcode; see [docs/iphone.md](docs/iphone.md).
**Which build?** On a Mac, check Apple menu → About This Mac: the download is
for Apple Silicon (M-series); no Intel Mac build is published. On Windows,
check Settings → System → About → System type: the release is x64, not a native
Windows ARM build. On Linux, `uname -m` reports `x86_64` (x64) or `aarch64`
(arm64). Use `.deb` on Debian/Ubuntu, or AppImage on other distributions.
The app brings its own Python and `adb`; SSH is built into macOS and Windows.
**iPhone and iPad:** no App Store, TestFlight or `.ipa` download is provided in
the current release. It runs from your phone without a computer after setup.
Build it from [`ios/`](ios) in Xcode on a Mac with your own signing team; see
[docs/iphone.md](docs/iphone.md).
The app brings its own Python and `adb`. macOS includes SSH; Windows needs the
OpenSSH Client optional feature (normally installed).
From 0.4 it updates itself: when a new version is published, a banner offers
**Update and restart**. It sends anonymous usage statistics, which you can turn
off. Sharing compatibility results and error details is opt-in. See
@@ -139,7 +152,7 @@ distribution's. If you already have `adb`, the app uses yours.
There's no paid Apple developer account behind it, so macOS says the app is
damaged or can't be checked. Drag it to Applications, then clear the download
quarantine once:
quarantine once, only for a download you trust from the releases linked above:
```sh
xattr -dr com.apple.quarantine "/Applications/Frame Control.app"
@@ -168,26 +181,44 @@ If it complains about FUSE, install `libfuse2` (Ubuntu 24.04+: `libfuse2t64`),
or run it with `--appimage-extract-and-run`.
</details>
## Open the app
- **macOS:** open the `.dmg`, drag **Frame Control** to **Applications**, then
open it from Applications. For the unsigned-app warning, use the macOS steps
above. Allow local network access and control of Terminal when prompted.
- **Windows:** run the installer, then open **Frame Control** from Start. For
the portable download, extract the entire `.zip` first and run
`Frame Control.exe` inside it. See the SmartScreen note above.
- **Linux:** install the `.deb` with your package installer and launch
**Frame Control** from your applications menu; or make the AppImage executable
and run it as described above. Install the OpenSSH client if `ssh` is missing.
## Set up the headset
You type one password on the headset, once. Everything else happens on your
computer.
Keep the Frame awake and connect it and your computer to the same trusted local
network. Guest Wi-Fi/client isolation can prevent discovery and connections.
1. **On the Frame:** Steam Settings → System → **Enable Developer Mode**, then
in the Developer section, **Set User Password**. Pick something short:
you'll type it once more on your computer and then never again.
2. **On your computer:** open Frame Control. It offers to **Set Up
Connection**, which finds the headset, creates an SSH key, and asks for that
password once in a terminal window. If it can't find the Frame, type the
IP address from the Frame's Quick Settings.
Before asking for the password it tries Valve's SteamOS devkit pairing: in
the headset, open Steam Settings → Developer → **Pair new host** and approve
the request, and no password is needed. (The service and the pairing-mode
step are verified on a Frame; the approval itself isn't yet. See
[SSH](docs/ssh.md#password-free-pairing-steamos-devkit-service).)
3. That's it. The app now reaches the headset whenever it's awake and on the
same network. For anywhere else, see [Tailscale](docs/tailscale.md).
Developer → **Set User Password**. Choose a password that isn't easy to guess:
it also protects `sudo` and remote desktop, even after SSH keys are set up.
2. **On your computer:** open Frame Control and choose **Set Up Connection…**.
If you dismissed the first-run prompt, use **Frame → Set Up Connection…**.
Setup opens a terminal and tries to find the headset. If it can't, use its IP
address from Quick Settings or Steam Settings → Internet. Windows/Linux setup
prompts for it; macOS exits instead. On macOS, return to the app →
**Devices & connection → + Add a headset…**, set SSH alias to `frame` for
the default headset, fill in **Address**, then choose **Set Up…**.
3. **Pair or enter the password:** setup first tries Valve's devkit pairing.
Open Steam Settings → Developer → **Pair new host** in the headset and approve
only the request you just started. The service and pairing-mode step are
verified on a Frame; approval and key installation through that flow remain
unverified. If pairing fails or times out, setup falls back to asking for the
Developer Mode password in the computer's terminal. Password typing may show
no characters; press Enter when done. See [SSH details](docs/ssh.md#password-free-pairing-steamos-devkit-service).
4. After setup succeeds, return to Frame Control. It uses SSH keys for later
connections whenever the Frame is awake and reachable. If it stays offline,
check Developer Mode, the address and network isolation, then run setup again.
For connections away from home, see [Tailscale](docs/tailscale.md).
**What it changes:** only what you click. Installs go to your user account on
the Frame (`--user` Flatpaks, Lepton instances, Steam downloads, sideloaded
@@ -252,8 +283,8 @@ Frame's software fits together, all checked against a real headset and labelled
loopback `127.0.0.1:8080`) only through SSH tunnels. The compatibility
database key (maintainer-only) is never written to the repo.
- `steamos` has `sudo`, protected by the same Developer Mode password. Once
you've switched to key auth, a short password still protects `sudo` and
RDP, so pick one that isn't trivially guessable.
you've switched to key auth, that password still protects `sudo` and RDP,
so pick one that isn't trivially guessable.
- Don't port-forward 22, 3389, or 5555–5599 from your router. For remote access,
use Tailscale: `scripts/tailscale-on-frame.sh` (no sudo). In its userspace mode
**every** Frame port is reachable from your tailnet, including Steam's DevTools
+4
View File
@@ -13,6 +13,10 @@ const path = require("path");
const REQUIRED = [
"ui/server.py",
"ui/frame_power.py",
"ui/frame_status.py",
"scripts/frame_power_sample.py",
"scripts/frame_power_report.py",
"ui/frame_android.py",
"frame/android/lepton-app.sh",
"frame/openxr-compat/XrApiLayer_FRAME_compat.json",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "frame-control",
"version": "0.4.14",
"version": "0.4.17",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frame-control",
"version": "0.4.14",
"version": "0.4.17",
"license": "MIT",
"devDependencies": {
"electron": "^44.4.5",
+4 -2
View File
@@ -1,7 +1,7 @@
{
"name": "frame-control",
"productName": "Frame Control",
"version": "0.4.14",
"version": "0.4.17",
"description": "Desktop app for managing a Valve Steam Frame over SSH",
"private": true,
"main": "main.js",
@@ -68,7 +68,9 @@
"from": "../scripts",
"to": "scripts",
"filter": [
"*.sh"
"*.sh",
"frame_power_sample.py",
"frame_power_report.py"
]
},
{
@@ -0,0 +1,38 @@
{
"date_utc": "2026-10-24T07:54:37Z",
"frame_control_tag": "v0.4.16",
"steamos_version": "0.5.6",
"steamos_build": "20261015.6141207",
"host": "lxso2",
"interface": "source UI served by a temporary private Frame Control server, opened in T3 Code's desktop browser",
"action": "Clicked the visible Export button for Steam's retained real saved clip in Capture & Live",
"clip_id": "10230640/clips/clip_13009719723623972864_20261024_072115",
"api_observed": {
"post_clips_export_http": 200,
"get_job_http": 200,
"get_clips_http": 200
},
"ui_result": "Saved clip_13009719723623972864_20261024_072115.mp4 to ~/Videos/SteamFrame; button changed to Export again",
"output": {
"path": "~/Videos/SteamFrame/clip_13009719723623972864_20261024_072115.mp4",
"bytes": 159829,
"sha256": "f8a476eefb2bde7ba5cb464632ec9b952eea3ab1610b5bed2098bf1f11d62cf1",
"matches_previously_fully_decoded_export": true,
"duration_seconds": 10.288532,
"video": "H.264 1920x1080",
"audio": "AAC stereo"
},
"cleanup": {
"temporary_server_stopped": true,
"shared_device_lock_released": true,
"battery_percent_after": 99,
"desktop_mode_active_after": false,
"test_title_created": false,
"steam_source_clip_retained": true
},
"limits": [
"The test used the source UI, not a packaged desktop installer.",
"The retained source clip was nearly black; visible gameplay capture remains unverified.",
"Perceptual audio/video sync, long clips, trims and automatic copying were not tested."
]
}
@@ -0,0 +1,95 @@
{
"date": "2026-10-24",
"command": "scripts/frame-power-sample.sh --count 2 --interval 1",
"exitCode": 0,
"stopped": null,
"lockPolicy": "Existing sampler checked local and remote /tmp/frame-test.lock before reading; no lock acquired, bypassed or removed. Read-only run only.",
"samples": [
{
"time": 1792828506.4317346,
"osBuild": "20261015.6141207",
"elapsedSeconds": 0.057539,
"battery": {
"battery.percent": {
"value": 99,
"unit": "%",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
},
"battery.status": {
"value": "Not charging",
"unit": "state",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
},
"battery.watts": {
"value": -0.06,
"unit": "W",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
},
"battery.tempC": {
"value": 24.0,
"unit": "C",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
}
}
},
{
"time": 1792828507.4357972,
"osBuild": "20261015.6141207",
"elapsedSeconds": 1.061612,
"battery": {
"battery.percent": {
"value": 99,
"unit": "%",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
},
"battery.status": {
"value": "Not charging",
"unit": "state",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
},
"battery.watts": {
"value": -0.05,
"unit": "W",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
},
"battery.tempC": {
"value": 24.0,
"unit": "C",
"source": "/sys/class/power_supply/max1720x_bat_7-36",
"state": "available"
}
}
}
],
"limitations": [
"No real low-charge or thermal condition induced.",
"No native notification delivery verified.",
"No worn-headset or native package tests.",
"Read-only parser/transport check; no background monitor or power-saving claim."
],
"browserCheck": {
"page": "Production ui/index.html served statically; API calls intentionally unavailable",
"viewport": {
"width": 1280,
"height": 800
},
"bridge": "Synthetic desktop notification bridge; no native OS notification sent",
"result": "Initially unchecked and visible only after desktop host/bridge setup. Checkbox enabled through browser. Synthetic 12%, Discharging, -4 W samples at 0/30/60 seconds produced one bridge request, an in-page status and a toast. No horizontal overflow.",
"apiLimit": "Static server returned expected 404/501 API errors; not an end-to-end live desktop connection test."
},
"offlineValidation": [
"test_desktop_battery_comfort.py: 2 tests, production JS with monotonic fake clock and notification bridge",
"test_comfort*.py: 25 tests",
"test_battery.py: 7 tests",
"test_power*.py: 36 tests (loopback HTTP test run outside socket-restricted sandbox)",
"test_ui_workspace.py: 1 Python wrapper / Node workspace suite",
"test_ui_review.py: 1 Python wrapper / 9 Node regression tests, including switch reset and retained cooldown"
]
}
@@ -0,0 +1,65 @@
# Panel discovery investigation, 2026-10-24
Base: v0.4.16 (`040581a`). Scope: issue #73, Desktop Capture and Control.
## Evidence and change
Issue #73 reports SteamOS 0.4.5 with its desktop visibly running, without a
Frame Control version or steps. The maintainer's 2026-10-12 comment identifies
the duplicate `loadPanels` UI function fixed in 0.4.3 and requests the exact
remaining message and SteamOS build if it persists. There is no reporter
follow-up. At this base, the functions are distinct and the existing Node
regression checks their uniqueness and the Desktop GET request.
Read-only source inspection found a remaining diagnostic ambiguity:
`read_props()` returns `{}` for failed/timed-out X queries and missing root
properties. `panels()` treated that like a confirmed empty focusable-window
list. With no detected Plasma process it claimed no panel was open; with Plasma
it claimed SteamOS was not listing the desktop. Neither claim follows from an
unreadable list.
The change checks for the presence of `GAMESCOPE_FOCUSABLE_WINDOWS` before
those claims. An absent list now reports unknown panel state, suggests checking
SteamVR and retrying/Headset view, and asks for the exact message and SteamOS
version if persistent. Missing-tool and whole-run deadline explanations retain
precedence. No new probes, retries, timeouts, input or capture routes are added.
## Real-device boundary
A preliminary read-only SSH inspection returned SteamOS 0.5.6, BUILD_ID
`20261015.6141207`, battery 99%, discharging, and X0/X1 socket names. It made
no headset changes. The shared lock was absent at that moment.
The subsequent atomic `mkdir /tmp/frame-test.lock` failed with `File exists`.
The guarded command exited with status 3 before the session, X-property or
panel-helper probes ran. The other task's lock was left alone. No application
was installed, started, stopped or focused; no headset settings changed.
That implementation probe was blocked by the occupied shared device. The
coordinator later supplied a separate narrow read-only observation on SteamOS
0.5.6, BUILD_ID `20261015.6141207`, at battery 99%, with the shared lock absent
and both `xprop` and `xwininfo` installed:
- In **Game Mode**, `DISPLAY=:0 xprop -root GAMESCOPE_FOCUSABLE_WINDOWS
GAMESCOPE_FOCUSED_WINDOW` returned both properties **present but empty**.
- On `DISPLAY=:1`, both properties were reported **not found**.
This observation distinguishes a confirmed empty list on `:0` from absent
properties on `:1`. It does **not** reproduce #73's Desktop Mode report on
SteamOS 0.4.5, and it does **not** test this PR's code on the headset. It is a
coordinator-supplied observation, separate from the blocked implementation probe
above; no new headset probe was run for this follow-up.
Remaining limit: there is no reproduction establishing a further
capture/discovery fix for the reported Desktop Mode/build combination. This PR
improves a demonstrated diagnostic error; it must not close #73 as a verified
new capture fix.
## Offline verification
Focused Python regressions distinguish absent, focus-only, failed/timed-out X
queries, confirmed empty and desktop-running lists. Existing tests cover
missing tools, alternate displays, successful discovery and the 12-second
deadline. The production page's Node behavior test verifies that both Capture
and Control preserve the unreadable-list advice. These use fake X/HTTP/DOM
boundaries and do not prove real SteamOS 0.4.5 capture or physical input.
@@ -0,0 +1,36 @@
{
"date": "2026-10-24",
"base": "c7489a8 (v0.4.14)",
"feature": "Desktop Tools power and heat observations",
"automated": {
"targeted": "python3 -m unittest discover -s tests -p 'test_power*.py': 35 passed",
"uiAndResourceGuard": "node --test tests/power_desktop.cjs: 7 passed",
"desktopApp": "node --test app/test/*.test.js: 37 passed",
"packaging": "Materialized ui/scripts resources selected by app/package.json; isolated Python -I imported frame_power, constructed remote payload including frame_status, and read idle status. Missing resource detection tested. Shared phone bundle import passed.",
"syntax": "Python compilation, sampler shell syntax and git diff --check passed",
"fullSuite": "python3 -m unittest discover -s tests -v: 1363 tests, OK (skipped=15), 153.274 seconds",
"transientFailure": "An earlier full run had one nested sandbox-test failure: the existing OneServer second-server child exited -11 (SIGSEGV), expected 1. Isolated sandbox rerun passed (6 tests), then the complete suite passed. No unrelated server-lifecycle code was changed."
},
"browser": {
"environment": "T3 collaborative Chromium preview, Linux, local Python Handler server; synthetic observation subprocess at accelerated one-second intervals; normal headset SSH disabled during start/stop/download verification",
"observations": [
"Opened #powerReport and verified labeled duration selector, disabled Stop/downloads before start and accessible sample progress.",
"Started a synthetic observation and observed 11 of 12 samples in progress; completion allowed another start.",
"Started again, observed progress, stopped, and saw 7 of 12 samples retained with explicit incomplete state and original frame alias.",
"Clicked HTML download and saw the UI acknowledge the request; T3's download list did not record the blob download, so filesystem save was not verified.",
"Fetched all three authenticated export endpoints in the browser: HTML 200 (7599 characters), JSON 200 (2618 characters, 7 samples), CSV 200 (977 characters); each retained the stop reason."
]
},
"realFrame": {
"lock": "ssh frame 'mkdir /tmp/frame-test.lock' succeeded before real-device probe; this task removed only that owned empty lock with rmdir after verification",
"probe": "Ran the production desktop Observation using strict, batch SSH to frame. The first attempt exposed a missing structured reason on early remote lock refusal; fixed and reran successfully.",
"result": "0 of 12 samples; running=false; stopped='Smoke session active (/tmp/frame-test.lock); no sensors read'. Exported HTML included the same incomplete reason.",
"scope": "Lock refusal only. No successful real sensor session, installation, app launch/stop, power control or thermal control was performed for this feature."
},
"limitations": [
"Native Electron installers were not built or launched; resource staging and build-hook contracts were tested.",
"One latest report is retained only in server memory. Starting again, restarting the server or quitting discards it; the UI warns users to download first.",
"Stopping ends only the owned local SSH process. The bounded remote reader discovers closure on its next write; immediate remote cancellation is not guaranteed.",
"Phone-hosted observation starts are unsupported; the shared server bundle still imports without desktop sampler resources."
]
}
+39
View File
@@ -6,6 +6,45 @@ This is Frame Control code using Python, Steam and SteamVR already on the Frame.
![Family and comfort controls in the desktop app](img/comfort-desktop.png)
## Desktop low-battery alert without a session
In the desktop app, open **Tools → Family & comfort** and check **Alert on this
computer at 15% or less**. This separate option does not start a session, install
a worker or change the headset. It starts off whenever the page opens and turns
off when you switch headsets. The choice is only for the current open page.
It consumes the battery parser already used by normal status refreshes (also
shared by the read-only power sampler). It adds no SSH calls, timers, sensor
reads, third-party push or heat thresholds. Normal automatic status refreshes
pause while the page is hidden, so this is **not a background or safety monitor**.
Keep the app visible and connected. Use **Enable / test notifications** to check
system delivery; operating-system settings may block notifications.
Two fresh readings, at least 20 seconds and at most 90 seconds apart, must show
15% or less, driver state `Discharging`, and signed battery power below −0.5 W.
This avoids alerting on plugged-in idle readings, which can report discharging.
Missing, invalid, stale or interrupted readings break confirmation. Disconnect,
a failed status request, hiding the page or toggling the option also breaks
confirmation. Unknown readings never mean zero charge.
An alert appears in the page and requests a native desktop notification once
per low-charge episode. Two readings at 20% or more rearm it, and at least ten
minutes must pass between alerts (including across headset switches). A single
recovery spike cannot rearm it. Toggling off/on does not clear the episode latch.
Notification failure stays visible in the page and does not retry on every
refresh. While an active family session has battery alerts enabled, that session
handles battery alerts instead. Multiple app windows have independent state;
this does not coordinate notifications between computers or windows.
A read-only check on 2026-10-24, build **20261015.6141207**, received two samples
at 99%, `Not charging`, approximately −0.06 W and 24 °C. No low-battery condition
was induced, no notification was sent to the real headset, and no headset state
was changed. The sampler's local and remote smoke-lock checks allowed the run;
no lock was acquired or removed. Deterministic tests exercise low charge,
recovery, missing readings, idle drain, timing and notification denial. See
[recorded evidence](evidence/desktop-battery-comfort-2026-10-24.json). Native OS
notification display, worn use and macOS/Windows packaging were not verified.
## Sessions
Set a limit of 1–240 minutes, optional break and check-in intervals, then
+50 -3
View File
@@ -46,11 +46,10 @@ raw measurements. The HTML also embeds those measurements; review it before
sharing. No automatic browser launch occurs.
HTML sessions are limited to `count × interval <= 600` seconds, with a 30-second
transport allowance and at most nine seconds of local child/reader cleanup. The default
transport allowance and at most twelve seconds of local child/pipe cleanup. The default
12 samples at five-second intervals take about 55 seconds. Existing output files
are never overwritten; choose a new filename for each run. `--html` cannot be
combined with `--csv`. This source-checkout flow is not a desktop Tools panel
and is not added to the packaged app.
combined with `--csv`. The desktop flow below uses the same sampler and renderer.
Stop, timeout, SSH failure or a smoke-test lock marks the report incomplete;
earlier received samples remain downloadable. Exit status is 75 for incomplete
@@ -67,6 +66,47 @@ not an immediate headset-side cancellation guarantee. The reader still checks
the smoke-test lock before every sample. No lock is acquired or removed by this
flow, and no power, thermal, service, password or security controls are exposed.
## Desktop Tools → Power & heat report
In the packaged desktop app, connect to an already paired Frame, open **Tools →
Power & heat report**, choose **1 minute** (12 samples) or **5 minutes** (60 samples),
and select **Start observation**. Samples arrive every five seconds, starting at
zero (about 55 or 295 seconds total). Progress shows received samples and the
original headset alias. There is at most one observation per local app server;
viewing progress never starts another SSH connection. No terminal, checkout,
extra dependency or password is needed.
Use **Stop and keep samples** to end local collection. Disconnect, timeout,
app shutdown or switching to another headset also ends collection. Switching
network addresses for the same headset does not retarget an existing observation:
it keeps its captured SSH route and may finish incomplete if that route fails.
As with the CLI, only the owned local SSH child is terminated. The remote reader
is bounded and discovers a closed connection on its next write. Desktop sessions
have a 30-second transport allowance and bounded child cleanup. Stream lines are
limited to 262,144 characters, sample events to the requested count, and the receive queue
to count + 2 events; desktop SSH stderr is discarded rather than stored unbounded.
The existing smoke lock is checked locally before start and remotely before each
sample; this feature never creates, bypasses or removes that lock.
**Download HTML report**, **Download JSON** and **Download CSV** save local
snapshots through the browser/app download mechanism. Open the downloaded HTML
in your browser to view the offline table and its embedded JSON/CSV downloads.
Snapshots taken before completion explicitly say incomplete. Desktop CSV includes
`collection.state`, `collection.requestedSamples` and `collection.receivedSamples`
metadata rows with the original headset alias in the source column, even when no
sensor sample arrived. CSV text fields, including the alias, are escaped if they
begin with a spreadsheet formula prefix. JSON records the alias and device ID;
HTML names the alias.
Only the latest observation is retained in server memory, including partial
samples after stop or disconnect. **Download before starting another observation,
restarting the server or quitting the app**: those discard the previous report.
Page reloads retain server state. Download requests include an observation ID, so
an old page cannot silently download or stop a replacement observation. Reports
are not uploaded or automatically opened, and may contain device identifiers,
OS builds and sensor paths. Review before sharing. The phone-hosted UI does not
support starting observations.
## What it reads
- Battery percentage, driver charging state, signed battery watts and battery
@@ -175,3 +215,10 @@ summary counts, CSV quoting, strict SSH transport and smoke-lock interruption.
Export fixtures also cover HTML escaping, download round trips, zero versus unknown,
stream completion/failure, smoke-lock stop, timeout, Ctrl+C retention, local child
cleanup, duration bounds and refusing to overwrite reports.
Desktop validation on **2026-10-24** covered API start/stop, a synthetic browser
observation with partial exports, shared-module resource staging under isolated
Python and missing-resource build guards. A real Frame probe under this task's
owned smoke lock correctly returned zero samples with an explicit incomplete
reason; no successful live sensor baseline or native installer run was performed.
See [desktop evidence and limitations](evidence/power-desktop-2026-10-24.json).
+34 -16
View File
@@ -8,13 +8,13 @@ Both are on **Tools → Capture & Live**. Everything is saved to
Nothing needs installing on the computer or on the Frame: the work is done by
the `ffmpeg` that SteamOS ships.
**Recording is tested on a headset; Steam clip export isn't yet.** On a Frame
**Recording and Steam clip export have each been tested on a headset.** On a Frame
running SteamOS 0.5.6 (build 20261015.6141207), Record and Stop saved an
8-second 1080p H.264 recording with AAC sound to the computer, Stop took about a
second, and nothing was left running or stored on the Frame. That Frame had no
Steam recordings, so the clip list came back empty and export has only been
tested with files in Steam's format made by `ffmpeg`. The parts we're least sure
of are listed under [What hasn't been checked](#what-hasnt-been-checked).
second, and nothing was left running or stored on the Frame. A later test on
that build created a saved clip with Steam's own recorder and exported it with
Frame Control's production export function. The parts we're least sure of are
listed under [What hasn't been checked](#what-hasnt-been-checked).
## Record
@@ -147,19 +147,37 @@ stand-in `ffmpeg`, so Stop, the time limit and the clean-up are tested as they
run on the Frame. Where `ffmpeg` is installed, they also make a 65-second DASH
recording with Steam's file names and export it with the real `ffmpeg`.
## What hasn't been checked
## Real Steam clip verification and remaining checks
The 2026-10-24 read-only clip list on build `20261015.6141207` again returned
zero clips: its `gamerecordings` directory held only `gamerecording.pb`. No
Steam recording was created during that check, so a real Steam clip export is
still unverified. The recording and Stop path were verified earlier on that
build, as described above. Remaining checks:
On 2026-10-24, v0.4.15 on build `20261015.6141207` recorded a ten-second
reserved test session through Steam's own game recorder, saved it as a clip,
then exported it with `frame_clips.export_clip`, the same implementation used
by the desktop API. The 159,829-byte MP4 decoded completely: 10.29 seconds,
1920×1080 H.264 video and stereo AAC audio (SHA-256
`f8a476eefb2bde7ba5cb464632ec9b952eea3ab1610b5bed2098bf1f11d62cf1`).
All 616 decoded video frames and the decoded audio matched Steam's source
segments. Recording mode was restored
to off; the reserved title and its processes were removed, the shared test lock
was released, and the battery remained at 99%. The Steam source clip was kept.
- Audio and video sync. Both inputs are stamped with the wall clock, because
the camera device and the audio server otherwise count from different clocks.
- The exact layout of `gamerecordings` on the Frame's SteamOS build, and
whether a clip's segments start mid-recording. The parser is deliberately
loose about the layout.
The inspected frame is nearly black in both Steam's source and the export, so
this establishes file creation and faithful export, **not visible gameplay
capture**. On v0.4.16, the literal desktop **Export** button was also clicked
against that retained real Steam clip in the source UI on lxso2. The job
completed and saved `~/Videos/SteamFrame/clip_13009719723623972864_20261024_072115.mp4`;
its 159,829 bytes and SHA-256 matched the previously decoded export exactly.
The temporary server stopped, the shared device lock was released, and the
headset remained in Game Mode at 99% battery. See
[`docs/evidence/clip-gui-export-2026-10-24.json`](evidence/clip-gui-export-2026-10-24.json)
for the narrow proof. This did not exercise the packaged desktop installer.
Remaining checks include:
- Perceptual audio/video sync and audible content. Frame Control's separate
**Record** path stamps camera and audio inputs with the wall clock because
they otherwise count from different clocks.
- Long saved clips, trims starting partway through a Steam recording, and the
packaged desktop app's **Export** button. One real saved clip's directory
layout was checked; the parser remains deliberately loose for other layouts.
- How much x264 at 1080p30 costs the Frame while a game is running.
- Automatic copying: that 30 seconds without a write is a safe sign Steam has
finished saving a clip, and how a once-a-minute listing feels on the Frame.
+7
View File
@@ -285,6 +285,13 @@ How (**verified 2026-09-29**, SteamOS 0.4.1, build 20260925.6191901):
[#73](https://github.com/saphid/frame-control/issues/73) (SteamOS 0.4.5, desktop
open but not found). The likely cause there was the page itself: a second
`loadPanels` (the panel switcher's) replaced the Desktop view's, fixed in #84.
If the `GAMESCOPE_FOCUSABLE_WINDOWS` property cannot be read, discovery now
reports that the panel list is unreadable and whether a panel is open is
unknown. A failed X connection or missing property is not evidence that the
desktop is closed. Check that SteamVR is running, retry or use Headset view;
if it persists, report the exact message and SteamOS version. The confirmed
empty-list advice is retained when the property is present but empty.
[2026-10-24 investigation and verification limits](evidence/panel-discovery-2026-10-24.md).
- Tested from the iPhone app (Simulator): a tap on the Desktop view focused a
text box in the panel and the text field typed into it; a trackpad move went
exactly (+40, +25).
+1
View File
@@ -36,6 +36,7 @@ thead th,td{{white-space:nowrap}}th[scope=row]{{min-width:240px;max-width:300px;
td:last-child{{min-width:220px;max-width:300px;white-space:normal;overflow-wrap:anywhere}}
thead{{background:#edf1f5}}.scroll{{overflow:auto}}h1{{line-height:1.2}}</style>
<main><h1>Frame power and heat report</h1>
<p>Headset: {esc(report.get("headset", {}).get("alias", "frame"))}</p>
<p>{len(report['samples'])} of {report['requestedSamples']} requested samples received; target interval {esc(report['intervalSeconds'])} seconds.</p>
<p>Collection: {esc(report['stopped'] or 'Completed')}. Results describe only the samples received.</p>
<p>{links}</p>
+58 -12
View File
@@ -141,18 +141,28 @@ def collect(status, count, interval, emit=None):
def csv_samples(report):
# CSV quoting alone does not prevent spreadsheet formulas in text fields.
def cell(value):
if isinstance(value, str) and (value.startswith(('\t', '\r', '\n')) or
value.lstrip(' \t\r\n').startswith(('=', '+', '-', '@'))):
return "'" + value
return value
output = io.StringIO(newline='')
writer = csv.writer(output)
writer.writerow(('time', 'elapsedSeconds', 'metric', 'value', 'unit', 'source', 'state'))
if 'headset' in report:
for key, value in (('collection.state', report['stopped'] or 'Completed'),
('collection.requestedSamples', report['requestedSamples']),
('collection.receivedSamples', len(report['samples']))):
writer.writerow([cell(v) for v in ('', '', key, value, '', report['headset']['alias'],
'incomplete' if report['stopped'] else 'completed')])
for sample in report['samples']:
for key, row in sample['readings'].items():
# csv quoting does not prevent spreadsheet formulas in labels.
def cell(value):
return "'" + value if isinstance(value, str) and value.startswith(('=', '+', '-', '@')) else value
writer.writerow([cell(v) for v in (sample['time'], sample['elapsedSeconds'], key,
row['value'], row['unit'], row['source'], row['state'])])
for group in sample['unavailableGroups']:
writer.writerow((sample['time'], sample['elapsedSeconds'], group, '', '', '', UNAVAILABLE))
writer.writerow([cell(v) for v in (sample['time'], sample['elapsedSeconds'], group, '', '', '', UNAVAILABLE)])
return output.getvalue()
@@ -178,31 +188,61 @@ def remote_payload():
'sys.modules["frame_status"] = status\n' + Path(__file__).read_text())
def stream_report(command, payload, count, interval):
def stream_report(command, payload, count, interval, stop_event=None, on_sample=None, discard_errors=False):
"""Receive each sample before the next wait; stop only our local SSH child.
The remote bounded reader exits on its next write to the closed connection.
No remote process-control command is sent. Keep already received samples on
interrupt, transport failure or deadline, clearly marked as incomplete.
"""
if stop_event is not None and stop_event.is_set():
return {'schemaVersion': 1, 'requestedSamples': count, 'intervalSeconds': interval,
'stopped': 'Stopped before collection; no SSH started', 'samples': [], 'summary': {}}
samples, final, stopped = [], None, None
events = queue.Queue()
events = queue.Queue(maxsize=count + 2)
reader_stop = threading.Event()
deadline = time.monotonic() + count * interval + 30
with tempfile.TemporaryFile(mode='w+') as errors:
proc = subprocess.Popen(command + ['--stream'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=errors, text=True)
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL if discard_errors else errors, text=True)
def receive():
try:
for line in proc.stdout:
events.put(line)
for _ in range(count + 2):
line = proc.stdout.readline(262145)
if not line:
break
if len(line) > 262144 or not line.endswith('\n'):
line = 'invalid or oversized sample'
while not reader_stop.is_set():
try:
events.put(line, timeout=0.2)
break
except queue.Full:
continue
if reader_stop.is_set():
return
finally:
events.put(None)
while not reader_stop.is_set():
try:
events.put(None, timeout=0.2)
break
except queue.Full:
continue
reader = threading.Thread(target=receive, daemon=True)
reader.start()
def feed():
try:
proc.stdin.write(payload)
proc.stdin.close()
except OSError:
pass # transport exit/EOF below marks the observation incomplete
writer = threading.Thread(target=feed, daemon=True)
writer.start()
try:
proc.stdin.write(payload)
proc.stdin.close()
while True:
if stop_event is not None and stop_event.is_set() and events.empty():
stopped = 'Stopped; received samples retained'
break
remaining = deadline - time.monotonic()
if remaining <= 0:
stopped = 'Timed out; received samples retained'
@@ -218,6 +258,8 @@ def stream_report(command, payload, count, interval):
if len(samples) >= count:
raise ValueError('Too many samples received')
samples.append(event['sample'])
if on_sample:
on_sample(event['sample'])
print(f'Received {len(samples)}/{count} samples; Ctrl+C to stop and save.', file=sys.stderr)
elif 'finished' in event:
final = event['finished']
@@ -228,6 +270,7 @@ def stream_report(command, payload, count, interval):
except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
stopped = f'Collection interrupted: {exc}'
finally:
reader_stop.set()
if proc.poll() is None:
proc.terminate()
try:
@@ -235,6 +278,7 @@ def stream_report(command, payload, count, interval):
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=3)
writer.join(timeout=3)
if not proc.stdin.closed:
try:
proc.stdin.close()
@@ -263,6 +307,8 @@ def main(argv=None):
ap.error('--html output already exists; choose a new file')
# Also honor a coordinator lock on the computer before opening SSH.
if LOCK.exists():
if args.probe and args.stream:
print(json.dumps({'finished': {'stopped': 'Smoke session active (/tmp/frame-test.lock); no sensors read'}}), flush=True)
print('Smoke session active (/tmp/frame-test.lock); no SSH or sensors accessed.', file=sys.stderr)
return 75
if args.probe:
+29 -1
View File
@@ -5,7 +5,8 @@ The Frame Control website, <https://frame-control.pages.dev>, on Cloudflare Page
- `public/`: static pages. `/` is the landing page, `/feedback/` the feedback form, `/privacy/` the privacy note.
- `functions/api/feedback.js`: `POST /api/feedback`, which turns the form into a GitHub issue labelled `feedback`.
- `lib/feedback.js`: validation and issue formatting, tested by `test/feedback.test.mjs`.
- `public/js/site.js`: settings, including the Ko-fi page name for the donate buttons.
- `public/js/site.js`: settings, including the Ko-fi page name for the donate buttons, OS hints and opening-help deep links. OS hints lead to instructions, never directly to an architecture-specific installer.
- `test/onboarding.test.mjs`: desktop/mobile browser hints and opening-help deep links.
## Feedback → GitHub issues
@@ -33,3 +34,30 @@ npx wrangler pages deploy --branch main # production
```
Point `GITHUB_REPO` in `.dev.vars` at a scratch repo when testing locally so test issues don't land on the real tracker.
## First-run verification
Before changing download or setup instructions:
- Compare every linked filename with `gh release view --repo saphid/frame-control --json tagName,assets`.
Browser OS hints cannot establish CPU architecture; keep every platform choice visible.
- Run `node --test site/test/*.test.mjs` from the repo root, plus
`node --check site/public/js/site.js` and `node --check site/public/js/feedback.js`.
- Serve `public/` locally (for example `python3 -m http.server 8793 --directory site/public`
from the repo root). Check 320px, 390px, 768px and desktop widths: section navigation,
the hero link, download cards, opening-help links, feedback and privacy pages. Check
horizontal overflow and that anchor targets clear the sticky header. Repeat with
JavaScript disabled: downloads and navigation must remain available.
- Check setup labels against `app/main.js`, `scripts/connect.sh`, `ui/frame_connect.py`
and the Devices page. macOS discovery failure exits; Windows/Linux prompt for an IP.
The app's Devices → Add a headset dialog can pass an explicit address on all platforms.
- Separate website checks from native installation and real-headset pairing evidence.
A successful page/link check does not verify an installer or headset approval flow.
On 2026-10-24, the first-run update was checked against published v0.4.16 assets:
all seven linked desktop installers returned HTTP 200 after redirects, as did the
linked GitHub documentation and trailer. Local page/resource links and section
fragments were checked; navigation stayed visible without horizontal overflow at
320, 390, 768 and 1280 CSS pixels. Native macOS/Windows installs and real-headset
pairing were not exercised for this documentation change. No site deployment was
performed.
+15 -2
View File
@@ -38,8 +38,13 @@ code { font: 14px ui-monospace, SFMono-Regular, Menlo, monospace; background: rg
.top nav a { color: var(--muted); font-size: 14.5px; font-weight: 500; }
.top nav a:hover, .top nav a[aria-current] { color: var(--bright); }
.top .end { margin-left: auto; display: flex; gap: 10px; align-items: center; }
@media (max-width: 880px) { .top nav { display: none; } }
@media (max-width: 480px) { .top .end .ghost { display: none; } }
@media (max-width: 1050px) {
html { scroll-padding-top: 150px; }
.top .wrap { height: auto; min-height: 64px; flex-wrap: wrap; gap: 8px 16px; padding-top: 12px; padding-bottom: 8px; }
.top nav { order: 3; width: 100%; margin-left: 0; flex-wrap: wrap; gap: 0 18px; }
.top nav a { padding: 8px 0; }
}
@media (max-width: 480px) { .top .end { display: none; } }
/* ---- buttons ---- */
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 9px; height: 46px; padding: 0 22px; border-radius: 10px;
@@ -199,3 +204,11 @@ textarea { min-height: 180px; resize: vertical; }
.done p { color: var(--muted); margin: 10px auto 24px; max-width: 460px; }
.done .cta { margin-top: 0; }
.page h1 { font-size: clamp(34px, 5vw, 48px); }
/* Opening instructions remain readable on narrow screens. */
.dl p, .setup-note { color: var(--muted); font-size: 15px; margin-top: 16px; }
.dl { min-width: 0; }
code { overflow-wrap: anywhere; }
pre { white-space: pre-wrap; overflow-wrap: anywhere; }
pre code { background: none; padding: 0; }
@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
+39 -24
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Frame Control: manage your Steam Frame from your computer</title>
<meta name="description" content="Free, open-source app for the Valve Steam Frame. See what the headset sees, install Steam games and Android apps, move files and text across, and check battery and status. macOS, Windows, Linux and iPhone.">
<meta name="description" content="Free, open-source app for the Valve Steam Frame. See what the headset sees, install Steam games and Android apps, move files and text across, and check battery and status. Desktop downloads for macOS, Windows and Linux; iPhone build instructions.">
<meta name="theme-color" content="#0e141b">
<link rel="icon" href="/favicon.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
@@ -41,13 +41,13 @@
<main>
<section class="hero">
<div class="wrap">
<span class="eyebrow"><b>Free and open source</b><span class="sep"> · </span><span class="plats">macOS · Windows · Linux · iPhone</span></span>
<span class="eyebrow"><b>Free and open source</b><span class="sep"> · </span><span class="plats">macOS · Windows · Linux</span></span>
<h1>Your Steam Frame, <span>managed from your desk.</span></h1>
<p class="lede">See what the headset sees, install games and Android apps, move files and text across, and keep an eye on battery and status. All over SSH, with nothing to install on the Frame.</p>
<p class="lede">See what the headset sees, install games and Android apps, move files and text across, and keep an eye on battery and status. Install Frame Control on your computer, then connect to your headset over SSH. This website provides downloads and instructions; it does not control the headset in your browser.</p>
<div class="cta">
<a class="btn primary" id="hero-download" href="#download">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12m0 0-5-5m5 5 5-5M4 20h16"/></svg>
<span data-label>Download Frame Control</span>
<span data-label>Choose your computer’s download</span>
</a>
<a class="btn ghost" href="#trailer">
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5.5v13a1 1 0 0 0 1.5.86l10.5-6.5a1 1 0 0 0 0-1.72L9.5 4.64A1 1 0 0 0 8 5.5z"/></svg>
@@ -173,7 +173,7 @@
<div class="head">
<span class="kicker">iPhone and iPad</span>
<h2>Also in your pocket</h2>
<p>The same features on iPhone and iPad, served from the Frame itself, so there's nothing to run on a computer. Build it from the repo in Xcode.</p>
<p>The same features on iPhone and iPad, served from the Frame itself, so there's nothing to run on a computer. There is no App Store, TestFlight or iOS download in the current release. Building it requires a Mac, Xcode and your own signing team. <a href="https://github.com/saphid/frame-control/blob/main/docs/iphone.md">iPhone build and pairing instructions</a>.</p>
</div>
<div class="phones">
<img src="/img/phone-home.jpg" width="600" height="1304" loading="lazy" alt="Frame Control on iPhone: headset view and device status.">
@@ -186,23 +186,24 @@
<div class="wrap">
<div class="head">
<span class="kicker">Setup</span>
<h2>One password, typed once</h2>
<p>Everything else happens on your computer.</p>
<h2>Connect your computer to the Frame</h2>
<p>First <a href="#download">install and open the desktop app</a>. Keep the headset awake, on the same trusted network as your computer. Guest Wi-Fi or client isolation can block the connection.</p>
</div>
<div class="steps">
<div class="card">
<h3>Turn on Developer Mode</h3>
<p>On the Frame: Steam Settings → System → <b>Enable Developer Mode</b>, then <b>Set User Password</b> in the Developer section.</p>
<h3>Prepare the headset</h3>
<p>On the Frame: Steam Settings → System → <b>Enable Developer Mode</b>, then Developer → <b>Set User Password</b>. Choose a password that isn't easy to guess; it also protects remote desktop and <code>sudo</code>.</p>
</div>
<div class="card">
<h3>Set up the connection</h3>
<p>Open Frame Control and choose <b>Set Up Connection</b>. It finds the headset, makes an SSH key, and asks for that password once.</p>
<h3>Run connection setup</h3>
<p>In the desktop app, choose <b>Set Up Connection…</b>. If you skipped the first prompt, use <b>Frame → Set Up Connection…</b>. A terminal opens. If discovery fails, find the Frame's IP in Quick Settings or Steam Settings → Internet. Windows/Linux setup prompts for it. On macOS, return to the app → <b>Devices &amp; connection → + Add a headset…</b>, use SSH alias <code>frame</code> for the default headset, enter the IP in <b>Address</b> and choose <b>Set Up…</b>.</p>
</div>
<div class="card">
<h3>That's it</h3>
<p>The app reaches the headset whenever it's awake and on the same network. For anywhere else, use <a href="https://github.com/saphid/frame-control/blob/main/docs/tailscale.md">Tailscale</a>.</p>
<h3>Pair, with a password fallback</h3>
<p>Setup tries Valve's pairing first: open Developer → <b>Pair new host</b> in the headset and approve only your request. If it fails or times out, enter the Developer Mode password in the computer's terminal (typing may be invisible), then press Enter.</p>
</div>
</div>
<p class="setup-note">The devkit service and pairing-mode step were checked on a Frame; approval and key installation through that flow remain unverified. <a href="https://github.com/saphid/frame-control/blob/main/docs/ssh.md#password-free-pairing-steamos-devkit-service">Pairing details</a>. After setup succeeds, return to the app; future connections use SSH keys. Still offline? Check Developer Mode, the IP and network isolation, then rerun setup. For use away from home, see <a href="https://github.com/saphid/frame-control/blob/main/docs/tailscale.md">Tailscale</a>.</p>
</div>
</section>
@@ -211,32 +212,39 @@
<div class="head">
<span class="kicker">Download</span>
<h2>Get Frame Control</h2>
<p>Free, with Python and adb built in. <span hidden>Version <span data-version></span>.</span> <a href="https://github.com/saphid/frame-control/releases">Release notes</a></p>
<p>Choose your computer’s OS and processor, not the headset’s. Python is bundled; Linux needs <code>ssh</code>, and arm64 Linux also needs your distribution’s <code>adb</code> for Android apps. <span hidden>Version <span data-version></span>.</span> <a href="https://github.com/saphid/frame-control/releases">Release notes</a></p>
</div>
<div class="downloads">
<div class="dl" data-os="mac">
<div class="os"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M16.37 12.6c-.02-2.2 1.8-3.26 1.88-3.31-1.02-1.5-2.62-1.7-3.19-1.72-1.36-.14-2.65.8-3.34.8-.69 0-1.75-.78-2.88-.76a4.27 4.27 0 0 0-3.6 2.19c-1.53 2.66-.39 6.6 1.1 8.76.73 1.06 1.6 2.24 2.74 2.2 1.1-.04 1.51-.71 2.84-.71 1.32 0 1.7.71 2.86.69 1.18-.02 1.93-1.08 2.65-2.14.83-1.23 1.18-2.41 1.2-2.47-.03-.01-2.3-.88-2.32-3.5zM14.2 6.13c.6-.73 1.01-1.75.9-2.76-.87.04-1.92.58-2.54 1.3-.56.64-1.05 1.67-.92 2.66.97.08 1.96-.49 2.56-1.2z"/></svg><h3>macOS</h3><span class="tag" hidden>Your system</span></div>
<span class="need">Apple Silicon</span>
<div class="dl" id="download-mac" data-os="mac">
<div class="os"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M16.37 12.6c-.02-2.2 1.8-3.26 1.88-3.31-1.02-1.5-2.62-1.7-3.19-1.72-1.36-.14-2.65.8-3.34.8-.69 0-1.75-.78-2.88-.76a4.27 4.27 0 0 0-3.6 2.19c-1.53 2.66-.39 6.6 1.1 8.76.73 1.06 1.6 2.24 2.74 2.2 1.1-.04 1.51-.71 2.84-.71 1.32 0 1.7.71 2.86.69 1.18-.02 1.93-1.08 2.65-2.14.83-1.23 1.18-2.41 1.2-2.47-.03-.01-2.3-.88-2.32-3.5zM14.2 6.13c.6-.73 1.01-1.75.9-2.76-.87.04-1.92.58-2.54 1.3-.56.64-1.05 1.67-.92 2.66.97.08 1.96-.49 2.56-1.2z"/></svg><h3>macOS</h3><span class="tag" hidden>OS detected</span></div>
<span class="need">Apple Silicon (M-series) only · no Intel Mac build</span>
<div class="links">
<a class="btn primary" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-mac-arm64.dmg">Download .dmg</a>
</div>
<p>Check Apple menu → About This Mac for your chip. Open the DMG, drag Frame Control to Applications, then open it there. Allow local network access and Terminal control when asked.</p>
<p>The app isn't notarized. <a href="#mac-opening">macOS opening instructions</a>.</p>
</div>
<div class="dl" data-os="windows">
<div class="os"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 5.5 10 4.5v7H3zM11 4.35 21 3v8.5H11zM3 12.5h7v7L3 18.5zM11 12.5h10V21l-10-1.4z"/></svg><h3>Windows</h3><span class="tag" hidden>Your system</span></div>
<div class="dl" id="download-windows" data-os="windows">
<div class="os"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 5.5 10 4.5v7H3zM11 4.35 21 3v8.5H11zM3 12.5h7v7L3 18.5zM11 12.5h10V21l-10-1.4z"/></svg><h3>Windows</h3><span class="tag" hidden>OS detected</span></div>
<span class="need">Windows 10 or 11, x64</span>
<div class="links">
<a class="btn primary" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-Setup-x64.exe">Download installer</a>
<a class="btn ghost" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-win-x64.zip">Portable .zip</a>
</div>
<p>Check Settings → System → About → System type. No native Windows ARM build is published. Run the installer, then open Frame Control from Start. The OpenSSH Client optional feature must be installed (it normally is). For portable use, extract the entire ZIP and run <code>Frame Control.exe</code>.</p>
<p>The installer isn't code-signed. <a href="#windows-opening">SmartScreen instructions</a>.</p>
</div>
<div class="dl" data-os="linux">
<div class="os"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3M13 15h4"/></svg><h3>Linux</h3><span class="tag" hidden>Your system</span></div>
<div class="dl" id="download-linux" data-os="linux">
<div class="os"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3M13 15h4"/></svg><h3>Linux</h3><span class="tag" hidden>OS detected</span></div>
<span class="need">x64 or arm64 · needs <code>ssh</code></span>
<div class="links">
<a class="btn primary" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-x86_64.AppImage">AppImage (x64)</a>
<a class="btn ghost" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-amd64.deb">.deb (x64)</a>
<a class="btn ghost" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-arm64.AppImage">AppImage (arm64)</a>
<a class="btn ghost" href="https://github.com/saphid/frame-control/releases/latest/download/Frame-Control-linux-arm64.deb">.deb (arm64)</a>
</div>
<p>Run <code>uname -m</code>: <code>x86_64</code> means x64; <code>aarch64</code> means arm64. Install the matching .deb on Debian/Ubuntu and open Frame Control from your applications menu, or use AppImage on other distributions.</p>
<p><a href="#linux-opening">AppImage permissions and FUSE help</a>. On arm64 Debian/Ubuntu, install <code>adb</code> with <code>sudo apt install adb</code> for Android apps.</p>
</div>
</div>
</div>
@@ -249,15 +257,22 @@
<h2>Good questions</h2>
</div>
<div class="faq">
<details>
<details id="mac-opening">
<summary>macOS says the app is damaged or can't be checked</summary>
<div><p>The app isn't notarized, because there's no paid Apple developer account behind it. Drag it to Applications, then clear the download quarantine once in Terminal:</p>
<div><p>The app isn't notarized, because there's no paid Apple developer account behind it. Only for a download you trust from the releases linked above: drag it to Applications, then clear the download quarantine once in Terminal:</p>
<p><code>xattr -dr com.apple.quarantine "/Applications/Frame Control.app"</code></p></div>
</details>
<details>
<details id="windows-opening">
<summary>Windows SmartScreen says it protected my PC</summary>
<div><p>The installer isn't code-signed. Choose <b>More info → Run anyway</b>, or use the portable .zip: unzip it anywhere and run <code>Frame Control.exe</code>.</p></div>
</details>
<details id="linux-opening">
<summary>How do I open the Linux AppImage?</summary>
<div><p>In a terminal in your download folder, use the exact filename for your architecture. For x64:</p>
<pre><code>chmod +x Frame-Control-linux-x86_64.AppImage
./Frame-Control-linux-x86_64.AppImage</code></pre>
<p>If FUSE is missing, install <code>libfuse2</code> (Ubuntu 24.04+: <code>libfuse2t64</code>), or run the same AppImage with <code>--appimage-extract-and-run</code>. Install your distribution’s OpenSSH client if <code>ssh</code> is missing.</p></div>
</details>
<details>
<summary>What does it change on my headset?</summary>
<div><p>Only what you click. Installs go to your user account on the Frame, and nothing needs <code>sudo</code> except the power buttons. On your computer it adds a <code>Host frame</code> entry to <code>~/.ssh/config</code> and two SSH keys.</p></div>
+17 -17
View File
@@ -5,8 +5,6 @@ const SITE = {
kofi: "alexsouthwell",
};
const RELEASE = `https://github.com/${SITE.repo}/releases/latest/download/`;
// Donate buttons.
for (const el of document.querySelectorAll("[data-kofi]")) {
if (SITE.kofi) el.href = `https://ko-fi.com/${SITE.kofi}`;
@@ -15,37 +13,39 @@ for (const el of document.querySelectorAll("[data-kofi]")) {
for (const el of document.querySelectorAll("[data-needs-kofi]")) el.hidden = !SITE.kofi;
for (const el of document.querySelectorAll("[data-no-kofi]")) el.hidden = !!SITE.kofi;
// Best guess at the visitor's platform, for the hero button and the download cards.
// Browser hints identify an OS, not a reliable CPU architecture. Always show
// the install instructions and all choices before starting a download.
function detectPlatform() {
const ua = navigator.userAgent;
const hint = navigator.userAgentData?.platform || navigator.platform || "";
if (/iPhone|iPad|iPod/.test(ua) || (/Mac/.test(hint) && navigator.maxTouchPoints > 1)) return "ios";
if (/Android/.test(ua)) return null;
if (/iPhone|iPad|iPod|Android/.test(ua) || (/Mac/.test(hint) && navigator.maxTouchPoints > 1)) return null;
if (/Mac/.test(hint) || /Macintosh/.test(ua)) return "mac";
if (/Win/.test(hint) || /Windows/.test(ua)) return "windows";
if (/Linux/.test(hint) || /Linux/.test(ua)) return /aarch64|arm64/i.test(ua + hint) ? "linux-arm" : "linux";
if (/Linux/.test(hint) || /Linux/.test(ua)) return "linux";
return null;
}
const PLATFORMS = {
mac: { name: "macOS", file: "Frame-Control-mac-arm64.dmg" },
windows: { name: "Windows", file: "Frame-Control-Setup-x64.exe" },
linux: { name: "Linux", file: "Frame-Control-linux-x86_64.AppImage" },
"linux-arm": { name: "Linux (arm64)", file: "Frame-Control-linux-arm64.AppImage" },
};
const platform = detectPlatform();
const hero = document.getElementById("hero-download");
if (hero && PLATFORMS[platform]) {
hero.href = RELEASE + PLATFORMS[platform].file;
hero.querySelector("[data-label]").textContent = `Download for ${PLATFORMS[platform].name}`;
if (hero && platform) {
hero.href = `#download-${platform}`;
const name = { mac: "macOS", windows: "Windows", linux: "Linux" }[platform];
hero.querySelector("[data-label]").textContent = `Choose a ${name} download`;
}
const card = platform && document.querySelector(`.dl[data-os="${platform.replace("-arm", "")}"]`);
const card = platform && document.querySelector(`.dl[data-os="${platform}"]`);
if (card) {
card.classList.add("mine");
card.querySelector(".tag").hidden = false;
}
// Keep linked opening instructions visible, including direct FAQ deep links.
function revealInstructions() {
const target = document.getElementById(location.hash.slice(1));
if (target?.tagName === "DETAILS") target.open = true;
}
window.addEventListener("hashchange", revealInstructions);
revealInstructions();
// Latest version number, so the page never goes stale. Fails quietly.
const versionEls = document.querySelectorAll("[data-version]");
if (versionEls.length) {
+59
View File
@@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
const script = readFileSync(new URL('../public/js/site.js', import.meta.url), 'utf8');
const html = readFileSync(new URL('../public/index.html', import.meta.url), 'utf8');
function visit(navigator, hash = '') {
const label = { textContent: 'Choose your computer’s download' };
const hero = { href: '#download', querySelector: () => label };
const cards = Object.fromEntries(['mac', 'windows', 'linux'].map(os => [os, {
classes: [], classList: { add(name) { cards[os].classes.push(name); } },
tag: { hidden: true }, querySelector() { return this.tag; },
}]));
const details = { tagName: 'DETAILS', open: false };
const listeners = {};
const context = {
navigator, location: { hash }, window: { addEventListener: (name, fn) => { listeners[name] = fn; } },
document: {
querySelectorAll: () => [],
getElementById: id => id === 'hero-download' ? hero : id === 'mac-opening' ? details : null,
querySelector: selector => cards[selector.match(/data-os="([^"]+)"/)[1]],
},
};
runInNewContext(script, context);
return { hero, cards, details, listeners, context };
}
for (const [name, navigator, expected] of [
['Intel Mac', { platform: 'MacIntel', userAgent: 'Macintosh' }, 'mac'],
['Apple Silicon browser with Intel hint', { platform: 'MacIntel', userAgent: 'Macintosh', userAgentData: { platform: 'macOS' } }, 'mac'],
['Windows', { platform: 'Win32', userAgent: 'Windows NT 10.0' }, 'windows'],
['Linux x64', { platform: 'Linux x86_64', userAgent: 'Linux x86_64' }, 'linux'],
['Linux ARM', { platform: 'Linux aarch64', userAgent: 'Linux aarch64' }, 'linux'],
['iPhone', { platform: 'iPhone', userAgent: 'iPhone' }, null],
['iPad desktop mode', { platform: 'MacIntel', userAgent: 'Macintosh', maxTouchPoints: 5 }, null],
['Android', { platform: 'Linux armv8l', userAgent: 'Linux Android' }, null],
['unknown', { userAgent: '' }, null],
]) {
test(`${name} opens choices instead of guessing an installer architecture`, () => {
const { hero, cards } = visit(navigator);
assert.equal(hero.href, expected ? `#download-${expected}` : '#download');
assert.ok(html.includes(`id="${hero.href.slice(1)}"`));
assert.deepEqual(Object.keys(cards).filter(os => !cards[os].tag.hidden), expected ? [expected] : []);
});
}
test('opening help expands for direct and in-page links; unknown fragments are safe', () => {
const result = visit({ userAgent: '' }, '#mac-opening');
assert.equal(result.details.open, true);
result.details.open = false;
result.context.location.hash = '#unknown';
result.listeners.hashchange();
assert.equal(result.details.open, false);
result.context.location.hash = '#mac-opening';
result.listeners.hashchange();
assert.equal(result.details.open, true);
});
+48 -5
View File
@@ -23,7 +23,8 @@ function fixture() {
const page = element('controlCenter');
page.querySelectorAll = selector => selector === '[data-cc-category]' ? buttons : selector === '[data-cc-metric]' ? metrics : selector === '[data-cc-mac-link]' ? [element('macLink')] : [];
page.querySelector = selector => selector === '[href="#connection"]' ? element('connectionLink') : cards.find(e=>selector === `[data-cc-card="${e.dataset.ccCard}"]`);
return {document:{getElementById:element},element,cards,buttons};
const listeners = {};
return {document:{hidden:false,getElementById:element,addEventListener(name,callback){listeners[name]=callback;}},listeners,element,cards,buttons};
}
function mounted(options = {}) {
const f = fixture(), calls = [];
@@ -39,8 +40,10 @@ const flush = async () => { for(let i=0;i<12;i++)await Promise.resolve(); };
// bootstrap, including the real Home-to-Control status handoff. Only unrelated
// rendering helpers, timers and transport are stubbed.
function sharedPage({productionApi=false} = {}) {
const f=fixture(), requests=[], writes=[], host=deferred(), job=deferred();
const context={document:f.document,FrameControlCenter:cc,window:{frameApp:{setUpConnection(){}}},
const f=fixture(), requests=[], writes=[], notifications=[], host=deferred(), job=deferred();
let now=0;
const context={document:f.document,FrameControlCenter:cc,performance:{now:()=>now},
window:{frameApp:{setUpConnection(){},notify:async(message,request)=>{notifications.push({message,request});}}},
Date,setInterval,clearInterval,setTimeout:()=>1,clearTimeout(){},$:f.element,QUICK:[],installing:new Set(),
battery(){},setVolume(){},renderHome(){},gb:String,dur:String,esc:String,meter(){},toast(){},
runJob(title,id){context.installing.add(id);return job.promise;},
@@ -52,7 +55,11 @@ function sharedPage({productionApi=false} = {}) {
watchConnection(){context.watched=true;}};
vm.createContext(context);
const stateDeclaration=pageSource.match(/let state = null[^\n]*/)[0];
vm.runInContext(stateDeclaration+'\nlet online = true, devGen = 1; const HOST = {computer:"computer"}; window.connDevice="frame-a";',context);
vm.runInContext(stateDeclaration+'\nlet online = true, devGen = 1, comfortActive = false; const HOST = {computer:"computer"}; window.connDevice="frame-a";',context);
// Load the real alert state machine and DOM wiring used by render, refresh,
// setOnline and onConnection; do not stub away their lifecycle behavior.
const batteryStart=pageSource.indexOf('class DesktopBatteryAlert'),batteryEnd=pageSource.indexOf('// ---- battery ----',batteryStart);
vm.runInContext(pageSource.slice(batteryStart,batteryEnd),context);
const refreshStart=pageSource.indexOf('let refreshing = null'),refreshEnd=pageSource.indexOf('// ---- our VR HUD',refreshStart);
const renderStart=pageSource.indexOf('function render(s) {'),renderEnd=pageSource.indexOf('// ---- view ----',renderStart);
vm.runInContext(pageSource.slice(renderStart,renderEnd)+pageSource.slice(refreshStart,refreshEnd),context);
@@ -80,12 +87,48 @@ function sharedPage({productionApi=false} = {}) {
const hostStart=pageSource.lastIndexOf('api("/api/host").then(h =>'),hostEnd=pageSource.indexOf('</script>',hostStart);
vm.runInContext(pageSource.slice(hostStart,hostEnd),context);
const bootstrapStart=pageSource.indexOf('window.frameControlCenter = FrameControlCenter.mount('),bootstrapEnd=pageSource.indexOf('</script>',bootstrapStart);
return {...f,context,requests,writes,host,refresh:()=>vm.runInContext('refresh()',context),
return {...f,context,requests,writes,notifications,host,setNow(value){now=value;},refresh:()=>vm.runInContext('refresh()',context),
switchHeadset:()=>vm.runInContext('onConnection({now:Date.now()/1000,phase:"connected",devices_rev:0,device:{id:"frame-b",name:"Second Frame"}})',context),
installFlatpak:()=>vm.runInContext('installFlatpak("test.app")',context),
mount(){vm.runInContext(pageSource.slice(bootstrapStart,bootstrapEnd),context);return context.window.frameControlCenter;}};
}
const response = data => ({ok:true,status:200,json:async()=>data});
test('production refresh confirms desktop alerts and failures interrupt confirmation', async () => {
const f=sharedPage({productionApi:true});
const low=sample();low.battery={percent:15,status:'Discharging',watts:-4};
const read=async(now,data=low)=>{
f.setNow(now);const pending=f.refresh();
f.requests.at(-1).resolve(response(data));await pending;
};
await read(0);await read(30000);
assert.equal(f.notifications.length,0,'desktop alert starts off');
f.element('desktopBatteryAlert').checked=true;
f.element('desktopBatteryAlert').onchange();
await read(60000);
const failed=f.refresh();f.requests.at(-1).reject(Error('Status transport failed'));await failed;
await read(90000);
assert.equal(f.notifications.length,0,'failed status interrupts low-battery confirmation');
await read(120000);
assert.equal(f.notifications.length,1);
assert.match(f.notifications[0].message,/15%.*draining/);
assert.equal(f.notifications[0].request,false,'refresh never requests notification permission');
await read(150000);
assert.equal(f.notifications.length,1,'same episode stays latched');
assert.equal(f.requests.length,7,'only explicit existing status reads are used');
});
test('production headset switch clears desktop opt-in and pending confirmation', async () => {
const f=sharedPage({productionApi:true});
f.element('desktopBatteryAlert').checked=true;
const low=sample();low.battery={percent:10,status:'Discharging',watts:-3};
const pending=f.refresh();f.requests[0].resolve(response(low));await pending;
assert.equal(vm.runInContext('desktopBattery.pending.condition',f.context),'low');
f.setNow(30000);f.switchHeadset();
assert.equal(f.element('desktopBatteryAlert').checked,false);
assert.equal(vm.runInContext('desktopBattery.pending',f.context),null);
assert.match(f.element('desktopBatteryStatus').textContent,/Headset changed/);
f.requests[1].resolve(response(low));await flush();
assert.equal(f.notifications.length,0,'new headset cannot inherit the prior opt-in');
});
for(const rejection of ['transport','body'])for(const delayedMount of [false,true]) {
test(`production ${rejection} rejection from A preserves B ${delayedMount ? 'before delayed mount' : 'after mount'}`, async t => {
const f=sharedPage({productionApi:true});
+9
View File
@@ -40,6 +40,15 @@ function page(answer) {
if (!p.noPanelWhy().startsWith("The headset's desktop is running")) fail("why for capture: " + p.noPanelWhy());
if (!p.ctrlTarget().why.startsWith("The headset's desktop is running")) fail("why for control: " + p.ctrlTarget().why);
}
// An unreadable list is unknown: both Capture and Control retain that distinction.
{
const why = "Frame Control couldn't read gamescope's panel list, so it can't tell whether an app panel is open. " +
"Check that SteamVR is running in the headset, then try again or use the Headset view. " +
"If this persists, report your SteamOS version and this exact message.";
const p = page(() => ({ panels: [], focus: null, why }));
await p.loadPanels();
if (p.noPanelWhy() !== why || p.ctrlTarget().why !== why) fail("unreadable list reason lost");
}
// An older headset script without "why": the generic advice.
{
const p = page(() => ({ panels: [], focus: null }));
+77
View File
@@ -0,0 +1,77 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const {workspaceFixture,html}=require('./workspace_fixture.cjs');
function fixture() {
const f=workspaceFixture();
Object.assign(f.context, {clearTimeout(){},setTimeout(){},UI_KEY:'1',encodeURIComponent});
const formats=['html','json','csv'].map(format=>Object.assign(f.el('download-'+format),{dataset:{powerFormat:format}}));
const query=f.context.document.querySelectorAll;
f.context.document.querySelectorAll=s=>s==='[data-power-format]'?formats:query(s);
f.formats=formats;
f.run(html.slice(html.indexOf('// ---- Read-only power observation ----'),html.indexOf('// ---- Read-only game storage ----')));
return f;
}
const state={id:'abc',headset:{alias:'old-frame'},requested:12,received:3,running:true,stopped:null};
test('Tools navigation loads the report and renders accessible progress',async()=>{
const f=fixture();let calls=0;f.context.api=async()=>{calls++;return state;};
f.navigate('#powerReport');await new Promise(setImmediate);
assert.equal(f.activePage,'tools');assert.equal(f.el('powerReport').hidden,false);
assert.equal(f.el('powerReport').parentNode,f.el('toolWorkspace'));
assert.equal(calls,1);assert.equal(f.el('powerProgress').value,3);
assert.equal(f.el('powerStart').disabled,true);assert.equal(f.el('powerStop').disabled,false);
assert.match(f.el('powerStatus').textContent,/Headset: old-frame.*3 of 12.*Observing/);
});
test('incomplete result preserves original identity and start becomes available',()=>{
const f=fixture();f.context.sample={...state,running:false,stopped:'Headset switched; samples retained'};
f.run('renderPower(sample)');
assert.match(f.el('powerStatus').textContent,/old-frame.*Incomplete: Headset switched/);
assert.equal(f.el('powerStart').disabled,false);assert.equal(f.el('powerStop').disabled,true);
});
test('stop submits observation identity and keeps progress visible',async()=>{
const f=fixture(),calls=[];f.context.sample=state;f.run('renderPower(sample)');
f.context.api=async(path,body)=>{calls.push([path,body]);return {...state,running:false,stopped:'Stopped by user'};};
await f.el('powerStop').onclick();
assert.equal(calls[0][0],'/api/power');assert.equal(calls[0][1].action,'stop');assert.equal(calls[0][1].id,'abc');
assert.equal(f.el('powerProgress').value,3);assert.match(f.el('powerStatus').textContent,/Incomplete/);
});
test('old polls cannot overwrite newer report and retry explains retained samples',async()=>{
const f=fixture(),pending=[];f.context.api=()=>new Promise((resolve,reject)=>pending.push({resolve,reject}));
const first=f.run('loadPower()'),second=f.run('loadPower()');
pending[1].resolve({...state,running:false,stopped:'Disconnected'});await second;
const current=f.el('powerStatus').textContent;pending[0].resolve(state);await first;
assert.equal(f.el('powerStatus').textContent,current);
const next=f.run('loadPower()');pending[2].reject(new Error('Offline'));await next;
assert.match(f.el('powerStatus').textContent,/Offline.*Received samples remain/);
});
test('start failure remains actionable and does not imply success',async()=>{
const f=fixture();f.context.api=async()=>{throw new Error('Smoke session active');};
await f.el('powerStart').onclick();assert.match(f.el('powerStatus').textContent,/Smoke session/);
assert.equal(f.el('powerStart').disabled,false);
});
test('download captures observation ID, fetches an authenticated blob and names the file',async()=>{
const f=fixture(),requests=[],saved=[];
f.context.sample={...state,running:false,stopped:'Disconnected'};f.run('renderPower(sample)');
f.context.fetch=async(url,opts)=>{requests.push([url,opts]);return {ok:true,blob:async()=>({report:true})};};
f.context.URL={createObjectURL:()=> 'blob:report',revokeObjectURL(){}};
f.context.document.createElement=()=>({click(){saved.push({href:this.href,name:this.download});}});
await f.formats[0].onclick();
assert.equal(requests[0][0],'/api/power/report?id=abc&format=html');
assert.equal(requests[0][1].headers['X-Frame-UI'],'1');
assert.deepEqual(saved,[{href:'blob:report',name:'frame-power-abc.html'}]);
assert.match(f.el('powerSaveStatus').textContent,/Download requested/);
f.context.fetch=async()=>({ok:false,json:async()=>({error:'Report replaced'})});
await f.formats[0].onclick();
assert.match(f.el('powerSaveStatus').textContent,/Download failed: Report replaced/);
assert.equal(f.formats[0].disabled,false);
});
test('packaging guard requires shared modules and detects missing resources',()=>{
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const guard=require('../app/build/check-resources');const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'power-resources-'));
try {
for(const rel of guard.REQUIRED) {const file=path.join(tmp,rel);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,'test');}
assert.deepEqual(guard.missing(tmp),[]);
for(const rel of ['ui/frame_power.py','ui/frame_status.py','scripts/frame_power_sample.py','scripts/frame_power_report.py']) {
assert.ok(guard.REQUIRED.includes(rel));fs.unlinkSync(path.join(tmp,rel));assert.ok(guard.missing(tmp).includes(rel));
}
} finally {fs.rmSync(tmp,{recursive:true,force:true});}
});
+105
View File
@@ -0,0 +1,105 @@
"""Exercise the shipped desktop alert and its UI with a monotonic fake clock."""
import pathlib
import shutil
import subprocess
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
@unittest.skipUnless(shutil.which('node'), 'Node exercises production page JavaScript')
class DesktopBatteryComfort(unittest.TestCase):
def test_alert_confirmation_and_lifecycle(self):
page = (ROOT / 'ui/index.html').read_text(encoding='utf-8')
code = page.split('// ---- Desktop-only low-battery comfort:')[1].split('// ---- battery ----')[0]
code = code[code.index('class DesktopBatteryAlert'):]
js = r'''
const assert = require('node:assert/strict');
const elements = new Map();
const $ = id => {
if (!elements.has(id)) elements.set(id, {checked:false, textContent:''});
return elements.get(id);
};
let now = 0, calls = [], toasts = [], devGen = 1, comfortActive = false;
const performance = {now:()=>now};
const listeners = {};
const document = {hidden:false, addEventListener:(name,fn)=>listeners[name]=fn};
const HOST = {mobile:false};
const window = {frameApp:{notify:(message,request)=>{calls.push({message,request});return Promise.resolve();}}};
const toast = message => toasts.push(message);
''' + code + r'''
(async () => {
const low = {percent:15,status:'Discharging',watts:-4};
const high = {...low,percent:20};
const a = new DesktopBatteryAlert();
assert.equal(a.sample(low,0),false);
assert.equal(a.sample(low,1000),false); // rapid manual refreshes cannot confirm
assert.equal(a.sample(low,30000),true);
for (let t=60000;t<=900000;t+=30000) assert.equal(a.sample(low,t),false);
assert.equal(a.sample(high,930000),false);
assert.equal(a.sample(low,960000),false); // a recovery spike did not rearm
assert.equal(a.sample(low,990000),false);
a.sample(high,1020000); a.sample(high,1050000);
assert.equal(a.sample(low,1080000),false);
assert.equal(a.sample(low,1110000),true);
const c = new DesktopBatteryAlert();
c.sample(low,0); assert.equal(c.sample(low,30000),true);
c.sample(high,60000); c.sample(high,90000);
c.sample(low,120000); assert.equal(c.sample(low,150000),false); // ten minute cap
assert.equal(c.sample(low,631000),false); // long gap requires fresh confirmation
assert.equal(c.sample(low,661000),true);
for (const bad of [null,{}, {...low,percent:null}, {...low,percent:NaN}, {...low,percent:-1},
{...low,percent:101},{...low,percent:'10'}, {...low,status:'Unknown'},
{...low,status:'Charging'}, {...low,status:'Full'}, {...low,status:'Not charging'},
{...low,watts:0},{...low,watts:-0.5},{...low,watts:null},{...low,watts:NaN}]) {
const b = new DesktopBatteryAlert();
b.sample(low,0); assert.equal(b.sample(bad,30000),false);
assert.equal(b.sample(low,60000),false); // unknown interrupts confirmation
}
const b = new DesktopBatteryAlert();
b.sample(low,0); b.invalidate(); assert.equal(b.sample(low,30000),false);
assert.equal(b.sample(low,121000),false); // stale gap
assert.equal(b.sample(low,120000),false); // clock rollback
desktopBatterySample(low); now=30000; desktopBatterySample(low);
assert.equal(calls.length,0); // opt-in starts unchecked
$('desktopBatteryAlert').checked=true; $('desktopBatteryAlert').onchange();
now=60000;desktopBatterySample(low);now=90000;desktopBatterySample(low);
assert.equal(calls.length,1); assert.equal(calls[0].request,false);
assert.match(calls[0].message,/15%.*draining/);
$('desktopBatteryAlert').checked=false;$('desktopBatteryAlert').onchange();
$('desktopBatteryAlert').checked=true;$('desktopBatteryAlert').onchange();
now=120000;desktopBatterySample(low);now=150000;desktopBatterySample(low);
assert.equal(calls.length,1); // toggling does not clear episode latch
desktopBattery.latched=false;desktopBattery.lastAlert=-Infinity;desktopBattery.invalidate();
now=180000;desktopBatterySample(low);document.hidden=true;listeners.visibilitychange();
document.hidden=false;now=210000;desktopBatterySample(low);assert.equal(calls.length,1);
now=240000;desktopBatterySample(low);assert.equal(calls.length,2);
desktopBattery.latched=false;desktopBattery.lastAlert=-Infinity;desktopBattery.invalidate();
comfortActive=true;$('batteryAlert').checked=true;
now=270000;desktopBatterySample(low);now=300000;desktopBatterySample(low);
assert.equal(calls.length,2); // existing session owns battery alerts
comfortActive=false;HOST.mobile=true;
now=330000;desktopBatterySample(low);now=360000;desktopBatterySample(low);
assert.equal(calls.length,2);
HOST.mobile=false;
window.frameApp.notify=()=>Promise.reject(Error('denied'));
now=390000;desktopBatterySample(low);now=420000;desktopBatterySample(low);
await new Promise(setImmediate);
assert.match($('desktopBatteryStatus').textContent,/not confirmed/);
now=450000;desktopBatterySample(low);
assert.equal(toasts.length,3); // delivery failure does not retry on refresh
})().catch(e=>{console.error(e);process.exitCode=1;});
'''
result = subprocess.run(['node', '-e', js], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_existing_status_path_and_switch_reset(self):
page = (ROOT / 'ui/index.html').read_text(encoding='utf-8')
self.assertIn('desktopBatterySample(s.battery);', page)
switch = page.split('if (link.device !== null && devId !== link.device)')[1].split('devGen++;')[0]
self.assertIn('$("desktopBatteryAlert").checked = false;', switch)
refresh = page.split('function refresh()')[1].split('async function refreshAfterAudio')[0]
self.assertIn('desktopBattery.invalidate();', refresh)
block = page.split('// ---- Desktop-only low-battery comfort:')[1].split('// ---- battery ----')[0]
self.assertNotIn('setTimeout', block)
self.assertNotIn('api(', block)
+1 -1
View File
@@ -9,7 +9,7 @@ import subprocess
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
STUBS = ['$', 'toggleLive', 'scrollToY', 'scroller', 'loadMacView', 'loadPanels', 'loadPanelSwitcher', 'loadBackups', 'loadStorage', 'loadTitles', 'showAndroidTab',
STUBS = ['$', 'toggleLive', 'scrollToY', 'scroller', 'loadMacView', 'loadPanels', 'loadPanelSwitcher', 'loadBackups', 'loadStorage', 'loadPower', 'loadTitles', 'showAndroidTab',
'loadAndroid', 'loadDisplays', 'setGameSource', 'requestAnimationFrame']
RUN = r'''
+256
View File
@@ -0,0 +1,256 @@
"""Desktop observation lifecycle, guarded HTTP API and packaged resource contract."""
import sandbox # noqa: F401
import contextlib
import io
import http.client
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import time
from types import SimpleNamespace
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'ui'))
import frame_power
import server
STREAM = frame_power.sampler.stream_report
SAMPLE = {'time': 1, 'elapsedSeconds': 0, 'osBuild': 'test', 'readings': {
'battery.watts': {'value': 0, 'unit': 'W', 'source': '/sys/test', 'state': 'available'}},
'unavailableGroups': ['fan']}
class DesktopPower(unittest.TestCase):
def setUp(self):
self.observation = frame_power.Observation()
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.lock = Path(self.temp.name) / 'frame-test.lock'
self.patches = [patch.object(frame_power.sampler, 'LOCK', self.lock)]
for p in self.patches:
p.start()
self.addCleanup(p.stop)
self.addCleanup(self.observation.shutdown)
def wait(self):
self.observation.thread.join(4)
self.assertFalse(self.observation.thread.is_alive())
def stream(self, program, preset='minute'):
real = STREAM
def collect(command, payload, count, interval, stop, received, **kw):
return real([sys.executable, '-u', '-c', program], '', count, interval, stop, received, **kw)
mocked_stream = patch.object(frame_power.sampler, 'stream_report', side_effect=collect)
mocked_stream.start()
self.addCleanup(mocked_stream.stop)
return self.observation.start(preset, ('ssh', '-o', 'HostName=old', 'frame-old'),
{'alias': 'frame-old', 'deviceId': 'old'})
def test_complete_exports_match_and_no_background_collection_on_status(self):
def collect(command, payload, count, interval, stop, received, **kw):
self.assertEqual(count, 12)
self.assertEqual(interval, 5)
self.assertIn('HostName=old', command)
self.assertIn('StrictHostKeyChecking=yes', command)
self.assertIn('frame-old', command)
self.assertNotIn('pkill', ' '.join(command))
for _ in range(count):
received(SAMPLE.copy())
return {'schemaVersion': 1, 'requestedSamples': count, 'intervalSeconds': interval,
'stopped': None, 'samples': [SAMPLE.copy() for _ in range(count)], 'summary': {}}
with patch.object(frame_power.sampler, 'stream_report', side_effect=collect) as run:
self.observation.start('minute', ('ssh', '-o', 'HostName=old', 'frame-old'), {'alias': 'frame-old'})
self.wait()
state = self.observation.status()
self.assertEqual((state['received'], state['running'], state['stopped']), (12, False, None))
for _ in range(3):
self.observation.status()
self.assertEqual(run.call_count, 1)
report, _ = self.observation.export(state['id'], 'json')
self.assertEqual(json.loads(report)['summary']['battery.watts']['mean'], 0)
html, _ = self.observation.export(state['id'], 'html')
csv, _ = self.observation.export(state['id'], 'csv')
self.assertIn('Headset: frame-old', html)
self.assertIn('collection.state,Completed', csv)
self.assertIn('collection.receivedSamples,12', csv)
self.assertIn('battery.watts,0,W', csv)
def test_stop_keeps_received_sample_and_reaps_only_owned_child(self):
real_popen = subprocess.Popen
children = []
def spawn(*a, **kw):
proc = real_popen(*a, **kw)
children.append(proc)
return proc
event = json.dumps({'sample': SAMPLE})
with patch.object(frame_power.sampler.subprocess, 'Popen', side_effect=spawn):
state = self.stream(f'import sys,time; sys.stdin.read(); print({event!r}, flush=True); time.sleep(30)')
deadline = time.monotonic() + 3
while self.observation.status()['received'] < 1 and time.monotonic() < deadline:
time.sleep(.01)
self.assertEqual(self.observation.status()['received'], 1)
with self.assertRaisesRegex(ValueError, 'already running'):
self.observation.start('minute', ('ssh', 'frame'), {'alias': 'other'})
active, _ = self.observation.export(state['id'], 'json')
self.assertIn('in progress', json.loads(active)['stopped'])
self.observation.stop()
self.wait()
self.assertIsNotNone(children[0].poll())
data, _ = self.observation.export(state['id'], 'json')
self.assertEqual(json.loads(data)['samples'], [SAMPLE])
self.assertIn('Stopped by user', json.loads(data)['stopped'])
csv, _ = self.observation.export(state['id'], 'csv')
self.assertIn('incomplete', csv)
def test_disconnect_and_oversize_keep_partial_and_incomplete(self):
for ending in ('sys.exit(255)', 'print("x"*262145, flush=True)'):
with self.subTest(ending=ending):
event = json.dumps({'sample': SAMPLE})
state = self.stream(f'import sys; sys.stdin.read(); print({event!r}, flush=True); {ending}')
self.wait()
data, _ = self.observation.export(state['id'], 'json')
report = json.loads(data)
self.assertEqual(report['samples'], [SAMPLE])
self.assertTrue(report['stopped'])
def test_local_lock_preserves_previous_report_and_invalid_inputs_do_not_spawn(self):
with patch.object(frame_power.sampler, 'stream_report') as run:
self.lock.mkdir()
with self.assertRaisesRegex(ValueError, 'Smoke session'):
self.observation.start('minute', ('ssh', 'frame'), {'alias': 'frame'})
for preset in ('hour', 1000, None):
with self.assertRaises(ValueError):
self.observation.start(preset, ('ssh', 'frame'), {'alias': 'frame'})
run.assert_not_called()
self.assertIsNone(self.observation.status()['id'])
def test_headset_switch_preserves_original_identity_and_requests_cancel(self):
done = threading.Event()
def collect(command, payload, count, interval, cancel, received, **kw):
received(SAMPLE)
done.set()
cancel.wait(3)
return {'requestedSamples': count, 'intervalSeconds': interval, 'samples': [SAMPLE], 'stopped': None}
with patch.object(frame_power.sampler, 'stream_report', side_effect=collect), \
patch.object(server, '_power', self.observation):
original = server.FRAME, list(server.HOST_OPTS)
try:
state = self.observation.start('five-minutes', ('ssh', 'old'), {'alias': 'old'})
self.assertTrue(done.wait(2))
server.route('different-headset', [])
self.wait()
current = self.observation.status()
self.assertEqual(current['headset']['alias'], 'old')
self.assertEqual(current['requested'], 60)
self.assertIn('Headset switched', current['stopped'])
with self.assertRaises(ValueError):
self.observation.export('stale-id', 'html')
with self.assertRaises(ValueError):
self.observation.export(state['id'], '../file')
finally:
server.route(*original)
def test_http_guards_stale_target_stop_id_and_download_headers(self):
httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), server.Handler)
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
conn = http.client.HTTPConnection(*httpd.server_address)
def request(method, path, body=None, device=None, key=True):
headers = {'X-Frame-UI': server.UI_KEY} if key else {}
if device:
headers['X-Frame-Device'] = device
conn.request(method, path, json.dumps(body) if body is not None else None, headers)
r = conn.getresponse()
return r.status, dict(r.getheaders()), r.read()
try:
with patch.object(server, '_power', self.observation), \
patch.object(server, 'LINK', SimpleNamespace(active_device=lambda: {'id': 'new'})), \
patch.object(frame_power.sampler, 'stream_report') as run:
for path in ('/api/power', '/api/power/report?id=x&format=html'):
self.assertEqual(request('GET', path, key=False)[0], 403)
self.assertEqual(request('POST', '/api/power', {'action': 'start', 'preset': 'minute'}, key=False)[0], 403)
for device, expected in ((None, 400), ('old', 409)):
self.assertEqual(request('POST', '/api/power', {'action': 'start', 'preset': 'minute'}, device)[0], expected)
run.assert_not_called()
self.observation.id = 'test-id'
self.observation.report = {'schemaVersion': 1, 'requestedSamples': 12, 'intervalSeconds': 5,
'headset': {'alias': 'old'}, 'stopped': 'Disconnected', 'samples': [SAMPLE]}
status, headers, data = request('GET', '/api/power/report?id=test-id&format=html')
self.assertEqual(status, 200)
self.assertIn('attachment;', headers['Content-Disposition'])
self.assertIn('no-store', headers['Cache-Control'])
self.assertIn(b'Disconnected', data)
self.assertEqual(request('POST', '/api/power', {'action': 'stop', 'id': 'stale'}, 'new')[0], 409)
self.assertEqual(request('POST', '/api/power', {'action': 'stop', 'id': 'test-id'}, 'new')[0], 200)
received = threading.Event()
def collect(command, payload, count, interval, cancel, emit, **kw):
emit(SAMPLE)
received.set()
cancel.wait(3)
return {'schemaVersion': 1, 'requestedSamples': count, 'intervalSeconds': interval,
'samples': [SAMPLE], 'stopped': 'Stopped'}
run.side_effect = collect
code, _, data = request('POST', '/api/power', {'action': 'start', 'preset': 'minute'}, 'new')
self.assertEqual(code, 200)
new_id = json.loads(data)['id']
self.assertNotEqual(new_id, 'test-id')
self.assertTrue(received.wait(2))
self.assertEqual(request('GET', '/api/power/report?id=test-id&format=json')[0], 409)
self.assertEqual(request('POST', '/api/power', {'action': 'stop', 'id': new_id}, 'new')[0], 200)
self.wait()
self.assertEqual(self.observation.status()['received'], 1)
self.assertEqual(self.observation.status()['headset']['deviceId'], 'new')
finally:
conn.close()
httpd.shutdown()
httpd.server_close()
thread.join()
def test_early_remote_smoke_lock_has_structured_reason_without_sensor_reads(self):
self.lock.mkdir()
output = io.StringIO()
with patch.object(frame_power.sampler, 'snapshot') as sensor, contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(frame_power.sampler.main(['--probe', '--stream']), 75)
sensor.assert_not_called()
self.assertIn('Smoke session active', json.loads(output.getvalue())['finished']['stopped'])
def test_phone_can_import_without_desktop_sampler_resources(self):
with tempfile.TemporaryDirectory() as tmp:
import os
import shutil
shutil.copyfile(ROOT / 'ui/frame_power.py', Path(tmp) / 'frame_power.py')
program = 'import sys; sys.path.insert(0, sys.argv[1]); import frame_power; assert frame_power.Observation().status()["id"] is None'
result = subprocess.run([sys.executable, '-I', '-B', '-c', program, tmp],
env={**os.environ, 'FRAME_LOCAL': '1'}, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_packaged_resources_under_isolated_python(self):
config = json.loads((ROOT / 'app/package.json').read_text())
# Materialize exactly the Python resources selected by electron-builder.
with tempfile.TemporaryDirectory() as tmp:
resources = Path(tmp)
import shutil
for spec in config['build']['extraResources']:
if spec.get('to') not in ('ui', 'scripts'):
continue
source = ROOT / 'app' / spec['from']
for pattern in spec['filter']:
for file in source.glob(pattern):
if file.is_file():
dest = resources / spec['to'] / file.name
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(file, dest)
program = ('import sys; sys.path.insert(0, sys.argv[1]); import frame_power; '
'p=frame_power.sampler.remote_payload(); '
'assert "def snapshot" in p and "def battery" in p; '
'o=frame_power.Observation(); assert not o.status()["running"]')
run = subprocess.run([sys.executable, '-I', '-B', '-c', program, str(resources / 'ui')], capture_output=True, text=True)
self.assertEqual(run.returncode, 0, run.stderr)
run = subprocess.run(['node', '--test', str(ROOT / 'tests/power_desktop.cjs')], capture_output=True, text=True)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+36
View File
@@ -2,6 +2,7 @@
import sandbox # noqa: F401
import base64
import contextlib
import csv
from html.parser import HTMLParser
import io
import json
@@ -43,6 +44,19 @@ class Report(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()):
return power.stream_report([sys.executable, '-c', program], '', count, 1)
def test_csv_metadata_headset_alias_is_plain_text_in_spreadsheets(self):
for prefix in ('=', '+', '-', '@', ' =', '\t='):
with self.subTest(prefix=prefix):
alias = prefix + 'HYPERLINK("https://example.invalid")'
report = {'headset': {'alias': alias}, 'requestedSamples': 12,
'stopped': 'Stopped', 'samples': []}
rows = list(csv.reader(io.StringIO(power.csv_samples(report))))
self.assertEqual(len(rows), 4)
self.assertEqual([row[5] for row in rows[1:]], ["'" + alias] * 3)
report['headset']['alias'] = 'living-room-frame'
rows = list(csv.reader(io.StringIO(power.csv_samples(report))))
self.assertEqual([row[5] for row in rows[1:]], ['living-room-frame'] * 3)
def test_completed_stream_preserves_zero_unknown_units_and_downloads(self):
event = json.dumps({'sample': SAMPLE})
program = f'import sys; sys.stdin.read(); print({event!r}); print(\'{{"finished": {{"stopped": null}}}}\')'
@@ -89,6 +103,28 @@ class Report(unittest.TestCase):
self.assertIn('Stopped by user', report['stopped'])
self.assertIsNotNone(children[0].poll())
def test_canceled_launch_does_not_open_ssh(self):
import threading
stop = threading.Event()
stop.set()
with mock.patch.object(power.subprocess, 'Popen') as spawn:
report = power.stream_report(['ssh', 'frame'], '', 12, 5, stop_event=stop)
spawn.assert_not_called()
self.assertIn('Stopped before collection', report['stopped'])
def test_stop_interrupts_child_that_never_reads_payload(self):
import threading
stop = threading.Event()
timer = threading.Timer(0.1, stop.set)
timer.start()
try:
report = power.stream_report([sys.executable, '-c', 'import time; time.sleep(30)'],
'x' * 1048576, 1, 1, stop_event=stop)
finally:
timer.cancel()
self.assertIn('Stopped', report['stopped'])
self.assertEqual(report['samples'], [])
def test_invalid_stream_is_not_completed(self):
report = self.collect('import sys; sys.stdin.read(); print("not json")')
self.assertIn('interrupted', report['stopped'])
+37
View File
@@ -355,6 +355,8 @@ class FindingPanels(unittest.TestCase):
t.subprocess.run = lambda *a, **k: subprocess.CompletedProcess(a, 0, out, "")
self.assertEqual(self.real_read_props(":0"), {"GAMESCOPE_FOCUSABLE_WINDOWS": [1, 0, 2, 3, 769, 4],
"GAMESCOPE_FOCUSED_WINDOW": [0]})
t.subprocess.run = lambda *a, **k: subprocess.CompletedProcess(a, 0, "GAMESCOPE_FOCUSABLE_WINDOWS(CARDINAL) = \n", "")
self.assertEqual(self.real_read_props(":0"), {"GAMESCOPE_FOCUSABLE_WINDOWS": []})
t.subprocess.run = lambda *a, **k: subprocess.CompletedProcess(a, 0, "GAMESCOPE_FOCUSED_WINDOW: not found.\n", "")
self.assertEqual(self.real_read_props(":0"), {})
@@ -392,17 +394,52 @@ class FindingPanels(unittest.TestCase):
self.assertIn("Headset view", out["why"])
def test_desktop_running_but_not_listed(self):
self.props[(":0", "GAMESCOPE_FOCUSABLE_WINDOWS")] = []
self.t.desktop_running = lambda: True
out = self.t.panels()
self.assertEqual(out["panels"], [])
self.assertIn("desktop is running", out["why"])
def test_nothing_open(self):
self.props[(":0", "GAMESCOPE_FOCUSABLE_WINDOWS")] = []
out = self.t.panels()
self.assertEqual(out, {"focus": None, "focus_display": None, "panels": [],
"why": "No app panel is open in the headset. Open the desktop or an app in "
"the headset, then try again."})
def test_absent_list_is_unknown_even_when_desktop_is_running(self):
for desktop in (False, True):
with self.subTest(desktop=desktop):
self.t.desktop_running = lambda: desktop
self.t._ROOT.clear()
out = self.t.panels()
self.assertEqual(out["panels"], [])
self.assertIn("couldn't read gamescope's panel list", out["why"])
self.assertIn("can't tell whether", out["why"])
self.assertIn("Headset view", out["why"])
self.assertNotIn("No app panel is open", out["why"])
def test_focus_property_without_panel_list_is_unknown(self):
self.props[(":0", "GAMESCOPE_FOCUSED_WINDOW")] = [0]
self.assertIn("couldn't read gamescope's panel list", self.t.panels()["why"])
def test_failed_xprop_does_not_claim_no_panels_are_open(self):
t = self.t
t.read_props = self.real_read_props
saved = t.subprocess.run
self.addCleanup(setattr, t.subprocess, "run", saved)
for failure in ("refused", "timeout"):
with self.subTest(failure=failure):
def run(*args, **kwargs):
if failure == "timeout":
raise subprocess.TimeoutExpired(args[0], kwargs["timeout"])
return subprocess.CompletedProcess(args[0], 1, "", "Can't open display")
t.subprocess.run = run
t._ROOT.clear()
out = t.panels()
self.assertIn("couldn't read gamescope's panel list", out["why"])
self.assertNotIn("No app panel is open", out["why"])
def test_missing_x_tools_are_named(self):
self.plasma_on(":0")
self.t.shutil.which = lambda tool: None if tool == "xwininfo" else "/usr/bin/" + tool
+9
View File
@@ -10,6 +10,8 @@ function connectionFixture() {
sourceState:{jobs:new Map(),detail:null,detailRequest:0},touches:new Map(),gesture:null,padType:{blur(){},value:''},
log(){},renderPill(){},renderConnDlg(){},renderHome(){},resetShots(){},resetClips(){},renderBanner(){},loadDevices(){},renderDevices(){},renderTests(){},viaText(){return 'test';},netLabel(){return 'test';},refresh:()=>Promise.resolve(),reloadAll(){},checkContactPrompt(){},ctrlReset(){},padShow:s=>{c.pad.state=s.state;}});
c.window.connDevice='a';
c.document.addEventListener=()=>{};
f.run(pick(html,'class DesktopBatteryAlert {','// ---- battery ----'));
f.run('const UI_KEY="test";'+pick(html,'const HEADSET_FREE =','// What a panel shows'));
f.run(pick(html,'function onConnection(s) {','// Read the event stream'));
return f;
@@ -41,8 +43,15 @@ test('a device switch discards completed install results and the open detail',()
Object.assign(c,{pad:{state:'off',queue:[]},padReset(){},sourceState:{jobs:new Map([['test:one',{done:true,result:{package:'app.on.a',game_data:true}}]]),detail:{app:{}},detailRequest:0}});
f.el('appDetail').open=true;
f.el('storageResult').textContent='Old headset storage';
f.el('desktopBatteryAlert').checked=true;
f.run('desktopBattery.pending={condition:"low",at:0};desktopBattery.latched=true;desktopBattery.lastAlert=42;');
f.run('onConnection({phase:"connected",device:{id:"b",name:"B"},devices_rev:1,now:0})');
assert.match(f.el('storageResult').textContent,/Headset changed/);
assert.equal(f.el('desktopBatteryAlert').checked,false);
assert.equal(f.run('desktopBattery.pending'),null);
assert.equal(f.run('desktopBattery.latched'),false);
assert.equal(f.run('desktopBattery.lastAlert'),42);
assert.match(f.el('desktopBatteryStatus').textContent,/Off.*Headset changed/);
assert.equal(c.sourceState.jobs.size,0);assert.equal(c.sourceState.detail,null);assert.equal(f.el('appDetail').open,false);
});
test('only a preview matching current diagnostics consent can be sent or copied',async()=>{
+111
View File
@@ -0,0 +1,111 @@
"""One desktop observation using the read-only sampler; reports stay in memory."""
import json
from pathlib import Path
import sys
import threading
import time
import uuid
# Shared with the source-checkout CLI; shipped as explicit desktop resources.
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
try:
import frame_power_sample as sampler
from frame_power_report import render
except ModuleNotFoundError as exc:
# Phone/headset bundles host the same UI without desktop-only resources.
if exc.name not in ('frame_power_sample', 'frame_power_report'):
raise
sampler = render = None
PRESETS = {'minute': (12, 5), 'five-minutes': (60, 5)}
class Observation:
def __init__(self):
self.lock = threading.RLock()
self.report = None
self.running = False
self.thread = None
self.cancel = None
self.reason = None
self.id = None
self.started = None
def status(self):
with self.lock:
return {'id': self.id, 'running': self.running, 'received': len(self.report['samples']) if self.report else 0,
'requested': self.report['requestedSamples'] if self.report else 0,
'headset': self.report['headset'] if self.report else None,
'started': self.started, 'stopped': self.report['stopped'] if self.report else None}
def start(self, preset, route, headset):
if sampler is None:
raise ValueError('Desktop power-report resources are missing; reinstall the desktop app')
if preset not in PRESETS:
raise ValueError('Choose a one-minute or five-minute observation')
with self.lock:
if self.running:
raise ValueError('An observation is already running')
if sampler.LOCK.exists():
raise ValueError('Smoke session active (/tmp/frame-test.lock); observation not started')
count, interval = PRESETS[preset]
self.id = uuid.uuid4().hex
self.cancel = threading.Event()
self.reason = None
self.started = time.time()
self.report = {'schemaVersion': 1, 'requestedSamples': count, 'intervalSeconds': interval,
'headset': headset, 'stopped': 'Observation in progress; received samples only',
'samples': [], 'summary': {}}
self.running = True
# Pin the route before the caller releases the server's route lock.
command = [*route[:-1], '-T', '-o', 'StrictHostKeyChecking=yes',
'-o', 'ServerAliveInterval=5', '-o', 'ServerAliveCountMax=2', route[-1],
'python3', '-', '--probe', '--count', str(count), '--interval', str(interval)]
self.thread = threading.Thread(target=self._collect, args=(command, count, interval), daemon=True)
self.thread.start()
return self.status()
def _collect(self, command, count, interval):
def received(sample):
with self.lock:
self.report['samples'].append(sample)
try:
result = sampler.stream_report(command, sampler.remote_payload(), count, interval,
self.cancel, received, discard_errors=True)
with self.lock:
result['headset'] = self.report['headset']
result['stopped'] = self.reason or result['stopped']
self.report = result
except Exception as exc:
with self.lock:
self.report['stopped'] = self.reason or f'Observation interrupted: {exc}'
finally:
with self.lock:
self.running = False
def stop(self, reason='Stopped by user; received samples retained'):
with self.lock:
if self.running:
self.reason = reason
self.report['stopped'] = reason
self.cancel.set()
return self.status()
def export(self, observation_id, format):
if format not in ('html', 'json', 'csv'):
raise ValueError('Unknown report format')
with self.lock:
if not self.report or observation_id != self.id:
raise ValueError('This report was replaced; refresh the observation')
# Independent snapshot, including samples already received while running.
report = json.loads(json.dumps(self.report, allow_nan=False))
report['summary'] = sampler.summarize(report['samples'])
if format == 'json':
return json.dumps(report, allow_nan=False, indent=2), 'application/json'
csv = sampler.csv_samples(report)
return (render(report, csv), 'text/html; charset=utf-8') if format == 'html' else (csv, 'text/csv; charset=utf-8')
def shutdown(self):
self.stop('App closed; received samples retained')
if self.thread:
self.thread.join(timeout=8)
+8 -3
View File
@@ -271,7 +271,7 @@ def panels(limit=None):
out["why"] = ("The headset took too long to list its panels (its X tools didn't answer in time). "
+ ("Some may be missing. " if found else "") + "Try again, or use the Headset view.")
elif not found:
out["why"] = why_none(unfound)
out["why"] = why_none(unfound, props)
return out
@@ -295,13 +295,18 @@ def desktop_running():
return False
def why_none(listed):
def why_none(listed, props):
"""Why panels() found nothing, in words the person at the computer can act on.
listed: how many of the windows gamescope lists aren't X11 windows on any display."""
listed: how many of the windows gamescope lists aren't X11 windows on any display.
props: the root properties actually read; an absent list is not an empty list."""
missing = [tool for tool in ("xprop", "xwininfo") if not shutil.which(tool)]
if missing:
return (f"This SteamOS build has no {' or '.join(missing)}, which Frame Control uses to find the "
"headset's panels. Use the Headset view instead, and please report your SteamOS version.")
if "GAMESCOPE_FOCUSABLE_WINDOWS" not in props:
return ("Frame Control couldn't read gamescope's panel list, so it can't tell whether an app panel is open. "
"Check that SteamVR is running in the headset, then try again or use the Headset view. "
"If this persists, report your SteamOS version and this exact message.")
if listed:
# gamescope lists windows, but none is an X11 window on any display: a Wayland
# window (a desktop drawn straight to gamescope, say) can't be found or captured this way.
+145 -4
View File
@@ -1430,8 +1430,22 @@
<div class="page" data-page="tools">
<div class="workspace-heading"><div><a href="#tools" id="toolBack" class="workspace-link" hidden>← All tools</a><h1 id="toolTitle">Tools</h1><p id="toolSubtitle">Choose a task for your Frame.</p></div></div>
<div id="toolDirectory"><section class="tool-group"><h2>Content & files</h2><div class="quick-routes"><a href="#transfer"><span>Send to Frame</span><small>Add files, APKs or your own games</small></a><a href="#media"><span>Media player</span><small>Play your own videos and media</small></a><a href="#linuxApps"><span>Linux apps</span><small>Install and manage desktop apps</small></a></div></section><section class="tool-group"><h2>Play & control</h2><div class="quick-routes"><a href="#capture"><span>Capture & Live</span><small>See and control the headset view</small></a><a href="#pad" title="Type on the headset (T)"><span>Type on the headset</span><small>Keyboard, trackpad and clipboard</small></a><a href="#panels"><span>Panel switcher</span><small>Bring an open panel into view</small></a><a href="#vrTools"><span>VR tools</span><small>Performance HUD and VR utilities</small></a><a href="#comfort"><span>Family & comfort</span><small>Session reminders and breaks</small></a><a href="#macview" id="macToolLink" hidden><span>Mac in the headset</span><small>Share Mac windows and displays</small></a><a href="#macview" id="pcToolLink" hidden><span>PC in the headset</span><small>Experimental: share this PC's screen</small></a></div></section><section class="tool-group"><h2>Your Frame</h2><div class="quick-routes"><a href="#storage"><span>Game storage</span><small>Free space and Steam install sizes</small></a><a href="#backup" id="backupToolLink"><span>Backup &amp; recovery</span><small>Save games and settings, restore after a reset</small></a></div><a class="workspace-link" href="#settings">Connection, display &amp; preferences →</a></section><section class="tool-group"><h2>Assistant</h2><a class="workspace-link" href="/assistant">Open assistant &amp; AI agents →</a><p class="sub">Use your own model endpoint or review a proposed MCP action.</p></section></div>
<div id="toolDirectory"><section class="tool-group"><h2>Content & files</h2><div class="quick-routes"><a href="#transfer"><span>Send to Frame</span><small>Add files, APKs or your own games</small></a><a href="#media"><span>Media player</span><small>Play your own videos and media</small></a><a href="#linuxApps"><span>Linux apps</span><small>Install and manage desktop apps</small></a></div></section><section class="tool-group"><h2>Play & control</h2><div class="quick-routes"><a href="#capture"><span>Capture & Live</span><small>See and control the headset view</small></a><a href="#pad" title="Type on the headset (T)"><span>Type on the headset</span><small>Keyboard, trackpad and clipboard</small></a><a href="#panels"><span>Panel switcher</span><small>Bring an open panel into view</small></a><a href="#vrTools"><span>VR tools</span><small>Performance HUD and VR utilities</small></a><a href="#comfort"><span>Family & comfort</span><small>Session reminders and breaks</small></a><a href="#macview" id="macToolLink" hidden><span>Mac in the headset</span><small>Share Mac windows and displays</small></a><a href="#macview" id="pcToolLink" hidden><span>PC in the headset</span><small>Experimental: share this PC's screen</small></a></div></section><section class="tool-group"><h2>Your Frame</h2><div class="quick-routes"><a href="#powerReport"><span>Power &amp; heat report</span><small>Read-only observation and offline downloads</small></a><a href="#storage"><span>Game storage</span><small>Free space and Steam install sizes</small></a><a href="#backup" id="backupToolLink"><span>Backup &amp; recovery</span><small>Save games and settings, restore after a reset</small></a></div><a class="workspace-link" href="#settings">Connection, display &amp; preferences →</a></section><section class="tool-group"><h2>Assistant</h2><a class="workspace-link" href="/assistant">Open assistant &amp; AI agents →</a><p class="sub">Use your own model endpoint or review a proposed MCP action.</p></section></div>
<div class="grid-3" id="toolWorkspace">
<section class="panel" id="powerReport">
<h2>Power &amp; heat report</h2>
<p class="sub">Observe battery, CPU, temperatures and available sensors without changing settings. One observation at a time, every five seconds, for at most five minutes.</p>
<label for="powerPreset">Observation length</label>
<select id="powerPreset"><option value="minute">1 minute · 12 samples</option><option value="five-minutes">5 minutes · 60 samples</option></select>
<div class="row"><button class="action" id="powerStart">Start observation</button><button id="powerStop" disabled>Stop and keep samples</button></div>
<progress id="powerProgress" max="12" value="0" aria-label="Samples received" hidden></progress>
<p id="powerStatus" role="status" aria-live="polite">No observation yet.</p>
<div class="row"><button data-power-format="html" disabled>Download HTML report</button><button data-power-format="json" disabled>Download JSON</button><button data-power-format="csv" disabled>Download CSV</button></div>
<p id="powerSaveStatus" role="status" aria-live="polite"></p>
<p class="hint">Download before starting again or quitting: only the latest observation is kept in memory. Downloads during collection are incomplete snapshots. Stop, disconnect or switching headsets keeps received samples, labeled with the original headset. A smoke session blocks sensor reads.</p>
<p class="hint">Open the saved HTML in your browser; it works offline and includes JSON/CSV downloads. Unknown readings are never treated as zero. Rails overlap; do not add them. Sensor accuracy is unverified. Reports include sensor paths and OS builds: review before sharing.</p>
</section>
<section class="panel" id="vrTools">
<div class="shelf-head"><h2>VR comfort and performance</h2><span class="spacer"></span><span class="sub" id="vrUpdated">Waiting for the Frame</span></div>
<div class="stats" id="vrMetrics"></div>
@@ -1451,6 +1465,12 @@
</details>
</section><section class="panel" id="comfort" style="margin:20px 0;padding:16px">
<div class="shelf-head"><h2>Family and comfort</h2><span class="count">Session timer and reminders</span></div>
<div id="desktopBatteryComfort" hidden>
<h3>Desktop low-battery alert</h3>
<label><input id="desktopBatteryAlert" type="checkbox"> Alert on this computer at 15% or less</label>
<p class="hint">No session timer needed. Off when this page opens or you switch headsets. Uses normal status refreshes while the page is visible; no extra polling or headset changes. Two readings must confirm low charge and battery drain. One alert until charge recovers to 20%, with at least ten minutes between alerts.</p>
<p id="desktopBatteryStatus" class="hint" role="status">Off.</p>
</div>
<form id="comfortForm">
<div class="row" style="flex-wrap:wrap;gap:12px">
<label>Session limit (minutes) <input id="sessionMinutes" type="number" min="1" max="240" value="30" required style="width:75px"></label>
@@ -2116,6 +2136,7 @@ const HOST = { computer: "computer" };
function applyHostWording(h) {
Object.assign(HOST, h);
window.frameControlCenter?.host(h);
$("desktopBatteryComfort").hidden = !!h.mobile || !window.frameApp?.notify;
// The iPhone app: the server runs on the Frame, and saving goes to the phone's Photos.
document.body.classList.toggle("mobile", !!h.mobile);
$("shotsFolder").hidden = !!h.mobile;
@@ -2158,7 +2179,7 @@ const savesToDevice = () => !!(window.frameApp && window.frameApp.saveImages);
// then are about the old one, so they're dropped rather than shown.
let devGen = 0;
// Answers that don't depend on the headset (this computer's data, the catalogue, jobs).
const HEADSET_FREE = /^\/api\/(devices|connection|host|job|titles\/job|webinstall\/job|apk-versions|android\/(catalog|reports)|steam\/search)\b/;
const HEADSET_FREE = /^\/api\/(power|devices|connection|host|job|titles\/job|webinstall\/job|apk-versions|android\/(catalog|reports)|steam\/search)\b/;
async function api(path, body, device = window.connDevice) {
const gen = devGen;
const checkGeneration = () => {
@@ -2226,6 +2247,7 @@ function setOnline(ok, why) {
if (HOST.mobile) $('mobileConnectionStatus').textContent = ok ? 'Connected to the Frame serving this session.' : 'The Frame is disconnected. Retry or check its address in connection setup.';
$('offline').hidden = ok;
if (!ok) {
desktopBattery.invalidate();
$("offMsg").textContent = why || "Can't reach the Frame";
setConn(false, "Offline");
$("battChip").hidden = true; closeDevPop();
@@ -2262,6 +2284,7 @@ function refresh() {
setConn(true, state.hostname);
setOnline(true);
} catch (e) {
desktopBattery.invalidate();
renderPerformance(null);
if (!e.stale) stateRead = {valid: false, error: e};
renderHome();
@@ -2442,6 +2465,60 @@ $("castBtn").onclick = () => {
$("viewer").requestFullscreen?.().catch(() => {});
};
// ---- Desktop-only low-battery comfort: consumes existing status, never polls ----
class DesktopBatteryAlert {
constructor() {
this.pending = null;
this.latched = false;
this.lastAlert = -Infinity;
}
invalidate() { this.pending = null; }
sample(b, now) {
// Require actual drain as well as driver state: plugged-in idle can report Discharging.
const valid = Number.isFinite(b?.percent) && b.percent >= 0 && b.percent <= 100 &&
["Charging", "Discharging", "Full", "Not charging"].includes(b.status);
const low = valid && b.percent <= 15 && b.status === "Discharging" &&
Number.isFinite(b.watts) && b.watts < -0.5;
const recovered = valid && b.percent >= 20;
const condition = low ? "low" : recovered ? "recovered" : null;
if (!condition) { this.invalidate(); return false; }
if (!this.pending || this.pending.condition !== condition || now - this.pending.at > 90000 || now < this.pending.at) {
this.pending = {condition, at: now};
return false;
}
if (now - this.pending.at < 20000) return false;
if (recovered) this.latched = false;
if (!low || this.latched || now - this.lastAlert < 600000) return false;
this.latched = true;
this.lastAlert = now; // latch even when system delivery fails; never retry on each refresh
return true;
}
}
const desktopBattery = new DesktopBatteryAlert();
$("desktopBatteryAlert").onchange = () => {
desktopBattery.invalidate();
$("desktopBatteryStatus").textContent = $("desktopBatteryAlert").checked
? "On. Waiting for two fresh status readings confirming low charge and battery drain."
: "Off.";
};
function desktopBatterySample(b) {
if (!$("desktopBatteryAlert").checked || HOST.mobile || !window.frameApp?.notify || document.hidden ||
(comfortActive && $("batteryAlert").checked)) {
desktopBattery.invalidate();
return;
}
if (!desktopBattery.sample(b, performance.now())) return;
const message = `Frame battery is low (${b.percent}%) and draining. Consider charging or taking a break.`;
$("desktopBatteryStatus").textContent = message;
toast(message);
// Desktop bridge only: never prompt or send a phone/browser push from a status refresh.
const generation = devGen;
window.frameApp.notify(message, false).catch(() => {
if (generation !== devGen || !$("desktopBatteryAlert").checked) return;
$("desktopBatteryStatus").textContent = message + " System notification delivery was not confirmed. Check system settings or use Enable / test notifications below.";
});
}
document.addEventListener("visibilitychange", () => desktopBattery.invalidate());
// ---- battery ----
function battery(b, power) {
const pct = b?.percent;
@@ -2497,6 +2574,7 @@ function render(s) {
renderHome(s);
window.frameControlCenter?.status(s, stateReceivedAt, stateRead);
battery(s.battery, s.power);
desktopBatterySample(s.battery);
$("devPopTitle").textContent = $("devPopTitle").title = window.connName || "Headset";
$("devName").textContent = `${s.hostname} · ${s.ip ?? "no IP"}`;
$("updated").textContent = new Date(s.time * 1000).toLocaleTimeString();
@@ -5454,6 +5532,63 @@ $("panelList").onclick = e => {
act("Show panel", () => api("/api/panels", {action: "focus", key: b.dataset.panel}), b);
};
// ---- Read-only power observation ----
let powerState = null, powerTimer = null, powerSeq = 0;
function renderPower(s) {
powerState = s;
$('powerStart').disabled = !!s.running;
$('powerPreset').disabled = !!s.running;
$('powerStop').disabled = !s.running;
$('powerProgress').max = s.requested || 1;
$('powerProgress').value = s.received;
$('powerProgress').hidden = !s.id;
const identity = s.headset ? `Headset: ${s.headset.alias}. ` : '';
$('powerStatus').textContent = s.id ? identity + `${s.received} of ${s.requested} samples received. ` +
(s.running ? (s.stopped?.startsWith('Stopped') ? 'Stopping…' : 'Observing…') : s.stopped ? `Incomplete: ${s.stopped}` : 'Completed.') : 'No observation yet.';
document.querySelectorAll('[data-power-format]').forEach(b => b.disabled = !s.id);
}
async function loadPower() {
const seq = ++powerSeq;
clearTimeout(powerTimer);
try {
const s = await api('/api/power');
if (seq !== powerSeq) return;
renderPower(s);
if (s.running && location.hash === '#powerReport') powerTimer = setTimeout(loadPower, 1000);
} catch (e) {
if (seq !== powerSeq) return;
$('powerStatus').textContent = `Observation status unavailable: ${e.message}. Received samples remain on the local server while it is running.`;
if (location.hash === '#powerReport') powerTimer = setTimeout(loadPower, 3000);
}
}
$('powerStart').onclick = async () => {
$('powerStart').disabled = true;
try {
renderPower(await api('/api/power', {action:'start', preset:$('powerPreset').value}));
loadPower();
} catch (e) { $('powerStatus').textContent = e.message; $('powerStart').disabled = !!powerState?.running; }
};
$('powerStop').onclick = async () => {
if (!powerState?.id) return;
$('powerStop').disabled = true;
try { renderPower(await api('/api/power', {action:'stop', id:powerState.id})); loadPower(); }
catch (e) { $('powerStatus').textContent = e.message; $('powerStop').disabled = false; }
};
document.querySelectorAll('[data-power-format]').forEach(b => b.onclick = async () => {
if (!powerState?.id) return;
const id = powerState.id, format = b.dataset.powerFormat;
b.disabled = true;
try {
const r = await fetch(`/api/power/report?id=${encodeURIComponent(id)}&format=${format}`, {headers:{'X-Frame-UI':UI_KEY}});
if (!r.ok) throw new Error((await r.json()).error || `HTTP ${r.status}`);
const blob = await r.blob(), a = document.createElement('a');
a.href = URL.createObjectURL(blob); a.download = `frame-power-${id}.${format}`; a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
$('powerSaveStatus').textContent = 'Download requested. Open the saved HTML in your browser to view it offline; it includes JSON and CSV downloads.';
} catch (e) { $('powerSaveStatus').textContent = `Download failed: ${e.message}`; }
finally { b.disabled = !powerState?.id; }
});
// ---- Read-only game storage ----
let storageSeq = 0;
const storageState = s => ({'permission-denied':'Permission denied', missing:'Missing or disconnected',
@@ -5761,10 +5896,10 @@ const PAGES = ["apps", "games", "tools", "settings"];
const SECONDARY_PAGES = ["home", "capture", "devices", "control"];
const SECTION_PAGE = {library:"games", discover:"apps", android:"apps", view:"capture", shots:"capture", device:"home",
vrTools:"tools", comfort:"tools", assistant:"tools", pad:"tools", sideloaded:"games", getgames:"games", steamStore:"games", androidLibrary:"apps", appStore:"apps", linuxApps:"apps",
display:"settings", androidSettings:"settings", transfer:"tools", media:"tools", artworkSettings:"settings", autoSync:"settings", power:"settings", macview:"tools", privacy:"settings", panels:"tools", storage:"tools", backup:"tools"};
display:"settings", androidSettings:"settings", transfer:"tools", media:"tools", artworkSettings:"settings", autoSync:"settings", power:"settings", macview:"tools", privacy:"settings", panels:"tools", storage:"tools", powerReport:"tools", backup:"tools"};
const TOOL_TITLES = {transfer:"Send to Frame", media:"Media player", artworkSettings:"Library artwork", autoSync:"Copy to this computer",
pad:"Type on the headset", panels:"Panel switcher", vrTools:"VR tools", comfort:"Family & comfort", androidSettings:"App display & reports",
power:"Remote & power", macview:"Mac in the headset", privacy:"Privacy & updates", storage:"Game storage", backup:"Backup & recovery"};
power:"Remote & power", macview:"Mac in the headset", privacy:"Privacy & updates", storage:"Game storage", powerReport:"Power & heat report", backup:"Backup & recovery"};
const workspace = {source:"all", scope:"installed", apps:"installed", scroll:new Map(), key:null, hash:null, y:0};
let page = "apps";
// Reuse the existing live lists and form handlers in their new destinations.
@@ -5872,6 +6007,7 @@ function showPage(e) {
if (tool === 'panels') loadPanelSwitcher();
if (tool === 'backup') loadBackups();
if (tool === 'storage') loadStorage();
if (tool === 'powerReport') loadPower();
if (tool === 'androidSettings') {
$('repNew').hidden = false; $('androidSettings').prepend($('repNew')); loadDisplays();
}
@@ -6826,6 +6962,11 @@ function onConnection(s) {
stateReceivedAt = null;
stateRead = {valid: false, error: null};
online = null;
$("desktopBatteryAlert").checked = false;
desktopBattery.invalidate();
// Keep the cooldown across switches, but a new headset can start its own charge episode.
desktopBattery.latched = false;
$("desktopBatteryStatus").textContent = "Off. Headset changed; enable for this headset if wanted.";
devGen++; // answers still on their way are about the other headset
padReset(); ctrlReset();
sourceState.jobs.clear(); sourceState.detail = null; sourceState.detailRequest++;
+39
View File
@@ -64,6 +64,7 @@ import frame_media # noqa: E402
import frame_panels # noqa: E402
import frame_quest # noqa: E402
import frame_meta # noqa: E402
import frame_power # noqa: E402
import frame_report # noqa: E402
import frame_store # noqa: E402
import frame_telemetry # noqa: E402
@@ -109,6 +110,7 @@ HOST_OPTS = []
frame_android.SSH_OPTS = SSH[1:]
_power = frame_power.Observation()
_route_lock = threading.Lock()
@@ -120,6 +122,7 @@ def route(alias, host_opts):
with _route_lock:
moved = alias != FRAME
if moved:
_power.stop('Headset switched; received samples retained for the previous headset')
frame_catalog._env.clear() # the SteamOS and Lepton builds reports record are per headset
# Invalidate launches before publishing the new route. send/stop share
# a writer lock, so an old process cannot receive events after this.
@@ -3009,7 +3012,28 @@ def source_manage(body):
raise Failure(str(e), 400)
def power_action(body):
action = body.get('action')
if LOCAL:
raise Failure('Power observations are available on the desktop app', 400)
if action == 'stop':
# ID prevents an old page stopping a replacement observation.
with _power.lock:
if body.get('id') != _power.id:
raise Failure('This observation was replaced; refresh', 409)
return _power.stop()
if action != 'start':
raise Failure('Unknown observation action', 400)
with _route_lock:
headset = {'alias': FRAME, 'deviceId': LINK.active_device()['id'] if LINK else None}
try:
return _power.start(body.get('preset'), tuple([*SSH, FRAME]), headset)
except ValueError as exc:
raise Failure(str(exc), 409) from exc
POST = {
"/api/power": power_action,
"/api/android/backup": android_backup, "/api/backup": backup_action,
"/api/vr": vr,
"/api/comfort": comfort, "/api/media": media, "/api/agent/call": agent_call,
@@ -3193,6 +3217,18 @@ class Handler(BaseHTTPRequestHandler):
elif path == "/store":
# The Android store as a headset panel (scripts/store-on-frame.sh).
self.send_bytes((HERE / "store.html").read_bytes(), "text/html; charset=utf-8")
elif path == "/api/power":
self.send_json(_power.status())
elif path == "/api/power/report":
args = parse_qs(url.query)
try:
format = args.get('format', ['html'])[0]
report_id = args.get('id', [''])[0]
data, mime = _power.export(report_id, format)
except ValueError as exc:
raise Failure(str(exc), 409) from exc
self.send_bytes(data.encode('utf-8'), mime,
headers=[('Content-Disposition', f'attachment; filename="frame-power-{report_id}.{format}"')])
elif path == "/api/settings/artwork":
self.send_json(frame_steamgriddb.settings())
elif path == "/artwork-settings.js":
@@ -3368,6 +3404,8 @@ class Handler(BaseHTTPRequestHandler):
body = json.loads(self.rfile.read(length) or b"{}")
if not isinstance(body, dict):
raise Failure("request body must be a JSON object", 400)
if path == '/api/power' and body.get('action') == 'start' and LINK and not meant:
raise Failure('Observation start needs the intended X-Frame-Device headset', 400)
# Not headset work: switching headsets mustn't wait for (or refuse) these.
with (contextlib.nullcontext() if path in NOT_HEADSET_WORK else working(meant)):
result = handler(body)
@@ -3641,6 +3679,7 @@ def main():
# mid-cleanup would abort it and leave the SSH master running.
if not frame_host.WINDOWS:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
_power.shutdown()
_stop_sync.set()
webinstall_shutdown()
macview.shutdown() # close the headset's viewers before the agent goes