Skip to content

Add a native desktop app for macOS and Windows - #233

Merged
bitxeno merged 35 commits into
masterfrom
feat/desktop-app
Oct 25, 2026
Merged

bitxeno merged 35 commits into
masterfrom
feat/desktop-app

Conversation

@bitxeno

@bitxeno bitxeno commented Oct 25, 2026

Copy link
Copy Markdown
Owner

Why

atvloadly only ships as a Docker service for Linux/OpenWrt. On a Mac or a Windows machine that means running Docker Desktop, which puts the service behind a VM network: mDNS discovery of the Apple TV is unreliable and the host's own usbmuxd is out of reach. #228 showed the service can run natively on macOS; this branch turns that into a packaged app that also covers Windows, and keeps the Docker/Linux behaviour untouched.

The goal is a download-and-run app: no Docker, no avahi-daemon, no usbmuxd2.

Approach

Shell + embedded server, not a rewrite. The desktop app is a mygo menu bar / notification area shell that starts the existing service on a random loopback port and opens the web UI in the default browser. Every piece of internal/* (install manager, device manager, WebSocket login/pair/progress) and the whole Vue frontend in web/static is reused as is. Rewriting the UI on top of mygo.Bind typed IPC was rejected: it would have duplicated the API surface and risked behaviour drift for no user-visible gain.

One bootstrap, two callers. The startup sequence used to live inline in cmd/server's action(). It moved to internal/bootstrap, which both the CLI and the desktop app call. web.Run gained a RunListener entry point so the shell can bind port 0 and hand the listener over (fiber's app.Listener), which is what makes a random free port on 127.0.0.1 possible without the shell having to guess one.

A separate Go module. desktop/app is its own module because mygo needs Go 1.27+ while the root module is on 1.25; isolating it keeps the server build and CI on their existing toolchain. The desktop module reaches the server code through a replace to the repository root.

plumesign ships inside the bundle rather than being expected on PATH, since a double-clicked app inherits none of the user's shell environment. The shell prepends Resources/bin to PATH for its child processes, so the existing plumesign call sites need no changes.

How it works

  • Boot: bootstrap.Run returns the bound address plus a stop func. The shell sets the app data directory to ~/Library/Application Support/atvloadly (macOS) or %APPDATA%\atvloadly (Windows), embeds the message catalogs, takes a single-instance lock, and puts an icon in the menu bar / notification area with Open in Browser, Open Log File and Quit.
  • No main window: LSUIElement on macOS, no taskbar button on Windows; the app is a background service with a menu.
  • Signing engine: desktop/scripts/fetch-plumesign.sh pulls the macOS universal and Windows binaries into resources/<platform>/bin/ at build time (gitignored). mygo build signs the executables along with the bundle.
  • Windows specifics: internal/exec gains HideWindow + CREATE_NO_WINDOW so GUI-triggered plumesign calls do not flash a console window, and the workspace lockfile is ported off Unix-only syscalls.
  • i18n: the tray menu uses new tray.* keys; it follows the language saved by the web UI and relabels itself through i18n.OnLanguageChanged.
  • Release: release.yml gains a desktop job (darwin/universal on macos-latest, windows/amd64+arm64 on ubuntu-latest) that publishes the DMG and the NSIS installers into the same Release as the server tarballs, plus a Homebrew cask push to bitxeno/homebrew-tap. release-nightly.yml builds the same targets but uploads them as artifacts only, never to a Release. The standalone desktop-release.yml is gone.
  • Unsigned builds: the DMG is ad hoc signed, so the release notes end with the one-time sudo xattr -dr com.apple.quarantine /Applications/atvloadly.app step. The recursive -dr matters: the bundled plumesign carries the quarantine flag too and the system kills it at run time otherwise. The cask does this in postflight_steps.

The Linux/Docker path is unchanged: same bootstrap order, same avahi/usbmuxd2 dependencies, same container image.

Validation

  • go build ./..., go test ./..., golangci-lint run (0 issues), the desktop/app module build, and the web/static production build all pass.
  • actionlint is clean on both modified workflows.
  • npm run build:release on macOS produces a signed .app; CFBundleShortVersionString picks up the tag with the v stripped.
  • The packaged app was run end to end: the browser shows the full frontend, mDNS finds devices, and check/afc executes the bundled plumesign under a clean env -i.
  • Windows builds and the NSIS installer are produced on the Linux runner; signing there needs a certificate secret.

Links

Add a dedicated add-device page that replaces the pairable-device card on
the home sidebar with a persistent "Add New Device" entry.

The page offers two tabs:
- Apple TV (default, left): pick a discovered pairable Apple TV from a
  combobox and start the existing pairing flow; no port or pairing file.
- iPhone: pick an iPhone from a combobox and upload a pairing file, reusing
  the existing lab import flow.

Both device lists use a shared combobox (typing an IP is supported) with a
refresh button; the Apple TV list keeps its spinner up for at least one
second so the fast endpoint still gives visible feedback. Lists are filtered
to Apple TV / iPhone devices (unknown classes kept) and refreshed on tab
entry. Add the /add-device route, sidebar icons, and locale strings for all
bundled languages. Hide the service-status card on phones.
Stack the Anisette server presets (URL above name and default badge) and
let device names wrap instead of being clipped, with 44px tap targets and a
scrollable list under 767px. Desktop layout is unchanged.
Allow pairing an Apple TV entered by IP (e.g. over Tailscale) whose
pairing port is unknown. The pair page now discovers the manual-pairing
port first: the start button stays disabled until a port is found, shows
a progress panel (mDNS lookup, TCP scan percentage, service probe) and
offers a rediscover button.

Backend:
- Add RPPairing port discovery (handshake + unicast DNS-SD fast path +
  two-stage TCP scan) in internal/manager/pairing_port_discovery.go.
- Add Device.Manual; pass --manual to `plumesign pair` for manual IPs.
- Extend the pair websocket with t=3 (discover) and t=4 (start with ip+port);
  discovery streams JSON progress lines on the same socket.

Frontend:
- Pair page manual mode driven by ?ip= / the pair-manual route.
- add-device routes a typed IP that matches no discovered device into the
  manual pairing flow instead of erroring.

Includes Go unit tests (frame/parse/mock-server/scan) and a frontend test
for the discovery messages and start payload.
Let the add-device iPhone tab connect an iPhone typed by IP whose
_remotepairing tunnel port is unknown.

Backend:
- Generalize port discovery with a shared predicate-based scanner and add
  DiscoverManualTunnelPort (unicast _remotepairing._tcp + TCP scan picking
  allowsIncomingTunnelConnections).
- Pass --manual through ImportPairingFile (manager/service/router) so
  `plumesign check pairing` knows the IP was entered manually.
- Add GET /api/pair/tunnel-port?ip= returning the discovered tunnel port
  (IPv4-only).

Frontend:
- api.discoverTunnelPort; iPhone startConnect uses a discovered device's
  port when present, otherwise probes the tunnel port and imports with
  manual=true. Button spinner covers probe+import; failures show a toast.
- Rewrite the iPhone no_device text to tunnel-service semantics (5 locales).

Tests: tunnel discovery (picks tunnel, ignores pair-setup), pairingCheckArgs
--manual, and a frontend test for the discovered/manual/failure branches.
Manual / Tailscale devices do not broadcast mDNS, so they never reached the
device list. Read them directly from the pairing files instead of adding a
new store: the .json peer record already carries manual, remotepairing_ip,
name, model and udid.

Backend:
- RemoteDevice gains Manual and RemotePairingIP.
- DeviceManager keeps a separate manualDevices map loaded from
  <pairing_files>/*.json (manual=true + remotepairing_ip) and merges it into
  GetDevices, deduped by UDID with mDNS entries winning. ReloadDevices
  refreshes it; Scan() leaves it intact.
- DeleteManualDevice removes both <udid>.json and <udid>.plist and the
  in-memory entry; POST /api/devices/:id/manual/delete exposes it.

Frontend:
- Manual devices show status "已添加" (added) and an "IP" badge on the icon's
  top-right corner (brand blue) instead of the online dot; IP stays after the
  name. A "忘记" action with click-to-confirm deletes the pairing files.

Tests: manual device loading/skip, dedupe with discovered, file deletion.
Port probing for install is deferred to a later step.
- Move the "IP" badge onto .avatar instead of .avatar > div, which daisyUI
  clips with overflow:hidden, so the badge is no longer cut off.
- Float the forget button to the far right of the row and show it only on
  row hover (or keyboard focus / armed state); on phones (<=767px) it stays
  always visible and the row wraps so it never overlaps the device text.
Take the forget button out of the row's flex flow (position: absolute at the
right edge) so the device title keeps the full width and never reflows to make
room for it. Hidden until row hover on desktop; always visible on phones with
reserved right padding so it does not cover the text.
- Move the manual-device forget button inline right after the status text
  ("已添加 · RPPairing") instead of floating at the row's right edge, so it
  never competes with the title for space.
- Change the forget/delete tooltip to "删除设备" (Delete device) across
  locales.
Replace the delete icon with an underlined "删除" text link on the status
line, prefixed by a "·" separator that only appears on row hover. The link
defaults to the danger color; the underline lives on an inner label so the
separator dot stays clean. Always visible on phones.
Manual (pairing-file/Tailscale) devices carry no tunnel port, so every flow
that reached them over RSD failed. Resolve the dynamic _remotepairing port on
demand (60s cache, per-UDID mutex, no automatic retry) and inject it before
use.

- manager.PrepareManualDevice / ManualPortNeedsResolve: probe the tunnel port
  for manual devices only, cache it on the in-memory device (PortResolvedAt),
  preserve it across pairing-file reloads, and serialize concurrent probes.
- Install: prepare before the queue (task.runInternal), interactive websocket
  (runInstallMessage) and external-certificate (runExternalInstall) paths; the
  install log shows "Resolving tunnel port for manual device...".
- Refresh: manager.CheckAfcServiceStatus prepares the port first, covering the
  cron schedule, device-triggered refresh and /api refresh. Manual devices rely
  on the cron schedule (no mDNS connect event).
- Mount/screenshot: prepare the port before RSD commands.

Tests: port resolution, no-op for discovered devices, TTL reuse/expiry, error
keeps port 0, and concurrent single-probe.
A device that leaves the network without an mDNS goodbye stayed in the
discovery map forever and shadowed its manual (pairing-file) record. Add a
background liveness loop for devices that have BOTH an mDNS entry and a manual
record:

- Every minute, TCP-dial the tunnel port of dual-source remote devices that
  have not been probed in the last minute; a fresh mDNS announcement counts as
  a probe. Lockdown/USB, pairable and port-less entries are never probed.
- After 5 consecutive failures the device is marked stale (hidden from
  GetDevices) so the manual entry surfaces; a later successful probe or a new
  announcement clears the flag and mDNS wins again.
- Stale is a flag, not a delete, so avahi never needs to re-announce for the
  device to come back.

Constants (interval, min age, fail threshold, dial timeout) are grouped at the
top of device_probe.go for easy tuning. Adds unit tests for targeting,
min-age skip, threshold/recovery and announcement reset.
discoverTunnelPort now sends silent:true so the request interceptor does not
toast the API error, leaving only the page's own "tunnel service not found"
message. The response interceptor's network-error branch also honours
silent so a timeout cannot double-toast either.
Error toasts used the global 3s autoClose and were easy to miss. Wrap
toast.error once at startup so error toasts default to 6s while success and
other toasts keep the global 3s; an explicit autoClose in a call still wins.
Drop the request interceptor's own 5s override so API errors use the same
default.
Switching tabs reuses the cached device list instead of reloading
every time; a failed load still retries on the next switch. The
combobox refresh button keeps reloading on demand.
…go build

Move the bitxeno/bom fork (pinned at 0e05147) into pkg/bom as a nested
module and swap its cgo github.com/blacktop/lzfse-cgo dependency for
bitxeno/lzfse-go, which calls the native lzfse through purego from an
embedded shared library. Decoded pixels are verified identical to the
cgo version on a real Assets.car.

With the last hard cgo dependency gone the whole service builds with
CGO_ENABLED=0, which the release and nightly xgo workflows already set.
At 250ms the dial budget matched the Tailscale relay RTT, so the open
service ports that need a full handshake were often missed under the
1024-concurrent scan, making tunnel discovery fail intermittently with
"manual tunnel port not found". 600ms leaves room for the measured
100-250ms relay latencies, as the design doc already recommended for
full port lists.
Ports are dialled in ascending order and probed as soon as each dial succeeds; the first matching RPPairing service cancels the rest of the scan. Darwin allocates ephemeral ports ascending, so the tunnel port sits near 49152 in practice and is found without sweeping the full range: ~0.9s vs ~5s to a real device over Tailscale.

Unicast mDNS is skipped for 100.x.x.x addresses (Tailscale CGNAT range): the query can never cross the overlay tunnel and only cost its 1.5s timeout.

Two scan stalls surfaced by this change are also fixed: silent local listeners (rapportd, the app's own HTTP server) accept the probe and answer nothing, so the handshake response deadline is now 800ms separate from the 2s dial timeout, and the probe pool is widened to 32 slots so a handful of such listeners cannot starve the real service.
DiscoverManualPairingPort now shares the pipelined ascending scan and the 100.x.x.x mDNS skip with the tunnel discovery, instead of its own full-range collect-all scan. The tunnel port it reported was never consumed by the pair page, so the field and the collect-all variant are removed.

Scan concurrency rises to 1536 (doc-proven stable) because Apple devices silently drop SYNs to closed ports, making a full sweep timeout-bound: a paired Apple TV outside pairing mode is found in ~4.3s instead of ~8.7s on LAN, while the Tailscale tunnel path stays at ~0.9-1.6s.
WebKit moves focus on mousedown, so clicking an option blurred the
input and closed the dropdown before the click could land on the
button: the click retargeted to the enclosing form and the selection
was lost (Safari and the desktop webview). Prevent the default on
mousedown in both comboboxes — DeviceComboBox and the settings
anisette server list — so the input keeps focus until pick runs.
Verified in headless WebKit and Chromium with real click sequences.
The manual-pairing scan probes every open port in the range, so it also
sees the _remotepairing tunnel service in the same pass and returns it
in the discovery result (tunnel_port on the websocket message).

The scan goes back to the two-stage form (dial the whole range, then
probe the open ports) with the 250ms dial timeout: capturing the tunnel
port requires probing the full range anyway, so the pipelined
early-exit scan, the raised 600ms dial timeout and the tailnet mDNS
skip are removed again.
The server command initialization sequence moves to bootstrap.Run,
which binds the listener and returns a stop function. The server command
and the desktop app both run it, so the desktop shell serves the same
sequence without duplicating it.

To bind a random free port for the desktop app, web gains RunListener on
an existing net.Listener, cfg gains an AppDataDir override so the desktop
app can point the data directory at its user directory, and the default
config paths read that override instead of DefaultConfigDir directly.
The desktop app is a mygo webview shell around the existing server: it
starts the service on a random loopback port through the shared
bootstrap, points the data directory at the OS user data directory, and
shows the current web frontend in a native window. The frontend keeps
using the HTTP API and websockets unchanged.

The shell prepends the bundled plumesign to PATH, so the managers exec
the signed binary inside the app bundle with no code changes; in dev
builds it falls back to the PATH plumesign. Release builds inject the
version through a generated version_gen.go, sign and notarize on macOS
when credentials are configured, and a desktop-release workflow builds
universal macOS and Windows apps on desktop-v* tags.

scripts/fetch-plumesign.sh downloads the release binaries for the
platform resources; missing assets warn and the app falls back to PATH.
The lockfile was missing the jszip and plist entries and still pinned
the tailwindcss specifier at ^3.0.23, so a fresh pnpm install rewrote
it. Record the resolved state matching the committed package.json.
The desktop shell is a GUI program without a console, so Windows opened a
new console window for every console child it started, plumesign included:
pairing and installing flashed a command line window. Set HideWindow and
CREATE_NO_WINDOW on the children of the shared exec package, which every
plumesign call goes through.
Replace the syscall.Flock and O_NOFOLLOW calls, which do not build on
Windows, with openNoFollow and flock helpers: flock(2) on Unix, LockFileEx
on Windows. writeSecretFile and the lock files now chmod 0600 after opening
instead of asking for it in the open flags.
Add OnLanguageChanged so the desktop shell rebuilds its tray menu when the
web UI switches language, and guard the bundle and localizer with a mutex
since the switch reaches them from another goroutine. Load catalogs with
path.Join, as fs.FS paths use forward slashes on Windows too.

Add the tray.* messages and copy the catalogs into the desktop app with a
node script instead of a shell mkdir/cp, which only runs on Unix.
The tray icon was a hand-drawn blue ring, and Windows never read
AppIcon.icon: that is the macOS Icon Composer format, so the taskbar and
installer took resources/icon.png. Render AppIcon.icon with ictool into
resources/icon.png and a 32x32 assets/tray-windows.png, and show the latter
in the notification area. Keep IconIsTemplate to macOS, which tints the
black menu bar mark; on Windows it would flatten the colored icon to white.

Also set LSUIElement in the bundle so a packaged app starts without a Dock
icon.
Build darwin/universal on macos-latest so the DMG and code signing run
where hdiutil and the signing tools exist, and the Windows targets on
ubuntu-latest. Fetch plumesign before building so the app bundles its
signing engine, install NSIS for the installer, and push the DMG as a
Homebrew cask.

Fall back to the x86_64 plumesign for windows-arm64 (Windows runs it under
emulation) and drop the empty bin directories when no binary is available,
which would otherwise break the NSIS file copy. Pass the tag's version
through mygo.config.ts, skip the DMG unless a darwin target is built, and
update the README for the menu bar design.
Drop the "Linux/OpenWrt only" claim from the three READMEs and the agent
instructions: the Docker server still targets Linux/OpenWrt, while the
desktop app in desktop/ covers macOS 15+ and Windows 10/11.

Installation now lists Docker first, then the desktop app (Homebrew cask
on macOS, the .exe installer from Releases on Windows). The FAQ follows
the current wiki: the "AppleTV not found" answer becomes a numbered list
that adds restarting avahi-daemon, and the Apple account answer no longer
mentions a proxy.
Translate the whole document, keeping the existing terminology for the
menu bar shell, the bootstrap extraction and the plumesign bundling.
Redraw the architecture diagram as an 80-column ASCII grid so the boxes
and arrows stay aligned now that the labels are single width.

Also state that the bootstrap extraction is done rather than planned:
internal/bootstrap.Run already backs both cmd/server and desktop/app.
The desktop DMG is ad hoc signed, so Gatekeeper holds it until the
quarantine flag is cleared. Append the xattr command to the end of the
generated release notes.

action-gh-release prepends body to the generated notes, so a second
step edits the release after creation to land the note last. The
recursive -dr is required: the bundled plumesign carries the same flag
and the system kills it at run time otherwise.
Bring in the add-device flow and the hardened manual (Tailscale) port
discovery, plus the pkg/bom vendoring that master picked up from this
branch's history.

Conflict resolution:

- internal/manager/*, internal/model/pairing_discovery.go, web/router.go,
  internal/service/websocket.go: take master. Both sides descend from the
  same add-device work, and master's c77fae6 is the squashed PR #232 which
  contains the hardened discovery (pipelined scan, CGNAT-aware address
  check, DiscoverManualTunnelPort, WarmManualDevicePort). This branch's
  copies were an earlier snapshot of that work, so master's version is a
  strict superset.
- locales/*.json: keep both sides. This branch added the desktop "tray"
  block, master reworded addDevice.iphone.no_device.
- web/static/src/page/*: take master (same earlier-snapshot situation).

Nothing under desktop/, internal/bootstrap or cmd/ was touched by master,
so the desktop app is unaffected.

Verified: go build ./..., go test ./..., golangci-lint run (0 issues),
the desktop module build, and the web/static production build.
Drop the separate desktop-release.yml: one `v*` tag now builds the server
and the desktop app together and publishes a single Release holding the
server tarballs, the macOS DMG and the Windows installers.

release.yml: the new desktop job builds darwin/universal on macos-latest
and windows/amd64+arm64 on ubuntu-latest, taking VERSION, COMMIT and
BUILDDATE from the build job instead of github.ref_name and
github.event.head_commit.timestamp, which are empty on a tag push. A new
release job downloads both desktop artifacts plus the server build, so
the changelog now has to leave the build job as an output.

release-nightly.yml: builds the same desktop targets and uploads them as
artifacts only; nothing reaches a Release. The version is
0.0.0-nightly.<run_number> and no signing secrets are passed, so nightly
stays ad hoc signed.

Also fix two latent problems the merge exposed:

- clean now depends on release. It deletes the same artifacts release
  downloads, so without the dependency it could win the race.
- docker/setup-qemu-action and setup-buildx-action move from v2 to v4;
  v2 no longer runs on GitHub Actions.

The version prefix follows the tag: mygo.config.ts strips `v` rather than
`desktop-v`.
@bitxeno
bitxeno merged commit 69f813d into master Oct 25, 2026
2 checks passed
@bitxeno
bitxeno deleted the feat/desktop-app branch November 11, 2026 13:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

⌂ 换网址