One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.10
Toby Kalkmanb4c5c32b8502
diff --git a/.gitattributes b/.gitattributesindex 1e30bde..d3477d6 100644--- a/.gitattributes+++ b/.gitattributes@@ -6,3 +6,6 @@# Vendored as they came: a third party's licence file is not ours to reflow.win_app/assets/** -text++# Reporter attachments retain their original bytes, including Windows line endings.+docs/ceo-17-10-2026/gh15-evidence/W*.log.log -textdiff --git a/README.md b/README.mdindex b80b2f9..e06356c 100644--- a/README.md+++ b/README.md@@ -17,17 +17,17 @@ still work, and what you type never leaves your network.## Download-Free, with no account. Mac, Windows and Linux downloads are on the [releases page](https://github.com/kalkman-code/beamer/releases/latest). Linux uses Flatpak; there is no AppImage.+Free, with no account. Mac, Windows and experimental Linux downloads are on the [releases page](https://github.com/kalkman-code/beamer/releases/latest). Linux uses Flatpak; there is no AppImage.| Platform | Get it | Notes ||---|---|---|| macOS 13 or later, Apple silicon or Intel | `Beamer-<version>.dmg` | One universal app, signed and notarised by Apple |-| Windows 10 and 11 | `Beamer-Setup-<version>.exe` | Code-signed; see step 1 below |-| Linux, 64-bit x86 and arm64 (Flatpak) | [Install from the Kalkman Code repository](https://flatpak.kalkmancode.co.uk/beamer.flatpakref); `Beamer-<version>-x86_64.flatpak` and `Beamer-<version>-aarch64.flatpak` are available as an offline alternative | Tested on Fedora 44 GNOME under Wayland; KDE Plasma is experimental and not yet tested on real hardware; X11 is not yet verified |+| Windows 10 and 11 | `Beamer-Setup-<version>.exe` | Not code-signed; see step 1 below |+| Linux, 64-bit x86 (experimental Flatpak) | [Install from the Kalkman Code repository](https://flatpak.kalkmancode.co.uk/beamer.flatpakref); `Beamer-<version>-x86_64.flatpak` is available as an offline alternative | Tested on Fedora 44 GNOME under Wayland; KDE Plasma 6 is a supported test target on this branch, awaiting hardware verification; X11 remains unverified |### Install on Linux-Beamer for Linux is a Flatpak for 64-bit x86 and arm64. There is no AppImage. Fedora, Linux+Beamer for Linux is an experimental Flatpak for 64-bit x86. There is no AppImage. Fedora, LinuxMint, Pop!_OS and other distributions with Flatpak can install it with one command:```sh@@ -61,9 +61,9 @@ flatpak uninstall --user uk.co.kalkman.beamerflatpak install --user https://flatpak.kalkmancode.co.uk/beamer.flatpakref```-The downloadable `Beamer-<version>-x86_64.flatpak` and `Beamer-<version>-aarch64.flatpak` bundles-remain available from the [releases page](https://github.com/kalkman-code/beamer/releases/latest)-as an offline alternative; the repository picks the right one for your machine by itself.+The downloadable `Beamer-<version>-x86_64.flatpak` bundle remains available from the [releases+page](https://github.com/kalkman-code/beamer/releases/latest) as an offline alternative. To build+for arm64, follow [the Linux instructions](docs/flatpak-build.md).## Quick start@@ -71,15 +71,13 @@ as an offline alternative; the repository picks the right one for your machine btwo Grant buttons on the Permissions page (Accessibility, then Input Monitoring), then RelaunchBeamer on the same page: macOS only passes keys to an app started after the grant, so until thenthe pointer crosses but the keyboard does not. On Windows,- run the installer. Since 1.5.8 it is code-signed, so Windows names the publisher instead of- "Unknown publisher". Windows may still say "Windows protected your PC" until the installer has- built a download reputation: choose More info, then Run anyway.+ run the installer. It is not code-signed, because a certificate costs money and Beamer is free,+ so Windows says "Windows protected your PC" the first time: choose More info, then Run anyway.Beamer on Windows runs as administrator, so expect one UAC prompt when you open it. On Linux,follow [Install on Linux](#install-on-linux) to install Beamer from the Kalkman Code repository.2. **Pair them.** On one machine, choose Pair a machine to show a six-digit code. On the other,- choose that machine from the list and enter the code. It lasts a minute and works once. Or choose- Pair nearby on both machines, compare the six digits shown on each, and confirm on both. If the- machine does not appear in the list, enter the address shown with its code on the other machine.+ choose that machine from the list and enter the code. It lasts a minute and works once. If it+ does not appear in the list, enter the address shown with its code on the other machine.3. **Cross.** Push the pointer through the edge you set, or use the shortcut. On Wayland, an edgesends input out and the shortcut brings it back. The other machine's keyboard and pointer comewith it. Cross back through the edge or use the shortcut again.@@ -93,9 +91,9 @@ In your own appearance: light if your GitHub is light, dark if it is dark.<table><tr><th>Mac</th><th>Windows</th></tr>-<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-overview-light.png"><img src="assets/mac-overview-dark.png" width="400" alt="Beamer's Overview page on the Mac: the pairing buttons, Pair nearby first, and a card for each paired machine, a desktop PC, a laptop and a Linux box, each showing it is linked, with an In use switch and Rename, Leave out, Directions and Remove buttons"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-overview-light.png"><img src="assets/windows-overview-dark.png" width="400" alt="Beamer's Overview page on Windows: the pairing buttons, Pair nearby first, and a card for each paired machine, a Mac, a laptop and a Linux box, each showing it is linked, with an In use switch and Rename, Directions, Leave out and Remove buttons"></picture></td></tr>-<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-crossing-light.png"><img src="assets/mac-crossing-dark.png" width="400" alt="Beamer's Crossing page on the Mac: a map with this Mac in the middle, a laptop to its left, a desktop PC to its right and a Linux box below, each edge lit where the pointer crosses, and a ledger of how each machine is reached, its edges and corners as chips"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-crossing-light.png"><img src="assets/windows-crossing-dark.png" width="400" alt="Beamer's Crossing page on Windows: a map with this PC in the middle, a Mac to its left, a laptop to its right and a Linux box below, each edge lit where the pointer crosses, and a ledger of how each machine is reached, its edges and corners as chips"></picture></td></tr>-<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-design-light.png"><img src="assets/mac-design-dark.png" width="400" alt="Beamer's Design page on the Mac: switches to animate crossings on this Mac and show where the pointer lands, a choice of style for crossing or for the shortcut and menu, shown at the edge, a corner or the notch, and a Light section of preview tiles"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-design-light.png"><img src="assets/windows-design-dark.png" width="400" alt="Beamer's Design page on Windows: switches to animate crossings on this PC and show where the pointer lands, a choice of style for crossing or for the shortcut and menu, shown at the edge or a corner, and a Light section of preview tiles"></picture></td></tr>+<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-overview-light.png"><img src="assets/mac-overview-dark.png" width="400" alt="Beamer's Overview page on the Mac: where input is, whether the link is up, Send input and Pause crossing, and a switch for each direction"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-overview-light.png"><img src="assets/windows-overview-dark.png" width="400" alt="Beamer's Overview page on Windows: where input is, Send input and Pause crossing, and a switch for each direction"></picture></td></tr>+<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-crossing-light.png"><img src="assets/mac-crossing-dark.png" width="400" alt="Beamer's Crossing page on the Mac: a drawing of the Mac and the PC side by side with the crossing edge lit, and the ways in"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-crossing-light.png"><img src="assets/windows-crossing-dark.png" width="400" alt="Beamer's Crossing page on Windows: a drawing of the Mac and the PC with the crossing edge lit, the ways in and where the Mac sits"></picture></td></tr>+<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-design-light.png"><img src="assets/mac-design-dark.png" width="400" alt="Beamer's Design page on the Mac: a tile for each crossing style, shown at the edge, a corner or the notch, and the colours"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-design-light.png"><img src="assets/windows-design-dark.png" width="400" alt="Beamer's Design page on Windows: a tile for each crossing style, shown at the edge, a corner or the notch, and the colours"></picture></td></tr></table>## What it does@@ -110,13 +108,10 @@ In your own appearance: light if your GitHub is light, dark if it is dark.- **Or press a key.** Double-tap or hold a trigger key to switch without moving the pointer. RightOption on the Mac and Right Ctrl on the PC to start with; on either machine it can be any keythat types nothing, recorded by pressing it.-- **Shake to come home.** While you drive another machine, a quick shake of this machine's mouse or- trackpad brings input straight back. Shake sensitivity sets how much movement it takes.- **Either way round.** The Mac drives the PC and the PC drives the Mac. Each machine has a switchper direction, so you can turn one way off and keep the other. Macs can drive Macs, and WindowsPCs can drive Windows PCs, too.-- **Pair them clearly.** Pair a machine and Pair nearby are at the top of Overview. Pair nearby- shows six digits to compare and confirm on both machines.+- **Pair them clearly.** Pair a machine is at the top of Overview, and the six digits are centred.- **Three machines.** Pair each machine with the others in the group. A chain needs a directpairing between every pair of machines in it.- **The clipboard comes with you.** Text and images, both ways, at the moment you switch. Files@@ -126,8 +121,7 @@ In your own appearance: light if your GitHub is light, dark if it is dark.arrives as the same physical key. On Windows, you can also choose a Mac keyboard layout, whereAlt acts as Command and the Windows key acts as Option.- **Media keys follow you.** Play, pause, skip, mute and volume cross between supported machines.- While input is on a Windows laptop, the Mac's brightness keys change that laptop's built-in- screen; the keyboard-backlight keys stay on the Mac.+ Brightness and keyboard-backlight keys stay on the Mac.- **Keys and buttons that stay put.** Each machine keeps a list of keys and mouse buttons that keepworking where they were pressed while its input is on the other one: a mouse's back button forthis machine's browser, a volume key for its speakers. Add one by pressing it. The back and@@ -137,17 +131,10 @@ In your own appearance: light if your GitHub is light, dark if it is dark.- **Make it yours.** Glow, Beam and Aperture, or effects in Membrane, Sparks, Instrument, Folio andSelvedge, each with colour packs of its own. Set the effect's Size and Length, the MacBook notchas an outline or an island with a meter, how hard you push before it crosses, and whether settings- windows follow the system's light or dark appearance. Choose Match display, Half or Quarter for- the effect frame rate. Beam fades softly inward from the edge.+ windows follow the system's light or dark appearance. Beam fades softly inward from the edge.- **Feels like your own.** Each machine sets how the other's pointer moves and scrolls on it, from25% to 400%, and can reverse its scrolling, so a Mac trackpad and a PC mouse each feel right onthe other screen.-- **Hide the pointer on the machine not in use.** On by default, it hides the pointer left behind- until that machine's own mouse or trackpad moves it, or a machine drives it again, and a PC or- Linux machine under X11 hides its own pointer while it drives another. Wayland does not allow apps- to hide the pointer.-- **See where input is.** The Windows and Linux tray icon shows whether input is here, on another- machine or held here while crossing is paused, like the Mac menu bar icon.- **Out of the way when it should be.** On macOS and Windows, you can choose whether a full-screenapp on each machine holds its edges; it is off by default, and shortcuts still work. A drag thatreaches the edge stays a drag. Switch to a machine that is asleep and Beamer wakes it, where that@@ -155,10 +142,6 @@ In your own appearance: light if your GitHub is light, dark if it is dark.- **Keep settings in step.** Same on all machines shares resistance, drag protection, Shortcut,effect style, colour, length, size and landing animation with compatible paired machines. Zones,jump keys, full-screen hold, whether effects animate, and window appearance stay local.-- **One desk, several profiles.** Same ways on every machine shares the crossing ways between- 1.5.5 machines, so you can set up any machine from the one in front of you and keep up to eight- named profiles. Machine tiles on the Crossing map resize, so different screen sizes line up.-- **In Italian too.** Language on the Connection page picks Automatic, English or Italiano.- **Match design.** Follow one paired machine's style, colour, length, size and landing animation.Changing one of those here stops following. Animation enable and window appearance stay local.- **A more responsive settings window.** Mac resizing and scrolling stay smooth, the Design grid@@ -179,9 +162,9 @@ About Beamer.|---|---|---|| Overview | Paired machines, where input is, the links and their round trips, Send input and Pause crossing, a switch per direction, Same on all machines, start at login, the update check | Paired machines, where input is, the links and their round trips, Send input and Pause crossing, a switch per direction, Same on all machines, start at sign-in, the update check || Permissions | Accessibility and Input Monitoring, with Relaunch Beamer | None; the firewall check is on Connection |-| Crossing | A map of the arrangement and a ledger of edge and corner chips for each machine, plus the notch and Return through the notch, with its jump key, full-screen hold, resistance and shortcut | A map of the arrangement and a ledger of edge and corner chips for each machine, with its jump key, full-screen hold, resistance and shortcut |+| Crossing | A drawing of the arrangement, the ways in for each machine (edge, part of the edge, corner, notch), the full-screen hold, resistance, the shortcut and jump keys | A drawing of the arrangement, the ways in for each machine (edge, part of the edge, corner), the full-screen hold, resistance, the shortcut and jump keys || Keyboard | Key mapping, what stays on this Mac, each peer's pointer and scroll speed | Key mapping, including a Mac layout, what stays on this PC, each peer's pointer and scroll speed |-| Design | Crossing and switch styles, colours, Size and Length, Frame rate, landing animation, Match design, notch and trackpad controls, window appearance (System, Light or Dark) | Crossing and switch styles, colours, Size and Length, Frame rate, landing animation, Match design, window appearance (System, Light or Dark) |+| Design | Crossing and switch styles, colours, Size and Length, landing animation, Match design, notch and trackpad controls, window appearance (System, Light or Dark) | Crossing and switch styles, colours, Size and Length, landing animation, Match design, window appearance (System, Light or Dark) || Connection | Hide addresses, a peer's address, port and pairing details | Whether Windows Firewall lets a peer in, with a one-button fix; hide addresses; this PC's address, port and pairing details |Each machine sets its own zones and the machine beyond each one. These settings stay local even@@ -196,8 +179,7 @@ when Same on all machines is on.- **AltGr is out of reach from the Mac.**- **Linux on Wayland has fewer controls.** Its limits are listed under [Linux](#linux).- **Linux gestures are not supported.**-- **SmartScreen may still warn.** The Windows installer is code-signed from 1.5.8, but SmartScreen- can show "Windows protected your PC" until it has built a download reputation; choose More+- **The Windows installer is unsigned.** SmartScreen may warn when you first run it; choose Moreinfo, then Run anyway.## In detail@@ -237,14 +219,14 @@ time you overshoot a close button. The default is 120 points; zero switches on c| Way in | Where it triggers | Mac | Windows ||---|---|---|---|| Shortcut | Double-tap the trigger key, or hold it | Yes | Yes |-| Edge | An edge chip in the ledger; a machine can have several. At a touching edge, only the shared span crosses; a free edge can wrap round | Yes | Yes |-| Corner | A corner chip in the ledger; a machine can have several. Each is an 8pt box needing a diagonal push | Yes | Yes |+| Edge | The whole of one outer edge | Yes | Yes |+| Part of the edge | Only the thirds of that edge you pick (start, middle, end), measured on the display under the pointer | Yes | Yes |+| Corner | An 8pt box in one corner, needing a diagonal push | Yes | Yes || Notch | The top edge, only within the notch's width | Yes | No |-Edges and corners are chips in each machine's ledger, and each machine can have several of each. A-touching edge crosses only along the span where the screens meet; a free edge can wrap round to-another machine. On the Mac, Shortcut and the right-hand edge are on to start with. On Linux under-Wayland, the shortcut only brings input back; the desktop only lets it go to another machine at an edge.+Any combination can be on, except Edge and Part of the edge, which exclude each other. On the Mac,+Shortcut and the right-hand edge are on to start with. On Linux under Wayland, the shortcut only+brings input back; the desktop only lets it go to another machine at an edge.- The notch has no pixels to light, so a push there draws on the notch itself. Outline, the default,runs a comet of light round a small tab under the notch that brightens and speeds up with the@@ -261,8 +243,7 @@ Wayland, the shortcut only brings input back; the desktop only lets it go to anothat screen holds pointer crossings; it does not apply to Beamer's own window. Shortcuts and jumpkeys still work. Wayland cannot detect a full-screen app.- Only one machine's input is on another at a time. The receiving machine can send it home or pass- it on through one of its own configured zones. If its driver sends no input for three seconds,- another machine can take over.+ it on through one of its own configured zones.- A machine's own switch, menu or shortcut sends input home. On Wayland, the shortcut only bringsinput back.- Switching to a sleeping PC sends wake-on-LAN when that PC supports it.@@ -306,8 +287,7 @@ trigger key cannot be added.The Mac's F7–F12 media row and volume keys cross as play/pause, next, previous, mute and volume.On the Mac they arrive as system events rather than key events and are captured separately-(`mac_app/media_keys.py`). The keyboard-backlight keys stay with macOS; the brightness keys reach a-Windows laptop's built-in screen.+(`mac_app/media_keys.py`). Brightness and keyboard-backlight keys stay with macOS.Ctrl+Alt+Del is the Secure Attention Sequence, trapped by the kernel before any app sees it.`SendInput` cannot produce it, and `SendSAS()` needs a Windows service or a signed `uiAccess` app@@ -380,12 +360,12 @@ password-authenticated key exchange, from the six-digit code. What that does and<summary><strong>Update check</strong></summary>Once a day, and at start, Beamer asks GitHub's public releases API for the latest release of this-repository and compares its version with its own, on the Mac, Windows and Linux. Every newer stable-release counts; drafts and pre-releases never do, and nothing is downloaded or installed. When a newer-one is out, the menu says Beamer X is available and the window shows a notice: What's new opens the-release page, and Dismiss hides that version for good. The Flatpak notice says how to update through-your software store. The request is an ordinary HTTPS request, so GitHub sees the address it came-from, as it would for a browser. Switch it off with Check for updates on Overview.+repository and compares its version with its own. A new minor or major version is always offered;+a patch release (1.5.0 to 1.5.1) only when its release notes ask for it, so a run of small fixes+does not nag. Drafts and pre-releases never count and nothing is downloaded. When a newer one is out, the menu says Beamer X is available and Overview offers a+Download button that opens the release page. The request is an ordinary HTTPS request, so GitHub+sees the address it came from, as it would for a browser. Switch it off with Check for updates on+Overview.</details>@@ -421,16 +401,17 @@ password. Without it, the Mac reports `Windows is locked — unlock it at the PC<details><summary><strong>Linux</strong></summary>-Linux support has been tested on GNOME; KDE Plasma support is experimental. There is no AppImage. Install the Flatpak, for 64-bit x86 or arm64, from the-Kalkman Code repository using [Install on Linux](#install-on-linux). The arm64 build has so far only-been started in a virtual machine, not on arm64 hardware. To build it yourself, follow [the Flatpak+Linux support is experimental. There is no AppImage. Install the 64-bit x86 Flatpak from the Kalkman+Code repository using [Install on Linux](#install-on-linux), or build for arm64 with [the Flatpakinstructions](docs/flatpak-build.md). On one Fedora 44 GNOME desktop under Wayland, paired with aMac and a Windows PC, the window and tray, pairing, crossing both ways, typing and the clipboard-work, and crossings show their effect through XWayland. X11 runs with Beamer's keyboard, pointer, pairing and clipboard features, but has not+work; crossings show no edge animation on the Linux machine, and the selected option in settings is+not filled in. X11 runs with Beamer's keyboard, pointer, pairing and clipboard features, but has notbeen tested on real hardware. Flatpak fetches the KDE runtime from Flathub if it is not already-present. Beamer targets GNOME and KDE Plasma under Wayland and X11. KDE Plasma support is-experimental and has not been tested on real hardware: KDE Wayland needs Plasma 6.1.1 or later-with the matching host portal, and the clipboard needs Plasma 6.6 or later.+present. This branch targets GNOME and KDE Plasma under Wayland and X11. KDE Wayland requires+Plasma 6.1.1 or later with the matching host portal; the full clipboard path targets Plasma 6.6 or+later. See the [KDE Plasma requirements and tester checklist](docs/kde-plasma-1.5.md); these branch+changes have not yet been built or published as a Flatpak.On Wayland, the desktop limits what Beamer can do:@@ -439,9 +420,8 @@ On Wayland, the desktop limits what Beamer can do:while input is away.”- “On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reachesan edge, so the edges are never held for one and a drag can cross.”-- Without XWayland, or if drawing through it fails, Beamer says: “On Wayland the desktop does not let- Beamer draw at the edges of the screen, so crossings show no effect on this machine. The other- machines still show theirs.”+- “On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no+ effect on this machine. The other machines still show theirs.”Older Ubuntu and Debian releases lack the InputCapture portal, so they cannot send input out underWayland; use an X11 session there. Linux does not offer gestures. KDE Plasma awaits hardwarediff --git a/VERSION b/VERSIONindex 2b26b8d..f0ed379 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.9+1.5.10diff --git a/assets/mac-design-dark.png b/assets/mac-design-dark.pngindex f2f4ff8..b799add 100644Binary files a/assets/mac-design-dark.png and b/assets/mac-design-dark.png differdiff --git a/assets/mac-design-light.png b/assets/mac-design-light.pngindex c883830..79800a7 100644Binary files a/assets/mac-design-light.png and b/assets/mac-design-light.png differdiff --git a/assets/mac-overview-dark.png b/assets/mac-overview-dark.pngindex 56c9dad..95e2397 100644Binary files a/assets/mac-overview-dark.png and b/assets/mac-overview-dark.png differdiff --git a/assets/mac-overview-light.png b/assets/mac-overview-light.pngindex 402e84d..13a73f3 100644Binary files a/assets/mac-overview-light.png and b/assets/mac-overview-light.png differdiff --git a/assets/social-preview.png b/assets/social-preview.pngindex 306e443..1048d75 100644Binary files a/assets/social-preview.png and b/assets/social-preview.png differdiff --git a/assets/windows-design-dark.png b/assets/windows-design-dark.pngindex 81a435c..eaadd96 100644Binary files a/assets/windows-design-dark.png and b/assets/windows-design-dark.png differdiff --git a/assets/windows-design-light.png b/assets/windows-design-light.pngindex 84e240d..996cd3e 100644Binary files a/assets/windows-design-light.png and b/assets/windows-design-light.png differdiff --git a/assets/windows-overview-dark.png b/assets/windows-overview-dark.pngindex 641ee18..609ce39 100644Binary files a/assets/windows-overview-dark.png and b/assets/windows-overview-dark.png differdiff --git a/assets/windows-overview-light.png b/assets/windows-overview-light.pngindex 5b0bf3b..ad7de00 100644Binary files a/assets/windows-overview-light.png and b/assets/windows-overview-light.png differdiff --git a/core/link.py b/core/link.pyindex 597962e..b8f016d 100644--- a/core/link.py+++ b/core/link.py@@ -43,6 +43,7 @@ QUEUE_BYTES = 32 * 1024 * 1024STALL_SECONDS = 2.0SENT_RECORD_LIMIT = 20000ACK_STALL_SECONDS = 1.5+INPUT_WINDOW = 32MEDIA_KEYS = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"})WINDOW_SECONDS = 30.0LOG_SECONDS = 60.0@@ -133,6 +134,7 @@ class OutboundLink:self._period = []self._last_ack_seq = -1self.last_ack_at = None+ self._last_ack_progress_at = Noneself._last_rx = 0.0self._last_tx = 0.0self._logged_at = 0.0@@ -149,6 +151,7 @@ class OutboundLink:self.down_since = clock()self._blocked_for = Noneself._try_host = None+ self._try_port = Noneself._followed_at = Noneself._followed_to = Noneself._answered = False@@ -277,8 +280,10 @@ class OutboundLink:self._blocked_for = Nonewith self._lock:tried, self._try_host = self._try_host, None+ tried_port, self._try_port = self._try_port, Noneif entry.get("host_pinned") is not False:tried = None+ tried_port = Noneif self._blocked_for is not None:self._wake.wait(0.25)self._wake.clear()@@ -288,7 +293,7 @@ class OutboundLink:self._wake.wait(0.25)self._wake.clear()continue- port = target[1]+ port = tried_port if tried is not None and tried_port is not None else target[1]host = tried or target[0]wait = self._reconnecttry:@@ -385,7 +390,7 @@ class OutboundLink:if self._stop.is_set():raise LinkEnded(tr("This link was stopped"), "off")deadline = time.monotonic() + HANDSHAKE_SECONDS- fields = self._handshake(_Interruptible(sock, self._stop), entry, host, deadline, direct)+ fields = self._handshake(_Interruptible(sock, self._stop), entry, host, deadline, direct, port)if self._stop.is_set():raise LinkEnded(tr("This link was stopped"), "off")except LinkEnded:@@ -437,7 +442,7 @@ class OutboundLink:return tr("Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again").format(name=name)return tr("{name} closed the connection: it may have removed this machine, or be too busy to answer").format(name=name)- def _handshake(self, sock, entry, host, deadline, direct):+ def _handshake(self, sock, entry, host, deadline, direct, port=None):name = self._name(entry)identity = self._identity()own_id = bytes(identity["id"])@@ -473,8 +478,9 @@ class OutboundLink:changes = {"name": welcome["name"], "platform": welcome["platform"]}if welcome["hw"] is not None:changes["hw"] = welcome["hw"]- if direct and host != entry.get("host"):+ if direct:changes["host"] = host+ changes["port"] = port if port is not None else entry.get("port")try:outcome, _ = self._book.admit(self.key_id, own_id, welcome["id"], changes)except Exception:@@ -553,6 +559,7 @@ class OutboundLink:self._period = []self._last_ack_seq = -1self.last_ack_at = None+ self._last_ack_progress_at = Noneself._locked = Falseself._drop_reason = Noneself._response_time.reset()@@ -671,6 +678,8 @@ class OutboundLink:pending = len(self._sent_at)ack_paused = self._ack_pause_since is not Noneoldest_age = now - oldest[1] - self._ack_stall_credit.get(oldest[0], 0.0) if oldest else 0.0+ if self._last_ack_progress_at is not None:+ oldest_age = min(oldest_age, now - self._last_ack_progress_at)if oldest is not None and not ack_paused and oldest_age > ACK_STALL_SECONDS:LOGGER.warning("%s stopped acknowledging input: oldest seq %d, last acked seq %d, %d unacknowledged",@@ -786,19 +795,32 @@ class OutboundLink:return self._enqueue(message, seq=True)def _enqueue(self, message, seq):- size = _weight(message)with self._cond:- if not self._live or len(self._outbox) >= QUEUE_LIMIT or self._queued_bytes + size > QUEUE_BYTES:+ if not self._live:return False- self._queued_bytes += sizeif seq:- self._seq += 1data = dict(message.get("data") or {})- data["seq"] = self._seq+ data["seq"] = self._seq + 1message = {"type": message["type"], "data": data}+ merged = None+ if seq and self._outbox:+ merged = protocol.coalesce_mousemove(self._outbox[-1], message, preserve_path="motion_path" in self._caps)+ previous_size = _weight(self._outbox[-1]) if merged is not None else 0+ added_size = _weight(merged) - previous_size if merged is not None else _weight(message)+ if ((merged is None and len(self._outbox) >= QUEUE_LIMIT)+ or self._queued_bytes + added_size > QUEUE_BYTES):+ return False+ self._queued_bytes += added_size+ if seq:+ self._seq += 1self.last_sent_seq = self._seqself._queued_at[self._seq] = time.monotonic()- self._outbox.append(message)+ if merged is not None:+ old_seq = self._outbox[-1]["data"]["seq"]+ self._queued_at[self._seq] = self._queued_at.pop(old_seq)+ self._outbox[-1] = merged+ else:+ self._outbox.append(message)self._cond.notify()return True@@ -806,7 +828,9 @@ class OutboundLink:try:while True:with self._cond:- while not self._outbox or self._stall.is_set():+ while (not self._outbox or self._stall.is_set()+ or (len(self._sent_at) >= INPUT_WINDOW+ and self._outbox[0].get("type") in protocol.INPUT_TYPES)):if self._sock is not sock:returnwaited_at = time.monotonic()@@ -869,6 +893,8 @@ class OutboundLink:if seq > self._written_seq:raise protocol.ProtocolError("ack is ahead of anything sent")advanced = seq > self._last_ack_seq+ if advanced and seq > 0:+ self._last_ack_progress_at = nowself._last_ack_seq = seqself.last_ack_at = nowsent = None@@ -883,6 +909,7 @@ class OutboundLink:self._period.append((sample, held))while self._samples and now - self._samples[0][0] > WINDOW_SECONDS:self._samples.popleft()+ self._cond.notify_all()self._locked = ack["locked"]@property@@ -895,17 +922,17 @@ class OutboundLink:with self._lock:return [sample for at, sample in self._samples if now - at <= min(max_age, WINDOW_SECONDS)]- # Following a peer to a new address (section 6)+ # Following a peer to a new endpoint (section 6)def follow(self, machines):"""`machines`: what discovery hears, dicts with `name`, `address` and, while that machine shows- a code, `id`. Only an address learnt into an empty entry may follow discovery; saved choices,+ a code, `id`. Only an endpoint learnt into an empty entry may follow discovery; saved choices,including older entries without provenance, stay put. A link down for ten seconds is- tried once at the address of a beacon with this- entry's exact name, at its saved port, at most every thirty seconds. The address is saved only- once the link authenticates. Two machines may share a name, so a beacon whose `id` is another- machine's is passed over, one at another paired machine's saved address is tried after the- rest (the two may have swapped addresses), and several are tried in turn rather than the+ tried once at a beacon endpoint with this entry's exact name, at most every thirty seconds.+ A beacon without a port uses the saved port. The endpoint is saved only once the link+ authenticates. Two machines may share a name, so a beacon whose `id` is another machine's+ is passed over, one at another paired machine's saved endpoint is tried after the+ rest (the two may have swapped endpoints), and several are tried in turn rather than thefirst for ever."""if self._live or self.key_id is None:return@@ -919,19 +946,30 @@ class OutboundLink:returnif entry.get("host_pinned") is not False:return- others = {peer.get("host") for peer in self._book.peers() if peer.get("token") != self.token}+ others = {(peer.get("host"), peer.get("port")) for peer in self._book.peers()+ if peer.get("token") != self.token}own_id = entry.get("id")- found = [m["address"] for m in machines- if m.get("name") == entry["name"] and m.get("address") and m["address"] != entry.get("host")- and not (own_id and m.get("id") and m["id"] != own_id)]- found = [address for address in found if address not in others] + [address for address in found if address in others]+ found = []+ for machine in machines:+ if not isinstance(machine, dict) or machine.get("name") != entry["name"]:+ continue+ address = machine.get("address")+ port = machine.get("port", entry.get("port"))+ if (not isinstance(address, str) or not address or isinstance(port, bool)+ or not isinstance(port, int) or not 1 <= port <= 65535+ or (address, port) == (entry.get("host"), entry.get("port"))+ or (own_id and machine.get("id") and machine["id"] != own_id)):+ continue+ if (address, port) not in found:+ found.append((address, port))+ found = [endpoint for endpoint in found if endpoint not in others] + [endpoint for endpoint in found if endpoint in others]if not found:return- address = found[(found.index(self._followed_to) + 1) % len(found)] if self._followed_to in found else found[0]+ endpoint = found[(found.index(self._followed_to) + 1) % len(found)] if self._followed_to in found else found[0]self._followed_at = now- self._followed_to = address+ self._followed_to = endpointwith self._lock:- self._try_host = address+ self._try_host, self._try_port = endpointself._wake.set()@@ -968,6 +1006,8 @@ class _Interruptible:def _weight(message):"""About how many bytes a queued message holds: a clipboard's text and image, else nothing."""+ if message.get("type") == protocol.MSG_MOUSEMOVE:+ return len((message.get("data") or {}).get("samples", ())) * 32if message.get("type") != protocol.MSG_CLIPBOARD:return 0data = message.get("data") or {}diff --git a/core/pairing.py b/core/pairing.pyindex af38b80..80a89c3 100644--- a/core/pairing.py+++ b/core/pairing.py@@ -333,7 +333,7 @@ def peer_entry(identity: bytes, name: str, platform: str, port: int, token: str,"in_use": True,"side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": int(paired_at),"linked": False, "from_1_4": False,- # Pairing learnt this address; only one typed in Settings is a choice that discovery must not replace.+ # Discovery and reverse pairing learn an address; a requester may pin a typed choice."host_pinned": False,}@@ -936,6 +936,23 @@ class PairingClient:return peer_entry(self.host_identity, self.host_name, self.host_platform, self.host_port, self._token, address, self.wall())+def discovery_endpoint(machine):+ return machine.get("address"), machine.get("reply_port", PAIRING_PORT)+++def refreshed_discovery(machine, machines):+ if machine is None:+ return None+ endpoint = discovery_endpoint(machine)+ exact = next((item for item in machines if discovery_endpoint(item) == endpoint), None)+ if exact is not None:+ return exact+ candidates = [item for item in machines+ if all(item.get(key) == machine.get(key) for key in ("address", "port", "name"))+ and not (machine.get("id") and item.get("id") and item["id"] != machine["id"])]+ return candidates[0] if len(candidates) == 1 else None++def _udp_socket(bind_port: int) -> socket.socket:sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)try:@@ -1649,10 +1666,13 @@ class Discovery:def _beacon_entry(self, message: dict, address):name = message.get("name")port = message.get("port")+ pair_port = message.get("pair_port", address[1])pair_id = message.get("pair")version = message.get("pairing")if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:return None+ if isinstance(pair_port, bool) or not isinstance(pair_port, int) or not 1 <= pair_port <= 65535:+ return Nonetry:name.encode("utf-8")except UnicodeError:@@ -1662,7 +1682,7 @@ class Discovery:"name": name[:64] or address[0],"address": address[0],"port": port,- "reply_port": address[1],+ "reply_port": pair_port,"pair_id": pair_id if isinstance(pair_id, str) and pair_id.isascii() and 0 < len(pair_id) <= MAX_PAIR_ID_CHARS else None,# A beacon from 1.4.2 or earlier carries no number: that is version 1."pairing": version if isinstance(version, int) and not isinstance(version, bool) else 1,@@ -1671,7 +1691,14 @@ class Discovery:def _remember(self, address, entry: dict) -> None:with self._lock:- if address[0] not in self._seen and len(self._seen) >= MAX_SEEN_HOSTS:+ # Routed replies use disposable source sockets; the advertised listener identifies+ # the app, whilst pair_port keeps requests aimed at its live pairing socket.+ endpoint = (address[0], entry["port"])+ for key in [key for key, known in self._seen.items()+ if key != endpoint and key[0] == address[0]+ and known["reply_port"] == entry["reply_port"]]:+ del self._seen[key]+ if endpoint not in self._seen and len(self._seen) >= MAX_SEEN_HOSTS:# The list is only read while the window is open, so what has gone quiet is# cleared here too. Beacons from made-up addresses then cost a fixed amount of# memory and no more.@@ -1683,8 +1710,9 @@ class Discovery:# can crowd real PCs off the list that way, which is a denial like any# other here, so the one address the user typed is never the one to go.wanted = self._finding[0] if self._finding else None- del self._seen[min((key for key in self._seen if key != wanted), key=lambda key: self._seen[key]["seen_at"])]- self._seen[address[0]] = entry+ candidates = [key for key in self._seen if key[0] != wanted] or list(self._seen)+ del self._seen[min(candidates, key=lambda key: self._seen[key]["seen_at"])]+ self._seen[endpoint] = entrydef _shut(sock) -> None:@@ -1843,6 +1871,7 @@ class PairingService(Discovery):self._nearby = Noneself._nearby_choice = Falseself._nearby_next = 0.0+ self.active_discovery = Falsedef begin_nearby(self) -> None:from .easy_pair import EasyPairWindow@@ -2159,6 +2188,7 @@ class PairingService(Discovery):with self._host_lock:from .easy_pair import PAIR_MODESbeacon = self.host.beacon(self.port_getter())+ beacon["pair_port"] = self.bind_portbeacon["pair_modes"] = PAIR_MODES.copy()if self._nearby is not None and self._nearby.active:beacon["nearby"] = self._nearby.window@@ -2176,6 +2206,8 @@ class PairingService(Discovery):for target in targets:try:sock.sendto(beacon, target)+ if self.active_discovery:+ sock.sendto(encode({"type": MSG_FIND}), target)delivered += 1except OSError:continue@@ -2334,7 +2366,7 @@ class PairingService(Discovery):resolved = socket.getaddrinfo((address or "").strip(), port, socket.AF_INET, socket.SOCK_STREAM)[0][4][0]except (OSError, IndexError, UnicodeError) as exc:raise PairingError("no_answer") from exc- return self._pair_tcp(resolved, port, code, None)+ return self._pair_tcp(resolved, port, code, None, pin_address=True)def pair_by_qr(self, text: str) -> dict:"""The exchange over TCP from a QR's text, with its secret and `qr: 1`. A QR of a machine@@ -2346,7 +2378,7 @@ class PairingService(Discovery):return PairingClient(pair_id, code, self.name, self.identity, version=PAIRING_V3, platform=self.platform,port=self.port_getter(), qr_secret=secret, peers=self._peer_entries, wall=self.wall)- def _pair_tcp(self, address: str, port: int, code: str, secret) -> dict:+ def _pair_tcp(self, address: str, port: int, code: str, secret, *, pin_address=False) -> dict:with self._attempt(code):peers = self._peer_entries()if len(peers) >= MAX_PEERS and not any(_dormant_repairable(peer) for peer in peers):@@ -2380,7 +2412,7 @@ class PairingService(Discovery):client.finish(_recv_frame(sock, deadline))except OSError as exc:raise PairingError("no_answer") from exc- return self._keep(client, address)+ return self._keep(client, address, pin_address=pin_address)def _not_paired_already(self, identity) -> None:"""A QR of a machine this one has paired already: the caller tries its link at that@@ -2394,13 +2426,15 @@ class PairingService(Discovery):if not _dormant_repairable(known):raise AlreadyPaired(known)- def _keep(self, client: PairingClient, address: str) -> dict:+ def _keep(self, client: PairingClient, address: str, *, pin_address=False) -> dict:"""The requester writes its entry once Td has checked out. The checks are made again,under the lock the host's side stores under, because this machine may have hosted orrequested another pairing since: two at once must not pass 32 peers or share an id. Afailed write leaves the host an entry that never links, which pairing again within tenminutes replaces."""entry = client.entry(address)+ if pin_address and entry["host"]:+ entry["host_pinned"] = Truewith self._host_lock:peers = self._peer_entries()known, replaced = _find_known(peers, self.identity, client.host_identity, client.host_name, client.host_platform, self.wall())diff --git a/core/peerlist.py b/core/peerlist.pyindex 85e438e..81cb4e7 100644--- a/core/peerlist.py+++ b/core/peerlist.py@@ -175,11 +175,17 @@ def add_peer(settings: dict, entry: dict, replaced: Optional[dict] = None) -> Nofor field in ("label", "left_out", "left_out_ways", "side", "side_set_at", "side_by"):if field in old:entry[field] = copy.deepcopy(old[field])+ # A re-pair may authenticate over another interface without changing the chosen one.+ # A newly typed pairing address is an explicit replacement of that choice.+ if old.get("host") and old.get("host_pinned") is not False and entry.get("host_pinned") is not True:+ entry.update(host=old["host"], port=old["port"], host_pinned=True)if (replaced is not None and replaced.get("from_1_4") is True and replaced.get("id") == "" and entry.get("id")and replaced.get("host") and replaced.get("host") == entry.get("host")and replaced.get("platform") == entry.get("platform")):entry.update({field: replaced.get(field, default) for field, default in(("side", ""), ("side_set_at", 0), ("side_by", ""))})+ if replaced.get("host_pinned") is not False:+ entry["host_pinned"] = Truefor zone in settings["zones"]:if zone.get("peer") == "":zone["peer"] = entry["id"]diff --git a/core/portable_runtime.py b/core/portable_runtime.pynew file mode 100644index 0000000..c3e4639--- /dev/null+++ b/core/portable_runtime.py@@ -0,0 +1,112 @@+"""Run-from-folder paths and process-only portable state; no native imports."""++import hashlib+import os+from pathlib import Path+import socket+import sys+import tempfile++MARKER = "Beamer.portable"+_root = None+store = None+listener = None+_port = None+++def portable_root(executable=None, frozen=None):+ frozen = getattr(sys, "frozen", False) if frozen is None else frozen+ root = Path(executable or sys.executable).resolve().parent+ return root if frozen and (root / MARKER).is_file() else None+++def root():+ return _root if _root is not None else portable_root()+++def enabled():+ return root() is not None+++def data_path():+ directory = root()+ if directory is None:+ raise OSError("Beamer is not running in portable mode")+ return directory / "data"+++def settings_path():+ return data_path() / "settings.beamer"+++def instance_suffix():+ directory = root()+ if directory is None:+ return ""+ return ".Portable." + hashlib.sha256(os.path.normcase(str(directory)).encode("utf-8")).hexdigest()[:24]+++def initialise(require_marker=False):+ global _root+ detected = portable_root()+ _root = detected.resolve() if detected is not None else None+ if _root is None:+ if require_marker:+ raise OSError("Keep Beamer.portable beside Beamer.exe to run the portable app")+ return+ # Establish writable storage before Qt, logging or settings can choose a host fallback.+ directory = data_path()+ directory.mkdir(exist_ok=True)+ for child in (directory, directory / "tmp", directory / "cache",+ directory / "cache" / "local", directory / "cache" / "roaming"):+ child.mkdir(exist_ok=True)+ if not child.resolve().is_relative_to(_root):+ raise OSError("Portable data must stay inside the app folder")+ with tempfile.TemporaryFile(dir=child):+ pass+ temporary = str(directory / "tmp")+ for key in ("TMP", "TEMP", "TMPDIR"):+ os.environ[key] = temporary+ os.environ["XDG_CACHE_HOME"] = str(directory / "cache")+ # Dependencies must not inherit host profile locations.+ os.environ["LOCALAPPDATA"] = str(directory / "cache" / "local")+ os.environ["APPDATA"] = str(directory / "cache" / "roaming")+ tempfile.tempdir = temporary+ sys.dont_write_bytecode = True+++def reserve_listener(preferred=0):+ """Keep the OS-selected TCP port reserved until LinkResponder takes this socket."""+ global listener, _port+ if _port is not None:+ return _port+ if listener is None:+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)+ if type(preferred) is not int or not 0 <= preferred <= 65535:+ preferred = 0+ try:+ sock.bind(("0.0.0.0", preferred))+ except OSError:+ if not preferred:+ raise+ sock.bind(("0.0.0.0", 0))+ except BaseException:+ sock.close()+ raise+ listener = sock+ _port = listener.getsockname()[1]+ return _port+++def close():+ global store, listener, _port+ if store is not None:+ store.lock()+ store = None+ if listener is not None:+ listener.close()+ listener = None+ _port = Nonediff --git a/core/portable_store.py b/core/portable_store.pynew file mode 100644index 0000000..d122e3d--- /dev/null+++ b/core/portable_store.py@@ -0,0 +1,201 @@+"""Passphrase-protected portable settings; no platform credential store is used."""++import json+import os+import stat+import tempfile+import threading+from pathlib import Path++from nacl.exceptions import CryptoError+from nacl.pwhash import argon2id+from nacl.secret import SecretBox+from nacl.utils import random+++_MAGIC = b"BEAMER-PORTABLE\x00\x01"+KDF_OPSLIMIT = argon2id.OPSLIMIT_INTERACTIVE+KDF_MEMLIMIT = argon2id.MEMLIMIT_INTERACTIVE+MAX_STATE_BYTES = 1024 * 1024+MAX_ENVELOPE_BYTES = (len(_MAGIC) + argon2id.SALTBYTES + SecretBox.NONCE_SIZE+ + SecretBox.MACBYTES + MAX_STATE_BYTES)+_MAX_DEPTH = 32+++class PortableStoreError(ValueError):+ """Portable state cannot be used safely."""+++class PortableStoreLockedError(PortableStoreError):+ """An unlock is required before reading or saving settings."""+++class PortableStoreUnlockError(PortableStoreError):+ """The passphrase or the existing encrypted state is invalid."""+++def _validate(value, depth=0):+ if depth > _MAX_DEPTH:+ raise ValueError("Portable settings are nested too deeply")+ if isinstance(value, dict):+ for key, item in value.items():+ if not isinstance(key, str):+ raise ValueError("Portable settings keys must be strings")+ _validate(item, depth + 1)+ elif isinstance(value, list):+ for item in value:+ _validate(item, depth + 1)+ elif value is not None and not isinstance(value, (str, int, float, bool)):+ raise ValueError("Portable settings must contain JSON values")+++def _encode(value):+ if not isinstance(value, dict):+ raise ValueError("Portable settings must be an object")+ _validate(value)+ encoded = json.dumps(value, ensure_ascii=False, allow_nan=False,+ separators=(",", ":")).encode("utf-8")+ if len(encoded) > MAX_STATE_BYTES:+ raise ValueError("Portable settings exceed the size limit")+ return encoded+++def _unique_object(pairs):+ value = {}+ for key, item in pairs:+ if key in value:+ raise ValueError("Duplicate setting")+ value[key] = item+ return value+++def _invalid_constant(value):+ raise ValueError("Invalid JSON number")+++def _decode(encoded):+ if len(encoded) > MAX_STATE_BYTES:+ raise ValueError("Portable settings exceed the size limit")+ value = json.loads(encoded, object_pairs_hook=_unique_object,+ parse_constant=_invalid_constant)+ _encode(value)+ return value+++class PortableStore:+ def __init__(self, path):+ self.path = Path(path)+ self._key = None+ self._salt = None+ self._data = None+ self._mutex = threading.RLock()++ @property+ def exists(self):+ # A dangling link is still existing state and must never trigger a reset.+ return os.path.lexists(self.path)++ @property+ def is_unlocked(self):+ return self._key is not None++ def unlock(self, passphrase):+ with self._mutex:+ self.lock()+ if not isinstance(passphrase, str):+ raise ValueError("Enter a passphrase")+ try:+ password = passphrase.encode("utf-8")+ except UnicodeError as exc:+ raise ValueError("Invalid passphrase") from exc+ if not 1 <= len(password) <= 1024:+ raise ValueError("Passphrase must contain 1 to 1024 UTF-8 bytes")+ if self.exists:+ envelope = self._read_envelope()+ salt = envelope[len(_MAGIC):len(_MAGIC) + argon2id.SALTBYTES]+ key = self._derive(password, salt)+ try:+ encrypted = envelope[len(_MAGIC) + argon2id.SALTBYTES:]+ data = _decode(SecretBox(bytes(key)).decrypt(encrypted))+ except (CryptoError, ValueError, UnicodeError, RecursionError) as exc:+ key[:] = b"\x00" * len(key)+ raise PortableStoreUnlockError(+ "Unable to unlock portable settings; check the passphrase and vault") from exc+ else:+ salt = random(argon2id.SALTBYTES)+ key = self._derive(password, salt)+ data = {}+ try:+ self._save(_encode(data), key, salt, create=True)+ except Exception:+ key[:] = b"\x00" * len(key)+ raise+ self._key, self._salt, self._data = key, salt, data++ @staticmethod+ def _derive(password, salt):+ # The envelope carries no attacker-controlled KDF cost parameters.+ return bytearray(argon2id.kdf(SecretBox.KEY_SIZE, password, salt,+ opslimit=KDF_OPSLIMIT, memlimit=KDF_MEMLIMIT))++ def _read_envelope(self):+ try:+ if self.path.is_symlink():+ raise ValueError("Linked vaults are not supported")+ if not stat.S_ISREG(self.path.stat().st_mode):+ raise ValueError("Invalid vault type")+ with self.path.open("rb") as stream:+ metadata = os.fstat(stream.fileno())+ if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > MAX_ENVELOPE_BYTES:+ raise ValueError("Invalid vault size or type")+ envelope = stream.read(MAX_ENVELOPE_BYTES + 1)+ minimum = (len(_MAGIC) + argon2id.SALTBYTES + SecretBox.NONCE_SIZE+ + SecretBox.MACBYTES + 2)+ if not minimum <= len(envelope) <= MAX_ENVELOPE_BYTES or not envelope.startswith(_MAGIC):+ raise ValueError("Invalid or unsupported vault")+ return envelope+ except (OSError, ValueError) as exc:+ raise PortableStoreUnlockError("Portable settings are unreadable or unsupported") from exc++ def read(self):+ with self._mutex:+ self._require_unlocked()+ return _decode(_encode(self._data))++ def write(self, value):+ with self._mutex:+ self._require_unlocked()+ encoded = _encode(value)+ self._save(encoded, self._key, self._salt)+ self._data = _decode(encoded)++ def _save(self, encoded, key, salt, create=False):+ envelope = _MAGIC + salt + bytes(SecretBox(bytes(key)).encrypt(encoded))+ descriptor, temporary = tempfile.mkstemp(prefix=".beamer-vault-", suffix=".tmp",+ dir=self.path.parent)+ try:+ with os.fdopen(descriptor, "wb") as stream:+ stream.write(envelope)+ stream.flush()+ os.fsync(stream.fileno())+ if create:+ # Windows rename refuses an existing destination; POSIX rename replaces it.+ if os.name == "nt":+ os.rename(temporary, self.path)+ else:+ os.link(temporary, self.path)+ else:+ os.replace(temporary, self.path)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)++ def _require_unlocked(self):+ if self._key is None:+ raise PortableStoreLockedError("Unlock portable settings before reading or saving")++ def lock(self):+ with self._mutex:+ if self._key is not None:+ self._key[:] = b"\x00" * len(self._key)+ self._key = self._salt = self._data = Nonediff --git a/core/protocol.py b/core/protocol.pyindex ac31a06..ec0920f 100644--- a/core/protocol.py+++ b/core/protocol.py@@ -448,6 +448,7 @@ MAX_NAME_CHARS = 48MAX_ASCII_FIELD = 32MAX_KEY_CHARS = 32MOVE_MAX = 65535+MOTION_SAMPLES_MAX = 64DEFAULT_RESISTANCE_PX = 120MAX_RESISTANCE_PX = 1000TEXT_MAX_BYTES = 4096@@ -1178,6 +1179,35 @@ def mousemove_msg(dx: int, dy: int, seq: int = None) -> dict:return _with_seq(MSG_MOUSEMOVE, {"dx": dx, "dy": dy}, seq)+def coalesce_mousemove(previous: dict, current: dict, *, preserve_path=True):+ """Sum relative travel while retaining the bounded path needed by crossing geometry."""+ if previous.get("type") != MSG_MOUSEMOVE or current.get("type") != MSG_MOUSEMOVE:+ return None+ before, after = previous.get("data") or {}, current.get("data") or {}+ if ("seq" in before) != ("seq" in after):+ return None+ if before.get("seq") is not None and after.get("seq", 0) <= before["seq"]:+ return None+ for axis in ("dx", "dy"):+ if not _int(before.get(axis), -MOVE_MAX, MOVE_MAX) or not _int(after.get(axis), -MOVE_MAX, MOVE_MAX):+ return None+ if not preserve_path and ((before[axis] > 0) != (after[axis] > 0)+ or (before[axis] < 0) != (after[axis] < 0)):+ return None+ if not preserve_path and (before["dx"] and before["dy"] or after["dx"] and after["dy"]):+ return None+ dx, dy = before["dx"] + after["dx"], before["dy"] + after["dy"]+ if abs(dx) > MOVE_MAX or abs(dy) > MOVE_MAX:+ return None+ merged = mousemove_msg(dx, dy, after.get("seq"))+ if preserve_path:+ samples = before.get("samples", [[before["dx"], before["dy"]]]) + after.get("samples", [[after["dx"], after["dy"]]])+ if len(samples) > MOTION_SAMPLES_MAX:+ return None+ merged["data"]["samples"] = samples+ return merged++def text_msg(text: str, seq: int = None) -> dict:return _with_seq(MSG_TEXT, {"text": text}, seq)@@ -1202,6 +1232,15 @@ def read_input(message):if not _int(data.get("dx"), -MOVE_MAX, MOVE_MAX) or not _int(data.get("dy"), -MOVE_MAX, MOVE_MAX):return Noneread.update(dx=data["dx"], dy=data["dy"])+ if "samples" in data:+ samples = data["samples"]+ if (not isinstance(samples, list) or not 1 <= len(samples) <= MOTION_SAMPLES_MAX+ or any(not isinstance(sample, list) or len(sample) != 2+ or not all(_int(value, -MOVE_MAX, MOVE_MAX) for value in sample) for sample in samples)+ or sum(sample[0] for sample in samples) != data["dx"]+ or sum(sample[1] for sample in samples) != data["dy"]):+ return None+ read["samples"] = sampleselif kind in (MSG_MOUSEDOWN, MSG_MOUSEUP):if not _one_of(data.get("button"), BUTTONS):return Nonediff --git a/core/receiver.py b/core/receiver.pyindex b8596f1..1b71093 100644--- a/core/receiver.py+++ b/core/receiver.py@@ -347,6 +347,7 @@ class PeerBook:if "host" in changes:if entry.get("host") and entry.get("host_pinned") is not False:changes.pop("host")+ changes.pop("port", None)elif changes["host"] and not entry.get("host"):changes["host_pinned"] = Falseentry.update(changes)@@ -430,20 +431,14 @@ class _Link:if isinstance(message, dict) and message.get("type") == protocol.MSG_MOUSEMOVE else None)with self.cond:while not self.closed.is_set():- if move is not None and not (move["dx"] and move["dy"]) and self.inbox:- previous = protocol.read_input(self.inbox[-1][0])- if (previous is not None and previous["type"] == protocol.MSG_MOUSEMOVE- and move["seq"] > previous["seq"]- and (previous["dx"] > 0) == (move["dx"] > 0)- and (previous["dx"] < 0) == (move["dx"] < 0)- and (previous["dy"] > 0) == (move["dy"] > 0)- and (previous["dy"] < 0) == (move["dy"] < 0)):- dx, dy = previous["dx"] + move["dx"], previous["dy"] + move["dy"]- if abs(dx) <= protocol.MOVE_MAX and abs(dy) <= protocol.MOVE_MAX:- # Wire motion is relative: keeping just the last delta loses travel.- # Diagonal samples must retain their tangent positions and individual- # corner pressure. Reversals and axis changes stay separate too.- self.inbox[-1][0] = protocol.mousemove_msg(dx, dy, move["seq"])+ if move is not None and self.inbox:+ merged = protocol.coalesce_mousemove(self.inbox[-1][0], message)+ if merged is not None:+ added_size = len(protocol.dumps_message(merged)) - len(protocol.dumps_message(self.inbox[-1][0]))+ if self.inbox_bytes + added_size <= INBOX_BYTES:+ self.inbox[-1][0] = merged+ self.inbox[-1][1] += added_size+ self.inbox_bytes += added_sizereturn Trueif len(self.inbox) < INBOX_LIMIT and self.inbox_bytes + size <= INBOX_BYTES:break@@ -545,6 +540,7 @@ class LinkResponder:paired_callback=None,link_callback=None,announce=None,+ listener=None,) -> None:self._book = bookself._identity = identity@@ -564,6 +560,7 @@ class LinkResponder:"link": link_callback,}self._announce = announce or (lambda peer: [])+ self._prebound_listener = listener# This machine's speed for a peer's pointer and scroll, and whether# its edges are held (Pause crossing, a full-screen app), which keeps the zones from firing.self.input_scale: Optional[InputScale] = None@@ -735,6 +732,9 @@ class LinkResponder:_close_socket(listener)def _bind(self, port: int, stop_event: threading.Event):+ if self._prebound_listener is not None:+ listener, self._prebound_listener = self._prebound_listener, None+ return listenerreported = Falsewhile not stop_event.is_set():listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)@@ -1103,11 +1103,11 @@ class LinkResponder:if self._releases_held(link, read):self._inject_timed_locked(link, read)else:- zones_at = time.monotonic()- consumed = read["type"] == protocol.MSG_MOUSEMOVE and self._zones_locked(link, read, after)- link.timing.add("zones", time.monotonic() - zones_at)- if not consumed:- self._inject_timed_locked(link, read)+ samples = read.get("samples")+ if samples:+ self._apply_motion_path_locked(link, read, after)+ else:+ self._apply_input_locked(link, read, after)except Exception:LOGGER.exception("Input from %s could not be injected", link.name)self._input_error_status(link)@@ -1117,6 +1117,71 @@ class LinkResponder:self._run(after)link.timing.add("input_callbacks", time.monotonic() - callbacks_at)+ def _apply_motion_path_locked(self, link, read, after):+ desktop = self._desktop_module()+ pointer, monitors = desktop.cursor_position(), desktop.monitors()+ display_map = getattr(desktop, "display_map", lambda: {})()+ geometry = (monitors, pointer, display_map)+ scale = max(1.0, self.input_scale.pointer if self.input_scale is not None else 1.0)+ radius_x = sum(abs(dx) for dx, _dy in read["samples"]) * scale+ radius_y = sum(abs(dy) for _dx, dy in read["samples"]) * scale+ # Fractional scaling can contribute another pixel; display edges accept a 1.5 px+ # approach. A stationary axis needs neither margin and can stay against an unused wall.+ if radius_x:+ radius_x += 2.5+ if radius_y:+ radius_y += 2.5++ def inside(screen):+ x, y = pointer+ return ((screen.x + radius_x < x < screen.right - radius_x if radius_x else screen.x <= x <= screen.right)+ and (screen.y + radius_y < y < screen.bottom - radius_y if radius_y else screen.y <= y <= screen.bottom))++ safe = any(inside(screen) for screen in monitors)+ if any(kind == "button" for kind, _name in link.held):+ # A straight axis-aligned drag retains the old fast path; bends and reversals+ # must reach the application as individual movements, even away from walls.+ safe = safe and (+ all(dy == 0 and (dx == 0 or dx * read["dx"] > 0) for dx, dy in read["samples"])+ or all(dx == 0 and (dy == 0 or dy * read["dy"] > 0) for dx, dy in read["samples"]))+ for _peer, model in self._armed:+ if model.display:+ screen = display_map.get(model.display) if isinstance(display_map, dict) else None+ safe = safe and isinstance(screen, crossing.Rect) and inside(screen)+ if safe and model._at_edge(monitors, pointer, display_map):+ safe = False+ # Every sample still feeds pressure and decay. Native movement is combined only when+ # no moving axis can reach a wall and no drag needs the intermediate path.+ # A stationary axis may already be against an unused wall.+ scaled_dx = scaled_dy = 0+ for dx, dy in read["samples"]:+ if self._owner is not link:+ return+ segment = dict(read, dx=dx, dy=dy)+ was_live = self._zones_live+ if safe:+ self._zones_locked(link, segment, after, geometry=geometry)+ if self.input_scale is not None:+ part_dx, part_dy = self.input_scale.move(dx, dy)+ scaled_dx += part_dx+ scaled_dy += part_dy+ else:+ self._apply_input_locked(link, segment, after)+ if was_live and not self._zones_live:+ return+ if safe:+ if self.input_scale is not None:+ self._inject_timed_locked(link, dict(read, dx=scaled_dx, dy=scaled_dy), scaled=True)+ else:+ self._inject_timed_locked(link, read)++ def _apply_input_locked(self, link, read, after):+ zones_at = time.monotonic()+ consumed = read["type"] == protocol.MSG_MOUSEMOVE and self._zones_locked(link, read, after)+ link.timing.add("zones", time.monotonic() - zones_at)+ if not consumed:+ self._inject_timed_locked(link, read)+def _record_incoming_move(self, link: _Link, read: dict) -> None:now = time.monotonic()if link.incoming_moves_at is None or now - link.incoming_move_last_at > 1.0:@@ -1146,10 +1211,10 @@ class LinkResponder:who = peerlist.label_for(self._settings_now()[0], peer_id=protocol.id_text(link.peer_id)) or link.nameself._set_status(ServerState.CONNECTED, tr("Input error from {name}; see log").format(name=who))- def _inject_timed_locked(self, link: _Link, read: dict) -> None:+ def _inject_timed_locked(self, link: _Link, read: dict, *, scaled=False) -> None:began = time.monotonic()try:- self._inject_locked(link, read)+ self._inject_locked(link, read, scaled=scaled)finally:elapsed = time.monotonic() - beganlink.timing.add("inject", elapsed)@@ -1188,7 +1253,7 @@ class LinkResponder:return "gestures" in link.own_capsreturn True- def _inject_locked(self, link: _Link, read: dict) -> None:+ def _inject_locked(self, link: _Link, read: dict, *, scaled=False) -> None:injector = self._injector_module()kind = read["type"]if kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):@@ -1200,7 +1265,9 @@ class LinkResponder:injector.inject_key(read["key"], down=down, us=read["us"])elif kind == protocol.MSG_MOUSEMOVE:dx, dy = read["dx"], read["dy"]- if self.input_scale is not None and (dx or dy):+ if scaled and not (dx or dy):+ return+ if not scaled and self.input_scale is not None and (dx or dy):dx, dy = self.input_scale.move(dx, dy)if not (dx or dy):return@@ -1335,14 +1402,17 @@ class LinkResponder:def _disarm_locked(self) -> None:self._armed, self._zones_live = [], False- def _zones_locked(self, link: _Link, read: dict, after: list) -> bool:+ def _zones_locked(self, link: _Link, read: dict, after: list, geometry=None) -> bool:"""Feeds one mouse move to the armed zones, first that holds the pointer winning. True whenthe move was used at an edge (held there, or crossed and the owner sent a `switch`)."""if not self._armed or self.edges_held():return Falsedesktop = self._desktop_module()- display_map = getattr(desktop, "display_map", lambda: {})()- monitors, pointer = desktop.monitors(), desktop.cursor_position()+ if geometry is None:+ display_map = getattr(desktop, "display_map", lambda: {})()+ monitors, pointer = desktop.monitors(), desktop.cursor_position()+ else:+ monitors, pointer, display_map = geometryfor peer, model in self._armed:outcome = model.feed(monitors, pointer, float(read["dx"]), float(read["dy"]), display_map=display_map)if outcome.action == crossing.PASS:@@ -1734,12 +1804,12 @@ class LinkResponder:if self._clipboard_stamp() != stamp:returntry:- text, image = self._clipboard_module().get_contents()+ clipboard = self._clipboard_module()+ text, image = getattr(clipboard, "read_contents", clipboard.get_contents)()except Exception:- text, image = None, Noneif attempt == CLIPBOARD_RETRY_ATTEMPTS - 1:LOGGER.exception("Could not read the clipboard for %s", link.name)- if text is not None or image is not None:+ else:breakif attempt < CLIPBOARD_RETRY_ATTEMPTS - 1:time.sleep(CLIPBOARD_RETRY_SECONDS)diff --git a/core/tests/test_address_choice_commit.py b/core/tests/test_address_choice_commit.pynew file mode 100644index 0000000..8595964--- /dev/null+++ b/core/tests/test_address_choice_commit.py@@ -0,0 +1,29 @@+"""Explicit address commits use the pin signal, including an unchanged address."""++from types import SimpleNamespace+import unittest+from unittest import mock++from core.tests.app_methods import load_methods+++class AddressCommitTests(unittest.TestCase):+ def test_mac_connection_commit_marks_the_same_address_as_explicit(self):+ cfg = SimpleNamespace(host="192.0.2.10")+ store = mock.Mock()+ methods = load_methods("mac_app/kvm_bridge_app.py", "ControlWindow", ("connect_",),+ {"config_to_raw": lambda _: {"host": cfg.host}, "tr": lambda text: text,+ "SettingsError": ValueError})+ window = methods()+ window.controller = SimpleNamespace(cfg=cfg, update_config=mock.Mock())+ window.settings_store = store+ window._host_text = lambda: cfg.host+ window.port_field = SimpleNamespace(stringValue=lambda: "24820")+ window._say = mock.Mock()+ window.connect_(None)+ self.assertEqual(store.save.call_args.kwargs, {"pin_address": True})+ self.assertNotIn("pc_name", store.save.call_args.args[0])+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_clipboard_reliability.py b/core/tests/test_clipboard_reliability.pyindex c61c0ca..ae346e5 100644--- a/core/tests/test_clipboard_reliability.py+++ b/core/tests/test_clipboard_reliability.py@@ -163,14 +163,19 @@ class ClipboardReliability(unittest.TestCase):self.responder._clipboard_worker()self.assertEqual(self.sent, [protocol.clipboard_msg("local immediately after write")])- def test_a_contended_return_read_recovers_at_the_same_stamp(self):- original = self.clipboard.get_contents- reads = iter([False, True])-- def read():- return original() if next(reads) else (None, None)+ def test_an_empty_return_read_finishes_without_retrying_or_warning(self):+ with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)) as read, \+ mock.patch.object(receiver.time, "sleep") as sleep, \+ mock.patch.object(receiver.LOGGER, "warning") as warning:+ self.return_clipboard()+ self.assertEqual(self.sent, [])+ self.assertEqual(read.call_count, 1)+ sleep.assert_not_called()+ warning.assert_not_called()- with mock.patch.object(self.clipboard, "get_contents", side_effect=read), \+ def test_a_native_failure_uses_the_strict_reader_and_recovers(self):+ self.clipboard.read_contents = mock.Mock(side_effect=[OSError("clipboard busy"), ("copied remotely", None)])+ with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \mock.patch.object(receiver.time, "sleep"):self.return_clipboard()self.assertEqual(self.sent, [protocol.clipboard_msg("copied remotely")])@@ -190,20 +195,20 @@ class ClipboardReliability(unittest.TestCase):self.assertEqual(self.sent, [protocol.clipboard_msg("copied remotely")])def test_a_local_copy_after_let_go_is_never_read_for_a_return_retry(self):- with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \+ with mock.patch.object(self.clipboard, "get_contents", side_effect=OSError("clipboard busy")), \mock.patch.object(receiver.time, "sleep", side_effect=lambda _: self.clipboard.copy("private local")):self.return_clipboard()self.assertEqual(self.sent, [])self.assertEqual(self.clipboard.text, "private local")def test_a_new_owner_cancels_a_return_retry(self):- with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \+ with mock.patch.object(self.clipboard, "get_contents", side_effect=OSError("clipboard busy")), \mock.patch.object(receiver.time, "sleep", side_effect=lambda _: setattr(self.responder, "_owner", self.link)):self.return_clipboard()self.assertEqual(self.sent, [])def test_a_closed_link_cancels_a_return_retry(self):- with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)), \+ with mock.patch.object(self.clipboard, "get_contents", side_effect=OSError("clipboard busy")), \mock.patch.object(receiver.time, "sleep", side_effect=lambda _: self.link.closed.set()):self.return_clipboard()self.assertEqual(self.sent, [])diff --git a/core/tests/test_dormant_repair.py b/core/tests/test_dormant_repair.pyindex 2ab09d5..9e0b193 100644--- a/core/tests/test_dormant_repair.py+++ b/core/tests/test_dormant_repair.py@@ -109,6 +109,30 @@ class DormantPeerTests(unittest.TestCase):self.assertEqual(self.settings["layout"][PEER], {"x": 20, "y": 30, "w": 160, "h": 100})self.assertNotIn("dormant", repaired)+ def test_repair_keeps_an_explicit_address_even_when_pairing_uses_wifi(self):+ old = self.settings["peers"][0]+ old.update(host="192.0.2.10", port=24821, host_pinned=True)+ repaired = entry(token="new", host="198.51.100.10", port=24820, host_pinned=False)+ peerlist.add_peer(self.settings, repaired, copy.deepcopy(old))+ self.assertEqual((repaired["host"], repaired["port"], repaired["host_pinned"]),+ ("192.0.2.10", 24821, True))++ def test_an_explicit_new_pairing_address_replaces_the_old_pin(self):+ old = self.settings["peers"][0]+ old.update(host="192.0.2.10", port=24821, host_pinned=True)+ repaired = entry(token="new", host="198.51.100.10", port=24820, host_pinned=True)+ peerlist.add_peer(self.settings, repaired, copy.deepcopy(old))+ self.assertEqual((repaired["host"], repaired["port"], repaired["host_pinned"]),+ ("198.51.100.10", 24820, True))++ def test_repair_keeps_a_legacy_saved_address_without_pin_provenance(self):+ old = self.settings["peers"][0]+ old.update(host="192.0.2.10", port=24821)+ repaired = entry(token="new", host="198.51.100.10", port=24820, host_pinned=False)+ peerlist.add_peer(self.settings, repaired, copy.deepcopy(old))+ self.assertEqual((repaired["host"], repaired["port"], repaired["host_pinned"]),+ ("192.0.2.10", 24821, True))+def test_repaired_peer_with_retained_side_and_intent_crosses_at_its_picture_contact(self):old = self.settings["peers"][0]old.update(side="left", side_set_at=42, side_by=OWN)diff --git a/core/tests/test_easy_pair_service.py b/core/tests/test_easy_pair_service.pyindex 7288d27..aef2db5 100644--- a/core/tests/test_easy_pair_service.py+++ b/core/tests/test_easy_pair_service.py@@ -15,6 +15,8 @@ def service(name, ident, clock=None):def note(a, b, address):+ if b.bind_port == 0:+ b.bind_port = address[1]a._note_beacon(pairing.decode(b._beacon()), address)@@ -82,7 +84,7 @@ class EasyPairServiceTests(unittest.TestCase):note(a, c, ("192.0.2.3", 9003))assert a.nearby_status["state"] == "choosing"with a._lock:- a._seen.pop("192.0.2.3")+ a._seen.pop(("192.0.2.3", 24800))a._tick_nearby(None)assert a.nearby_status["state"] == "choosing" and a.nearby_status["peer"] is Nonediff --git a/core/tests/test_i18n_coverage.py b/core/tests/test_i18n_coverage.pyindex e97b096..19d2b19 100644--- a/core/tests/test_i18n_coverage.py+++ b/core/tests/test_i18n_coverage.py@@ -51,7 +51,7 @@ NOT_SHOWN = {"pack", "warning", "append", "__init__", "find_library", "setValue_forHTTPHeaderField_","loadBundle", "lookUpClass", "protocolNamed", "normalize", "lookup", "len","dispatch", "ExecMethod_", "Methods_", "persistentDomainForName_",- "beginActivityWithOptions_reason_", "asset_path", "CreateMutexW", "QKeySequence",+ "beginActivityWithOptions_reason_", "asset_path", "CreateMutexW", "OpenMutexW", "QKeySequence","_turn_off_clashes", "exception", "_force_local", "stringForKey_", "open_dbus_connection", "update","require_version", "_log_helper_failure",}@@ -187,6 +187,19 @@ class I18nCoverageTests(unittest.TestCase):found = hard_coded(path)self.assertEqual(found, ["win_app/clipboard_win.py:1: CreateWindowExW('Visible title')"])+ def test_open_mutex_name_is_internal_but_message_box_text_is_visible(self):+ path = ROOT / "win_app/portable_entry.py"+ source = (+ 'ctypes.windll.kernel32.OpenMutexW(0, False, "Local\\\\Beamer.Receiver")\n'+ 'ctypes.windll.user32.MessageBoxW(None, "Visible body", "Visible title", 0x10)'+ )+ with mock.patch.object(Path, "read_text", return_value=source):+ found = hard_coded(path)+ self.assertEqual(found, [+ "win_app/portable_entry.py:2: MessageBoxW('Visible body')",+ "win_app/portable_entry.py:2: MessageBoxW('Visible title')",+ ])+def test_no_hard_coded_user_visible_strings(self):found = [line for path in source_files() for line in hard_coded(path)]self.assertEqual(found, [], "mark these with tr() or N_() from core.i18n:\n" + "\n".join(found))diff --git a/core/tests/test_link.py b/core/tests/test_link.pyindex c90500a..415288e 100644--- a/core/tests/test_link.py+++ b/core/tests/test_link.py@@ -608,7 +608,7 @@ class LinkLiveTests(unittest.TestCase):def test_a_full_queue_reports_failure(self):self.link._stall.set()- results = [self.link.send_input(protocol.mousemove_msg(1, 1)) for _ in range(2100)]+ results = [self.link.send_input(protocol.key_msg("keydown", "a")) for _ in range(2100)]self.link._stall.clear()self.assertIn(False, results)self.assertEqual(results.count(True), 2048)diff --git a/core/tests/test_link_endpoint_follow.py b/core/tests/test_link_endpoint_follow.pynew file mode 100644index 0000000..a7d2237--- /dev/null+++ b/core/tests/test_link_endpoint_follow.py@@ -0,0 +1,190 @@+"""Discovery endpoints are hints until a real loopback peer authenticates."""++import socket+import threading+import unittest++from core import pairing, peerlist+from core.tests.responder_harness import B, C, HERE, TOKENS, Machine, entry, wait_for+from core.tests.test_link import FakeClock, Side+++class EndpointFollowTests(unittest.TestCase):+ def test_repaired_pin_reconnects_after_outage_without_following_wifi(self):+ machine = self.machine()+ side, clock = Side(machine), FakeClock()+ side.peer().update(host_pinned=True)+ old = dict(side.peer())+ repaired = pairing.peer_entry(HERE, "Far", "windows", machine.port, old["token"],+ "127.0.0.2", 100)+ peerlist.add_peer(side.settings.data, repaired, old)+ outage = threading.Event()+ attempted = []++ def factory(endpoint, timeout=None):+ attempted.append(endpoint)+ if outage.is_set() or endpoint[0] != "127.0.0.1":+ raise OSError("synthetic cable outage")+ return socket.create_connection(endpoint, timeout=timeout)++ link = self.link(side, clock=clock, socket_factory=factory)+ link.start()+ self.assertTrue(wait_for(link.live), side.states)+ outage.set()+ link._close()+ self.assertTrue(wait_for(lambda: not link.live()))+ clock.now += 11+ link.follow([{"name": "Here", "address": "127.0.0.2", "port": machine.port}])+ self.assertIsNone(link._try_host)+ outage.clear()+ self.assertTrue(wait_for(link.live), side.states)+ self.assertEqual(link.dialled, ("127.0.0.1", machine.port))+ self.assertEqual(side.peer()["host"], "127.0.0.1")+ self.assertTrue(all(endpoint[0] == "127.0.0.1" for endpoint in attempted), attempted)++ def machine(self, port=0, token=TOKENS[B], own=None):+ fields = {} if own is None else {"own": own}+ machine = Machine([entry(B, "Synthetic peer", token=token, send=False)], **fields)+ self.addCleanup(machine.stop)+ machine.responder.start(port)+ self.assertTrue(wait_for(lambda: machine.responder.listening_port is not None))+ machine.port = machine.responder.listening_port+ return machine++ def link(self, side, **kwargs):+ link = side.link(**kwargs)+ self.addCleanup(link.stop)+ return link++ def test_receive_only_peer_restarts_at_new_port_while_old_port_is_occupied(self):+ first = self.machine()+ side, clock = Side(first), FakeClock()+ side.peer()["host_pinned"] = False+ link = self.link(side, clock=clock)+ link.start()+ self.assertTrue(wait_for(link.live))+ old_port = first.port+ first.stop()+ self.assertTrue(wait_for(lambda: not link.live()))++ collision = self.machine(port=old_port, token=TOKENS[C], own=C)+ restarted = self.machine()+ self.assertEqual(collision.port, old_port)+ self.assertNotEqual(restarted.port, old_port)+ self.assertEqual(side.peer()["port"], old_port)+ clock.now += 11+ link.follow([{"name": "Here", "address": "127.0.0.1", "port": restarted.port}])+ self.assertTrue(wait_for(lambda: link.live() and link.dialled == ("127.0.0.1", restarted.port)),+ side.states)+ self.assertEqual(side.peer()["host"], "127.0.0.1")+ self.assertEqual(side.peer()["port"], restarted.port)+ self.assertTrue(wait_for(lambda: restarted.responder.links() == {B}))++ def test_unauthenticated_alternate_port_never_changes_saved_endpoint(self):+ wrong = self.machine(token=TOKENS[C], own=C)+ reserved = socket.socket()+ reserved.bind(("127.0.0.1", 0))+ self.addCleanup(reserved.close)+ side, clock = Side(None), FakeClock()+ side.peer().update(host="127.0.0.1", port=reserved.getsockname()[1], host_pinned=False)+ saved = dict(side.peer())+ attempted = []+ rejected = threading.Event()++ class ObservedConnection:+ def __init__(self, connection):+ self.connection = connection++ def __getattr__(self, name):+ return getattr(self.connection, name)++ def close(self):+ self.connection.close()+ rejected.set()++ def factory(endpoint, timeout=None):+ attempted.append(endpoint)+ connection = socket.create_connection(endpoint, timeout=timeout)+ return ObservedConnection(connection) if endpoint[1] == wrong.port else connection++ link = self.link(side, clock=clock, socket_factory=factory)+ link.start()+ self.assertTrue(wait_for(lambda: attempted))+ clock.now += 11+ link.follow([{"name": "Far", "address": "127.0.0.1", "port": wrong.port}])+ self.assertTrue(wait_for(lambda: ("127.0.0.1", wrong.port) in attempted))+ self.assertTrue(rejected.wait(3), "the unauthenticated alternate never finished its handshake")+ self.assertFalse(link.live())+ self.assertEqual(side.peer(), saved)+ self.assertEqual(side.settings.saves, 0)++ def test_same_address_endpoints_rotate_after_downtime_and_cooldown(self):+ side, clock, attempted = Side(None), FakeClock(), []+ side.peer()["host_pinned"] = False++ def factory(endpoint, timeout=None):+ attempted.append(endpoint)+ raise OSError("synthetic unavailable endpoint")++ link = self.link(side, clock=clock, socket_factory=factory, reconnect_seconds=0.01)+ link.start()+ self.assertTrue(wait_for(lambda: attempted))+ beacons = [{"name": "Far", "address": "127.0.0.1", "port": port}+ for port in (41001, 41002)]+ link.follow(beacons)+ self.assertIsNone(link._try_host)+ self.assertNotIn(("127.0.0.1", 41001), attempted)+ clock.now += 11+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("127.0.0.1", 41001) in attempted))+ clock.now += 5+ link.follow(beacons)+ self.assertNotIn(("127.0.0.1", 41002), attempted)+ clock.now += 30+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("127.0.0.1", 41002) in attempted))+ attempted.clear()+ clock.now += 31+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("127.0.0.1", 41001) in attempted))+ self.assertEqual(side.peer()["port"], 24820)++ def test_pinned_choices_and_invalid_beacon_ports_are_never_followed(self):+ side, clock = Side(None), FakeClock()+ link = self.link(side, clock=clock)+ clock.now += 11+ for pinned in (None, True):+ side.peer()["host_pinned"] = pinned+ link.follow([{"name": "Far", "address": "127.0.0.1", "port": 41001}])+ self.assertIsNone(link._try_host)+ side.peer()["host_pinned"] = False+ for port in (True, False, 0, -1, 65536, "41001", None, 41001.0):+ with self.subTest(port=port):+ link.follow([{"name": "Far", "address": "127.0.0.1", "port": port}])+ self.assertIsNone(link._try_host)+ self.assertIsNone(link._followed_at)++ def test_missing_beacon_port_uses_saved_port_after_authentication(self):+ machine = self.machine()+ side, clock = Side(machine), FakeClock()+ side.peer().update(host="127.0.0.2", host_pinned=False)+ attempted = []++ def factory(endpoint, timeout=None):+ attempted.append(endpoint)+ if endpoint[0] == "127.0.0.2":+ raise OSError("synthetic old address unavailable")+ return socket.create_connection(endpoint, timeout=timeout)++ link = self.link(side, clock=clock, socket_factory=factory)+ link.start()+ self.assertTrue(wait_for(lambda: attempted))+ clock.now += 11+ link.follow([{"name": "Far", "address": "127.0.0.1"}])+ self.assertTrue(wait_for(link.live), side.states)+ self.assertEqual(side.peer()["host"], "127.0.0.1")+ self.assertEqual(side.peer()["port"], machine.port)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_motion_flow.py b/core/tests/test_motion_flow.pynew file mode 100644index 0000000..595c496--- /dev/null+++ b/core/tests/test_motion_flow.py@@ -0,0 +1,138 @@+"""GH15: motion stays bounded without mistaking a busy receiver for a dead peer."""++import threading+import time+import unittest+import collections+import queue+from types import SimpleNamespace++from core import link as link_module, owner, protocol+from core.tests.app_methods import load_methods+from core.tests.test_link import Side+++class MotionFlowTests(unittest.TestCase):+ def test_non_motion_queue_and_clipboard_barriers_do_not_consult_motion_capabilities(self):+ sender_type = load_methods("win_app/sender.py", "LinkSender", ["_queue", "_deliver"],+ {"owner_module": owner, "protocol": protocol, "queue": queue,+ "MODIFIER_KEYS": frozenset()})+ sender = sender_type()+ sender.links = SimpleNamespace()+ sender._outbound = queue.Queue()+ key = owner.Send("far", protocol.key_msg("keydown", "a"))+ scroll = owner.Send("far", protocol.scroll_msg(1, 0, "line"))+ sender._queue([key, scroll, owner.Send("far", protocol.mousemove_msg(1, 1))])+ self.assertEqual(sender._outbound.qsize(), 3)+ sender._clip_lock = threading.Lock()+ sender._clip_wait = {"far": collections.deque([key])}+ sender._deliver(scroll)+ sender._deliver(owner.Send("far", protocol.mousemove_msg(1, 1)))+ self.assertEqual(len(sender._clip_wait["far"]), 3)++ def test_sender_clipboard_wait_coalesces_motion_without_crossing_a_key(self):+ sender_type = load_methods("win_app/sender.py", "LinkSender", ["_deliver"],+ {"owner_module": owner, "protocol": protocol})+ sender = sender_type()+ peer = "far"+ sender._clip_lock = threading.Lock()+ sender.links = SimpleNamespace(caps=lambda _: {"motion_path"})+ sender._clip_wait = {peer: collections.deque()}+ for index in range(1000):+ sender._deliver(owner.Send(peer, protocol.mousemove_msg(1, 1 if index % 2 else -1)))+ sender._deliver(owner.Send(peer, protocol.key_msg("keydown", "a")))+ sender._deliver(owner.Send(peer, protocol.mousemove_msg(2, 3)))+ waiting = sender._clip_wait[peer]+ self.assertLessEqual(len(waiting), 18)+ self.assertEqual(sum(a.message["data"]["dx"] for a in list(waiting)[:-2]), 1000)+ self.assertEqual(sum(a.message["data"]["dy"] for a in list(waiting)[:-2]), 0)+ self.assertEqual(waiting[-2].message["type"], "keydown")++ def setUp(self):+ self.now = [10.0]+ self.link = Side().link(clock=lambda: self.now[0])+ self.link._live = True+ self.link._caps = frozenset({"motion_path"})+ self.link._checked_at = self.link._logged_at = 10.0+ self.link._last_tx = 10.0++ def test_unsent_motion_merges_mixed_axes_and_keeps_control_order(self):+ for dx, dy in ((1, 0), (0, 2), (3, 4)):+ self.assertTrue(self.link.send_input(protocol.mousemove_msg(dx, dy)))+ self.assertTrue(self.link.send_input(protocol.key_msg("keydown", "a")))+ self.assertTrue(self.link.send_input(protocol.mousemove_msg(5, 6)))+ messages = list(self.link._outbox)+ self.assertEqual([m["type"] for m in messages], ["mousemove", "keydown", "mousemove"])+ self.assertEqual(protocol.read_input(messages[0]), {"type": "mousemove", "dx": 4, "dy": 6, "seq": 3,+ "samples": [[1, 0], [0, 2], [3, 4]]})+ self.assertEqual(set(self.link._queued_at), {3, 4, 5})+ self.assertEqual(self.link._queued_bytes, sum(link_module._weight(m) for m in messages))++ def test_progressing_ack_does_not_drop_a_slow_receiver(self):+ self.link._written_seq = 100+ self.link._sent_at.extend((seq, 10.0) for seq in range(1, 101))+ self.now[0] = 11.4+ self.link._ack({"seq": 1, "held_us": 0, "locked": False})+ self.now[0] = 11.6+ try:+ self.link._tick(self.now[0])+ except link_module.LinkEnded as exc:+ self.fail(f"An advancing ACK must keep a busy receiver connected: {exc}")+ self.assertTrue(self.link.live())+ self.now[0] = 11.4 + link_module.ACK_STALL_SECONDS + .01+ with self.assertRaises(link_module.LinkEnded):+ self.link._tick(self.now[0])++ def test_idle_or_duplicate_ack_cannot_keep_unprocessed_input_alive(self):+ self.link._written_seq = 1+ self.link._sent_at.append((1, 10.0))+ self.now[0] = 11.4+ self.link._ack({"seq": 0, "held_us": 0, "locked": False})+ self.now[0] = 11.6+ with self.assertRaises(link_module.LinkEnded):+ self.link._tick(self.now[0])++ def test_steady_travel_with_reversing_axis_jitter_cannot_fill_the_outbox(self):+ for index in range(10000):+ self.assertTrue(self.link.send_input(protocol.mousemove_msg(1, 1 if index % 2 else -1)))+ self.assertLessEqual(len(self.link._outbox), 157)+ self.assertEqual(sum(m["data"]["dx"] for m in self.link._outbox), 10000)+ self.assertEqual(sum(m["data"]["dy"] for m in self.link._outbox), 0)++ def test_writer_bounds_unacknowledged_input_and_resumes_on_ack(self):+ class Session:+ def seal(self, message):+ return b"x"++ class Socket:+ def send(self, frame):+ return len(frame)++ def shutdown(self, how):+ pass++ def close(self):+ pass++ sock = Socket()+ self.link._sock = sock+ for index in range(100):+ self.assertTrue(self.link.send_input(protocol.key_msg("keydown", "a")))+ worker = threading.Thread(target=self.link._write, args=(sock, Session()))+ worker.start()+ self.addCleanup(worker.join, 1)+ self.addCleanup(self.link._close)+ deadline = time.monotonic() + 1+ while self.link._written_seq < 32 and time.monotonic() < deadline:+ time.sleep(.001)+ time.sleep(.02)+ self.assertEqual(self.link._written_seq, 32)+ self.link._ack({"seq": 32, "held_us": 0, "locked": False})+ deadline = time.monotonic() + 1+ while self.link._written_seq < 64 and time.monotonic() < deadline:+ time.sleep(.001)+ self.assertEqual(self.link._written_seq, 64)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_motion_paths.py b/core/tests/test_motion_paths.pynew file mode 100644index 0000000..f05a78b--- /dev/null+++ b/core/tests/test_motion_paths.py@@ -0,0 +1,35 @@+"""A coalesced mouse frame retains the path needed by edge and corner geometry."""++import unittest++from core import protocol+++class MotionPathTests(unittest.TestCase):+ def test_coalescing_keeps_original_mixed_axis_segments(self):+ merged = protocol.coalesce_mousemove(protocol.mousemove_msg(119, 1, 1),+ protocol.mousemove_msg(1, 119, 2))+ self.assertEqual(merged["data"].get("samples"), [[119, 1], [1, 119]])+ self.assertEqual(protocol.read_input(merged).get("samples"), [[119, 1], [1, 119]])++ def test_malformed_or_unbounded_paths_are_rejected(self):+ for samples in ([], [[1]], [[True, 1]], [[1, 1]] * 65, [[65536, 0]], [[2, 1]]):+ with self.subTest(samples=samples):+ message = protocol.mousemove_msg(1, 1, 1)+ message["data"]["samples"] = samples+ self.assertIsNone(protocol.read_input(message))++ def test_path_limit_prevents_an_unbounded_coalesced_record(self):+ merged = protocol.mousemove_msg(1, 1, 1)+ for seq in range(2, 65):+ merged = protocol.coalesce_mousemove(merged, protocol.mousemove_msg(1, 1, seq))+ self.assertIsNotNone(merged)+ self.assertIsNone(protocol.coalesce_mousemove(merged, protocol.mousemove_msg(1, 1, 65)))++ def test_legacy_coalescing_does_not_erase_diagonal_path(self):+ self.assertIsNone(protocol.coalesce_mousemove(protocol.mousemove_msg(119, 1, 1),+ protocol.mousemove_msg(1, 119, 2), preserve_path=False))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_pair1_windows.py b/core/tests/test_pair1_windows.pynew file mode 100644index 0000000..35afe48--- /dev/null+++ b/core/tests/test_pair1_windows.py@@ -0,0 +1,109 @@+"""PAIR1: two synthetic Windows peers, using loopback and in-memory peer books only."""++import socket+import unittest+from unittest import mock++from core import pairing, peerlist, protocol+from . import responder_harness as responder+from .test_pairing_service import Machine, PC_ID, MAC_ID, wait_until+from .test_pairing_v3 import other_code+++class WindowsPairingTests(unittest.TestCase):+ def setUp(self):+ self.target = Machine(self, "PAIR1 Target", PC_ID, "windows")+ self.source = Machine(self, "PAIR1 Source", MAC_ID, "windows", peer_udp=self.target.udp_port)+ self.target.pair_with(self.source)++ def showing_code(self):+ code = self.target.service.begin_pairing()+ self.assertTrue(wait_until(lambda: any(m.get("pair_id") for m in self.source.service.machines())))+ return code, next(m for m in self.source.service.machines() if m.get("pair_id"))++ def test_two_windows_peers_pair_over_udp_with_receiving_enabled(self):+ code, seen = self.showing_code()+ saved = self.source.service.pair(seen, code)+ self.assertTrue(wait_until(lambda: self.target.paired))+ self.assertEqual(saved["token"], self.target.paired[0]["token"])+ for entry in (saved, self.target.paired[0]):+ self.assertEqual(entry["platform"], "windows")+ self.assertTrue(entry["send"])+ self.assertTrue(entry["allow_drive"])++ def test_two_windows_peers_pair_by_address(self):+ code, _ = self.showing_code()+ saved = self.source.service.pair_by_address("127.0.0.1", code, self.target.tcp_port)+ self.assertTrue(wait_until(lambda: self.target.paired))+ self.assertEqual(saved["token"], self.target.paired[0]["token"])++ def test_closed_code_refuses_a_stale_discovery_entry_without_an_accept_prompt(self):+ code, seen = self.showing_code()+ self.target.service.cancel_pairing()+ with self.assertRaises(pairing.PairingError) as caught:+ self.source.service.pair(seen, code)+ self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+ self.assertIn("not showing a code", peerlist.pairing_error_text(caught.exception, "PAIR1 Target"))+ self.assertEqual(self.target.book.entries, [])++ def test_expired_code_refuses_a_stale_discovery_entry(self):+ code, seen = self.showing_code()+ self.target.service.host.clock = lambda: self.target.service.host.expires_at + 1+ with self.assertRaises(pairing.PairingError) as caught:+ self.source.service.pair(seen, code)+ self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+ self.assertEqual(self.target.service.outcome, "expired")++ def test_wrong_code_is_refused_and_cancelled(self):+ code, seen = self.showing_code()+ with self.assertRaises(pairing.PairingError) as caught:+ self.source.service.pair(seen, other_code(code))+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertIn("code was not accepted", peerlist.pairing_error_text(caught.exception, "PAIR1 Target"))+ self.assertTrue(wait_until(lambda: self.target.service.code is None))+ self.assertEqual(self.target.book.entries, [])++ def test_filtered_pairing_packets_time_out_instead_of_reporting_permission_denied(self):+ code, seen = self.showing_code()+ dispatch = self.target.service._dispatch++ def filtered(sock, message, *args):+ if message.get("type") not in (pairing.MSG_PAIR_START, pairing.MSG_PAIR_CONFIRM):+ dispatch(sock, message, *args)++ with mock.patch.object(self.target.service, "_dispatch", filtered), \+ mock.patch.object(pairing, "PAIR_REPLY_TIMEOUT_SECONDS", 0.1), \+ mock.patch.object(pairing, "PAIR_ATTEMPTS", 2):+ with self.assertRaises(pairing.PairingError) as caught:+ self.source.service.pair(seen, code)+ self.assertEqual(str(caught.exception), "no_answer")+ self.assertIn("did not answer", peerlist.pairing_error_text(caught.exception, "PAIR1 Target"))+ self.assertIsNotNone(self.target.service.code)+ self.assertEqual(self.target.book.entries, [])++ def test_tcp_transport_failure_is_not_a_receiver_permission_refusal(self):+ with mock.patch.object(socket, "create_connection", side_effect=TimeoutError("synthetic filter")):+ with self.assertRaises(pairing.PairingError) as caught:+ self.source.service.pair_by_address("127.0.0.1", "123456", self.target.tcp_port)+ self.assertEqual(str(caught.exception), "no_answer")+++class WindowsReceivingPermissionTests(unittest.TestCase):+ def test_receiving_off_refuses_input_after_a_successful_authenticated_link(self):+ machine = responder.Machine([responder.entry(responder.B, "PAIR1 Source", platform="windows", allow_drive=False)]).start()+ self.addCleanup(machine.stop)+ source = responder.Initiator(machine)+ self.addCleanup(source.close)+ welcome = source.handshake(source.hello(platform="windows"))+ self.assertFalse(welcome["accepts"])+ route = source.take()+ self.assertEqual(source.answer(route), (protocol.MSG_REFUSE, {"route": route, "why": "not_allowed"}))+ machine.settings.peer(protocol.id_text(responder.B))["allow_drive"] = True+ machine.responder.peers_changed()+ self.assertEqual(source.expect(protocol.MSG_ACCEPTS), {"accepts": True})+ route = source.take()+ self.assertEqual(source.answer(route), (protocol.MSG_ACCEPT, {"route": route}))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_pairing_service.py b/core/tests/test_pairing_service.pyindex 9973511..a20c636 100644--- a/core/tests/test_pairing_service.py+++ b/core/tests/test_pairing_service.py@@ -201,6 +201,7 @@ class BeaconTests(unittest.TestCase):def test_id_and_pair_only_while_a_code_is_up(self):idle = self._next_beacon()self.assertEqual(idle, {"beamy": 1, "type": "beacon", "name": "Beacon PC", "port": 24820, "pairing": 3,+ "pair_port": self.pc.service.bind_port,"platform": "windows", "pair_modes": ["cpace_v3", "sas_v1"]})self.pc.service.begin_pairing()live = self._next_beacon()@@ -252,6 +253,19 @@ class TcpTests(unittest.TestCase):self.assertEqual(self.pc.book.entries[0]["host"], "127.0.0.1")self.assertEqual(self.pc.service.outcome, "paired")+ def test_a_typed_pairing_address_is_pinned_before_it_is_saved(self):+ code = self.pc.service.begin_pairing()+ saved = self.mac.service.pair_by_address("127.0.0.1", code, port=self.pc.tcp_port)+ self.assertIs(saved["host_pinned"], True)+ self.assertIs(self.mac.book.stored[-1][0]["host_pinned"], True)+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertIs(self.pc.book.entries[0]["host_pinned"], False)++ def test_a_qr_pairing_keeps_its_learnt_address_followable(self):+ self.pc.service.begin_pairing()+ saved = self.mac.service.pair_by_qr(self.pc.service.qr_text("127.0.0.1"))+ self.assertIs(saved["host_pinned"], False)+def test_the_requester_replaces_the_1_4_entry_held_at_that_address(self):old = {"id": "", "name": "Old PC", "platform": "windows", "token": "typed-in-1.4", "host": "127.0.0.1","port": 24820, "linked": False, "paired_at": 0, "from_1_4": True}diff --git a/core/tests/test_peer_address.py b/core/tests/test_peer_address.pyindex 8a90396..cadaefa 100644--- a/core/tests/test_peer_address.py+++ b/core/tests/test_peer_address.py@@ -2,7 +2,7 @@import unittest-from core import protocol, receiver+from core import pairing, peerlist, protocol, receiverfrom core.tests.test_link import FakeClock, Sidefrom core.tests.responder_harness import HERE@@ -75,6 +75,13 @@ class ChosenAddressTests(unittest.TestCase):class PairedAddressTests(unittest.TestCase):def test_pairing_saves_a_followable_address(self):- from core import pairingentry = pairing.peer_entry(bytes(16), "Far", "windows", 24820, "t", "192.0.2.10", 1)self.assertIs(entry["host_pinned"], False)++ def test_repair_of_a_migrated_typed_address_keeps_it_pinned(self):+ old = {"id": "", "name": "Far", "platform": "windows", "token": "old", "host": "192.0.2.10",+ "port": 24820, "from_1_4": True}+ settings = {"peers": [old], "zones": []}+ repaired = pairing.peer_entry(bytes(16), "Far", "windows", 24820, "new", "192.0.2.10", 1)+ peerlist.add_peer(settings, repaired, dict(old))+ self.assertIs(repaired["host_pinned"], True)diff --git a/core/tests/test_portable_discovery.py b/core/tests/test_portable_discovery.pynew file mode 100644index 0000000..7e4e772--- /dev/null+++ b/core/tests/test_portable_discovery.py@@ -0,0 +1,48 @@+import unittest++from core import pairing+++class PortableDiscoveryTests(unittest.TestCase):+ def test_routed_find_answers_keep_one_machine_and_its_live_pairing_port(self):+ service = pairing.PairingService("Peer", b"b" * 16, "windows", lambda: 41000,+ lambda: [], lambda *args: None, bind_port=53000)+ discovery = pairing.Discovery()+ beacon = pairing.decode(service._beacon())+ for port in (53000, 51001, 51002):+ discovery._note_beacon(beacon, ("192.0.2.20", port))+ self.assertEqual(len(discovery.pcs()), 1)+ self.assertEqual(discovery.pcs()[0]["reply_port"], 53000)++ def test_legacy_routed_beacons_are_deduplicated_by_advertised_app_endpoint(self):+ discovery = pairing.Discovery()+ for port in (24821, 51001, 51002):+ discovery._note_beacon(pairing.beacon_msg("Legacy", 41000), ("192.0.2.20", port))+ self.assertEqual(len(discovery.pcs()), 1)++ def test_invalid_advertised_pairing_ports_are_rejected(self):+ discovery = pairing.Discovery()+ for port in (True, 0, 65536, "53000"):+ beacon = pairing.beacon_msg("Peer", 41000)+ beacon["pair_port"] = port+ discovery._note_beacon(beacon, ("192.0.2.20", 51000))+ self.assertEqual(discovery.pcs(), [])++ def test_two_apps_on_one_ip_remain_selectable_and_update_independently(self):+ discovery = pairing.PairingService("Observer", b"a" * 16, "windows", lambda: 24820,+ lambda: [], lambda *args: None)+ for port, name, listener in ((24821, "Installed", 24820), (53000, "Portable", 53001)):+ discovery._note_beacon(pairing.beacon_msg(name, listener), ("127.0.0.1", port))+ self.assertEqual({(pc["name"], pc["reply_port"], pc["port"]) for pc in discovery.pcs()},+ {("Installed", 24821, 24820), ("Portable", 53000, 53001)})+ discovery._note_beacon(pairing.beacon_msg("Portable", 53002, "new-code"), ("127.0.0.1", 53000))+ self.assertEqual(len(discovery.pcs()), 2)+ portable = next(pc for pc in discovery.pcs() if pc["name"] == "Portable")+ self.assertEqual((portable["port"], portable["pair_id"]), (53002, "new-code"))++ def test_many_endpoints_on_typed_host_remain_bounded(self):+ discovery = pairing.Discovery()+ discovery._finding = ("127.0.0.1", 24821)+ for port in range(10000, 10000 + pairing.MAX_SEEN_HOSTS + 4):+ discovery._note_beacon(pairing.beacon_msg("Synthetic", port), ("127.0.0.1", port))+ self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)diff --git a/core/tests/test_portable_network.py b/core/tests/test_portable_network.pynew file mode 100644index 0000000..76a9f17--- /dev/null+++ b/core/tests/test_portable_network.py@@ -0,0 +1,148 @@+"""Portable sockets coexist with another Beamer using synthetic peers on loopback."""++from collections import deque+import logging+import socket+from types import SimpleNamespace+import unittest+from unittest import mock++from core import pairing, portable_runtime as runtime, receiver+from core.tests.responder_harness import (+ B, C, HERE, CAPS, FakeDesktop, FakeInjector, Initiator, Settings, entry, wait_for,+)+from core.tests.test_pairing_v3 import Book+++class PortableNetworkTests(unittest.TestCase):+ def setUp(self):+ runtime.close()+ self.addCleanup(runtime.close)++ def responder(self, name, own=HERE, port=0, listener=None):+ settings = Settings([entry(B, "Synthetic peer", host="127.0.0.1")], own=own)+ book = receiver.PeerBook(settings.load, settings.save)+ statuses = []+ responder = receiver.LinkResponder(+ book, lambda: {"id": own, "name": name, "platform": "windows",+ "app": "1.5.10", "caps": list(CAPS)},+ status_callback=lambda state, detail: statuses.append((state, detail)),+ injector=FakeInjector(), desktop=FakeDesktop(), listener=listener,+ )+ self.addCleanup(responder.stop)+ responder.start(port)+ self.assertTrue(wait_for(lambda: responder.listening_port is not None), statuses)+ return SimpleNamespace(responder=responder, port=responder.listening_port,+ settings=settings, book=book, statuses=statuses)++ def connect(self, machine):+ initiator = Initiator(machine, B)+ self.addCleanup(initiator.close)+ return initiator.handshake()++ def test_reserved_listener_serves_its_actual_port_beside_an_ordinary_responder(self):+ port = runtime.reserve_listener()+ reserved = runtime.listener+ portable = self.responder("Synthetic portable", port=0, listener=reserved)+ installed = self.responder("Synthetic installed", own=C)++ self.assertEqual(portable.port, port)+ self.assertIs(portable.responder._listener, reserved)+ self.assertNotEqual(installed.port, portable.port)+ portable_welcome = self.connect(portable)+ installed_welcome = self.connect(installed)+ self.assertEqual(portable_welcome["name"], "Synthetic portable")+ self.assertEqual(installed_welcome["name"], "Synthetic installed")+ self.assertEqual(portable_welcome["id"], HERE)+ self.assertEqual(installed_welcome["id"], C)+ self.assertTrue(wait_for(lambda: portable.responder.links() == {B}))+ self.assertTrue(wait_for(lambda: installed.responder.links() == {B}))++ def test_cached_port_survives_listener_handoff_close_and_can_be_bound_again(self):+ port = runtime.reserve_listener()+ original = runtime.listener+ first = self.responder("Synthetic first", port=port, listener=original)+ first.responder.stop()+ self.assertEqual(original.fileno(), -1)+ self.assertEqual(runtime.reserve_listener(), port)++ rebound = self.responder("Synthetic rebound", port=runtime.reserve_listener())+ self.assertEqual(rebound.port, port)+ self.assertEqual(self.connect(rebound)["name"], "Synthetic rebound")++ def pairing_service(self, name, identity, link_port, announce_to):+ book = Book()+ logger = logging.getLogger("portable-loopback-tests")+ logger.handlers = [logging.NullHandler()]+ logger.propagate = False+ service = pairing.PairingService(+ name, identity, "windows", lambda: link_port, book.peers, book.store,+ bind_port=0, tcp_port=0, announce_to=announce_to, logger=logger,+ )+ received = deque()+ dispatch = service._dispatch++ def record(sock, message, address, *rest):+ received.append((message.get("type"), address))+ return dispatch(sock, message, address, *rest)++ service._dispatch = record+ self.addCleanup(service.stop)+ service.start()+ self.assertTrue(wait_for(lambda: service.listening_port is not None), service.error)+ return service, book, received++ def test_active_discovery_finds_peer_from_its_reply_and_both_tcp_ports_are_unique(self):+ # Interface enumeration is outside this test; every transmitted datagram stays on loopback.+ for target, value in (("_local_ipv4_addresses", ["127.0.0.1"]),+ ("pairing_address", "127.0.0.1"), ("_answer_source", "127.0.0.1")):+ patch = mock.patch.object(pairing, target, return_value=value)+ patch.start()+ self.addCleanup(patch.stop)+ broadcasts = mock.patch.object(pairing, "broadcast_targets",+ side_effect=AssertionError("LAN broadcast is forbidden"))+ broadcast_targets = broadcasts.start()+ self.addCleanup(broadcasts.stop)+ sink = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ sink.bind(("127.0.0.1", 0))+ self.addCleanup(sink.close)+ destination = sink.getsockname()+ first, first_book, first_received = self.pairing_service(+ "Synthetic portable", HERE, 41001, destination)+ second, second_book, second_received = self.pairing_service(+ "Synthetic installed", C, 41002, destination)+ self.assertNotEqual(first.listening_port, second.listening_port)+ self.assertEqual(first.machines(), [])++ # The second service only announces to the sink, so its discovery here requires a find reply.+ first.announce_to = ("127.0.0.1", second.listening_port)+ first.active_discovery = True+ first._announce(first._sock)+ self.assertTrue(wait_for(lambda: any(kind == pairing.MSG_FIND for kind, _ in second_received)))+ self.assertTrue(wait_for(lambda: any(item["name"] == "Synthetic installed"+ for item in first.machines())))+ discovered = next(item for item in first.machines() if item["name"] == "Synthetic installed")+ self.assertEqual(discovered["address"], "127.0.0.1")+ self.assertEqual(discovered["port"], 41002)+ self.assertEqual(discovered["reply_port"], second.listening_port)+ self.assertEqual(len(first.machines()), 1)+ self.assertTrue(any(kind == pairing.MSG_BEACON for kind, _ in first_received))++ first.begin_pairing()+ second.begin_pairing()+ self.assertIsNone(first.tcp_error)+ self.assertIsNone(second.tcp_error)+ self.assertGreater(first.tcp_port, 0)+ self.assertGreater(second.tcp_port, 0)+ self.assertNotEqual(first.tcp_port, second.tcp_port)+ for service in (first, second):+ self.assertEqual(service._listener[0].getsockname()[1], service.tcp_port)+ with socket.create_connection(("127.0.0.1", service.tcp_port), timeout=2) as connection:+ self.assertEqual(connection.getpeername(), ("127.0.0.1", service.tcp_port))+ self.assertEqual(first_book.entries, [])+ self.assertEqual(second_book.entries, [])+ broadcast_targets.assert_not_called()+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_portable_packaging.py b/core/tests/test_portable_packaging.pynew file mode 100644index 0000000..3956200--- /dev/null+++ b/core/tests/test_portable_packaging.py@@ -0,0 +1,69 @@+"""Exercise the portable spec without importing Windows or GUI libraries."""+from pathlib import Path+from types import SimpleNamespace+import unittest+++ROOT = Path(__file__).resolve().parents[2]+++class PortablePackagingTests(unittest.TestCase):+ def setUp(self):+ self.calls = {}++ def analysis(scripts, **options):+ self.calls['analysis'] = (scripts, options)+ return SimpleNamespace(+ pure=['module'], scripts=scripts, datas=['assets'],+ binaries=[('ucrtbase.dll', 'system', 'BINARY'),+ ('api-ms-win-core.dll', 'system', 'BINARY'),+ ('Qt6Core.dll', 'qt', 'BINARY')],+ )++ def capture(name):+ def call(*args, **options):+ self.calls[name] = (args, options)+ return name+ return call++ spec = ROOT / 'win_app' / 'build_portable.spec'+ exec(compile(spec.read_text(), spec.name, 'exec'), {+ 'SPECPATH': str(spec.parent), 'Analysis': analysis,+ 'PYZ': capture('pyz'), 'EXE': capture('exe'), 'COLLECT': capture('collect'),+ })++ def test_one_folder_build_runs_without_admin_or_extraction(self):+ scripts, analysis = self.calls['analysis']+ self.assertEqual(scripts, [str(ROOT / 'win_app' / 'portable_entry.py')])+ self.assertIn('kvm_bridge_win', analysis['hiddenimports'])+ self.assertEqual(analysis['runtime_hooks'], [str(ROOT / 'win_app' / 'hooks' / 'portable_storage.py')])+ args, options = self.calls['exe']+ self.assertIs(options['exclude_binaries'], True)+ self.assertIs(options['uac_admin'], False)+ self.assertIs(options['uac_uiaccess'], False)+ self.assertEqual(options['contents_directory'], '_internal')+ self.assertEqual(args[-1], [])+ self.assertNotIn('runtime_tmpdir', options)+ self.assertEqual(self.calls['collect'][1]['name'], 'Beamer-portable')++ def test_qt_dlls_stay_beside_exe_and_system_stubs_stay_out(self):+ args, _ = self.calls['collect']+ self.assertEqual(args[0], 'exe')+ self.assertEqual(args[1], [('Qt6Core.dll', 'qt', 'BINARY')])+ self.assertEqual(args[2], ['assets'])++ def test_dynamic_core_modules_and_locales_are_included(self):+ _, options = self.calls['analysis']+ self.assertIn('core.effects', options['hiddenimports'])+ self.assertTrue(any(destination == 'locales' for _, destination in options['datas']))++ def test_runtime_only_hook_is_not_an_installed_module_probe(self):+ from tools.import_probe import module_names+ self.assertNotIn('portable_storage', module_names('win'))+ self.assertNotIn('hooks.portable_storage', module_names('win'))+ _, options = self.calls['analysis']+ self.assertNotIn('portable_storage', options['hiddenimports'])+++if __name__ == '__main__':+ unittest.main()diff --git a/core/tests/test_portable_runtime.py b/core/tests/test_portable_runtime.pynew file mode 100644index 0000000..00153b6--- /dev/null+++ b/core/tests/test_portable_runtime.py@@ -0,0 +1,70 @@+import os+from pathlib import Path+import socket+import tempfile+import unittest+from unittest.mock import patch++from core import portable_runtime as runtime+++class PortableRuntimeTests(unittest.TestCase):+ def tearDown(self):+ runtime.close()++ def test_marker_uses_executable_not_working_directory(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ (root / runtime.MARKER).touch()+ exe = root / "Beamer.exe"+ self.assertEqual(runtime.portable_root(exe, True), root.resolve())+ self.assertIsNone(runtime.portable_root(exe, False))+ self.assertIsNone(runtime.portable_root(root / "other" / "Beamer.exe", True))++ def test_installed_and_two_portable_copies_have_separate_names(self):+ with patch.object(runtime, "root", return_value=None):+ installed = runtime.instance_suffix()+ with patch.object(runtime, "root", return_value=Path("/first")):+ first = runtime.instance_suffix()+ with patch.object(runtime, "root", return_value=Path("/second")):+ second = runtime.instance_suffix()+ self.assertEqual(installed, "")+ self.assertNotEqual(installed, first)+ self.assertNotEqual(first, second)++ def test_reserved_port_is_held_and_distinct_from_installed(self):+ with socket.socket() as installed:+ installed.bind(("127.0.0.1", 0))+ port = runtime.reserve_listener()+ self.assertNotEqual(port, installed.getsockname()[1])+ with socket.socket() as other:+ with self.assertRaises(OSError):+ other.bind(("127.0.0.1", port))++ def test_writable_setup_keeps_temp_inside_folder(self):+ previous_temp = tempfile.tempdir+ try:+ with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ):+ root = Path(directory)+ with patch.object(runtime, "portable_root", return_value=root):+ with patch.object(runtime, "_root", None):+ runtime.initialise(True)+ self.assertEqual(runtime.settings_path(), root.resolve() / "data" / "settings.beamer")+ self.assertEqual(Path(tempfile.gettempdir()), root.resolve() / "data" / "tmp")+ self.assertEqual(Path(os.environ["LOCALAPPDATA"]), root.resolve() / "data" / "cache" / "local")+ self.assertEqual(Path(os.environ["APPDATA"]), root.resolve() / "data" / "cache" / "roaming")+ self.assertFalse(any((root / "data" / "tmp").iterdir()))+ finally:+ tempfile.tempdir = previous_temp++ def test_missing_marker_and_unwritable_storage_never_fall_back(self):+ with patch.object(runtime, "portable_root", return_value=None):+ with self.assertRaises(OSError):+ runtime.initialise(True)+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ (root / "data").write_text("not a directory")+ with patch.object(runtime, "portable_root", return_value=root):+ with patch.object(runtime, "_root", None):+ with self.assertRaises(OSError):+ runtime.initialise(True)diff --git a/core/tests/test_portable_store.py b/core/tests/test_portable_store.pynew file mode 100644index 0000000..f00fd16--- /dev/null+++ b/core/tests/test_portable_store.py@@ -0,0 +1,176 @@+"""Synthetic portable-state persistence; no platform or GUI dependencies."""++import json+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from core import portable_store+++class PortableStoreTests(unittest.TestCase):+ def setUp(self):+ self.directory = tempfile.TemporaryDirectory()+ self.addCleanup(self.directory.cleanup)+ self.path = Path(self.directory.name) / "pairing.vault"+ self.store = portable_store.PortableStore(self.path)++ def test_locked_state_cannot_be_read_or_written(self):+ self.assertFalse(self.store.exists)+ self.assertFalse(self.store.is_unlocked)+ for operation in (self.store.read, lambda: self.store.write({"token": "secret"})):+ with self.assertRaises(portable_store.PortableStoreLockedError):+ operation()+ self.assertFalse(self.path.exists())++ def test_create_round_trip_and_lock(self):+ self.store.unlock("synthetic passphrase")+ self.assertTrue(self.store.exists)+ self.assertEqual(self.store.read(), {})+ data = {"identity": "identity-secret", "peers": [{"token": "pairing-secret"}],+ "label": "Synthetic desk", "port": 48123}+ self.store.write(data)+ for secret in (b"identity-secret", b"pairing-secret", b"Synthetic desk"):+ self.assertNotIn(secret, self.path.read_bytes())+ self.store.lock()+ self.assertFalse(self.store.is_unlocked)+ with self.assertRaises(portable_store.PortableStoreLockedError):+ self.store.read()+ self.store.unlock("synthetic passphrase")+ self.assertEqual(self.store.read(), data)+ self.assertEqual(list(self.path.parent.iterdir()), [self.path])++ def test_wrong_password_never_replaces_state_and_relocks(self):+ self.store.unlock("right password")+ self.store.write({"token": "synthetic-token"})+ before = self.path.read_bytes()+ with self.assertRaises(portable_store.PortableStoreUnlockError):+ self.store.unlock("wrong password")+ self.assertFalse(self.store.is_unlocked)+ self.assertEqual(self.path.read_bytes(), before)++ def test_corrupt_and_unsupported_files_never_reset_or_run_kdf(self):+ for bad in (b"", b"{}", b"wrong header" * 100,+ portable_store._MAGIC + b"\x00" * 4):+ with self.subTest(bad=bad[:20]):+ self.path.write_bytes(bad)+ with mock.patch.object(portable_store.argon2id, "kdf") as kdf:+ with self.assertRaises(portable_store.PortableStoreUnlockError):+ self.store.unlock("synthetic password")+ kdf.assert_not_called()+ self.assertEqual(self.path.read_bytes(), bad)++ def test_authenticated_ciphertext_rejects_mutation(self):+ self.store.unlock("synthetic password")+ damaged = bytearray(self.path.read_bytes())+ damaged[-1] ^= 1+ self.path.write_bytes(damaged)+ with self.assertRaises(portable_store.PortableStoreUnlockError):+ self.store.unlock("synthetic password")+ self.assertEqual(self.path.read_bytes(), damaged)++ def test_fresh_salt_and_nonce_and_fresh_nonce_for_every_write(self):+ self.store.unlock("synthetic password")+ first = self.path.read_bytes()+ self.store.write({})+ second = self.path.read_bytes()+ self.assertNotEqual(first, second)+ other = portable_store.PortableStore(self.path.with_name("other.vault"))+ other.unlock("synthetic password")+ self.assertNotEqual(first, other.path.read_bytes())++ def test_atomic_failure_preserves_disk_and_memory_without_plaintext_temp(self):+ self.store.unlock("synthetic password")+ self.store.write({"token": "old synthetic token"})+ before = self.path.read_bytes()++ def reject_replace(source, destination):+ self.assertEqual(Path(destination), self.path)+ self.assertNotIn(b"new synthetic token", Path(source).read_bytes())+ raise OSError("synthetic interrupted save")++ with mock.patch.object(portable_store.os, "replace", side_effect=reject_replace):+ with self.assertRaises(OSError):+ self.store.write({"token": "new synthetic token"})+ self.assertEqual(self.path.read_bytes(), before)+ self.assertEqual(self.store.read(), {"token": "old synthetic token"})+ self.assertEqual(list(self.path.parent.iterdir()), [self.path])++ def test_read_and_write_do_not_share_mutable_objects(self):+ self.store.unlock("synthetic password")+ value = {"nested": ["original"]}+ self.store.write(value)+ value["nested"].append("changed")+ read = self.store.read()+ read["nested"].append("changed again")+ self.assertEqual(self.store.read(), {"nested": ["original"]})++ def test_invalid_passphrases_and_values_do_not_create_a_file(self):+ for passphrase in ("", "a" * 1025, None, b"password"):+ with self.subTest(passphrase_type=type(passphrase)):+ with self.assertRaises(ValueError):+ self.store.unlock(passphrase)+ self.assertFalse(self.path.exists())+ self.store.unlock("synthetic password")+ before = self.path.read_bytes()+ for value in ([], {1: "bad key"}, {"value": float("nan")}, {"value": object()},+ {"huge": "x" * portable_store.MAX_STATE_BYTES}):+ with self.subTest(value_type=type(value)):+ with self.assertRaises(ValueError):+ self.store.write(value)+ self.assertEqual(self.path.read_bytes(), before)++ def test_oversized_envelope_rejected_before_key_derivation(self):+ self.path.write_bytes(b"x" * (portable_store.MAX_ENVELOPE_BYTES + 1))+ with mock.patch.object(portable_store.argon2id, "kdf") as kdf:+ with self.assertRaises(portable_store.PortableStoreUnlockError):+ self.store.unlock("synthetic password")+ kdf.assert_not_called()++ def test_new_vault_never_overwrites_a_concurrently_created_file(self):+ derive = self.store._derive++ def create_competing_vault(password, salt):+ self.path.write_bytes(b"synthetic existing vault")+ return derive(password, salt)++ with mock.patch.object(self.store, "_derive", side_effect=create_competing_vault):+ with self.assertRaises(FileExistsError):+ self.store.unlock("synthetic password")+ self.assertFalse(self.store.is_unlocked)+ self.assertEqual(self.path.read_bytes(), b"synthetic existing vault")+ self.assertEqual(list(self.path.parent.iterdir()), [self.path])++ def test_excessive_nesting_is_rejected_without_changing_state(self):+ self.store.unlock("synthetic password")+ before = self.path.read_bytes()+ value = []+ for _ in range(40):+ value = [value]+ with self.assertRaises(ValueError):+ self.store.write({"deep": value})+ self.assertEqual(self.path.read_bytes(), before)++ def test_authenticated_invalid_json_never_unlocked(self):+ from nacl.secret import SecretBox++ salt = b"s" * portable_store.argon2id.SALTBYTES+ key = portable_store.argon2id.kdf(+ SecretBox.KEY_SIZE, b"synthetic password", salt,+ opslimit=portable_store.KDF_OPSLIMIT, memlimit=portable_store.KDF_MEMLIMIT)+ for plaintext in (b"[]", b'{"duplicate": 1, "duplicate": 2}', b'{"n": NaN}',+ b'{"broken"', json.dumps({"deep": [[[[[]]]]]}).encode()):+ # The last case is valid and proves the same envelope can unlock.+ self.path.write_bytes(portable_store._MAGIC + salt + bytes(SecretBox(key).encrypt(plaintext)))+ if b"deep" in plaintext:+ self.store.unlock("synthetic password")+ self.assertIn("deep", self.store.read())+ else:+ with self.assertRaises(portable_store.PortableStoreUnlockError):+ self.store.unlock("synthetic password")+ self.assertFalse(self.store.is_unlocked)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_receiver_backlog.py b/core/tests/test_receiver_backlog.pyindex 922c73d..c182d39 100644--- a/core/tests/test_receiver_backlog.py+++ b/core/tests/test_receiver_backlog.py@@ -245,9 +245,13 @@ class InboxTests(unittest.TestCase):def test_relative_travel_is_preserved_with_the_latest_sequence(self):self.assertEqual(self.moves([(2, 0, 1), (3, 0, 2), (4, 0, 3)]), [(9, 0, 3)])- def test_reversals_and_axis_changes_do_not_create_or_erase_edge_pushes(self):+ def test_mixed_axes_and_diagonal_jitter_merge_without_losing_travel(self):+ self.assertEqual(self.moves([(2, 0, 1), (0, 3, 2), (4, 1, 3)]), [(6, 4, 3)])++ def test_reversals_retain_their_geometry_samples(self):self.assertEqual(self.moves([(120, 0, 1), (0, 120, 2), (0, -120, 3)]),- [(120, 0, 1), (0, 120, 2), (0, -120, 3)])+ [(120, 0, 3)])+ self.assertEqual(self.link.inbox[0][0]["data"]["samples"], [[120, 0], [0, 120], [0, -120]])def test_delta_overflow_and_decreasing_sequences_stay_separate(self):self.assertEqual(self.moves([(65535, 0, 2), (1, 0, 3), (2, 0, 1)]),@@ -259,13 +263,13 @@ class InboxTests(unittest.TestCase):self.link.closed.clear()self.link.inbox.clear()self.link.inbox_bytes = 0- self.link.receive(protocol.mousemove_msg(1, 0, 1), 80)+ self.link.receive(protocol.mousemove_msg(protocol.MOVE_MAX, 0, 1), 80)result = []entered = threading.Event()def receive():entered.set()- result.append(self.link.receive(protocol.mousemove_msg(-1, 0, 2), 80))+ result.append(self.link.receive(protocol.mousemove_msg(1, 0, 2), 80))reader = threading.Thread(target=receive)reader.start()diff --git a/core/tests/test_rel1510b_geometry.py b/core/tests/test_rel1510b_geometry.pyindex 596d400..91711f6 100644--- a/core/tests/test_rel1510b_geometry.py+++ b/core/tests/test_rel1510b_geometry.py@@ -8,17 +8,25 @@ from core.tests.responder_harness import B, HERE, FakeDesktop, Machine, entryclass ReceiverQueuedGeometryTests(unittest.TestCase):- def deliver(self, moves, pointer, model, queued):+ def deliver(self, moves, pointer, model, queued, sender=False, calls=None, display_map=None, input_scale=None, held_button=None):desktop = FakeDesktop(cursor=pointer)+ if display_map is not None:+ desktop.display_map = lambda: display_mapmachine = Machine([entry(B, "Driver")], desktop=desktop)link = receiver._Link(SimpleNamespace(shutdown=lambda _how: None), None, B, None,"127.0.0.1", "Driver", [], HERE, [], True,)responder = machine.responder+ responder.input_scale = input_scaleresponder._owner = link- responder._armed = [(B, model)]+ responder._armed = [(B, model)] if model is not None else []responder._zones_live = True+ if held_button is not None:+ responder._dispatch(link, {"type": protocol.MSG_MOUSEDOWN,+ "data": {"button": held_button, "seq": 1}})+ self.assertIn(("button", held_button), link.held)+ machine.injector.calls.clear()original = machine.injector.inject_mouse_movedef move_pointer(dx, dy):@@ -33,6 +41,12 @@ class ReceiverQueuedGeometryTests(unittest.TestCase):machine.injector.inject_mouse_move = move_pointermessages = [protocol.mousemove_msg(dx, dy, seq)for seq, (dx, dy) in enumerate(moves, 1)]+ if sender:+ pending = messages[0]+ for following in messages[1:]:+ pending = protocol.coalesce_mousemove(pending, following)+ self.assertIsNotNone(pending)+ messages = [pending]if queued:for message in messages:link.receive(message, len(protocol.dumps_message(message)))@@ -41,8 +55,137 @@ class ReceiverQueuedGeometryTests(unittest.TestCase):responder._dispatch(link, message)switches = [message for message in link.outboxif message.get("type") == protocol.MSG_SWITCH]+ if calls is not None:+ calls.extend(machine.injected())return desktop.cursor, len(switches)+ def test_interior_drag_keeps_each_native_path_segment(self):+ paths = [+ [(20, 0), (0, 20), (-20, 0), (0, -20)],+ [(20, 0), (-20, 0)],+ [(0, 20), (0, -20)],+ [(20, 0), (0, 20)],+ [(10, 10), (10, 5)],+ ]+ for moves, speed in ((path, speed) for path in paths for speed in (None, 1.0)):+ with self.subTest(moves=moves, speed=speed):+ direct_calls, batch_calls = [], []+ direct_scale = None if speed is None else receiver.InputScale(speed)+ batch_scale = None if speed is None else receiver.InputScale(speed)+ direct = self.deliver(moves, (500, 500), None, False, calls=direct_calls,+ input_scale=direct_scale, held_button="left")+ batch = self.deliver(moves, (500, 500), None, True, sender=True, calls=batch_calls,+ input_scale=batch_scale, held_button="left")+ self.assertEqual(direct_calls, [("move", dx, dy) for dx, dy in moves])+ self.assertEqual(batch, direct)+ self.assertEqual(batch_calls, direct_calls)++ def test_unarmed_wall_reversals_keep_each_native_clipping_step(self):+ for moves, pointer in [+ ([(5, 0), (-5, 0)], (1919, 500)),+ ([(-5, 0), (5, 0)], (0, 500)),+ ([(0, 5), (0, -5)], (500, 1079)),+ ([(0, -5), (0, 5)], (500, 0)),+ ]:+ with self.subTest(pointer=pointer):+ self.assertEqual(self.deliver(moves, pointer, None, True, sender=True),+ self.deliver(moves, pointer, None, False))++ def test_unarmed_interior_and_parallel_wall_paths_still_batch_native_calls(self):+ for pointer in ((500, 500), (1919, 500)):+ with self.subTest(pointer=pointer):+ calls = []+ result = self.deliver([(0, 1), (0, -1)] * 32, pointer, None,+ True, sender=True, calls=calls)+ self.assertEqual(result, (pointer, 0))+ self.assertLessEqual(len(calls), 1)++ def test_interior_batch_preserves_per_sample_scaling_and_fractional_carry(self):+ for speed in (.6, 1.4):+ with self.subTest(speed=speed):+ direct_scale, batch_scale = receiver.InputScale(speed), receiver.InputScale(speed)+ direct = self.deliver([(2, 0), (-1, 0)], (500, 500), None, False, input_scale=direct_scale)+ calls = []+ batched = self.deliver([(2, 0), (-1, 0)], (500, 500), None, True,+ sender=True, calls=calls, input_scale=batch_scale)+ self.assertEqual(batched, direct)+ self.assertEqual(batch_scale._carry, direct_scale._carry)+ self.assertEqual(len(calls), 1)++ def test_scaled_carry_and_display_edge_tolerance_do_not_hide_a_crossing(self):+ mapping = {"inner": return_edge.Rect(0, 0, 1000, 1080)}+ def run(queued):+ scale = receiver.InputScale(1.4)+ scale._carry = [.8, 0]+ return self.deliver([(1, 0), (1, 0)], (996, 500),+ return_edge.ReturnEdge("right", resistance_px=1, clock=lambda: 0, display="inner"),+ queued, sender=queued, display_map=mapping, input_scale=scale)+ self.assertEqual(run(False), ((998, 500), 1))+ self.assertEqual(run(True), run(False))++ def test_bounded_near_edge_path_sweep_matches_original_sample_geometry(self):+ paths = [+ [(1, 0), (1, 0)], [(2, 0), (-1, 0)], [(0, 1), (1, 0)],+ [(1, 1), (1, -1)], [(-1, 1), (2, 0)], [(1, 2), (2, 1)],+ [(0, 2), (0, -1)], [(2, 1), (1, 2)],+ ]+ mapping = {"inner": return_edge.Rect(0, 0, 1000, 1080)}+ models = [+ lambda: return_edge.ReturnEdge("right", resistance_px=3, clock=lambda: 0, display="inner"),+ lambda: return_edge.PartEdge("right", ["start"], resistance_px=3, clock=lambda: 0, display="inner"),+ lambda: return_edge.CornerPush("bottom_right", "right", resistance_px=3, clock=lambda: 0, display="inner"),+ ]+ for model_index, model in enumerate(models):+ for x in (996, 998, 999):+ for y in (358, 360, 1078):+ for speed in (.6, 1.0, 1.4, 3.7):+ for carry in (-.8, .8):+ for moves in paths:+ with self.subTest(model=model_index, pointer=(x, y), speed=speed, carry=carry, moves=moves):+ direct_scale, batch_scale = receiver.InputScale(speed), receiver.InputScale(speed)+ direct_scale._carry = [carry, -carry]+ batch_scale._carry = [carry, -carry]+ direct = self.deliver(moves, (x, y), model(), False,+ display_map=mapping, input_scale=direct_scale)+ batch = self.deliver(moves, (x, y), model(), True, sender=True,+ display_map=mapping, input_scale=batch_scale)+ self.assertEqual(batch, direct)+ self.assertEqual(batch_scale._carry, direct_scale._carry)++ def test_parallel_wall_jitter_outside_selected_part_batches_native_injection(self):+ calls = []+ result = self.deliver([(0, 1), (0, -1)] * 32, (1919, 500),+ return_edge.PartEdge("right", ["start"], resistance_px=120, clock=lambda: 0),+ True, sender=True, calls=calls)+ self.assertEqual(result, ((1919, 500), 0))+ self.assertLessEqual(len(calls), 2)++ def test_first_cross_discards_the_rest_of_its_batched_path(self):+ calls = []+ self.assertEqual(self.deliver([(1, 0), (-500, -300)], (1919, 500),+ return_edge.ReturnEdge("right", resistance_px=1, clock=lambda: 0),+ True, sender=True, calls=calls), ((1919, 500), 1))+ self.assertEqual(calls, [])++ def test_tangent_motion_at_an_active_part_keeps_each_actual_pointer_position(self):+ class TrackedPart(return_edge.PartEdge):+ def feed(self, monitors, pointer, dx, dy, display_map=None):+ seen.append(pointer)+ return super().feed(monitors, pointer, dx, dy, display_map=display_map)+ seen = []+ model = TrackedPart("right", ["start"], resistance_px=120, clock=lambda: 0)+ model._travel = 100+ self.deliver([(0, 20), (0, -20)], (1919, 350), model, True, sender=True)+ self.assertEqual(seen, [(1919, 350), (1919, 370)])++ def test_larger_overlapping_display_does_not_hide_an_armed_display_edge(self):+ mapping = {"inner": return_edge.Rect(0, 0, 1000, 1080)}+ def model():+ return return_edge.PartEdge("right", ["start"], resistance_px=120, clock=lambda: 0, display="inner")+ direct = self.deliver([(1, 4), (200, 1)], (999, 358), model(), False, display_map=mapping)+ self.assertEqual(self.deliver([(1, 4), (200, 1)], (999, 358), model(), True,+ sender=True, display_map=mapping), direct)+def test_queued_diagonal_motion_does_not_cross_after_leaving_selected_part(self):def run(queued):return self.deliver(@@ -55,6 +198,20 @@ class ReceiverQueuedGeometryTests(unittest.TestCase):self.assertEqual(direct, ((1919, 363), 0))self.assertEqual(run(True), direct)+ def test_sender_coalesced_path_keeps_selected_part_and_corner_geometry(self):+ cases = [+ ([(1, 4), (200, 1)], (1919, 358),+ lambda: return_edge.PartEdge("right", ["start"], resistance_px=120, clock=lambda: 0)),+ ([(119, 1), (1, 119)], (1919, 1079),+ lambda: return_edge.CornerPush("bottom_right", "right", resistance_px=200, clock=lambda: 0)),+ ([(120, 0), (0, 120)], (1919, 1079),+ lambda: return_edge.CornerPush("bottom_right", "right", resistance_px=120, clock=lambda: 0)),+ ]+ for moves, pointer, model in cases:+ with self.subTest(moves=moves):+ self.assertEqual(self.deliver(moves, pointer, model(), True, sender=True),+ self.deliver(moves, pointer, model(), False))+def test_queued_diagonal_motion_keeps_corner_push_pressure(self):def run(queued):return self.deliver(diff --git a/core/tests/test_updates.py b/core/tests/test_updates.pyindex 69303fa..662a095 100644--- a/core/tests/test_updates.py+++ b/core/tests/test_updates.py@@ -143,5 +143,71 @@ class NoticeTests(unittest.TestCase):self.assertIsNone(updates.visible_notice(None, True, ""))+class PortableCheckerTests(unittest.TestCase):+ NAME = "Beamer-Portable-1.5.10-windows-x64.zip"+ URL = "https://github.com/kalkman-code/beamer/releases/download/v1.5.10/" + NAME++ def make(self, assets, portable=True):+ payload = release("v1.5.10", assets=assets)+ results = []+ checker = updates.Checker("1.5.9", lambda: True, results.append,+ fetcher=lambda: json.dumps(payload).encode(), portable=portable)+ checker.check_once()+ return checker, results++ def test_portable_download_keeps_the_release_page_for_whats_new(self):+ checker, results = self.make([{"name": self.NAME, "browser_download_url": self.URL}])+ page = "https://github.com/kalkman-code/beamer/releases/tag/v1.5.10"+ self.assertEqual(checker.download_url, self.URL)+ self.assertEqual(checker.latest, ("1.5.10", page))+ self.assertEqual(results, [checker.latest])++ def test_missing_portable_zip_never_offers_the_installer(self):+ for assets in (None, [], {}, [None, "asset"],+ [{"name": "Beamer-Setup-1.5.10.exe", "browser_download_url": self.URL}]):+ with self.subTest(assets=assets):+ checker, results = self.make(assets)+ self.assertEqual(checker.latest[0], "1.5.10")+ self.assertIsNone(checker.download_url)+ self.assertEqual(results, [checker.latest])++ def test_untrusted_or_wrong_release_assets_are_rejected(self):+ for url in (self.URL.replace("github.com", "github.com.evil.invalid"),+ self.URL.replace("https:", "http:"),+ self.URL.replace("/beamer/", "/another-project/"),+ self.URL.replace("/v1.5.10/", "/v1.5.9/"),+ self.URL + "?source=untrusted", self.URL + "#fragment",+ self.URL.replace(self.NAME, "Beamer-Setup-1.5.10.exe"),+ "https://evil.invalid/" + self.NAME):+ with self.subTest(url=url):+ checker, _ = self.make([{"name": self.NAME, "browser_download_url": url}])+ self.assertIsNone(checker.download_url)++ def test_installed_checker_keeps_its_existing_release_page_behaviour(self):+ checker, results = self.make([{"name": self.NAME, "browser_download_url": self.URL}],+ portable=False)+ self.assertIsNone(checker.download_url)+ self.assertEqual(results, [checker.latest])++ def test_new_answer_clears_an_asset_from_the_previous_answer(self):+ checker, _ = self.make([{"name": self.NAME, "browser_download_url": self.URL}])+ checker.fetcher = lambda: json.dumps(release("v1.5.11", assets=[])).encode()+ checker.check_once()+ self.assertEqual(checker.latest[0], "1.5.11")+ self.assertIsNone(checker.download_url)+ checker.fetcher = lambda: json.dumps(release("v1.5.9")).encode()+ checker.check_once()+ self.assertIsNone(checker.latest)+ self.assertIsNone(checker.download_url)++ def test_failed_request_keeps_matching_cached_page_and_asset(self):+ checker, _ = self.make([{"name": self.NAME, "browser_download_url": self.URL}])+ previous = checker.latest+ checker.fetcher = lambda: (_ for _ in ()).throw(OSError("synthetic offline"))+ checker.check_once()+ self.assertEqual(checker.latest, previous)+ self.assertEqual(checker.download_url, self.URL)++if __name__ == "__main__":unittest.main()diff --git a/core/updates.py b/core/updates.pyindex 36fbea2..6163be5 100644--- a/core/updates.py+++ b/core/updates.py@@ -64,6 +64,18 @@ def visible_notice(found, enabled, dismissed):return found if enabled and found and found[0] != dismissed else None+def _portable_download(version, payload):+ name = f"Beamer-Portable-{version}-windows-x64.zip"+ url = f"https://github.com/kalkman-code/beamer/releases/download/v{version}/{name}"+ assets = payload.get("assets")+ if isinstance(assets, list):+ for asset in assets:+ if (isinstance(asset, dict) and asset.get("name") == name+ and asset.get("browser_download_url") == url):+ return url+ return None++def fetch(url=LATEST_URL):"""The response body as bytes. The Mac goes through Foundation, which trusts the system'scertificates; a bundled Python has no certificate store of its own there."""@@ -90,13 +102,15 @@ class Checker:calls `on_result((version, url) or None)` on that thread after each check that got an answer;the owner marshals it. A failed check keeps the last answer and logs once."""- def __init__(self, current, enabled, on_result, fetcher=fetch, logger=None):+ def __init__(self, current, enabled, on_result, fetcher=fetch, logger=None, portable=False):self.current = currentself.enabled = enabledself.on_result = on_resultself.fetcher = fetcherself.logger = logger or LOGGER+ self.portable = portableself.latest = None+ self.download_url = Noneself._wake = threading.Event()self._stop = threading.Event()self._thread = None@@ -129,6 +143,8 @@ class Checker:if not self.enabled() or self._stop.is_set():returnself.latest = newer_release(self.current, payload)+ self.download_url = (_portable_download(self.latest[0], payload)+ if self.portable and self.latest else None)if self.latest:self.logger.info("Beamer %s is available", self.latest[0])try:diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xmlindex b4cc078..6939230 100644--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml@@ -43,6 +43,9 @@</screenshots><content_rating type="oars-1.1"/><releases>+ <release version="1.5.10" date="2026-10-21">+ <description><p>Avoids repeatedly reading clipboard contents that cannot be shared and removes an unnecessary wait when returning with an empty clipboard. Failed clipboard reads can still retry.</p><p>Limits repeated Identify screens requests and leaves machines without an active desktop link out. Disabling update checks also clears the Mac menu's stale update action. Flatpak update actions consistently point to store update guidance. Windows input recovery clears stale modifiers after returning from the secure desktop.</p><p>The separate Windows portable package keeps its settings beside the executable and protects them with a passphrase. It needs no installation or administrator rights and does not change startup tasks or firewall rules. It cannot control elevated applications or the secure desktop. Discovery keeps installed and portable copies separate without duplicating replies sent through temporary network sockets.</p></description>+ </release><release version="1.5.9" date="2026-10-21"><description><p>Reduces mouse input building up on a slow receiver by reading ahead and combining waiting horizontal or vertical movement. Total travel and the order of buttons, keys and scrolling are preserved. Diagonal moves, reversals and axis changes stay separate to preserve crossing zones.</p><p>Improves clipboard reliability around switching machines, including brief retries when the clipboard is busy. Adds a visible notice for newer stable updates, with What's new and a per-version Dismiss button. Flatpak users get store update guidance. Linux builds now check GitHub for new versions too; turn off Check for updates in Settings to stop it. Nothing downloads or installs automatically.</p><p>Adds a Mouse only switch on macOS, Windows and Linux X11 to keep the keyboard on the machine you are using while sharing the mouse and clipboard. This switch is unavailable on Wayland.</p><p>Improves Windows-to-Linux accent handling by reading the foreground Windows app's layout, preserving printable AltGr output and trying Linux AltGr levels and supported single-accent dead-key sequences. Wayland still cannot type characters outside these supported layout paths.</p><p>Includes the missing library for generating pairing QR codes in Linux Flatpak builds. The README and bug-report form now list the Linux log locations.</p><p>Adds Identify screens on the Crossing page, showing numbers on local and directly linked desktop displays for three seconds. Machines on older versions are left out.</p><p>On Windows, Beamer no longer crashes at startup when the account name has an accented letter, such as É; thanks to kinowill for tracking it down.</p><p>While machines are linked, Beamer's log now summarises connection timings about every 30 seconds and tries to add a final summary when a connection ends: how long each machine spends queueing, sending, reading and applying input and scheduling its acknowledgement, and which addresses each connection uses. These lines hold times, counts and addresses only, not keys, text or pointer positions.</p></description></release>diff --git a/locales/beamer.pot b/locales/beamer.potindex c0faf6d..7435edd 100644--- a/locales/beamer.pot+++ b/locales/beamer.pot@@ -4136,17 +4136,16 @@ msgid "Check again"msgstr ""#: win_app/firewall_win.py-msgid "Fix the firewall"+msgid "Windows Firewall is blocking Beamer's input or pairing traffic. This can happen when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rules for private networks."msgstr ""#: win_app/firewall_win.py-#, python-brace-format-msgid "Beamer could not read the Windows Firewall: {error}"+msgid "Fix the firewall"msgstr ""#: win_app/firewall_win.py#, python-brace-format-msgid "Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rule for private networks."+msgid "Beamer could not read the Windows Firewall: {error}"msgstr ""#: win_app/firewall_win.py@@ -4165,7 +4164,7 @@ msgstr ""#: win_app/firewall_win.py#, python-brace-format-msgid "Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."+msgid "Windows treats {names} as a public network, so some of Beamer's firewall rules do not cover it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."msgstr ""#: win_app/firewall_win.py@@ -4183,7 +4182,7 @@ msgstr ""#: win_app/firewall_win.py#, python-brace-format-msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for {rules}, so {effects}. Installs made before these rules existed are missing them. Fixing it adds what is missing and leaves the working rules alone."+msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule covering this network for {rules}, so {effects}. Fixing it replaces Beamer's inbound firewall rules."msgstr ""#: win_app/firewall_win.py@@ -4487,6 +4486,22 @@ msgstr ""msgid "On this PC"msgstr ""+#: win_app/kvm_bridge_win.py+msgid "Protect Beamer Portable"+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "Unlock Beamer Portable"+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "Choose a passphrase of at least 12 characters. You need it each time Beamer starts. It protects pairing keys if this folder is lost. A forgotten passphrase cannot be recovered."+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "Enter the passphrase for this portable folder."+msgstr ""+#: win_app/kvm_bridge_win.pymsgid "Beamer requests keyboard and pointer access when each Wayland session starts."msgstr ""@@ -4499,6 +4514,10 @@ msgstr ""msgid "Ask again"msgstr ""+#: win_app/kvm_bridge_win.py+msgid "Download portable zip"+msgstr ""+#: win_app/kvm_bridge_win.pymsgid "Input:"msgstr ""@@ -4572,6 +4591,18 @@ msgstr ""msgid "Not known yet"msgstr ""+#: win_app/kvm_bridge_win.py+msgid "Portable mode leaves Windows Firewall unchanged. Your network must already allow Beamer."+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "Portable — settings and pairing keys stay in this folder, protected by your passphrase. Administrator apps cannot be controlled."+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "Enter the passphrase again."+msgstr ""+#: win_app/kvm_bridge_win.pymsgid "With it off, closing the window quits Beamer. Open Beamer again to bring the window back."msgstr ""@@ -4631,11 +4662,27 @@ msgstr ""msgid "Save failed"msgstr ""+#: win_app/kvm_bridge_win.py+msgid "Another Beamer copy controls input on this PC. Quit it to use input in this copy."+msgstr ""+#: win_app/kvm_bridge_win.py#, python-brace-formatmsgid "<b>Beamer {version}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br><a href=\"{url}\" style=\"color: {colour};\">{link}</a>"msgstr ""+#: win_app/kvm_bridge_win.py+msgid "Use at least 12 characters for the passphrase."+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "The passphrases do not match. Try again."+msgstr ""++#: win_app/kvm_bridge_win.py+msgid "The portable settings could not be unlocked or saved. Check the passphrase and that the folder is writable. Existing pairing keys have been kept."+msgstr ""+#: win_app/kvm_bridge_win.py#, python-brace-formatmsgid "Ready on TCP port {port}"@@ -5145,6 +5192,14 @@ msgstr ""msgid "This PC's keyboard and pointer are on {name}. Do the same again to bring them home."msgstr ""+#: win_app/portable_entry.py+msgid "Beamer Portable needs its Beamer.portable marker and a writable folder beside the app. Move the whole folder to writable storage and try again."+msgstr ""++#: win_app/portable_entry.py+msgid "Beamer Portable"+msgstr ""+#: win_app/sender.pymsgid "Not connected"msgstr ""diff --git a/locales/it.po b/locales/it.poindex bdb6322..a143e08 100644--- a/locales/it.po+++ b/locales/it.po@@ -4197,6 +4197,10 @@ msgstr "Nessuna spinta. La pressione attuale è 0 su {threshold} unità del puntmsgid "Check again"msgstr "Controlla di nuovo"+#: win_app/firewall_win.py+msgid "Windows Firewall is blocking Beamer's input or pairing traffic. This can happen when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rules for private networks."+msgstr "Windows Firewall sta bloccando il traffico di input o di abbinamento di Beamer. Può succedere se è stato premuto Annulla nella richiesta di Windows «Consenti l'accesso» per l'app: una regola di blocco prevale su qualsiasi regola di autorizzazione, quindi reinstallare non risolve il problema. La correzione rimuove il blocco e aggiunge le regole corrette per le reti private."+#: win_app/firewall_win.pymsgid "Fix the firewall"msgstr "Correggi il firewall"@@ -4206,11 +4210,6 @@ msgstr "Correggi il firewall"msgid "Beamer could not read the Windows Firewall: {error}"msgstr "Beamer non è riuscito a leggere Windows Firewall: {error}"-#: win_app/firewall_win.py-#, python-brace-format-msgid "Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rule for private networks."-msgstr "Windows Firewall blocca Beamer sulla porta {port}. Succede quando si preme Annulla nella richiesta di Windows \"consenti questa app\", e una regola di blocco prevale su qualsiasi regola di consenso, quindi reinstallare non la elimina. La correzione rimuove il blocco e aggiunge la regola giusta per le reti private."-#: win_app/firewall_win.pymsgid "Trust this network"msgstr "Considera attendibile questa rete"@@ -4227,8 +4226,8 @@ msgstr "Windows Firewall non ha una regola che consenta agli altri tuoi computer#: win_app/firewall_win.py#, python-brace-format-msgid "Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."-msgstr "Windows considera {names} una rete pubblica, quindi la regola del firewall di Beamer non vale lì e gli altri tuoi computer non possono entrare. Considerarla attendibile la contrassegna come privata, e li lascia entrare senza aprire la porta su ogni altra rete a cui si collega questo PC."+msgid "Windows treats {names} as a public network, so some of Beamer's firewall rules do not cover it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."+msgstr "Windows considera {names} una rete pubblica, quindi alcune regole del firewall di Beamer non la coprono e gli altri tuoi computer non possono accedere. Considerandola attendibile, la rete diventa privata: così possono accedere senza aprire la porta su tutte le altre reti a cui questo PC si collega."#: win_app/firewall_win.pymsgid "this private network"@@ -4245,8 +4244,8 @@ msgstr "La regola del firewall di Beamer non vale su questa rete (Windows la chi#: win_app/firewall_win.py#, python-brace-format-msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for {rules}, so {effects}. Installs made before these rules existed are missing them. Fixing it adds what is missing and leaves the working rules alone."-msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port}, ma non c'è una regola per {rules}, quindi {effects}. Le installazioni precedenti a queste regole ne sono prive. La correzione aggiunge ciò che manca e lascia invariate le regole funzionanti."+msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule covering this network for {rules}, so {effects}. Fixing it replaces Beamer's inbound firewall rules."+msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port}, ma nessuna regola copre questa rete per {rules}, quindi {effects}. La correzione sostituisce le regole in entrata del firewall di Beamer."#: win_app/firewall_win.py#, python-brace-format@@ -4553,6 +4552,22 @@ msgstr "Gli altri computer controllano questo PC"msgid "On this PC"msgstr "Su questo PC"+#: win_app/kvm_bridge_win.py+msgid "Protect Beamer Portable"+msgstr "Proteggi Beamer Portable"++#: win_app/kvm_bridge_win.py+msgid "Unlock Beamer Portable"+msgstr "Sblocca Beamer Portable"++#: win_app/kvm_bridge_win.py+msgid "Choose a passphrase of at least 12 characters. You need it each time Beamer starts. It protects pairing keys if this folder is lost. A forgotten passphrase cannot be recovered."+msgstr "Scegli una frase segreta di almeno 12 caratteri. Ti servirà a ogni avvio di Beamer. Protegge le chiavi di abbinamento se perdi questa cartella. Una frase segreta dimenticata non può essere recuperata."++#: win_app/kvm_bridge_win.py+msgid "Enter the passphrase for this portable folder."+msgstr "Inserisci la frase segreta di questa cartella portatile."+#: win_app/kvm_bridge_win.pymsgid "Beamer requests keyboard and pointer access when each Wayland session starts."msgstr "Beamer chiede l'accesso a tastiera e puntatore all'inizio di ogni sessione Wayland."@@ -4565,6 +4580,10 @@ msgstr "Non richiesto"msgid "Ask again"msgstr "Chiedi di nuovo"+#: win_app/kvm_bridge_win.py+msgid "Download portable zip"+msgstr "Scarica lo zip portatile"+#: win_app/kvm_bridge_win.pymsgid "Input:"msgstr "Input:"@@ -4640,6 +4659,18 @@ msgstr "Nasconde ogni indirizzo IP e hardware in questa finestra e nell'area dimsgid "Not known yet"msgstr "Non ancora noto"+#: win_app/kvm_bridge_win.py+msgid "Portable mode leaves Windows Firewall unchanged. Your network must already allow Beamer."+msgstr "La modalità portatile non modifica Windows Firewall. La rete deve già consentire Beamer."++#: win_app/kvm_bridge_win.py+msgid "Portable — settings and pairing keys stay in this folder, protected by your passphrase. Administrator apps cannot be controlled."+msgstr "Portatile: impostazioni e chiavi di abbinamento restano in questa cartella, protette dalla frase segreta. Non è possibile controllare le app eseguite come amministratore."++#: win_app/kvm_bridge_win.py+msgid "Enter the passphrase again."+msgstr "Inserisci di nuovo la frase segreta."+#: win_app/kvm_bridge_win.pymsgid "With it off, closing the window quits Beamer. Open Beamer again to bring the window back."msgstr "Se disattivato, chiudere la finestra chiude Beamer. Apri di nuovo Beamer per riavere la finestra."@@ -4701,11 +4732,27 @@ msgstr "la porta deve essere un numero intero da 1 a 65535"msgid "Save failed"msgstr "Salvataggio non riuscito"+#: win_app/kvm_bridge_win.py+msgid "Another Beamer copy controls input on this PC. Quit it to use input in this copy."+msgstr "Un'altra copia di Beamer controlla l'input su questo PC. Chiudila per usare l'input in questa copia."+#: win_app/kvm_bridge_win.py#, python-brace-formatmsgid "<b>Beamer {version}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br><a href=\"{url}\" style=\"color: {colour};\">{link}</a>"msgstr "<b>Beamer {version}</b><br>Una sola tastiera e un solo mouse per tutti i tuoi Mac e PC.<br><br><a href=\"{url}\" style=\"color: {colour};\">{link}</a>"+#: win_app/kvm_bridge_win.py+msgid "Use at least 12 characters for the passphrase."+msgstr "Usa almeno 12 caratteri per la frase segreta."++#: win_app/kvm_bridge_win.py+msgid "The passphrases do not match. Try again."+msgstr "Le frasi segrete non coincidono. Riprova."++#: win_app/kvm_bridge_win.py+msgid "The portable settings could not be unlocked or saved. Check the passphrase and that the folder is writable. Existing pairing keys have been kept."+msgstr "Impossibile sbloccare o salvare le impostazioni portatili. Controlla la frase segreta e che la cartella sia scrivibile. Le chiavi di abbinamento esistenti sono state conservate."+#: win_app/kvm_bridge_win.py#, python-brace-formatmsgid "Ready on TCP port {port}"@@ -5220,6 +5267,14 @@ msgstr "La tastiera e il puntatore di {name} sono su questo PC. Riporta il puntamsgid "This PC's keyboard and pointer are on {name}. Do the same again to bring them home."msgstr "La tastiera e il puntatore di questo PC sono su {name}. Ripeti la stessa azione per riportarli a casa."+#: win_app/portable_entry.py+msgid "Beamer Portable needs its Beamer.portable marker and a writable folder beside the app. Move the whole folder to writable storage and try again."+msgstr "Beamer Portable richiede il marcatore Beamer.portable e una cartella scrivibile accanto all'app. Sposta l'intera cartella in un percorso scrivibile e riprova."++#: win_app/portable_entry.py+msgid "Beamer Portable"+msgstr "Beamer Portable"+#: win_app/sender.pymsgid "Not connected"msgstr "Non connesso"diff --git a/mac_app/bridge.py b/mac_app/bridge.pyindex ee56d04..c2988f2 100644--- a/mac_app/bridge.py+++ b/mac_app/bridge.py@@ -80,7 +80,7 @@ ROUND_TRIP_MAX_AGE_SECONDS = 5.0# the ownership by force after one second), then goes ahead.LET_GO_WAIT_SECONDS = 1.3OWN_PLATFORM = "macos"-CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt", "identify_screens")+CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt", "identify_screens", "motion_path")MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause", "brightness_up", "brightness_down"})# Why input came home, in words, for the alert. A why that is not here comes home quietly.@@ -2706,10 +2706,10 @@ class KVMController:except Exception:if attempt == 2:self.logger.exception("the clipboard could not be sent")- if sent:+ if sent is not False:breakfinally:- if not sent:+ if sent is False:with self._owner_lock:self.owner.clipboard_failed(peer)while True:@@ -2928,22 +2928,23 @@ class KVMController:"""Read this Mac's clipboard and send it as a clipboard message. Text over CLIPBOARD_MAX_BYTESand an image protocol.png_fits refuses are each dropped on their own, so an oversizedscreenshot still lets its text through; with nothing left nothing is sent. Nothing is sent- either when `waiting` was dropped with its link while the pasteboard was read."""+ either when `waiting` was dropped with its link while the pasteboard was read.+ True means posted, None means no supported content, and False means failed or cancelled."""if self._peers_up.get(peer) is None:- return+ return Falseif generation is not None and (self.owner.on != peer or self.owner._visit_route != generation or(stamp is not None and self._clipboard_stamp_now() != stamp)):- return- text, image = self.clipboard.get_contents()+ return False+ text, image = getattr(self.clipboard, "read_contents", self.clipboard.get_contents)()if generation is not None and (self.owner.on != peer or self.owner._visit_route != generation or(stamp is not None and self._clipboard_stamp_now() != stamp)):- return+ return Falsewith self._clip_lock:if self._clip_wait.get(peer) is not waiting:- return+ return Falselink = self._peers_up.get(peer)if link is None:- return+ return Falsecaps = getattr(link, "caps", ()) or ()if text and ("clipboard" not in caps or len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES):if "clipboard" in caps:@@ -2955,7 +2956,7 @@ class KVMController:image = Noneif not text and image is None:self.logger.debug("local clipboard is empty; not sending it")- return+ return Nonereturn link.post(protocol.clipboard_msg(text or None, image))def _set_clipboard(self, message):diff --git a/mac_app/clipboard_mac.py b/mac_app/clipboard_mac.pyindex 0497be3..469aa20 100644--- a/mac_app/clipboard_mac.py+++ b/mac_app/clipboard_mac.py@@ -34,12 +34,16 @@ _written_count = None_LOCK = threading.Lock()-def _text_from_pasteboard(pasteboard):+def _text_from_pasteboard(pasteboard, *, strict=False):text = pasteboard.stringForType_(AppKit.NSPasteboardTypeString)+ # NSPasteboard also reports provider timeouts as nil while the advertised type remains.+ if (strict and text is None and+ AppKit.NSPasteboardTypeString in (getattr(pasteboard, "types", lambda: ())() or ())):+ raise OSError("the advertised pasteboard text could not be read")return text if isinstance(text, str) and text else None-def _png_from_pasteboard(pasteboard):+def _png_from_pasteboard(pasteboard, *, strict=False):"""PNG bytes for the image on the pasteboard, or None. PNG is taken asis; TIFF (what most apps put up, and what a Retina grab carriesuncompressed at 25MB+) is re-encoded through NSBitmapImageRep, which@@ -47,23 +51,31 @@ def _png_from_pasteboard(pasteboard):png = pasteboard.dataForType_(AppKit.NSPasteboardTypePNG)if png is not None and len(png):return bytes(png)+ missing_png = (strict and png is None and+ AppKit.NSPasteboardTypePNG in (getattr(pasteboard, "types", lambda: ())() or ()))tiff = pasteboard.dataForType_(AppKit.NSPasteboardTypeTIFF)- if tiff is None or not len(tiff):- return None- rep = AppKit.NSBitmapImageRep.imageRepWithData_(tiff)- if rep is None:- return None- png = rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, None)- return bytes(png) if png is not None and len(png) else None---def get_contents():+ missing_tiff = (strict and tiff is None and+ AppKit.NSPasteboardTypeTIFF in (getattr(pasteboard, "types", lambda: ())() or ()))+ if tiff is not None and len(tiff):+ rep = AppKit.NSBitmapImageRep.imageRepWithData_(tiff)+ if rep is not None:+ png = rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, None)+ if png is not None and len(png):+ return bytes(png)+ if missing_png or missing_tiff:+ raise OSError("the advertised pasteboard image could not be read")+ return None+++def get_contents(*, strict=False):"""(text, png) from the general pasteboard, either None when absent.Both are read independently and both are sent: an image copied fromFinder or a browser usually carries a filename or URL as its text, andthe pasting app on the other side picks the representation it wants,exactly as it would from the source clipboard. Never raises."""if AppKit is None:+ if strict:+ raise OSError("the macOS clipboard is unavailable")return None, Nonetry:with _LOCK:@@ -71,23 +83,37 @@ def get_contents():for _ in range(3):count = pasteboard.changeCount()text, png = None, None+ failed = Falsetry:- text = _text_from_pasteboard(pasteboard)+ text = _text_from_pasteboard(pasteboard, strict=strict)except Exception:+ failed = TrueLOGGER.exception("failed to read pasteboard text")try:- png = _png_from_pasteboard(pasteboard)+ png = _png_from_pasteboard(pasteboard, strict=strict)except Exception:+ failed = TrueLOGGER.exception("failed to read the pasteboard image")if count == pasteboard.changeCount():+ if strict and failed and text is None and png is None:+ raise OSError("the pasteboard provider could not be read")return text, pngLOGGER.warning("the pasteboard kept changing during a read")+ if strict:+ raise OSError("the pasteboard kept changing during a read")return None, None- except Exception:+ except Exception as exc:LOGGER.exception("failed to read the macOS clipboard")+ if strict:+ raise OSError("failed to read the macOS clipboard") from excreturn None, None+def read_contents():+ """Like get_contents, but raise OSError on failure so a caller can retry an unchanged copy."""+ return get_contents(strict=True)++def _change_count():try:return AppKit.NSPasteboard.generalPasteboard().changeCount()diff --git a/mac_app/identify_overlay.py b/mac_app/identify_overlay.pyindex 86939cd..744a929 100644--- a/mac_app/identify_overlay.py+++ b/mac_app/identify_overlay.py@@ -1,5 +1,7 @@"""Brief, click-through display labels. All AppKit work stays on the main thread."""+import time+import AppKitfrom PyObjCTools import AppHelper@@ -24,8 +26,13 @@ class IdentifyOverlay:self.logger = loggerself.panels = []self._generation = 0+ self._last_request_at = Nonedef show(self, labels):+ now = time.monotonic()+ if self._last_request_at is not None and now - self._last_request_at < OVERLAY_SECONDS:+ return+ self._last_request_at = nowself.hide()generation = self._generationtry:diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex 11fc307..035b42a 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -1214,6 +1214,7 @@ class ControlWindow(AppKit.NSObject):# made during this run needs a relaunch before the keyboard crosses, however ready the tap looks.self.granted_at_launch = accessibility_granted() and input_monitoring_granted()self.update_checker = None+ self.update_handler = Noneself._update = None# The list of paired machines and the pairing sheet; TrayApp gives it the pairing service.self.panel = machines_panel.MachinesPanel(controller, settings_store, logger, self)@@ -2933,7 +2934,7 @@ class ControlWindow(AppKit.NSObject):if on and self.update_checker is not None:self.update_checker.check_now()if not on:- self.show_update(None)+ (self.update_handler or self.show_update)(None)@objc.python_methoddef show_update(self, found):@@ -4572,7 +4573,7 @@ class ControlWindow(AppKit.NSObject):# What was learned belonged to the old address.raw["pc_name"] = ""raw["mac_address"] = ""- cfg = self.settings_store.save(raw)+ cfg = self.settings_store.save(raw, pin_address=True)except (SettingsError, TypeError, ValueError) as exc:self._say(str(exc), "fault")return@@ -5111,6 +5112,7 @@ class TrayApp(rumps.App):lambda found: AppHelper.callAfter(self._update_found, found), logger=logger,)self.control_window.update_checker = self.update_checker+ self.control_window.update_handler = self._update_foundself._notch_failed = Falseself.header_item = header = _tray_item(f"Beamer {VERSION}", callback=None)self.update_url = Nonediff --git a/mac_app/machines_panel.py b/mac_app/machines_panel.pyindex d062354..3943495 100644--- a/mac_app/machines_panel.py+++ b/mac_app/machines_panel.py@@ -855,17 +855,18 @@ class MachinesPanel:def _refresh_heard(self):service = self.serviceheard = service.machines() if service is not None else []- chosen = self.chosen["address"] if self.chosen is not None else None+ chosen = pairing.discovery_endpoint(self.chosen) if self.chosen is not None else Nonehide = self.controller.cfg.hide_addresseskey = (chosen, hide, tuple(tuple(sorted((k, str(v)) for k, v in item.items())) for item in heard))if key == self._heard_key:returnself._heard_key = keyself._heard = heard- current = next((item for item in heard if item["address"] == chosen), None)+ current = pairing.refreshed_discovery(self.chosen, heard)if current is not None and current != self.chosen:showed = self.chosen["pair_id"]self.chosen = current+ chosen = pairing.discovery_endpoint(current)fault = self._pair_ink == "fault"if current["pair_id"] != showed and not self.pairing and (current["pair_id"] or not fault):self._say_choice()@@ -873,7 +874,7 @@ class MachinesPanel:self.heard_list.removeArrangedSubview_(view)view.removeFromSuperview()for index, (item, shared) in enumerate(zip(heard, peerlist.sharing_a_name(heard))):- self._heard_row(index, item, item["address"] == chosen, shared)+ self._heard_row(index, item, pairing.discovery_endpoint(item) == chosen, shared)if service is not None and service.error:self.heard_empty.set(tr("Beamer cannot look for machines: {reason}").format(reason=service.error), ink="fault")else:@@ -881,7 +882,7 @@ class MachinesPanel:tr("Looking for machines running Beamer. Open it on the other machine and it appears here; across a VPN or on guest Wi-Fi it may not, so type its address below."), ink="ink_2")self.heard_frame.setHidden_(not heard)self.heard_empty.view.setHidden_(bool(heard))- if chosen is not None and chosen not in {item["address"] for item in heard}:+ if chosen is not None and chosen not in {pairing.discovery_endpoint(item) for item in heard}:self.chosen = Noneself._heard_key = None@@ -952,7 +953,7 @@ class MachinesPanel:self._cancel_nearby()if kind == "machine":# The list may have refreshed since the row was chosen; pair with the latest beacon.- target = next((item for item in self._heard if item["address"] == target["address"]), target)+ target = pairing.refreshed_discovery(target, self._heard) or targetname = target["name"]if target.get("pairing") != pairing.PAIRING_V3:self.chosen = targetdiff --git a/mac_app/settings_store.py b/mac_app/settings_store.pyindex 9192330..e429584 100644--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@ -278,7 +278,7 @@ def _rename_zones(zones, old, new):return [{**zone, "peer": new} if zone.get("peer") == old else zone for zone in zones]-def _merge_config(base, cfg):+def _merge_config(base, cfg, *, pin_address=False):"""`base` with `cfg`'s pairing fields in the first desktop and the rest by name."""settings = copy.deepcopy(base)raw = config_to_raw(cfg)@@ -314,6 +314,9 @@ def _merge_config(base, cfg):if cfg.host != peer.get("host"):peer.update(name=cfg.pc_name, hw=cfg.mac_address, host_pinned=True)peer.update(host=cfg.host, port=cfg.port, send=cfg.send_to_windows, allow_drive=cfg.allow_windows_to_drive)+ chosen = peerlist.first_desktop(peers)+ if pin_address and chosen is not None and chosen.get("host"):+ chosen["host_pinned"] = Truesettings["crossing"] = {name: value for name, value in crossing.items() if not (peerlist.first_desktop(peers) is not None and name in MOVED_CROSSING)}@@ -467,7 +470,7 @@ class SettingsStore:self.save_settings(outcome["settings"])return outcome["changed"], []- def save(self, raw, settings_changes=None, remove_settings=()):+ def save(self, raw, settings_changes=None, remove_settings=(), *, pin_address=False):try:cfg = config_module.parse_config(raw)except (config_module.ConfigError, TypeError, ValueError, OverflowError) as exc:@@ -487,7 +490,7 @@ class SettingsStore:base.update(copy.deepcopy(settings_changes))for key in remove_settings:base.pop(key, None)- return self._config(self.save_settings(_merge_config(base, cfg)))+ return self._config(self.save_settings(_merge_config(base, cfg, pin_address=pin_address)))@staticmethoddef _without_stale_pairing(cfg, base, handed):diff --git a/mac_app/tests/test_atlas_canvas.py b/mac_app/tests/test_atlas_canvas.pyindex 059a3ca..1c38038 100644--- a/mac_app/tests/test_atlas_canvas.py+++ b/mac_app/tests/test_atlas_canvas.py@@ -623,7 +623,7 @@ class AtlasCanvas(Page):self.assertLess(canvas._map()[1], base_scale)- def test_small_tiles_hide_detail_and_centre_the_title(self):+ def test_small_tiles_hide_detail_and_keep_title_clear_of_display_numbers(self):window = self.layout()canvas = window.atlas_canvascanvas.setFrame_(((0, 0), (480, canvas.HEIGHT)))@@ -631,13 +631,18 @@ class AtlasCanvas(Page):canvas._draw(False)frame = canvas._map()[0][BEE]- self.assertLess(frame[3], 56)+ self.assertLess(frame[3], 32)self.assertTrue(canvas.state_for_tile[BEE].isHidden())self.assertTrue(canvas.dot_for_tile[BEE].isHidden())self.assertTrue(canvas.outcome_for_tile[BEE].isHidden())title = canvas.label_for_tile[BEE].frame()- self.assertAlmostEqual(title.origin.y + title.size.height / 2,- frame[1] + frame[3] / 2)+ self.assertAlmostEqual(title.origin.y, frame[1] + 11)+ self.assertGreater(title.size.width, 0)+ self.assertTrue(AppKit.NSContainsRect(diagram._rect(frame), title))+ badges = canvas.display_number_layers[BEE]+ self.assertTrue(badges)+ for badge in badges:+ self.assertFalse(AppKit.NSIntersectsRect(title, badge.frame()))def test_edge_seam_lights_the_whole_contact_and_part_only_the_picked_thirds(self):window = self.layout()diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.pyindex eac1c9f..5663eab 100644--- a/mac_app/tests/test_clipboard_mac.py+++ b/mac_app/tests/test_clipboard_mac.py@@ -6,6 +6,7 @@ import structimport threadingimport timeimport unittest+from unittest import mockimport zlibimport osimport sys@@ -46,6 +47,9 @@ class FakePasteboard:def dataForType_(self, kind):return self.data.get(kind)+ def types(self):+ return list(self.data) + ([clipboard_mac.AppKit.NSPasteboardTypeString] if self.string is not None else [])+def clearContents(self):self.cleared += 1self.count += 1@@ -151,6 +155,75 @@ class ChangedContentsTests(unittest.TestCase):self.board.dataForType_ = failed_imageself.assertEqual(clipboard_mac.get_contents(), ("copied", None))+ def test_strict_read_distinguishes_a_provider_failure_from_empty(self):+ self.board.string = None+ self.assertEqual(clipboard_mac.read_contents(), (None, None))+ with mock.patch.object(self.board, "stringForType_", side_effect=OSError("provider busy")):+ with self.assertRaises(OSError):+ clipboard_mac.read_contents()+ self.assertEqual(clipboard_mac.get_contents(), (None, None))+ self.board.string = "copied"+ self.assertEqual(clipboard_mac.read_contents(), ("copied", None))++ def test_strict_read_preserves_valid_text_when_the_image_provider_fails(self):+ with mock.patch.object(self.board, "dataForType_", side_effect=OSError("image busy")):+ self.assertEqual(clipboard_mac.read_contents(), ("copied", None))++ def test_strict_read_retries_advertised_text_returning_nil_at_a_stable_count(self):+ count = self.board.count+ with mock.patch.object(self.board, "stringForType_", side_effect=[None, "copied"]):+ with self.assertRaises(OSError):+ clipboard_mac.read_contents()+ self.assertEqual(self.board.count, count)+ self.assertEqual(clipboard_mac.read_contents(), ("copied", None))++ def test_strict_read_retries_advertised_png_returning_nil(self):+ AppKit = clipboard_mac.AppKit+ self.board.string = None+ self.board.data = {AppKit.NSPasteboardTypePNG: tiny_png()}+ original = self.board.dataForType_+ with mock.patch.object(self.board, "dataForType_", return_value=None):+ with self.assertRaises(OSError):+ clipboard_mac.read_contents()+ self.assertEqual(clipboard_mac.get_contents(), (None, None))+ self.assertEqual(clipboard_mac.read_contents(), (None, original(AppKit.NSPasteboardTypePNG)))++ def test_strict_read_keeps_real_empty_text_and_an_unoffered_clipboard_terminal(self):+ self.board.string = ""+ self.assertEqual(clipboard_mac.read_contents(), (None, None))+ self.board.string = None+ self.assertEqual(clipboard_mac.read_contents(), (None, None))++ def test_strict_read_retries_advertised_tiff_returning_nil(self):+ AppKit = clipboard_mac.AppKit+ self.board.string = None+ self.board.data = {AppKit.NSPasteboardTypeTIFF: b"promised TIFF"}+ with mock.patch.object(self.board, "dataForType_", return_value=None):+ with self.assertRaises(OSError):+ clipboard_mac.read_contents()+ self.assertEqual(clipboard_mac.get_contents(), (None, None))++ def test_strict_read_keeps_an_unsupported_tiff_terminal(self):+ AppKit = clipboard_mac.AppKit+ self.board.string = None+ self.board.data = {AppKit.NSPasteboardTypeTIFF: b"not a TIFF"}+ with mock.patch.object(AppKit, "NSBitmapImageRep", create=True) as codec, \+ mock.patch.object(AppKit, "NSBitmapImageFileTypePNG", 0, create=True):+ codec.imageRepWithData_.return_value = None+ self.assertEqual(clipboard_mac.read_contents(), (None, None))+ codec.imageRepWithData_.return_value = mock.Mock()+ codec.imageRepWithData_.return_value.representationUsingType_properties_.return_value = None+ self.assertEqual(clipboard_mac.read_contents(), (None, None))++ def test_strict_read_rejects_a_pasteboard_that_never_stabilises(self):+ def read(kind):+ self.board.count += 1+ return self.board.string+ with mock.patch.object(self.board, "stringForType_", side_effect=read):+ with self.assertRaises(OSError):+ clipboard_mac.read_contents()+ self.assertEqual(clipboard_mac.get_contents(), (None, None))+def test_copy_during_read_retries_the_newest_stable_snapshot(self):original = self.board.stringForType_def read(kind):diff --git a/mac_app/tests/test_identify_screens.py b/mac_app/tests/test_identify_screens.pyindex 8ae6356..ed476f2 100644--- a/mac_app/tests/test_identify_screens.py+++ b/mac_app/tests/test_identify_screens.py@@ -73,10 +73,17 @@ class OverlayTests(unittest.TestCase):self.assertEqual(self.overlay.panels, [])self.assertFalse(any(panel.isVisible() for panel in panels))- def test_repeat_invocation_replaces_panels_and_old_timeout_cannot_hide_new_ones(self):+ @mock.patch("time.monotonic", return_value=0.0)+ def test_repeat_does_not_replace_panels_or_extend_expiry_and_reopens_at_boundary(self, clock):self.overlay.show({"0": 2, "1": 1})previous = list(self.overlay.panels)_delay, old_expire, old_args = self.later[-1]+ clock.return_value = 2.9+ for _ in range(100):+ self.overlay.show({"0": 1, "1": 2})+ self.assertEqual(self.overlay.panels, previous)+ self.assertEqual(len(self.later), 1)+ clock.return_value = 3.0self.overlay.show({"0": 2, "1": 1})old_expire(*old_args)self.assertEqual(len(self.overlay.panels), 2)@@ -86,6 +93,18 @@ class OverlayTests(unittest.TestCase):expire(*args)self.assertEqual(self.overlay.panels, [])+ @mock.patch("time.monotonic", return_value=0.0)+ def test_failed_show_and_explicit_hide_do_not_reset_request_limit(self, clock):+ with mock.patch.object(identify_overlay.desktop_mac, "display_map", side_effect=RuntimeError("unavailable")):+ self.overlay.show({"0": 1})+ self.overlay.hide()+ clock.return_value = 2.9+ self.overlay.show({"0": 1})+ self.assertEqual(self.overlay.panels, [])+ clock.return_value = 3.0+ self.overlay.show({"0": 1})+ self.assertEqual(len(self.overlay.panels), 2)+def test_stale_request_is_replaced_by_numbers_for_all_current_displays(self):self.overlay.show({"missing": 3})self.assertEqual([panel.identify_number for panel in self.overlay.panels], [1, 2])diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.pyindex b6258fd..40fb4dc 100644--- a/mac_app/tests/test_mac_links.py+++ b/mac_app/tests/test_mac_links.py@@ -567,6 +567,33 @@ class ComingHomeTests(Base):class ClipboardTests(Base):+ def test_unsendable_clipboards_are_read_once_until_the_next_local_copy(self):+ for text, image, caps in ((None, None, CAPS), ("", None, CAPS),+ ("x" * (protocol.CLIPBOARD_MAX_BYTES + 1), None, CAPS),+ (None, b"not a PNG", CAPS), ("unsupported", None, ())):+ with self.subTest(text_length=len(text or ""), image=image, caps=caps):+ self.setUp()+ self.up(caps=caps)+ self.clipboard.copy(text)+ self.clipboard.image = image+ with mock.patch.object(self.clipboard, "get_contents", wraps=self.clipboard.get_contents) as read:+ self.controller.set_redirecting(True)+ settle(self.controller)+ self.link.arrives(self.controller, protocol.accept_msg(self.controller.owner.route))+ self.controller.set_redirecting(False)+ settle(self.controller)+ self.controller.set_redirecting(True)+ settle(self.controller)+ self.link.arrives(self.controller, protocol.accept_msg(self.controller.owner.route))+ self.assertEqual(read.call_count, 1)+ self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())+ self.clipboard.copy("new copy")+ self.controller._owner_tick()+ settle(self.controller)+ self.assertEqual(read.call_count, 2)+ if "clipboard" in caps:+ self.assertEqual(self.link.posted[-1], protocol.clipboard_msg("new copy"))+def test_a_read_finishing_after_home_never_posts_private_local_text(self):self.up()self.controller.set_redirecting(True)@@ -619,7 +646,7 @@ class ClipboardTests(Base):self.controller.set_redirecting(True)settle(self.controller)self.link.arrives(self.controller, protocol.accept_msg(1))- for failure in ("read", "read_exception", "post", "post_exception"):+ for failure in ("read_exception", "post", "post_exception"):with self.subTest(failure=failure):text = "new local copy: " + failureself.clipboard.copy(text)@@ -630,7 +657,7 @@ class ClipboardTests(Base):if len(calls) == 1:if failure.endswith("exception"):raise OSError("clipboard temporarily busy")- return (None, None) if failure == "read" else False+ return Falsereturn read() if failure.startswith("read") else post(*args)target, name = (self.clipboard, "get_contents") if failure.startswith("read") else (self.link, "post")with mock.patch.object(target, name, side_effect=attempt):@@ -645,7 +672,7 @@ class ClipboardTests(Base):settle(self.controller)self.link.arrives(self.controller, protocol.accept_msg(1))self.clipboard.copy("temporarily unreadable")- with mock.patch.object(self.clipboard, "get_contents", return_value=(None, None)) as read:+ with mock.patch.object(self.clipboard, "get_contents", side_effect=OSError("clipboard busy")) as read:self.controller._owner_tick()self.controller._step(lambda owner: owner.input({"type": "keydown", "data": {"key": "a"}}))settle(self.controller)@@ -694,7 +721,7 @@ class ClipboardTests(Base):def test_a_failed_read_is_tried_again_on_the_next_crossing(self):self.up()read = self.clipboard.get_contents- self.clipboard.get_contents = lambda: (None, None)+ self.clipboard.get_contents = mock.Mock(side_effect=OSError("clipboard busy"))self.controller.set_redirecting(True)settle(self.controller)self.link.arrives(self.controller, protocol.accept_msg(1))diff --git a/mac_app/tests/test_machines_panel.py b/mac_app/tests/test_machines_panel.pyindex ff0b4a8..407b3ea 100644--- a/mac_app/tests/test_machines_panel.py+++ b/mac_app/tests/test_machines_panel.py@@ -794,6 +794,19 @@ class EnteringACodeTests(Base):self.assertIsNone(self.panel.chosen["pair_id"])self.assertIn("not showing a code yet", self.panel.pair_status.text)+ def test_installed_and_portable_on_one_ip_keep_separate_selection(self):+ installed = heard(pair_id="installed")+ portable = dict(installed, name="Laptop (Portable)", port=53000,+ reply_port=53001, pair_id="portable")+ self.service.heard = [installed, portable]+ self.panel.refresh()+ self.panel._choose(1)+ self.assertEqual(self.panel.chosen, portable)+ refreshed = dict(portable, pair_id="new-portable")+ self.service.heard = [dict(installed, pair_id="new-installed"), refreshed]+ self.panel.refresh()+ self.assertEqual(self.panel.chosen, refreshed)+def test_a_new_code_or_reply_port_replaces_what_pairing_will_use(self):self.refresh_heard(heard(pair_id="first"))self.panel._choose(0)diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.pyindex 4f76a00..1fe7125 100644--- a/mac_app/tests/test_settings_store.py+++ b/mac_app/tests/test_settings_store.py@@ -15,6 +15,20 @@ from settings_store import SettingsError, SettingsStore, config_to_rawclass SettingsStoreTests(unittest.TestCase):+ def test_explicitly_saving_the_same_learnt_host_pins_it(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "settings.json"+ store = SettingsStore(path)+ store.save(self.valid_raw())+ settings = store.current()+ settings["peers"][0]["host_pinned"] = False+ store.save_settings(settings)+ raw = config_to_raw(store.load())+ store.save(raw)+ self.assertIs(store.current()["peers"][0]["host_pinned"], False)+ store.save(raw, pin_address=True)+ self.assertIs(SettingsStore(path).current()["peers"][0]["host_pinned"], True)+def test_editing_a_learnt_host_pins_it_and_survives_reload(self):with tempfile.TemporaryDirectory() as directory:path = Path(directory) / "settings.json"diff --git a/mac_app/tests/test_update_notice.py b/mac_app/tests/test_update_notice.pyindex c43ceae..30eca8e 100644--- a/mac_app/tests/test_update_notice.py+++ b/mac_app/tests/test_update_notice.py@@ -39,6 +39,21 @@ class UpdateNoticeTest(fixture.Page):self.assertTrue(window.update_notice.view.isHidden())self.assertIsNone(window.update_url)+ def test_switching_off_clears_the_tray_download_action(self):+ window = self.build([])+ header = SimpleNamespace(title="", set_callback=lambda callback: setattr(header, "callback", callback))+ tray = SimpleNamespace(controller=self.controller, control_window=window, header_item=header,+ open_update=lambda _sender: None, update_url=None)+ window.update_handler = lambda found: kvm.TrayApp._update_found(tray, found)+ window.update_handler(FOUND)+ self.assertIsNotNone(header.callback)+ window._set_check_updates(False)+ self.assertIsNone(tray.update_url)+ self.assertIsNone(header.callback)+ self.assertNotIn("available", header.title)+ window.update_handler(FOUND)+ self.assertIsNone(header.callback)+def test_whats_new_opens_the_release_only_on_a_click(self):window = self.build([])workspace = mock.Mock()diff --git a/tools/portable_acceptance.py b/tools/portable_acceptance.pynew file mode 100644index 0000000..e382b5f--- /dev/null+++ b/tools/portable_acceptance.py@@ -0,0 +1,261 @@+"""Opt-in frozen portable qualification, imported by --import-probe; source imports do nothing."""++import json+import os+from pathlib import Path+import sys+++def qualify():+ import base64+ import ctypes+ import ipaddress+ import socket+ import tempfile+ import time+ from contextlib import ExitStack++ from PySide6.QtWidgets import QApplication, QMessageBox, QSystemTrayIcon, QWidget+ import app_config+ import kvm_bridge_win as kvm+ import theme+ from core import portable_runtime+ from core.portable_store import PortableStore++ root = Path(sys.executable).resolve().parent+ output = root / 'data' / 'acceptance.json'+ result = {'passed': False, 'checks': [], 'network_scope': 'loopback', 'medium_token': False}+ window = None+ app = None++ def check(name, condition):+ if not condition:+ raise AssertionError(name)+ result['checks'].append(name)++ def forbidden(*args, **kwargs):+ raise AssertionError('A host mutation or network update was attempted')++ class patch:+ def __init__(self, owner, name, value):+ self.owner, self.name, self.value = owner, name, value++ def __enter__(self):+ self.before = getattr(self.owner, self.name)+ setattr(self.owner, self.name, self.value)+ return self.value++ def __exit__(self, *exc):+ setattr(self.owner, self.name, self.before)++ def wait_for(predicate):+ deadline = time.monotonic() + 8+ while time.monotonic() < deadline:+ app.processEvents()+ if predicate():+ return True+ time.sleep(0.02)+ return False++ original_socket = socket.socket+ non_loopback_attempts = []++ def loopback_address(address):+ try:+ allowed = ipaddress.ip_address(address[0]).is_loopback+ except ValueError:+ allowed = False+ if not allowed:+ non_loopback_attempts.append('blocked')+ raise OSError('Qualification permits loopback sockets only')+ return address++ class LoopbackSocket(original_socket):+ def bind(self, address):+ if self.family == socket.AF_INET and address[0] in ('', '0.0.0.0'):+ address = ('127.0.0.1', address[1])+ if self.family == socket.AF_INET6 and address[0] in ('', '::'):+ address = ('::1', *address[1:])+ if self.family in (socket.AF_INET, socket.AF_INET6):+ loopback_address(address)+ return super().bind(address)++ def connect(self, address):+ return super().connect(loopback_address(address))++ def connect_ex(self, address):+ return super().connect_ex(loopback_address(address))++ def sendto(self, data, *args):+ loopback_address(args[-1])+ return super().sendto(data, *args)++ try:+ check('frozen_portable_boundary', bool(getattr(sys, 'frozen', False))+ and portable_runtime.enabled() and (root / 'Beamer.portable').is_file())+ check('fresh_synthetic_folder', not portable_runtime.settings_path().exists())+ check('offscreen_platform', os.environ.get('QT_QPA_PLATFORM') == 'offscreen')+ data = root / 'data'+ check('temporary_files_stay_in_payload', Path(tempfile.gettempdir()).resolve() == data / 'tmp'+ and all(Path(os.environ[name]).resolve() == data / 'tmp' for name in ('TEMP', 'TMP', 'TMPDIR')))+ check('cache_stays_in_payload', Path(os.environ['XDG_CACHE_HOME']).resolve() == data / 'cache')+ check('profile_paths_stay_in_payload', Path(os.environ['LOCALAPPDATA']).resolve() == data / 'cache' / 'local'+ and Path(os.environ['APPDATA']).resolve() == data / 'cache' / 'roaming')+ log_path = kvm.configure_logging()+ check('actual_log_stays_in_payload', log_path is not None and log_path.resolve().parent == data+ and kvm.LOG_PATH == log_path and log_path.is_file())+ # The linked UAC token is used by the wrapper when available; prove the child's token.+ advapi = ctypes.WinDLL('advapi32', use_last_error=True)+ kernel = ctypes.WinDLL('kernel32', use_last_error=True)+ token = ctypes.c_void_p()+ kernel.GetCurrentProcess.restype = ctypes.c_void_p+ advapi.OpenProcessToken.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_void_p)]+ advapi.GetTokenInformation.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p,+ ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong)]+ kernel.CloseHandle.argtypes = [ctypes.c_void_p]+ if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), 8, ctypes.byref(token)):+ raise OSError('Could not inspect qualification process token')+ try:+ elevation, needed = ctypes.c_ulong(), ctypes.c_ulong()+ if not advapi.GetTokenInformation(token, 20, ctypes.byref(elevation), ctypes.sizeof(elevation), ctypes.byref(needed)):+ raise OSError('Could not inspect token elevation')+ advapi.GetTokenInformation(token, 25, None, 0, ctypes.byref(needed))+ integrity = ctypes.create_string_buffer(needed.value)+ if not advapi.GetTokenInformation(token, 25, integrity, needed, ctypes.byref(needed)):+ raise OSError('Could not inspect token integrity')+ sid = ctypes.c_void_p.from_buffer(integrity).value+ advapi.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]+ advapi.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte)+ advapi.GetSidSubAuthority.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ advapi.GetSidSubAuthority.restype = ctypes.POINTER(ctypes.c_ulong)+ count = advapi.GetSidSubAuthorityCount(sid)[0]+ level = advapi.GetSidSubAuthority(sid, count - 1)[0]+ result['token_elevated'] = bool(elevation.value)+ result['integrity_rid'] = int(level)+ result['medium_token'] = not elevation.value and level == 0x2000+ finally:+ kernel.CloseHandle(token)++ locks = kvm._windows_kernel32()+ sentinel = locks.CreateMutexW(None, False, 'Local\\Beamer.Receiver')+ if not sentinel:+ # An existing elevated app may admit synchronise access but deny a new all-access handle.+ locks.OpenMutexW.restype = ctypes.c_void_p+ locks.OpenMutexW.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_wchar_p]+ sentinel = locks.OpenMutexW(0x00100000, False, 'Local\\Beamer.Receiver')+ check('installed_mutex_sentinel_open', bool(sentinel))+ release = None+ try:+ release = kvm._claim_instance()+ check('portable_coexists_with_installed_mutex', release is not None)+ duplicate = kvm._claim_instance()+ if duplicate is not None:+ duplicate()+ check('same_portable_folder_is_single_instance', duplicate is None)+ release()+ release = None+ release = kvm._claim_instance()+ check('portable_mutex_can_be_reclaimed', release is not None)+ session = ctypes.c_ulong()+ check('windows_session_identified', bool(locks.ProcessIdToSessionId(locks.GetCurrentProcessId(), ctypes.byref(session))))+ activation = kvm._instance_server_name()+ installed_activation = 'Beamer.Receiver.' + str(session.value)+ check('portable_activation_name_is_separate', activation != installed_activation+ and activation.endswith(portable_runtime.instance_suffix()))+ finally:+ if release is not None:+ release()+ locks.CloseHandle(sentinel)++ about = []+ with ExitStack() as stack:+ stack.enter_context(patch(socket, 'socket', LoopbackSocket))+ stack.enter_context(patch(kvm.pairing, 'pairing_address', lambda: '127.0.0.1'))+ stack.enter_context(patch(kvm.pairing, '_local_ipv4_addresses', lambda: ['127.0.0.1']))+ stack.enter_context(patch(QWidget, 'show', lambda self: None))+ stack.enter_context(patch(QSystemTrayIcon, 'setVisible', lambda *args: None))+ stack.enter_context(patch(QSystemTrayIcon, 'showMessage', forbidden))+ stack.enter_context(patch(QMessageBox, 'show', lambda box: about.append(box.informativeText())))+ stack.enter_context(patch(QMessageBox, 'warning', forbidden))+ stack.enter_context(patch(kvm.WindowsApplication, '_make_idle_pointer', lambda self: None))+ for name in ('repair', 'trust_network'):+ stack.enter_context(patch(kvm.firewall_win, name, forbidden))+ for name in ('_run', 'set_enabled', 'remove_legacy_task', 'migrate_legacy_task'):+ stack.enter_context(patch(kvm.autostart_win, name, forbidden))+ app = QApplication.instance() or QApplication([])+ app.setQuitOnLastWindowClosed(False)+ theme.init_fonts()+ passphrase = 'Synthetic portable qualification passphrase'+ answers = iter([(passphrase, True), (passphrase, True)])+ with patch(kvm.QInputDialog, 'getText', lambda *args: next(answers)):+ check('passphrase_bootstrap', kvm.unlock_portable())+ settings = app_config.load_settings(portable_runtime.settings_path())+ settings.update(name='Portable acceptance', check_updates=False)+ app_config.write_settings(portable_runtime.settings_path(), settings)+ synthetic_token = base64.urlsafe_b64encode(bytes(range(32))).decode('ascii').rstrip('=')+ paired = app_config.migrate({'host': '127.0.0.1', 'port': 24820, 'auth_token': synthetic_token})+ settings['peers'] = paired['peers']+ app_config.write_settings(portable_runtime.settings_path(), settings)+ portable_runtime.store.lock()+ reopened = PortableStore(portable_runtime.settings_path())+ reopened.unlock(passphrase)+ portable_runtime.store = reopened+ check('encrypted_pairing_round_trip', app_config.load_settings(portable_runtime.settings_path())['peers'][0]['token'] == synthetic_token)+ settings['peers'] = []+ app_config.write_settings(portable_runtime.settings_path(), settings)+ check('no_plaintext_pairing_file', all(synthetic_token.encode() not in file.read_bytes()+ for file in (root / 'data').rglob('*') if file.is_file()))+ window = kvm.WindowsApplication(portable_runtime.settings_path())+ check('actual_native_window_constructed', not window.isVisible() and window._config is not None)+ window.update_checker.fetcher = forbidden+ check('portable_update_channel', window.update_checker.portable)+ check('settings_save', window._persist())+ window.show_about()+ check('about_portable_label', bool(about) and 'Portable' in about[0] and 'passphrase' in about[0])+ check('autostart_unavailable', kvm.autostart_win.installed_exe() is None)+ check('pairing_service_constructed', window.pairing is not None)+ with original_socket(socket.AF_INET, socket.SOCK_DGRAM) as beacon_sink:+ beacon_sink.bind(('127.0.0.1', 0))+ window.pairing.announce_to = beacon_sink.getsockname()+ window.start()+ check('real_udp_pairing_listener', wait_for(lambda: window.pairing.listening_port is not None))+ beacon_sink.settimeout(3)+ beacon, address = beacon_sink.recvfrom(4096)+ check('real_loopback_pairing_datagram', bool(beacon) and address[0] == '127.0.0.1')+ code = window.pairing.begin_pairing()+ check('real_tcp_pairing_listener', bool(code) and window.pairing.code == code+ and wait_for(lambda: window.pairing._listener is not None))+ window.server.start(settings['port'])+ check('real_receiver_listener', wait_for(lambda: window.server.listening_port is not None))+ result['ports'] = {'pairing_udp': window.pairing.listening_port,+ 'pairing_tcp': window.pairing.tcp_port,+ 'receiver': window.server.listening_port}+ check('receiver_uses_reserved_port', window.server.listening_port == settings['port'])+ check('loopback_listener_scope', window.server._listener.getsockname()[0] == '127.0.0.1'+ and window.pairing._listener[0].getsockname()[0] == '127.0.0.1'+ and window.pairing._sock.getsockname()[0] == '127.0.0.1')+ window.quit()+ check('clean_socket_shutdown', not window.server.listening and window.pairing.listening_port is None)+ check('window_never_shown', not window.isVisible())+ check('no_non_loopback_network_attempt', not non_loopback_attempts)+ result['passed'] = True+ except BaseException as exc:+ result['error_type'] = type(exc).__name__+ if isinstance(exc, AssertionError):+ result['failed_check'] = str(exc)+ raise+ finally:+ if window is not None:+ try:+ window.quit()+ except Exception:+ result['passed'] = False+ result['cleanup_error'] = True+ window.deleteLater()+ portable_runtime.close()+ output.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')+++if (getattr(sys, 'frozen', False) and os.environ.get('BEAMER_PORTABLE_ACCEPTANCE') == '1'+ and (Path(sys.executable).resolve().parent / 'Beamer.portable').is_file()):+ qualify()diff --git a/tools/portable_qualify.ps1 b/tools/portable_qualify.ps1new file mode 100644index 0000000..ae1201d--- /dev/null+++ b/tools/portable_qualify.ps1@@ -0,0 +1,346 @@+param(+ [Parameter(Mandatory = $true)][string]$Zip,+ [string]$AcceptanceDirectory,+ [ValidateRange(10, 60)][int]$TimeoutSeconds = 45+)++$ErrorActionPreference = 'Stop'+$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition+$ProjectDir = Split-Path -Parent $ScriptDir+if (-not $AcceptanceDirectory) { $AcceptanceDirectory = Join-Path $ProjectDir 'win_app\dist\portable\qualification' }+$AcceptanceDirectory = [IO.Path]::GetFullPath($AcceptanceDirectory)+if (Test-Path $AcceptanceDirectory) { throw 'Use a fresh acceptance directory; existing test state is never removed' }+$Zip = (Resolve-Path $Zip).Path+New-Item -ItemType Directory -Path $AcceptanceDirectory | Out-Null+$Extracted = Join-Path $AcceptanceDirectory 'extracted'+Expand-Archive -Path $Zip -DestinationPath $Extracted+$Payload = Join-Path $Extracted 'Beamer-portable'+$Executable = Join-Path $Payload 'Beamer.exe'+if (-not (Test-Path $Executable) -or -not (Test-Path (Join-Path $Payload 'Beamer.portable'))) { throw 'The zip is not a Beamer portable payload' }+if (Test-Path (Join-Path $Payload 'data')) { throw 'The zip contains user data; qualification requires an empty payload' }+Copy-Item (Join-Path $ScriptDir 'portable_acceptance.py') (Join-Path $Payload 'portable_acceptance.py')+New-Item -ItemType Directory -Path (Join-Path $Payload 'data') | Out-Null+$ProfileRoot = Join-Path $AcceptanceDirectory 'host-profile'+$LocalProfile = Join-Path $ProfileRoot 'local'+$RoamingProfile = Join-Path $ProfileRoot 'roaming'+$TemporaryProfile = Join-Path $ProfileRoot 'temp'+New-Item -ItemType Directory -Path $LocalProfile, $RoamingProfile, $TemporaryProfile | Out-Null++# SSH administrator logons need not have a linked token. Restrict only our own token.+# Keep the parent environment untouched: ShellExecute creates profile caches before app startup.+# https://learn.microsoft.com/en-us/windows/win32/secauthz/restricted-tokens+Add-Type -TypeDefinition @'+using System;+using System.Collections.Generic;+using System.Runtime.InteropServices;+using System.Text;+public static class PortableQualificationToken {+ [StructLayout(LayoutKind.Sequential)]+ struct SidAndAttributes { public IntPtr sid; public uint attributes; }+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ struct StartupInfo {+ public int cb; public string reserved, desktop, title;+ public int x, y, width, height, xChars, yChars, fill, flags;+ public short show, reservedSize; public IntPtr reservedData, input, output, error;+ }+ [StructLayout(LayoutKind.Sequential)]+ struct ProcessInfo { public IntPtr process, thread; public int pid, tid; }+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool CreateRestrictedToken(IntPtr token, uint flags, uint disableCount,+ IntPtr disable, uint deleteCount, IntPtr delete, uint restrictCount, IntPtr restrict,+ out IntPtr restricted);+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool GetTokenInformation(IntPtr token, int kind, IntPtr value, int size, out int needed);+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool SetTokenInformation(IntPtr token, int kind, IntPtr value, int size);+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool ConvertStringSidToSidW(string value, out IntPtr sid);+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool ConvertSidToStringSidW(IntPtr sid, out IntPtr value);+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool ConvertStringSecurityDescriptorToSecurityDescriptorW(string value,+ uint revision, out IntPtr descriptor, IntPtr size);+ [DllImport("advapi32.dll", SetLastError = true)]+ static extern bool GetSecurityDescriptorDacl(IntPtr descriptor, out bool present,+ out IntPtr acl, out bool defaulted);+ [DllImport("advapi32.dll")] static extern uint GetLengthSid(IntPtr sid);+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool CreateProcessAsUserW(IntPtr token, string application,+ StringBuilder command, IntPtr processAttributes, IntPtr threadAttributes,+ bool inheritHandles, uint flags, IntPtr environment, string directory,+ ref StartupInfo startup, out ProcessInfo process);+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr pointer);+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);+ [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr handle, uint timeout);+ [DllImport("kernel32.dll")] static extern bool GetExitCodeProcess(IntPtr handle, out uint code);+ [DllImport("kernel32.dll")] static extern bool TerminateProcess(IntPtr handle, uint code);+ public static int RunRestricted(string exe, string arguments, string directory,+ string[] environmentPairs, int timeout, out int launchError, out string launchStage) {+ launchError = 0;+ launchStage = "open-current-token";+ IntPtr token = IntPtr.Zero, restricted = IntPtr.Zero, user = IntPtr.Zero,+ owner = IntPtr.Zero, stringSid = IntPtr.Zero, descriptor = IntPtr.Zero,+ dacl = IntPtr.Zero, mediumSid = IntPtr.Zero, label = IntPtr.Zero,+ environment = IntPtr.Zero;+ ProcessInfo child = new ProcessInfo();+ try {+ if (!OpenProcessToken(GetCurrentProcess(), 0x8B, out token)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ launchStage = "create-restricted-token";+ if (!CreateRestrictedToken(token, 0x1 | 0x4, 0, IntPtr.Zero,+ 0, IntPtr.Zero, 0, IntPtr.Zero, out restricted)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ launchStage = "query-user";+ int needed;+ GetTokenInformation(restricted, 1, IntPtr.Zero, 0, out needed);+ if (needed <= 0) { launchError = Marshal.GetLastWin32Error(); return -1; }+ user = Marshal.AllocHGlobal(needed);+ if (!GetTokenInformation(restricted, 1, user, needed, out needed)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ IntPtr userSid = Marshal.ReadIntPtr(user);+ // LUA makes Administrators deny-only; new objects must remain accessible to this user.+ launchStage = "set-owner";+ owner = Marshal.AllocHGlobal(IntPtr.Size);+ Marshal.WriteIntPtr(owner, userSid);+ if (!SetTokenInformation(restricted, 4, owner, IntPtr.Size)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ launchStage = "set-default-dacl";+ if (!ConvertSidToStringSidW(userSid, out stringSid)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ string sddl = "D:(A;;GA;;;" + Marshal.PtrToStringUni(stringSid) + ")(A;;GA;;;SY)";+ if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1,+ out descriptor, IntPtr.Zero)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ bool present, defaulted;+ IntPtr acl;+ if (!GetSecurityDescriptorDacl(descriptor, out present, out acl, out defaulted)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ if (!present || acl == IntPtr.Zero) { launchError = 1336; return -1; }+ dacl = Marshal.AllocHGlobal(IntPtr.Size);+ Marshal.WriteIntPtr(dacl, acl);+ if (!SetTokenInformation(restricted, 6, dacl, IntPtr.Size)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ launchStage = "set-integrity-medium";+ if (!ConvertStringSidToSidW("S-1-16-8192", out mediumSid)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ int labelSize = Marshal.SizeOf(typeof(SidAndAttributes));+ label = Marshal.AllocHGlobal(labelSize);+ Marshal.WriteIntPtr(label, mediumSid);+ Marshal.WriteInt32(label, IntPtr.Size, 0x20);+ if (!SetTokenInformation(restricted, 25, label, labelSize + (int)GetLengthSid(mediumSid))) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ launchStage = "build-environment";+ var pairs = new List<string>(environmentPairs);+ pairs.Sort(StringComparer.OrdinalIgnoreCase);+ environment = Marshal.StringToHGlobalUni(string.Join("\0", pairs.ToArray()) + "\0\0");+ StartupInfo startup = new StartupInfo(); startup.cb = Marshal.SizeOf(startup);+ StringBuilder command = new StringBuilder("\"" + exe + "\" " + arguments);+ launchStage = "create-process-as-user";+ if (!CreateProcessAsUserW(restricted, exe, command, IntPtr.Zero, IntPtr.Zero,+ false, 0x400 | 0x08000000, environment, directory, ref startup, out child)) {+ launchError = Marshal.GetLastWin32Error(); return -1;+ }+ launchStage = "launched";+ CloseHandle(child.thread); child.thread = IntPtr.Zero;+ if (WaitForSingleObject(child.process, (uint)timeout) != 0) {+ TerminateProcess(child.process, 124);+ WaitForSingleObject(child.process, 5000);+ return 124;+ }+ uint code;+ return GetExitCodeProcess(child.process, out code) ? (int)code : 125;+ } finally {+ if (child.thread != IntPtr.Zero) CloseHandle(child.thread);+ if (child.process != IntPtr.Zero) CloseHandle(child.process);+ if (environment != IntPtr.Zero) Marshal.FreeHGlobal(environment);+ if (label != IntPtr.Zero) Marshal.FreeHGlobal(label);+ if (mediumSid != IntPtr.Zero) LocalFree(mediumSid);+ if (dacl != IntPtr.Zero) Marshal.FreeHGlobal(dacl);+ if (descriptor != IntPtr.Zero) LocalFree(descriptor);+ if (stringSid != IntPtr.Zero) LocalFree(stringSid);+ if (owner != IntPtr.Zero) Marshal.FreeHGlobal(owner);+ if (user != IntPtr.Zero) Marshal.FreeHGlobal(user);+ if (restricted != IntPtr.Zero) CloseHandle(restricted);+ if (token != IntPtr.Zero) CloseHandle(token);+ }+ }+}+'@++function Get-TextHash([string]$Text) {+ $Sha = [Security.Cryptography.SHA256]::Create()+ try { return ([BitConverter]::ToString($Sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Text)))).Replace('-', '').ToLowerInvariant() }+ finally { $Sha.Dispose() }+}++function Get-SharedFileHash([string]$Path) {+ $Share = [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete+ $Stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, $Share)+ $Sha = [Security.Cryptography.SHA256]::Create()+ try { return ([BitConverter]::ToString($Sha.ComputeHash($Stream))).Replace('-', '').ToLowerInvariant() }+ finally { $Sha.Dispose(); $Stream.Dispose() }+}++function Get-HostSnapshot {+ $Items = @{}+ $Errors = [Collections.Generic.List[string]]::new()+ foreach ($Entry in @(@('synthetic-localappdata', $LocalProfile), @('synthetic-appdata', $RoamingProfile))) {+ $Label, $Directory = $Entry+ try {+ if (-not (Test-Path $Directory -ErrorAction Stop)) { $Items["directory:$Label"] = 'absent'; continue }+ $Items["directory:$Label"] = 'present'+ foreach ($File in Get-ChildItem $Directory -Force -Recurse -ErrorAction Stop) {+ $Relative = $File.FullName.Substring($Directory.Length).TrimStart('\')+ $Items["file:$Label/$Relative"] = if ($File.PSIsContainer) { 'directory' } else { "$($File.Length):$(Get-SharedFileHash $File.FullName)" }+ }+ } catch { $Errors.Add("Synthetic profile snapshot unavailable ($Label): " + $_.Exception.GetType().Name) }+ }+ try {+ Get-ChildItem $TemporaryProfile -Force -ErrorAction Stop | ForEach-Object {+ $Length = if ($_.PSIsContainer) { 'directory' } else { $_.Length }+ $Items["temp:$($_.Name)"] = "$Length`:$($_.LastWriteTimeUtc.Ticks)"+ }+ } catch { $Errors.Add('Synthetic TEMP immediate-entry snapshot unavailable: ' + $_.Exception.GetType().Name) }+ $RunKey = $null+ try {+ $RunKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Software\Microsoft\Windows\CurrentVersion\Run', $false)+ if ($null -eq $RunKey -or $RunKey.GetValueNames() -notcontains 'Beamer') {+ $Items['registry:run-beamer'] = 'absent'+ } else {+ $RunValue = @($RunKey.GetValueKind('Beamer').ToString(), $RunKey.GetValue('Beamer', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames))+ $Items['registry:run-beamer'] = Get-TextHash (ConvertTo-Json -InputObject $RunValue -Compress)+ }+ } catch { $Errors.Add('Run registry snapshot unavailable: ' + $_.Exception.GetType().Name) }+ finally { if ($null -ne $RunKey) { $RunKey.Dispose() } }+ foreach ($Entry in @(@('HKCU', [Microsoft.Win32.Registry]::CurrentUser, 'Software\Microsoft\Windows\CurrentVersion\Uninstall'),+ @('HKLM', [Microsoft.Win32.Registry]::LocalMachine, 'Software\Microsoft\Windows\CurrentVersion\Uninstall'),+ @('HKLM', [Microsoft.Win32.Registry]::LocalMachine, 'Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'))) {+ $Label, $Hive, $Path = $Entry+ $Base = $null+ try {+ $Base = $Hive.OpenSubKey($Path, $false)+ if ($null -eq $Base) { continue }+ foreach ($Name in $Base.GetSubKeyNames()) {+ $Key = $null+ try {+ $Key = $Base.OpenSubKey($Name, $false)+ if ($null -eq $Key) { throw 'Uninstall key disappeared during snapshot' }+ if ($Key.GetValue('DisplayName') -like '*Beamer*' -or $Name -like '*Beamer*') {+ $Values = [ordered]@{}+ foreach ($ValueName in ($Key.GetValueNames() | Sort-Object)) {+ $Values[$ValueName] = @($Key.GetValueKind($ValueName).ToString(), $Key.GetValue($ValueName, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames))+ }+ $Items["registry:uninstall:$Label/$Path/$Name"] = Get-TextHash (ConvertTo-Json -InputObject $Values -Depth 5 -Compress)+ }+ } finally { if ($null -ne $Key) { $Key.Dispose() } }+ }+ } catch { $Errors.Add("Uninstall registry snapshot unavailable ($Label/$Path): " + $_.Exception.GetType().Name) }+ finally { if ($null -ne $Base) { $Base.Dispose() } }+ }+ try {+ foreach ($Task in Get-ScheduledTask -ErrorAction Stop | Where-Object TaskName -like '*Beamer*') {+ $Xml = Export-ScheduledTask -TaskName $Task.TaskName -TaskPath $Task.TaskPath -ErrorAction Stop+ $Items["task:$($Task.TaskPath)$($Task.TaskName)"] = "$($Task.State):$(Get-TextHash $Xml)"+ }+ } catch { $Errors.Add('Scheduled-task snapshot unavailable: ' + $_.Exception.GetType().Name) }+ try {+ foreach ($Rule in Get-NetFirewallRule -ErrorAction Stop | Where-Object DisplayName -like '*Beamer*') {+ $State = @($Rule | Select-Object Name, DisplayName, Enabled, Direction, Action, Profile;+ $Rule | Get-NetFirewallApplicationFilter -ErrorAction Stop | Select-Object Program;+ $Rule | Get-NetFirewallPortFilter -ErrorAction Stop | Select-Object Protocol, LocalPort, RemotePort)+ $Items["firewall:$($Rule.Name)"] = Get-TextHash ($State | ConvertTo-Json -Depth 5 -Compress)+ }+ } catch { $Errors.Add('Firewall snapshot unavailable: ' + $_.Exception.GetType().Name) }+ try {+ foreach ($Service in Get-Service -ErrorAction Stop | Where-Object { $_.Name -like '*Beamer*' -or $_.DisplayName -like '*Beamer*' }) {+ $Items["service:$($Service.Name)"] = [string]$Service.Status+ }+ } catch { $Errors.Add('Service snapshot unavailable: ' + $_.Exception.GetType().Name) }+ return @{ items = $Items; errors = $Errors.ToArray() }+}++$Before = Get-HostSnapshot+$ChildEnvironment = @{+ QT_QPA_PLATFORM = 'offscreen'+ BEAMER_PORTABLE_ACCEPTANCE = '1'+ LOCALAPPDATA = $LocalProfile+ APPDATA = $RoamingProfile+ TEMP = $TemporaryProfile+ TMP = $TemporaryProfile+}+$EnvironmentPairs = [Collections.Generic.List[string]]::new()+foreach ($Entry in [Environment]::GetEnvironmentVariables('Process').GetEnumerator()) {+ if (-not $ChildEnvironment.ContainsKey([string]$Entry.Key)) {+ $EnvironmentPairs.Add("$($Entry.Key)=$($Entry.Value)")+ }+}+foreach ($Name in $ChildEnvironment.Keys) { $EnvironmentPairs.Add("$Name=$($ChildEnvironment[$Name])") }+$ImportReport = Join-Path $Payload 'data\imports.txt'+$Arguments = "--import-probe `"$ImportReport`" portable_acceptance"+$Mode = 'self-restricted-token-create-process-as-user'+$LaunchError = 0+$LaunchStage = 'not-attempted'+$ProbeErrors = [Collections.Generic.List[string]]::new()+$ExitCode = 125+try {+ $ExitCode = [PortableQualificationToken]::RunRestricted($Executable, $Arguments, $Payload,+ $EnvironmentPairs.ToArray(), $TimeoutSeconds * 1000, [ref]$LaunchError, [ref]$LaunchStage)+ if ($ExitCode -eq -1) {+ $ProbeErrors.Add("Restricted probe launch failed at $LaunchStage (Win32 $LaunchError)")+ }+} catch { $ProbeErrors.Add('Probe launch/wait unavailable: ' + $_.Exception.GetType().Name) }+$After = Get-HostSnapshot+$Keys = @($Before.items.Keys) + @($After.items.Keys) | Sort-Object -Unique+$Changes = @($Keys | Where-Object { $Before.items[$_] -ne $After.items[$_] })+$AcceptancePath = Join-Path $Payload 'data\acceptance.json'+$Acceptance = $null+try {+ if (Test-Path $AcceptancePath) { $Acceptance = Get-Content $AcceptancePath -Raw | ConvertFrom-Json }+} catch { $ProbeErrors.Add('Probe report unreadable: ' + $_.Exception.GetType().Name) }+$ImportOk = (Test-Path $ImportReport) -and ((Get-Content $ImportReport -Raw) -match '^ok portable_acceptance ')+$Functional = $ExitCode -eq 0 -and $ImportOk -and $Acceptance -and $Acceptance.passed+$Medium = $Acceptance -and $Acceptance.medium_token+$SnapshotsComplete = $Before.errors.Count -eq 0 -and $After.errors.Count -eq 0+$OutsideUnchanged = $SnapshotsComplete -and $Changes.Count -eq 0+$Complete = $Functional -and $Medium -and $OutsideUnchanged -and $ProbeErrors.Count -eq 0+$Report = [ordered]@{+ status = $(if ($Complete) { 'DONE' } else { 'BLOCKED' })+ functional_passed = [bool]$Functional+ medium_token_proven = [bool]$Medium+ host_snapshot_complete = $SnapshotsComplete+ outside_unchanged = $OutsideUnchanged+ process_exit_code = $ExitCode+ launch_mode = $Mode+ launch_error = $LaunchError+ launch_api = 'CreateProcessAsUserW'+ launch_stage = $LaunchStage+ archive_sha256 = (Get-FileHash $Zip -Algorithm SHA256).Hash.ToLowerInvariant()+ changed_host_entries = $Changes+ snapshot_errors = @($Before.errors) + @($After.errors)+ probe_errors = $ProbeErrors.ToArray()+ snapshot_scope = @('Controlled synthetic LOCALAPPDATA/APPDATA file hashes outside payload', 'Controlled synthetic TEMP immediate-entry metadata outside payload', 'Actual Beamer Run/uninstall registry values', 'Actual Beamer scheduled tasks', 'Actual Beamer firewall rules', 'Actual Beamer services')+ synthetic_profile_root = $ProfileRoot+ real_profile_files_inspected = $false+ outside_unchanged_scope = 'Controlled synthetic profile paths and named actual Windows integration state; not an exhaustive real-profile audit'+ probe = $Acceptance+}+$ReportPath = Join-Path $AcceptanceDirectory 'qualification.json'+$Before | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $AcceptanceDirectory 'before.json') -Encoding UTF8+$After | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $AcceptanceDirectory 'after.json') -Encoding UTF8+$Report | ConvertTo-Json -Depth 8 | Set-Content $ReportPath -Encoding UTF8+Write-Output "Portable qualification $($Report.status): $ReportPath"+Write-Output "Functional=$Functional medium=$Medium outside_unchanged=$OutsideUnchanged snapshot_complete=$SnapshotsComplete"+if (-not $Complete) { exit 1 }diff --git a/win_app/app_config.py b/win_app/app_config.pyindex 682e3ba..cf810a8 100644--- a/win_app/app_config.py+++ b/win_app/app_config.py@@ -32,6 +32,8 @@ from core import i18nfrom core import return_edgefrom core import ways, crossing_statefrom core import profiles+from core import portable_runtime+from core.portable_store import PortableStoreErrorfrom core.pairing import local_address_towardsimport tokens@@ -223,6 +225,8 @@ def default_config() -> Config:def default_config_path() -> Path:+ if portable_runtime.enabled():+ return portable_runtime.settings_path()base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_CONFIG_HOME")if base:return Path(base) / "Beamer" / "settings.json"@@ -713,6 +717,12 @@ def learn_peer_id(settings: dict, index: int, peer_id: str) -> None:def _write_json(path: Path, payload: dict) -> None:"""A new file beside the old, then a rename over it."""+ if portable_runtime.enabled():+ try:+ _portable_store(path).write(payload)+ except PortableStoreError as exc:+ raise SettingsFileError("Portable settings could not be saved") from exc+ return_backup_before_profile_upgrade(path)path.parent.mkdir(parents=True, exist_ok=True)temporary_path = None@@ -740,6 +750,16 @@ def _write_json(path: Path, payload: dict) -> None:def _read_object(path: Path):"""The JSON object in a file, or None when it is missing or does not parse. A file that cannot beread for any other reason (locked, denied) raises, so it is never taken for a missing one."""+ if portable_runtime.enabled():+ if Path(path).resolve() == legacy_config_path(portable_runtime.settings_path()).resolve():+ return None+ try:+ settings = _portable_store(path).read()+ except PortableStoreError as exc:+ raise SettingsFileError("Portable settings could not be read") from exc+ if settings:+ settings["port"] = portable_runtime.reserve_listener(settings.get("port", 0))+ return settingstry:raw = json.loads(path.read_text(encoding="utf-8"))except (FileNotFoundError, ValueError):@@ -747,14 +767,24 @@ def _read_object(path: Path):return raw if isinstance(raw, dict) else None+def _portable_store(path):+ if Path(path).resolve() != portable_runtime.settings_path().resolve():+ raise SettingsFileError("Portable settings must stay beside the app")+ if portable_runtime.store is None or not portable_runtime.store.is_unlocked:+ raise SettingsFileError("Portable settings are locked")+ return portable_runtime.store++def load_settings(path: Path) -> dict:"""settings.json at `path`, made from 1.4.x's config.json beside it (or defaults) when there isnone, and brought up to date when 1.4.x paired again after the upgrade."""if legacy_config_path(path) == path:raise ConfigError("the settings file is settings.json; config.json is 1.4.x's and is never written")legacy = _read_object(legacy_config_path(path))- if not path.exists():+ if not path.exists() or (portable_runtime.enabled() and not _portable_store(path).read()):settings = migrate(legacy)+ if portable_runtime.enabled():+ settings["port"] = portable_runtime.reserve_listener()settings, notes = profiles.before_load(settings)_remember_profile_notes(path, notes)settings = crossing_state.migrate(settings, "pc")["settings"]@@ -869,7 +899,7 @@ def _flat_from_settings(settings: dict) -> dict:return flat-def _apply_flat(settings: dict, flat: dict) -> None:+def _apply_flat(settings: dict, flat: dict, *, pin_address=False) -> None:"""Write a Config's flat fields (from `config_to_dict`) into the settings: this PC's own, and thefirst desktop's address, name and switches, never a side or a zone. A token that is not thatdesktop's is a new pairing: it replaces that entry, and its zones point at the empty id until a link@@ -903,6 +933,8 @@ def _apply_flat(settings: dict, flat: dict) -> None:# put the old one back.if flat["mac_host"] != peer.get("host"):peer.update(name=flat["paired_with"], hw=flat["mac_hardware_address"], host_pinned=True)+ if pin_address and flat["mac_host"]:+ peer["host_pinned"] = Truepeer.update(host=flat["mac_host"], send=flat["send_to_mac"], allow_drive=flat["allow_mac_to_drive"])if flat["port"] != old_port and peer.get("port") == old_port:peer["port"] = flat["port"]@@ -955,7 +987,7 @@ class ReadFallbackPeerBook(receiver.PeerBook):copy.deepcopy(list(settings.get("zones") or [])))-def save_config(path: Path, config: Config) -> None:+def save_config(path: Path, config: Config, *, pin_address=False) -> None:payload = config_to_dict(config)with SETTINGS_LOCK:settings = load_settings(path)@@ -965,7 +997,7 @@ def save_config(path: Path, config: Config) -> None:except ValueError as exc:raise ConfigError(str(exc)) from excold_tokens = [entry.get("token") for entry in settings["peers"]]- _apply_flat(settings, payload)+ _apply_flat(settings, payload, pin_address=pin_address)if old_tokens != [entry.get("token") for entry in settings["peers"]]:settings = crossing_state.paired(settings, platform="pc", own_displays={}, now=time.time())["settings"]write_settings(path, settings)@@ -1008,6 +1040,8 @@ def _without_profile_state(settings: dict) -> dict:def _backup_before_profile_upgrade(path: Path) -> None:"""Keep the exact schema-6 source before the first save of a profile-migrated file."""+ if portable_runtime.enabled():+ returnbackup = path.with_name("settings.json.before-1.5.5")if backup.exists():returndiff --git a/win_app/autostart_win.py b/win_app/autostart_win.pyindex aeee30d..5fcfcbe 100644--- a/win_app/autostart_win.py+++ b/win_app/autostart_win.py@@ -25,6 +25,7 @@ from xml.sax.saxutils import escapeimport xml.etree.ElementTree as ETfrom core import windows_tools+from core import portable_runtimeTASK_PREFIX = "Beamer-"CREATE_NO_WINDOW = 0x08000000@@ -97,7 +98,7 @@ def can_run_for_current_user() -> bool:def installed_exe() -> Optional[str]:"""The exe a task can start, or None when running from source, where there is none."""- return sys.executable if getattr(sys, "frozen", False) else None+ return sys.executable if getattr(sys, "frozen", False) and not portable_runtime.enabled() else Nonedef task_xml(exe: str, user: str, arguments: str = "--hidden") -> str:@@ -135,6 +136,8 @@ def task_xml(exe: str, user: str, arguments: str = "--hidden") -> str:def is_enabled(run: Runner = _run, user: Optional[str] = None) -> bool:+ if portable_runtime.enabled():+ return Falseuser = user or current_user()migrate_legacy_task(run, user)return _task_enabled(task_name(user), run)@@ -172,6 +175,8 @@ def _replacement_ready(root, exe: str, arguments: str) -> bool:def migrate_legacy_task(run: Runner = _run, user: Optional[str] = None) -> None:"""Keep the old starter until its owner's replacement has been registered successfully."""+ if portable_runtime.enabled():+ returnuser = user or current_user()root = _task_root("Beamer", run)if root is None:@@ -215,6 +220,8 @@ def _user_sid(user: str) -> str:def set_enabled(enabled: bool, exe: str, user: Optional[str] = None, run: Runner = _run,*, arguments: str = "--hidden") -> None:"""Raises OSError with schtasks' own words when Windows refuses."""+ if portable_runtime.enabled():+ raise OSError("Portable Beamer cannot change start at sign-in")user = user or current_user()name = task_name(user)if not enabled:@@ -239,6 +246,8 @@ def set_enabled(enabled: bool, exe: str, user: Optional[str] = None, run: Runnerdef remove_legacy_task(run: Runner = _run, *, disable_first: bool = False) -> None:+ if portable_runtime.enabled():+ returnif run(["schtasks", "/query", "/tn", "Beamer"]).returncode == 0:if disable_first:result = run(["schtasks", "/change", "/tn", "Beamer", "/disable"])diff --git a/win_app/build_portable.ps1 b/win_app/build_portable.ps1new file mode 100644index 0000000..abe3309--- /dev/null+++ b/win_app/build_portable.ps1@@ -0,0 +1,100 @@+param([string]$OutputDirectory)++$ErrorActionPreference = 'Stop'++function Invoke-Native {+ param([Parameter(Mandatory = $true)][scriptblock]$Command)+ $ErrorActionPreference = 'Continue'+ & $Command+}++$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition+$ProjectDir = Split-Path -Parent $ScriptDir+$DistDir = Join-Path $ScriptDir 'dist\portable'+$WorkDir = Join-Path $ScriptDir 'build\portable'+$Payload = Join-Path $DistDir 'Beamer-portable'+$Version = (Get-Content (Join-Path $ProjectDir 'VERSION') -Raw).Trim()+if ($Version -notmatch '^\d+\.\d+\.\d+(?:-[A-Za-z0-9.]+)?$') { throw 'VERSION is not a supported Beamer version' }+if (-not $OutputDirectory) { $OutputDirectory = $DistDir }+$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)+$Archive = Join-Path $OutputDirectory "Beamer-Portable-$Version-windows-x64.zip"++Push-Location $ScriptDir+try {+ $Python = Join-Path $ScriptDir '.venv\Scripts\python.exe'+ if (-not (Test-Path $Python)) {+ $BootstrapPython = Get-Command python -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source+ if (-not $BootstrapPython) { throw 'Python was not found on PATH' }+ Invoke-Native { & $BootstrapPython -m venv .venv }+ if ($LASTEXITCODE -ne 0) { throw 'Virtual environment creation failed' }+ }+ $Toolchain = @'+import platform, struct, sys+print('Portable build: Python', platform.python_version(), platform.machine())+sys.exit(0 if sys.platform == 'win32' and struct.calcsize('P') == 8 and sys.version_info.releaselevel == 'final' else 'A stable 64-bit Windows Python is required')+'@+ Invoke-Native { & $Python -c $Toolchain }+ if ($LASTEXITCODE -ne 0) { throw 'Unsupported portable build toolchain' }+ Invoke-Native { & $Python -m pip install -r requirements-win.txt }+ if ($LASTEXITCODE -ne 0) { throw 'Dependency installation failed' }+ Invoke-Native { & $Python -m PyInstaller --version }+ if ($LASTEXITCODE -ne 0) { throw 'PyInstaller is unavailable' }+ Invoke-Native { & $Python -m PyInstaller --clean --noconfirm --distpath $DistDir --workpath $WorkDir build_portable.spec }+ if ($LASTEXITCODE -ne 0) { throw 'Portable PyInstaller build failed' }+ $Executable = Join-Path $Payload 'Beamer.exe'+ if (-not (Test-Path $Executable)) { throw 'Portable build did not create Beamer.exe' }++ Copy-Item (Join-Path $ProjectDir 'LICENSE') (Join-Path $Payload 'LICENSE') -Force+ [IO.File]::WriteAllText((Join-Path $Payload 'Beamer.portable'), '')+ $Notices = @'+import importlib.metadata as metadata+from pathlib import Path+import shutil+import sys++payload = Path(sys.argv[1])+licences = payload / 'licences'+licences.mkdir()+python_licence = Path(sys.base_prefix) / 'LICENSE.txt'+if not python_licence.is_file():+ raise SystemExit('Python LICENSE.txt is missing')+shutil.copyfile(python_licence, licences / 'Python-LICENSE.txt')+notices = ['Beamer portable: GPL-3.0-only; see LICENSE.',+ 'Third-party components retain their own licences, reproduced in licences/.',+ 'Qt libraries are dynamically linked and may be replaced in _internal/.',+ 'Python ' + sys.version.split()[0] + ': see licences/Python-LICENSE.txt.']+packages = ('PySide6-Essentials', 'shiboken6', 'PyNaCl', 'cffi', 'pycparser', 'pywin32', 'segno', 'PyInstaller')+for name in packages:+ package = metadata.distribution(name)+ files = []+ for relative in package.files or ():+ if any(part.lower() in {'licenses', 'licences'} for part in relative.parts) or relative.name.lower().startswith(('license', 'licence', 'copying', 'notice')):+ source = Path(package.locate_file(relative))+ if source.is_file():+ target = licences / name / relative+ if '..' in relative.parts or relative.is_absolute():+ raise SystemExit('Unsafe licence path in ' + name)+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source, target)+ files.append(target.relative_to(payload).as_posix())+ if not files:+ raise SystemExit('No distributed licence text found for ' + name)+ licence = package.metadata.get('License-Expression') or package.metadata.get('License') or 'See reproduced licence text.'+ notices.append('\n' + name + ' ' + package.version + '\n' + licence + '\n' + '\n'.join(sorted(files)))+(payload / 'THIRD-PARTY-NOTICES.txt').write_text('\n'.join(notices) + '\n', encoding='utf-8')+'@+ Invoke-Native { & $Python -c $Notices $Payload }+ if ($LASTEXITCODE -ne 0) { throw 'Portable licence collection failed' }++ # A new COLLECT payload contains no settings, pairings, logs, caches or host identity.+ $Unexpected = Get-ChildItem $Payload -Force | Where-Object Name -notin @('Beamer.exe', '_internal', 'Beamer.portable', 'LICENSE', 'licences', 'THIRD-PARTY-NOTICES.txt')+ if ($Unexpected) { throw 'Unexpected files in portable payload' }+ if ((Get-AuthenticodeSignature $Executable).Status -ne 'NotSigned') { throw 'The portable candidate must be unsigned' }+ New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null+ Compress-Archive -Path $Payload -DestinationPath $Archive -Force+ Write-Output "Built unsigned portable candidate: $Archive"+ Write-Output "SHA256: $((Get-FileHash $Archive -Algorithm SHA256).Hash.ToLowerInvariant())"+}+finally {+ Pop-Location+}diff --git a/win_app/build_portable.spec b/win_app/build_portable.specnew file mode 100644index 0000000..0cd2585--- /dev/null+++ b/win_app/build_portable.spec@@ -0,0 +1,62 @@+from pathlib import Path+++source_dir = Path(SPECPATH)+app_modules = sorted(path.stem for path in source_dir.glob("*.py") if path.stem != "kvm_bridge_win")+core_modules = sorted(f"core.{path.stem}" for path in (source_dir.parent / "core").glob("*.py") if path.stem != "__init__")++analysis = Analysis(+ [str(source_dir / "portable_entry.py")],+ pathex=[str(source_dir), str(source_dir.parent)],+ binaries=[],+ datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"),+ (str(source_dir.parent / "VERSION"), "."),+ (str(source_dir / "identify_layer_shell.py"), ".")]+ + [(str(path), "locales") for path in (source_dir.parent / "locales").glob("*.po")],+ hiddenimports=["kvm_bridge_win", "nacl", "_cffi_backend", "segno", "win32com.client", "pythoncom", "pywintypes"] + app_modules + core_modules,+ hookspath=[],+ hooksconfig={},+ runtime_hooks=[str(source_dir / "hooks" / "portable_storage.py")],+ excludes=["PIL", "pystray", "tkinter", "numpy", "PySide6.QtQml", "PySide6.QtQuick", "PySide6.Qt3DCore", "PySide6.QtMultimedia"],+ noarchive=False,+)++# Keep the installed build's UCRT policy: Windows supplies these, while Qt's ICU DLLs stay.+filtered_binaries = [+ binary for binary in analysis.binaries+ if binary[0].lower() != "ucrtbase.dll"+ and not binary[0].lower().startswith("api-ms-win-")+]++python_archive = PYZ(analysis.pure)+executable = EXE(+ python_archive,+ analysis.scripts,+ [],+ exclude_binaries=True,+ name="Beamer",+ debug=False,+ bootloader_ignore_signals=False,+ strip=False,+ upx=False,+ console=False,+ disable_windowed_traceback=False,+ argv_emulation=False,+ target_arch=None,+ codesign_identity=None,+ entitlements_file=None,+ icon=str(source_dir / "Beamer.ico"),+ # The one-folder bootloader needs no temporary extraction or elevation.+ uac_admin=False,+ uac_uiaccess=False,+ contents_directory="_internal",+)++portable = COLLECT(+ executable,+ filtered_binaries,+ analysis.datas,+ strip=False,+ upx=False,+ name="Beamer-portable",+)diff --git a/win_app/capture_win.py b/win_app/capture_win.pyindex 3041a62..d953178 100644--- a/win_app/capture_win.py+++ b/win_app/capture_win.py@@ -59,6 +59,9 @@ user32 = ctypes.WinDLL("user32", use_last_error=True) if _IS_WINDOWS else Nonekernel32 = ctypes.WinDLL("kernel32", use_last_error=True) if _IS_WINDOWS else NoneWM_INPUT = 0x00FF+WM_MODIFIER_RESYNC = 0x8001+EVENT_SYSTEM_DESKTOPSWITCH = 0x0020+WINEVENT_OUTOFCONTEXT = 0RID_INPUT = 0x10000003RIDEV_INPUTSINK = 0x00000100RIM_TYPEMOUSE = 0@@ -541,6 +544,7 @@ class Hooks:self._composed_local: Dict[int, Union[DeadKey, TextInput]] = {}self._failure: Optional[BaseException] = Noneself._handles: List[int] = []+ self._desktop_hook = None# Kept alive for as long as the hooks are installed: a callback that# is garbage collected while Windows still holds its address crashes# the process the next time a key is pressed.@@ -591,7 +595,8 @@ class Hooks:keyboard = _LL_HOOK_PROC(self._keyboard_proc)mouse = _LL_HOOK_PROC(self._mouse_proc)window_proc = _WNDPROC(self._window_proc)- self._callbacks = [keyboard, mouse, window_proc]+ desktop_proc = _WINEVENTPROC(self._desktop_proc)+ self._callbacks = [keyboard, mouse, window_proc, desktop_proc]module = kernel32.GetModuleHandleW(None)self._thread_id = kernel32.GetCurrentThreadId()# Highest within Beamer's above-normal class: this thread answers the@@ -612,6 +617,12 @@ class Hooks:if not handle:raise ctypes.WinError(ctypes.get_last_error())self._handles.append(handle)+ self._desktop_hook = user32.SetWinEventHook(+ EVENT_SYSTEM_DESKTOPSWITCH, EVENT_SYSTEM_DESKTOPSWITCH, None, desktop_proc, 0, 0,+ WINEVENT_OUTOFCONTEXT,+ )+ if not self._desktop_hook:+ raise RuntimeError("Could not monitor Windows input desktop changes")self._state.caps_lock = read_caps_lock()self._ready.set()message = MSG()@@ -623,6 +634,9 @@ class Hooks:self._failure = excself._ready.set()finally:+ if self._desktop_hook:+ user32.UnhookWinEvent(self._desktop_hook)+ self._desktop_hook = Nonefor handle in self._handles:user32.UnhookWindowsHookEx(handle)self._handles = []@@ -641,7 +655,26 @@ class Hooks:self._dead_keys_swallowed.clear()self._composed_local.clear()+ def _desktop_proc(self, _hook, _event, _hwnd, _object, _child, _thread, _time):+ # OUTOFCONTEXT delivers on this hook thread; defer the snapshot to its window queue.+ if self._window and not user32.PostMessageW(self._window, WM_MODIFIER_RESYNC, 0, 0):+ LOGGER.warning("Could not queue the keyboard state after an input desktop switch")+def _window_proc(self, hwnd, message, wparam, lparam):+ if message == WM_MODIFIER_RESYNC:+ try:+ from desktop_win import _on_default_desktop++ # A secure desktop makes GetAsyncKeyState return zero even for held keys.+ if _on_default_desktop():+ ctrl_down = {vk for vk in self._state.ctrl_down if user32.GetAsyncKeyState(vk) & 0x8000}+ altgr_down = self._state.altgr_down and bool(user32.GetAsyncKeyState(0xA5) & 0x8000)+ # Only prune observed real Ctrl presses: AltGr's synthetic Ctrl also reads down.+ self._state.ctrl_down.intersection_update(ctrl_down)+ self._state.altgr_down = altgr_down+ except Exception:+ LOGGER.exception("Could not restore the keyboard state after an input desktop switch")+ return 0if message == WM_INPUT:try:motion = _raw_mouse_motion(lparam)@@ -845,12 +878,23 @@ if _IS_WINDOWS:_WNDPROC = ctypes.WINFUNCTYPE(ctypes.c_ssize_t, ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t)+ _WINEVENTPROC = ctypes.WINFUNCTYPE(+ None, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_long, ctypes.c_long,+ ctypes.c_ulong, ctypes.c_ulong,+ )user32.SetWindowsHookExW.restype = ctypes.c_void_puser32.SetWindowsHookExW.argtypes = [ctypes.c_int, _LL_HOOK_PROC, ctypes.c_void_p, ctypes.c_ulong]user32.CallNextHookEx.restype = ctypes.c_ssize_tuser32.CallNextHookEx.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t, ctypes.c_ssize_t]user32.UnhookWindowsHookEx.argtypes = [ctypes.c_void_p]+ user32.SetWinEventHook.restype = ctypes.c_void_p+ user32.SetWinEventHook.argtypes = [+ ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p, _WINEVENTPROC, ctypes.c_ulong, ctypes.c_ulong,+ ctypes.c_ulong,+ ]+ user32.UnhookWinEvent.argtypes = [ctypes.c_void_p]+ user32.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t]user32.ToUnicodeEx.restype = ctypes.c_intuser32.ToUnicodeEx.argtypes = [ctypes.c_uint,@@ -879,6 +923,8 @@ if _IS_WINDOWS:user32.UnregisterClassW.argtypes = [ctypes.c_wchar_p, ctypes.c_void_p]user32.GetKeyState.restype = ctypes.c_shortuser32.GetKeyState.argtypes = [ctypes.c_int]+ user32.GetAsyncKeyState.restype = ctypes.c_short+ user32.GetAsyncKeyState.argtypes = [ctypes.c_int]user32.CreateWindowExW.restype = ctypes.c_void_puser32.CreateWindowExW.argtypes = [ctypes.c_ulong,@@ -908,7 +954,7 @@ if _IS_WINDOWS:else: # pragma: no cover - the structures above are only used on WindowsPOINT = KBDLLHOOKSTRUCT = MSLLHOOKSTRUCT = MSG = NoneRAWINPUT = RAWINPUTDEVICE = WNDCLASS = None- _LL_HOOK_PROC = _WNDPROC = None+ _LL_HOOK_PROC = _WNDPROC = _WINEVENTPROC = None_WINDOW_CLASS_NAME = "BeamerRawInput"diff --git a/win_app/clipboard_portal.py b/win_app/clipboard_portal.pyindex 3ba7f04..b5ca2e3 100644--- a/win_app/clipboard_portal.py+++ b/win_app/clipboard_portal.py@@ -32,7 +32,7 @@ MAX_BYTES = 64 * 1024 * 1024_synced: Optional[int] = None-def _read_fd(fd: int, timeout: float = TIMEOUT_SECONDS) -> Optional[bytes]:+def _read_fd(fd: int, timeout: float = TIMEOUT_SECONDS, *, strict=False) -> Optional[bytes]:"""All an app writes into `fd` until it closes it, within `timeout`; None if it did not finish."""chunks = []size = 0@@ -42,6 +42,8 @@ def _read_fd(fd: int, timeout: float = TIMEOUT_SECONDS) -> Optional[bytes]:left = deadline - time.monotonic()if left <= 0:LOGGER.warning("The app holding the clipboard did not hand it over in time")+ if strict:+ raise OSError("the clipboard transfer timed out")return Noneready, _, _ = select.select([fd], [], [], left)if not ready:@@ -61,24 +63,35 @@ def _read_fd(fd: int, timeout: float = TIMEOUT_SECONDS) -> Optional[bytes]:def _read(mime: str) -> Optional[bytes]:fd = inject_portal.remote().ask(lambda session: session.open_selection(mime), discard=os.close)if fd is None:- return None- return _read_fd(fd)+ raise OSError("the clipboard transfer could not be opened")+ return _read_fd(fd, strict=True)-def _offered() -> Tuple[list, bool, int]:+def _offered() -> Optional[Tuple[list, bool, int]]:return inject_portal.remote().ask(lambda session: (list(session.offered), session.ours, session.changes),- default=([], False, 0))+ default=None)def _contents(offered: list) -> Tuple[Optional[str], Optional[bytes]]:text = png = None+ failed = Falsemime = next((m for m in TEXT_MIMES if m in offered), None)if mime is not None:- data = _read(mime)- if data:- text = data.decode("utf-8", "replace").replace("\r\n", "\n")+ try:+ data = _read(mime)+ if data:+ text = data.decode("utf-8", "replace").replace("\r\n", "\n")+ except Exception:+ failed = True+ LOGGER.exception("Could not read the clipboard text")if PNG_MIME in offered:- png = _read(PNG_MIME) or None+ try:+ png = _read(PNG_MIME) or None+ except Exception:+ failed = True+ LOGGER.exception("Could not read the clipboard image")+ if failed and text is None and png is None:+ raise OSError("the clipboard provider could not be read")return text or None, png@@ -86,15 +99,21 @@ def get_contents() -> Tuple[Optional[str], Optional[bytes]]:"""(text, png) another app has on the clipboard, either None when absent; both None when itis Beamer's own, or the clipboard cannot be reached. Never raises."""try:- offered, ours, _changes = _offered()- if ours:- return None, None- return _contents(offered)+ return read_contents()except Exception:LOGGER.exception("Could not read the clipboard")return None, None+def read_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """Like get_contents, but raise OSError if the portal or transfer is unavailable."""+ offered = _offered()+ if offered is None:+ raise OSError("the portal clipboard is unavailable")+ formats, ours, _changes = offered+ return (None, None) if ours else _contents(formats)++def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:"""get_contents(), or (None, None) when no other app has copied since the clipboard was lastsent or written. Either way it counts as sent from here on."""diff --git a/win_app/clipboard_win.py b/win_app/clipboard_win.pyindex 97dd7b7..f10dbfb 100644--- a/win_app/clipboard_win.py+++ b/win_app/clipboard_win.py@@ -44,6 +44,8 @@ if _IS_WINDOWS:user32.EmptyClipboard.argtypes = []user32.GetClipboardData.restype = ctypes.c_void_puser32.GetClipboardData.argtypes = [ctypes.c_uint]+ user32.IsClipboardFormatAvailable.restype = ctypes.c_int+ user32.IsClipboardFormatAvailable.argtypes = [ctypes.c_uint]user32.SetClipboardData.restype = ctypes.c_void_puser32.SetClipboardData.argtypes = [ctypes.c_uint, ctypes.c_void_p]kernel32.GlobalAlloc.restype = ctypes.c_void_p@@ -232,10 +234,12 @@ def _read_clipboard_text(win32, mem32):if there is none. Caller holds the clipboard open."""handle = win32.GetClipboardData(CF_UNICODETEXT)if not handle:+ if win32.IsClipboardFormatAvailable(CF_UNICODETEXT):+ raise OSError("the clipboard text provider could not be read")return Nonepointer = mem32.GlobalLock(handle)if not pointer:- return None+ raise OSError("the clipboard text could not be locked")try:text = ctypes.wstring_at(pointer)finally:@@ -249,11 +253,15 @@ def _read_clipboard_dib(win32, mem32):or CF_DIBV5 source, so this one format covers them all."""handle = win32.GetClipboardData(CF_DIB)if not handle:+ if win32.IsClipboardFormatAvailable(CF_DIB):+ raise OSError("the clipboard image provider could not be read")return Nonesize = mem32.GlobalSize(handle)+ if not size:+ raise OSError("the clipboard image size could not be read")pointer = mem32.GlobalLock(handle)- if not pointer or not size:- return None+ if not pointer:+ raise OSError("the clipboard image could not be locked")try:return ctypes.string_at(pointer, size)finally:@@ -282,19 +290,25 @@ def _put_clipboard_data(win32, mem32, clipboard_format, payload):return True-def _get_contents(win32, mem32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep):+def _get_contents(win32, mem32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep,+ strict=False):if not _open_clipboard(win32, attempts, delay, sleep):LOGGER.warning("could not open the clipboard for reading")+ if strict:+ raise OSError("could not open the clipboard for reading")return None, None+ failed = Falsetry:try:text = _read_clipboard_text(win32, mem32)except Exception:+ failed = TrueLOGGER.exception("failed to read clipboard text")text = Nonetry:dib = _read_clipboard_dib(win32, mem32)except Exception:+ failed = TrueLOGGER.exception("failed to read the clipboard image")dib = Nonefinally:@@ -302,7 +316,10 @@ def _get_contents(win32, mem32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_D# Converted after the clipboard is closed: a Retina-sized DIB takes# tens of milliseconds to encode and nothing else can use the clipboard# while it is held.- return text, dib_to_png(dib) if dib is not None else None+ png = dib_to_png(dib) if dib is not None else None+ if strict and failed and text is None and png is None:+ raise OSError("the clipboard provider could not be read")+ return text, pngdef _set_contents(win32, mem32, text, png, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep, written=None):@@ -341,20 +358,29 @@ def _set_contents(win32, mem32, text, png, attempts=OPEN_RETRY_ATTEMPTS, delay=Owin32.DestroyWindow(owner)-def get_contents() -> Tuple[Optional[str], Optional[bytes]]:+def get_contents(*, strict=False) -> Tuple[Optional[str], Optional[bytes]]:"""(text, png) from the Windows clipboard, either None when absent, bothNone if this isn't Windows or reading failed for any reason. Neverraises."""if not _IS_WINDOWS:+ if strict:+ raise OSError("the Windows clipboard is unavailable")return None, Nonetry:with _LOCK:- return _get_contents(user32, kernel32)- except Exception:+ return _get_contents(user32, kernel32, strict=strict)+ except Exception as exc:LOGGER.exception("failed to read the Windows clipboard")+ if strict:+ raise OSError("failed to read the Windows clipboard") from excreturn None, None+def read_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """Like get_contents, but raise OSError on failure so a caller can retry an unchanged copy."""+ return get_contents(strict=True)++def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:"""get_contents(), or (None, None) when the clipboard has not changed since it was last sentto or written from the Mac. Either way the current contents count as sent from here on."""diff --git a/win_app/clipboard_x11.py b/win_app/clipboard_x11.pyindex 56b41db..7e4255f 100644--- a/win_app/clipboard_x11.py+++ b/win_app/clipboard_x11.py@@ -188,6 +188,14 @@ def get_contents() -> Tuple[Optional[str], Optional[bytes]]:return _on_gui(_read, default=(None, None))+def read_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """Like get_contents, but raise OSError if the GUI read failed or timed out."""+ result = _on_gui(_read, default=None)+ if result is None:+ raise OSError("the X11 clipboard could not be read")+ return result++def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:"""get_contents(), or (None, None) when the clipboard has not changed since it was last sentto or written from the other machine. Either way the current contents count as sent from herediff --git a/win_app/desktop_win.py b/win_app/desktop_win.pyindex 58cf9d7..4550565 100644--- a/win_app/desktop_win.py+++ b/win_app/desktop_win.py@@ -273,6 +273,9 @@ def set_click_through(hwnd: int, through: bool) -> None:def _pointer_marker():+ from core import portable_runtime+ if portable_runtime.enabled():+ return str(portable_runtime.data_path() / "pointer-hidden")base = os.environ.get("LOCALAPPDATA")return os.path.join(base, "Beamer", "pointer-hidden") if base else Nonediff --git a/win_app/firewall_win.py b/win_app/firewall_win.pyindex 54c500e..a2b57b9 100644--- a/win_app/firewall_win.py+++ b/win_app/firewall_win.py@@ -50,6 +50,9 @@ class FirewallStatus:# pairing existed does not claim a missing rule it knows nothing about.pairing_allowed: bool = Truepairing_tcp_allowed: bool = True+ # Rule presence controls automatic setup; profile coverage only controls advice.+ pairing_covered: bool = True+ pairing_tcp_covered: bool = Truedef missing_rule(status: "FirewallStatus") -> bool:@@ -141,27 +144,36 @@ def _lan_networks(networks: Sequence[dict]) -> list:def interpret(payload: dict, exe: str, port: int, elevated: bool = True) -> FirewallStatus:rules = [rule for rule in payload.get("rules", []) if _rule_applies(rule, exe, port)]+ pairing_rules = {+ transport: [rule for rule in payload.get("rules", []) if _rule_applies(rule, exe, PAIRING_PORT, transport)]+ for transport in ("udp", "tcp")+ }networks = list(payload.get("networks", []))active = tuple(sorted({str(n.get("category", "")) for n in networks if n.get("category")}))lan = _lan_networks(networks)lan_profiles = tuple(sorted({str(n.get("category", "")) for n in lan if n.get("category")}))allow_profiles = [_profiles(r.get("profile")) for r in rules if str(r.get("action", "")).lower() == "allow"]- block_profiles = [_profiles(r.get("profile")) for r in rules if str(r.get("action", "")).lower() == "block"]+ block_profiles = [_profiles(r.get("profile")) for r in rules + pairing_rules["udp"] + pairing_rules["tcp"]+ if str(r.get("action", "")).lower() == "block"]def touches(profile_set: Optional[set], wanted: Iterable[str]) -> bool:- return profile_set is None or any(name in profile_set for name in wanted)+ return profile_set is None or any(("Domain" if name == "DomainAuthenticated" else name) in profile_set+ for name in wanted)++ def covers(profiles) -> bool:+ return bool(profiles) and all(any(touches(p, (name,)) for p in profiles) for name in lan_profiles)# A block rule beats an allow rule on any profile they share, so a block scoped to a# profile nothing is connected to is harmless and must not send the user chasing it.blocked = any(touches(p, active or ("Domain", "Private", "Public")) for p in block_profiles)- covered = all(any(touches(p, (name,)) for p in allow_profiles) for name in lan_profiles) and bool(allow_profiles)+ covered = covers(allow_profiles)public = tuple((int(n.get("index", 0)), str(n.get("alias", ""))) for n in lan if str(n.get("category", "")) == "Public")- def pairing_allowed(protocol: str) -> bool:- return any(- _rule_applies(rule, exe, PAIRING_PORT, protocol) and str(rule.get("action", "")).lower() == "allow"- for rule in payload.get("rules", [])- )+ pairing_profiles = {+ transport: [_profiles(rule.get("profile")) for rule in matching+ if str(rule.get("action", "")).lower() == "allow"]+ for transport, matching in pairing_rules.items()+ }return FirewallStatus(port=port,@@ -173,22 +185,26 @@ def interpret(payload: dict, exe: str, port: int, elevated: bool = True) -> Firepublic_interfaces=public,elevated=elevated,error="",- pairing_allowed=pairing_allowed("udp"),- pairing_tcp_allowed=pairing_allowed("tcp"),+ pairing_allowed=bool(pairing_profiles["udp"]),+ pairing_tcp_allowed=bool(pairing_profiles["tcp"]),+ pairing_covered=covers(pairing_profiles["udp"]),+ pairing_tcp_covered=covers(pairing_profiles["tcp"]),)def advise(status: FirewallStatus) -> Advice:"""One sentence a non-technical person can act on, and the one button that fixes it."""port = status.port+ pairing_udp = status.pairing_allowed and status.pairing_covered+ pairing_tcp = status.pairing_tcp_allowed and status.pairing_tcp_coveredrule_profiles = ("Private",) + (("Domain",) if "DomainAuthenticated" in status.lan_profiles else ())if status.error:return Advice(tr("Beamer could not read the Windows Firewall: {error}").format(error=status.error), tr("Check again"), "check")if status.blocked:advice = Advice(- tr("Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on "+ tr("Windows Firewall is blocking Beamer's input or pairing traffic. This can happen when Cancel was pressed on ""Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling "- "does not clear it. Fixing it removes the block and adds the right rule for private networks.").format(port=port),+ "does not clear it. Fixing it removes the block and adds the right rules for private networks."),tr("Fix the firewall"),"repair",rule_profiles,@@ -202,10 +218,10 @@ def advise(status: FirewallStatus) -> Advice:"repair",rule_profiles,)- elif not status.covered and status.public_interfaces:+ elif status.public_interfaces and not (status.covered and pairing_udp and pairing_tcp):names = ", ".join(alias for _, alias in status.public_interfaces if alias) or "this network"advice = Advice(- tr("Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and "+ tr("Windows treats {names} as a public network, so some of Beamer's firewall rules do not cover it and ""your other machines cannot get in. Trusting it marks the network as private, which lets them in without ""opening the port on every other network this PC joins.").format(names=names),tr("Trust this network"),@@ -220,23 +236,22 @@ def advise(status: FirewallStatus) -> Advice:"repair",rule_profiles,)- elif not status.pairing_allowed or not status.pairing_tcp_allowed:+ elif not pairing_udp or not pairing_tcp:missing = []- if not status.pairing_allowed:+ if not pairing_udp:missing.append((f"the pairing beacon on UDP {PAIRING_PORT}","a machine that has not been set up by hand will never see this PC in its list, and this PC will not ""hear other machines' pairing announcements",))- if not status.pairing_tcp_allowed:+ if not pairing_tcp:missing.append((f"the pairing exchange on TCP {PAIRING_PORT}","a machine that finds this PC cannot finish pairing with it",))advice = Advice(- tr("Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for "- "{rules}, so {effects}. Installs made before these rules existed are missing them. Fixing it adds "- "what is missing and leaves the working rules alone.").format(+ tr("Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule covering this network for "+ "{rules}, so {effects}. Fixing it replaces Beamer's inbound firewall rules.").format(port=port, rules=" or for ".join(rule for rule, _ in missing),effects=" and ".join(effect for _, effect in missing)),tr("Fix the firewall"),diff --git a/win_app/hooks/portable_storage.py b/win_app/hooks/portable_storage.pynew file mode 100644index 0000000..2460569--- /dev/null+++ b/win_app/hooks/portable_storage.py@@ -0,0 +1,6 @@+"""Establish portable storage before PyInstaller's Qt runtime hook imports QtCore."""++from portable_entry import prepare++if not prepare():+ raise SystemExit(1)diff --git a/win_app/identify_overlay.py b/win_app/identify_overlay.pyindex 0edbf88..e29f1b2 100644--- a/win_app/identify_overlay.py+++ b/win_app/identify_overlay.py@@ -7,6 +7,7 @@ import loggingimport osfrom pathlib import Pathimport sys+import timefrom PySide6.QtCore import QObject, QProcess, QProcessEnvironment, QRect, QRectF, Qt, QTimerfrom PySide6.QtGui import QColor, QGuiApplication, QPainter, QPen@@ -106,6 +107,7 @@ class IdentifyScreens(QObject):self.helper_focus = Noneself._helper_stderr = b""self._pending = []+ self._last_request_at = Noneself._expiry = QTimer(self)self._expiry.setSingleShot(True)self._expiry.timeout.connect(self.stop)@@ -114,6 +116,10 @@ class IdentifyScreens(QObject):self._startup.timeout.connect(self._fallback)def show_numbers(self, labels, displays):+ now = time.monotonic()+ if self._last_request_at is not None and now - self._last_request_at < OVERLAY_SECONDS:+ return+ self._last_request_at = nowself.stop()self.helper_focus = Nonewayland = QGuiApplication.platformName().startswith("wayland")diff --git a/win_app/input_injector.py b/win_app/input_injector.pyindex 1809c9d..a1db393 100644--- a/win_app/input_injector.py+++ b/win_app/input_injector.py@@ -527,6 +527,9 @@ def release_gameinput_foreground(after: Optional[Callable[[], None]] = None) ->session thread that must keep draining pings -- then run `after`. Falsewhen GameInput is not in front, or a restart is already running or ranwithin the cooldown."""+ from core import portable_runtime+ if portable_runtime.enabled():+ return Falseif foreground_class() != GAMEINPUT_WINDOW_CLASS:return Falseif time.monotonic() - _gameinput_restarted_at[0] < GAMEINPUT_RESTART_COOLDOWN_SECONDS:diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex bd7ac9b..cc2c807 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -29,6 +29,7 @@ from PySide6.QtWidgets import (QComboBox,QFrame,QGridLayout,+ QInputDialog,QHBoxLayout,QLabel,QLineEdit,@@ -63,6 +64,8 @@ from app_config import (save_config,)from core import crash_log+from core import portable_runtime+from core.portable_store import PortableStore, PortableStoreErrorfrom core.capture_types import DeadKey, TextInputfrom core.i18n import trfrom core import effects@@ -202,9 +205,18 @@ firewall_win = platform_parts.firewallLOG_PATH: Optional[Path] = None+def machine_name(name=""):+ if name:+ return name[:protocol.MAX_NAME_CHARS]+ suffix = " (Portable)" if portable_runtime.enabled() else ""+ return pairing.machine_name()[:protocol.MAX_NAME_CHARS - len(suffix)] + suffix++def configure_logging() -> Optional[Path]:global LOG_PATH- candidates = [default_config_path().parent, Path(tempfile.gettempdir()) / "Beamer"]+ candidates = [default_config_path().parent]+ if not portable_runtime.enabled():+ candidates.append(Path(tempfile.gettempdir()) / "Beamer")for directory in candidates:try:directory.mkdir(parents=True, exist_ok=True)@@ -219,6 +231,8 @@ def configure_logging() -> Optional[Path]:LOG_PATH = log_pathreturn log_pathexcept OSError:+ if portable_runtime.enabled():+ raisecontinuelogging.basicConfig(level=logging.INFO)return None@@ -339,7 +353,7 @@ def _instance_server_name() -> str:session = ctypes.c_ulong()if not kernel32.ProcessIdToSessionId(kernel32.GetCurrentProcessId(), ctypes.byref(session)):raise OSError("Beamer could not identify its Windows session")- return f"Beamer.Receiver.{session.value}"+ return f"Beamer.Receiver.{session.value}{portable_runtime.instance_suffix()}"suffix = f"Beamer.Receiver.{os.getuid()}"if sys.platform.startswith("linux"):runtime_location = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.RuntimeLocation)@@ -522,8 +536,11 @@ class WindowsApplication(QWidget):if hasattr(self, "footer_note"):self.footer_note.setVisible(self.width() >= 640)- def __init__(self, config_path: Path, start_after_first_paint: bool = False) -> None:+ def __init__(self, config_path: Path, start_after_first_paint: bool = False,+ input_controller_available: bool = True) -> None:super().__init__()+ self._input_controller_blocked = not input_controller_available+ self._input_controller_release = Noneself.config_path = config_pathself._status_lock = threading.RLock()self._status = ServerState.STOPPED@@ -620,14 +637,15 @@ class WindowsApplication(QWidget):protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None),settings_callback=lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data),- identify_callback=lambda peer, labels: self.bridge.identify.emit(labels),+ identify_callback=self._receive_identify_screens,paired_callback=self._store_paired,link_callback=lambda peer, up: self.bridge.peers_changed.emit(),announce=self._announce,away=lambda: self.sender.owner,zones=self._zones,clipboard=platform_parts.clipboard,- unlock=platform_parts.unlock,+ unlock=None if portable_runtime.enabled() else platform_parts.unlock,+ listener=portable_runtime.listener if portable_runtime.enabled() else None,hardware=hardware_win.hardware_address_towards,desktop=platform_parts.desktop,injector=platform_parts.injector,@@ -663,7 +681,7 @@ class WindowsApplication(QWidget):# Same on all machines, over either link: applied on the GUI thread, and announced with# this PC's own arrangement the moment a link comes up.self.sender.settings_callback = lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data)- self.sender.identify_callback = lambda peer, labels: self.bridge.identify.emit(labels)+ self.sender.identify_callback = self._receive_identify_screensself.sender.arrangement_callback = lambda peer, read: self.bridge.arrangement.emit(protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"),protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None@@ -722,7 +740,8 @@ class WindowsApplication(QWidget):self._trigger = capture_win.Trigger()self._sending_detail = "Not connected"self.update_checker = updates.Checker(- VERSION, lambda: self._config is None or self._config.check_updates, self.bridge.update.emit, logger=LOGGER+ VERSION, lambda: self._config is None or self._config.check_updates, self.bridge.update.emit,+ logger=LOGGER, portable=portable_runtime.enabled(),)self._paired = Falsetry:@@ -774,6 +793,7 @@ class WindowsApplication(QWidget):self.refresh_timer = QTimer(self)self.refresh_timer.setInterval(250)+ self.refresh_timer.timeout.connect(self._check_input_controller)self.refresh_timer.timeout.connect(lambda: self._refresh_window(skip_hidden=True))self.refresh_timer.start()self.full_screen_timer = QTimer(self)@@ -1114,7 +1134,7 @@ class WindowsApplication(QWidget):))self.update_button = QPushButton(tr("Download"))self.update_button.setProperty("vernier", "primary")- self.update_button.clicked.connect(self.open_update)+ self.update_button.clicked.connect(self.download_update)self.update_button.setVisible(False)module.body.addWidget(self.update_button)return module@@ -1135,9 +1155,12 @@ class WindowsApplication(QWidget):found = Noneself._update = foundself.update_button.setText(tr("Download Beamer {version}").format(version=found[0]) if found else tr("Download"))- motion.set_shown(self.update_button, found is not None and not portal.sandboxed())+ if portable_runtime.enabled() and found:+ self.update_button.setText(tr("Download portable zip"))+ motion.set_shown(self.update_button, found is not None and not portal.sandboxed()+ and (not portable_runtime.enabled() or bool(self.update_checker.download_url)))self.header_action.setText(tr("Beamer {version} is available…").format(version=found[0]) if found else tr("Beamer {version}").format(version=VERSION))- self.header_action.setEnabled(found is not None)+ self.header_action.setEnabled(found is not None and not portal.sandboxed())self._refresh_update_notice()def _refresh_update_notice(self) -> None:@@ -1173,6 +1196,13 @@ class WindowsApplication(QWidget):if self._update:QDesktopServices.openUrl(QUrl(self._update[1]))+ def download_update(self) -> None:+ if portable_runtime.enabled():+ if self._update and self.update_checker.download_url:+ QDesktopServices.openUrl(QUrl(self.update_checker.download_url))+ else:+ self.open_update()+def open_log_folder(self) -> None:folder = LOG_PATH.parent if LOG_PATH is not None else default_config_path().parentQDesktopServices.openUrl(QUrl.fromLocalFile(str(folder)))@@ -1752,6 +1782,12 @@ class WindowsApplication(QWidget):if "identify_screens" in caps:self._send_to(peer, protocol.identify_screens_msg(display_numbers(tiles.get(protocol.id_text(peer)))))+ def _receive_identify_screens(self, peer, labels) -> None:+ if isinstance(peer, bytes):+ peer = protocol.id_text(peer)+ if peer in {entry.get("id") for entry in peerlist.desktops(self.book.peers())}:+ self.bridge.identify.emit(labels)+def _on_identify_screens(self, labels) -> None:self._refresh_own_displays()displays = self._own_displays()@@ -1858,14 +1894,14 @@ class WindowsApplication(QWidget):def _identity(self) -> dict:"""This machine as a `hello` and a `welcome` say it (section 2)."""config = self._config or default_config()- name = (config.name or pairing.machine_name())[: protocol.MAX_NAME_CHARS]+ name = machine_name(config.name)return {"id": protocol.read_id(config.machine_id) or b"","name": name,"platform": OWN_PLATFORM,"app": VERSION[:32] if VERSION.isascii() and VERSION.isprintable() else "dev",# A swipe has no shortcut every Linux desktop shares, so Linux does not offer gestures.- "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "identify_screens", "ping_rtt")+ "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "identify_screens", "ping_rtt", "motion_path")if not (cap == "gestures" and OWN_PLATFORM == "linux")],"port": self._settings_port,}@@ -3937,11 +3973,14 @@ class WindowsApplication(QWidget):identity = protocol.read_id(settings["machine_id"])if identity is None:return None- name = settings.get("name") or pairing.machine_name()- return PairingService(+ name = machine_name(settings.get("name"))+ service = PairingService(name, identity, OWN_PLATFORM, self._announced_port, self.book.peers, self._store_peer,on_paired=self.bridge.paired.emit, logger=LOGGER,+ **({"bind_port": 0, "tcp_port": 0} if portable_runtime.enabled() else {}),)+ service.active_discovery = portable_runtime.enabled()+ return servicedef _store_peer(self, entry: dict, replaced) -> None:"""PairingService's write, on a socket thread with the service's lock held: the new peer takes@@ -4606,6 +4645,7 @@ class WindowsApplication(QWidget):self.host_readout.setAccessibleName(tr("This PC's address"))field(tr("This PC's address"), self.host_readout)self.port_entry = QLineEdit(str(current.port))+ self.port_entry.setReadOnly(portable_runtime.enabled())self.port_entry.setMaximumWidth(240)field(tr("This PC's listening port"), self.port_entry)self.save_message = widgets.label("", "note", wrap=True)@@ -4753,9 +4793,15 @@ class WindowsApplication(QWidget):return str(Path(sys.executable).resolve()), portdef _check_firewall(self) -> None:+ if portable_runtime.enabled():+ self.firewall_note.setText(tr("Portable mode leaves Windows Firewall unchanged. Your network must already allow Beamer."))+ self.firewall_button.hide()+ returnself._run_firewall(firewall_win.status, tr("Checking…"))def _firewall_action(self) -> None:+ if portable_runtime.enabled():+ return# Only the built exe changes the firewall, by the button or on its own. From source the# executable is python.exe, and repair() replaces Beamer's rules by name, so a test run on# the PC took the installed Beamer's rules with it and cut the Mac's link (29-09-2026).@@ -4808,6 +4854,8 @@ class WindowsApplication(QWidget):threading.Thread(target=work, name="Beamer-firewall", daemon=True).start()def _on_firewall(self, status) -> None:+ if portable_runtime.enabled():+ returnself._firewall_busy = Falseif self._closing:return@@ -5045,7 +5093,7 @@ class WindowsApplication(QWidget):def start(self) -> None:self.update_checker.start()- if getattr(sys, "frozen", False) and firewall_win.is_elevated():+ if not portable_runtime.enabled() and getattr(sys, "frozen", False) and firewall_win.is_elevated():# Beamer's own rules before any socket opens: a listener Windows has no rule for makes# it ask, and a click on Allow there writes rules for every network, public ones too,# where Beamer's are for private networks only. Not from source: see _firewall_action.@@ -5054,6 +5102,9 @@ class WindowsApplication(QWidget):self._listen()def _rules_then_listen(self) -> None:+ if portable_runtime.enabled():+ self.bridge.rules_ready.emit()+ returntry:exe, port = self._firewall_target()status = firewall_win.status(exe, port)@@ -5069,6 +5120,14 @@ class WindowsApplication(QWidget):returnif self.pairing is not None:self.pairing.start()+ if sys.platform == "win32" and self._input_controller_blocked:+ self._input_controller_release = _claim_input_controller()+ if self._input_controller_release is None:+ self._set_status(ServerState.ERROR, tr("Another Beamer copy controls input on this PC. Quit it to use input in this copy."))+ QTimer.singleShot(1000, self._listen)+ return+ self._input_controller_blocked = False+ self._idle_pointer = self._make_idle_pointer()if self._config is not None and self._paired:self._start_receiver(self._config)self._start_sending(self._config)@@ -5081,10 +5140,25 @@ class WindowsApplication(QWidget):# the receiver never starts, so nothing else would ever read it.self._check_firewall()+ def _check_input_controller(self):+ if (self._closing or not portable_runtime.enabled()+ or not self._input_controller_release or not _installed_instance_running()):+ return+ # A legacy installed copy does not know the shared lease. Yield before the next+ # refresh rather than letting its hooks and this copy's hooks keep running together.+ self._input_controller_blocked = True+ self.server.stop()+ self._stop_sending()+ release, self._input_controller_release = self._input_controller_release, None+ release()+ self._listen()+def _configure_trigger(self, config: Config) -> None:self._trigger.configure(config.trigger_key, config.trigger_style, config.double_tap_ms)def _start_receiver(self, config: Config) -> None:+ if getattr(self, "_input_controller_blocked", False):+ returnif self.server.listening and self._receiver_port != config.port:self.server.stop()self._receiver_port = config.port@@ -5095,6 +5169,8 @@ class WindowsApplication(QWidget):when sending is on: they are the one part of Beamer that can take thisPC's own keyboard away, so an install that never sends never installsthem."""+ if getattr(self, "_input_controller_blocked", False):+ returnif not self._any_send():returnself._configure_trigger(config)@@ -5215,7 +5291,7 @@ class WindowsApplication(QWidget):def _make_idle_pointer(self):"""The pointer hiding of this desktop, or None where it cannot hide another app's pointer(Wayland). A run that died with the pointer hidden is undone first."""- if not getattr(desktop_win, "CAN_HIDE_POINTER", False):+ if portable_runtime.enabled() or self._input_controller_blocked or not getattr(desktop_win, "CAN_HIDE_POINTER", False):return Nonetry:desktop_win.restore_pointer()@@ -5320,6 +5396,8 @@ class WindowsApplication(QWidget):box.setText(tr('<b>Beamer {version}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br><a href="{url}" style="color: {colour};">{link}</a>').format(version=VERSION, url=HOME_PAGE, colour=theme.colour("signal"), link=tr(HOME_PAGE_TEXT)))+ if portable_runtime.enabled():+ box.setInformativeText(tr("Portable — settings and pairing keys stay in this folder, protected by your passphrase. Administrator apps cannot be controlled."))box.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)for text in box.findChildren(QLabel):text.setOpenExternalLinks(True)@@ -5381,6 +5459,10 @@ class WindowsApplication(QWidget):LOGGER.exception("Could not show the pointer on the way out")if hasattr(self, "tray"):self.tray.hide()+ release = getattr(self, "_input_controller_release", None)+ if release is not None:+ self._input_controller_release = None+ release()QApplication.quit()def closeEvent(self, event) -> None:@@ -5669,6 +5751,8 @@ def _windows_kernel32():kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)kernel32.CreateMutexW.restype = ctypes.c_void_pkernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p]+ kernel32.OpenMutexW.restype = ctypes.c_void_p+ kernel32.OpenMutexW.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_wchar_p]kernel32.CloseHandle.argtypes = [ctypes.c_void_p]kernel32.GetCurrentProcess.restype = ctypes.c_void_pkernel32.GetCurrentProcessId.restype = ctypes.c_ulong@@ -5697,7 +5781,7 @@ def _claim_instance():# through windll can read an error ctypes' own marshalling set in between,# and 183 (already exists) is the whole single-instance check.kernel32 = _windows_kernel32()- mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.Receiver")+ mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.Receiver" + portable_runtime.instance_suffix())already_running = ctypes.get_last_error() == 183if not mutex:raise OSError("Beamer could not create its single-instance lock")@@ -5712,6 +5796,33 @@ def _claim_instance():return lock.unlock if lock.tryLock(0) else None+def _claim_input_controller():+ """App windows may coexist; session-wide hooks and injected input have one owner."""+ kernel32 = _windows_kernel32()+ if portable_runtime.enabled() and _installed_instance_running():+ # Older installed versions predate this lease. Their instance marker is enough to+ # keep portable input inactive, without activating or stopping the installed app.+ return None+ mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.InputController")+ already_running = ctypes.get_last_error() == 183+ if not mutex:+ return None+ if already_running:+ kernel32.CloseHandle(mutex)+ return None+ return lambda: kernel32.CloseHandle(mutex)+++def _installed_instance_running():+ kernel32 = _windows_kernel32()+ installed = kernel32.OpenMutexW(0x00100000, False, "Local\\Beamer.Receiver")+ error = ctypes.get_last_error()+ if installed:+ kernel32.CloseHandle(installed)+ return True+ return error == 5++# A relaunched Beamer starts while the one it replaces still holds the lock, and waits this long# for it to quit rather than handing over to it.RELAUNCH_WAIT_SECONDS = 15@@ -5736,12 +5847,55 @@ def activate_existing_instance(hidden: bool, activation_token: Optional[str] = Ndef prepare_windows_startup() -> None:- if sys.platform == "win32":+ if sys.platform == "win32" and not portable_runtime.enabled():autostart_win.migrate_legacy_task()+def unlock_portable(parent=None) -> bool:+ vault = PortableStore(portable_runtime.settings_path())+ creating = not vault.exists+ while True:+ title = tr("Protect Beamer Portable") if creating else tr("Unlock Beamer Portable")+ prompt = (tr("Choose a passphrase of at least 12 characters. You need it each time Beamer starts. "+ "It protects pairing keys if this folder is lost. A forgotten passphrase cannot be recovered.")+ if creating else tr("Enter the passphrase for this portable folder."))+ password, accepted = QInputDialog.getText(parent, title, prompt, QLineEdit.EchoMode.Password)+ if not accepted:+ vault.lock()+ return False+ if creating:+ if len(password) < 12:+ password = ""+ QMessageBox.warning(parent, title, tr("Use at least 12 characters for the passphrase."))+ continue+ confirmation, accepted = QInputDialog.getText(+ parent, title, tr("Enter the passphrase again."), QLineEdit.EchoMode.Password)+ if not accepted:+ password = ""+ vault.lock()+ return False+ if password != confirmation:+ password = confirmation = ""+ QMessageBox.warning(parent, title, tr("The passphrases do not match. Try again."))+ continue+ confirmation = ""+ try:+ vault.unlock(password)+ except (PortableStoreError, OSError, ValueError):+ QMessageBox.warning(parent, title, tr("The portable settings could not be unlocked or saved. "+ "Check the passphrase and that the folder is writable. Existing pairing keys have been kept."))+ else:+ portable_runtime.store = vault+ return True+ finally:+ password = ""++def main() -> None:+ portable_runtime.initialise()arguments = parse_args()+ if portable_runtime.enabled() and arguments.config.resolve() != portable_runtime.settings_path().resolve():+ raise ConfigError("Portable mode cannot use a settings file outside its folder")if arguments.identify_x11 is not None:from identify_overlay import run_x11_helpersys.exit(run_x11_helper(arguments.identify_x11))@@ -5772,7 +5926,7 @@ def main() -> None:if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASSLOGGER.warning("Could not raise Beamer's priority: %s", ctypes.WinError(ctypes.get_last_error()))_stay_unthrottled(kernel32)- instance_signal = quit_signals = None+ instance_signal = quit_signals = application = controller_release = Nonetry:app = QApplication(sys.argv)app.setApplicationName("Beamer")@@ -5780,14 +5934,22 @@ def main() -> None:app.setQuitOnLastWindowClosed(False)theme.init_fonts()app.setFont(theme.font(theme.TYPE["body"]))+ if portable_runtime.enabled():+ if not unlock_portable():+ returntry:startup_config = app_config.load_config(arguments.config.expanduser().resolve(), unpaired_ok=True)i18n.install(startup_config.language)except ConfigError:i18n.install("auto")+ if sys.platform == "win32":+ controller_release = _claim_input_controller()application = WindowsApplication(- arguments.config.expanduser().resolve(), start_after_first_paint=not arguments.hidden+ arguments.config.expanduser().resolve(), start_after_first_paint=not arguments.hidden,+ input_controller_available=sys.platform != "win32" or controller_release is not None,)+ application._input_controller_release = controller_release+ controller_release = Nonequit_signals = quit_signals_module.QuitSignals(application.quit, parent=app)instance_signal = InstanceSignal(application.show_window, parent=app)if not instance_signal.listening:@@ -5802,7 +5964,12 @@ def main() -> None:quit_signals.close()if instance_signal is not None:instance_signal.close()+ if application is not None:+ application.quit()+ if controller_release is not None:+ controller_release()release()+ portable_runtime.close()def import_probe(out_path: str, names: list) -> int:@@ -5824,6 +5991,8 @@ def import_probe(out_path: str, names: list) -> int:def register_autostart_for_setup() -> int:+ if portable_runtime.enabled():+ return 1try:exe = autostart_win.installed_exe()if exe is None:@@ -5836,6 +6005,8 @@ def register_autostart_for_setup() -> int:def cleanup_for_uninstall() -> int:+ if portable_runtime.enabled():+ return 1failed = Falseexe = autostart_win.installed_exe()if exe is None:diff --git a/win_app/machines_win.py b/win_app/machines_win.pyindex a362127..28b9251 100644--- a/win_app/machines_win.py+++ b/win_app/machines_win.py@@ -920,12 +920,12 @@ class PairingSheet(widgets.Module):`shown` (the window's Hide addresses) lets it."""listed = [item for item in machines if item.get("pair_id") or item.get("pairing") != pairing.PAIRING_V3]wheres = [shown(item["address"]) if shared else "" for item, shared in zip(listed, peerlist.sharing_a_name(listed))]- key = tuple((item["address"], item["name"], item.get("platform"), item.get("pairing"), item.get("pair_id"), where)+ key = tuple((pairing.discovery_endpoint(item), item["name"], item.get("platform"), item.get("pairing"), item.get("pair_id"), where)for item, where in zip(listed, wheres))if key == self._listed:returnself._listed = key- chosen = self.chosen_machine()+ chosen = pairing.refreshed_discovery(self.chosen_machine(), listed)self._machines = listedfor button in list(self.group.buttons()):self.group.removeButton(button)@@ -946,10 +946,12 @@ class PairingSheet(widgets.Module):# A list of machines reads down its left edge; the theme centres a choice.button.setStyleSheet("text-align: left; padding-left: 12px;")button.setProperty("address", item["address"])- button.clicked.connect(lambda _checked=False, address=item["address"]: self._pick(address))+ button.setProperty("reply_port", pairing.discovery_endpoint(item)[1])+ button.clicked.connect(lambda _checked=False, address=item["address"],+ port=pairing.discovery_endpoint(item)[1]: self._pick(address, port))self.group.addButton(button)self.heard_layout.addWidget(button)- if chosen is not None and chosen["address"] == item["address"]:+ if chosen is not None and pairing.discovery_endpoint(chosen) == pairing.discovery_endpoint(item):button.setChecked(True)if chosen is not None and not any(b.isChecked() for b in self.group.buttons()):self._on_pick(None)@@ -959,12 +961,14 @@ class PairingSheet(widgets.Module):def chosen_machine(self) -> Optional[dict]:for button in self.group.buttons():if button.isChecked():- return next((item for item in self._machines if item["address"] == button.property("address")), None)+ return next((item for item in self._machines if pairing.discovery_endpoint(item) ==+ (button.property("address"), button.property("reply_port"))), None)return None- def _pick(self, address: str) -> None:+ def _pick(self, address: str, reply_port=None) -> None:button = next((candidate for candidate in self.group.buttons()- if candidate.property("address") == address), None)+ if candidate.property("address") == address+ and (reply_port is None or candidate.property("reply_port") == reply_port)), None)self.group.setExclusive(False)for candidate in self.group.buttons():candidate.setChecked(False)@@ -972,7 +976,7 @@ class PairingSheet(widgets.Module):if button is not None:button.setChecked(True)self.address.clear()- self._on_pick(next((item for item in self._machines if item["address"] == address), None))+ self._on_pick(self.chosen_machine())self._refresh_pair_button()def _typed_address(self, _text: str) -> None:diff --git a/win_app/portable_entry.py b/win_app/portable_entry.pynew file mode 100644index 0000000..156bc50--- /dev/null+++ b/win_app/portable_entry.py@@ -0,0 +1,36 @@+"""Portable boot boundary: fail closed before importing the native application."""++import ctypes+import runpy+import sys++from core import portable_runtime+from core.i18n import tr+++def prepare():+ try:+ portable_runtime.initialise(require_marker=True)+ except OSError:+ ctypes.windll.user32.MessageBoxW(+ None,+ tr("Beamer Portable needs its Beamer.portable marker and a writable folder beside the app. "+ "Move the whole folder to writable storage and try again."),+ tr("Beamer Portable"), 0x10,+ )+ return False+ return True+++def main():+ if not prepare():+ return 1+ try:+ runpy.run_module("kvm_bridge_win", run_name="__main__")+ finally:+ portable_runtime.close()+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/win_app/sender.py b/win_app/sender.pyindex 6127742..bc5f1d7 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -43,6 +43,7 @@ from core.i18n import N_, trLOGGER = logging.getLogger(__name__)SEND_QUEUE_SIZE = 4096+MOTION_INTERVAL_SECONDS = 0.002MONITORS_MAX_AGE_SECONDS = 1.0TICK_SECONDS = 0.1ROUND_TRIP_MAX_AGE_SECONDS = 5.0@@ -1123,6 +1124,17 @@ class LinkSender:actions = queued_actionsfor index, action in enumerate(actions):if isinstance(action, (owner_module.Send, owner_module.SendClipboard, owner_module.SetClipboard, owner_module.Drop)):+ with self._outbound.mutex:+ if (isinstance(action, owner_module.Send) and self._outbound.queue+ and action.message.get("type") == protocol.MSG_MOUSEMOVE+ and isinstance(self._outbound.queue[-1], owner_module.Send)+ and self._outbound.queue[-1].message.get("type") == protocol.MSG_MOUSEMOVE+ and self._outbound.queue[-1].peer == action.peer):+ merged = protocol.coalesce_mousemove(self._outbound.queue[-1].message, action.message,+ preserve_path="motion_path" in self.links.caps(action.peer))+ if merged is not None:+ self._outbound.queue[-1] = owner_module.Send(action.peer, merged)+ continuetry:self._outbound.put_nowait(action)except queue.Full:@@ -1149,20 +1161,46 @@ class LinkSender:self._unreachable(action)def _outbound_worker(self) -> None:+ next_motion_at = 0.0while not self._stop_event.is_set():try:action = self._outbound.get(timeout=0.2)except queue.Empty:continue+ consumed = 1try:+ motion = isinstance(action, owner_module.Send) and action.message.get("type") == protocol.MSG_MOUSEMOVE+ if motion:+ delay = next_motion_at - time.monotonic()+ if delay > 0:+ # Python's Windows sleep uses a high-resolution waitable timer; an Event+ # wait can round this short interval to the system's 15.6 ms timer tick.+ time.sleep(delay)+ with self._outbound.mutex:+ while self._outbound.queue:+ following = self._outbound.queue[0]+ if (not isinstance(following, owner_module.Send) or following.peer != action.peer+ or following.message.get("type") != protocol.MSG_MOUSEMOVE):+ break+ merged = protocol.coalesce_mousemove(action.message, following.message,+ preserve_path="motion_path" in self.links.caps(action.peer))+ if merged is None:+ break+ action = owner_module.Send(action.peer, merged)+ self._outbound.queue.popleft()+ consumed += 1+ self._outbound.not_full.notify_all()self._deliver(action)+ if motion:+ next_motion_at = time.monotonic() + MOTION_INTERVAL_SECONDSexcept Exception:# One bad message must not end the only thread that drains this queue: nothing# restarts it, and the hooks would keep swallowing input into a queue nobody reads.LOGGER.exception("outbound worker recovered")self._lost()finally:- self._outbound.task_done()+ for _ in range(consumed):+ self._outbound.task_done()def _deliver(self, action) -> None:"""Sends in the order the owner gave them, except that reading the clipboard (which can be@@ -1188,6 +1226,15 @@ class LinkSender:with self._clip_lock:waiting = self._clip_wait.get(peer)if waiting is not None:+ if (isinstance(action, owner_module.Send) and waiting+ and action.message.get("type") == protocol.MSG_MOUSEMOVE+ and isinstance(waiting[-1], owner_module.Send)+ and waiting[-1].message.get("type") == protocol.MSG_MOUSEMOVE):+ merged = protocol.coalesce_mousemove(waiting[-1].message, action.message,+ preserve_path="motion_path" in self.links.caps(peer))+ if merged is not None:+ waiting[-1] = owner_module.Send(peer, merged)+ returnwaiting.append((action, generation, stamp) if isinstance(action, owner_module.SendClipboard) else action)returnif isinstance(action, owner_module.SendClipboard):@@ -1224,10 +1271,10 @@ class LinkSender:except Exception:if attempt == 2:LOGGER.exception("The clipboard could not be sent")- if sent:+ if sent is not False:breakfinally:- if not sent:+ if sent is False:with self._lock:self._owner.clipboard_failed(peer)while True:@@ -1382,20 +1429,22 @@ class LinkSender:return Falsedef _send_clipboard(self, peer: bytes, waiting, generation=None, stamp=None) -> Optional[bool]:+ """True means posted, None means no supported content, False means failed or cancelled."""if generation is not None and (self._owner.on != peer or self._owner._visit_route != generation or(stamp is not None and self._clipboard_stamp_now() != stamp)):- return+ return Falsetry:- text, image = self._clipboard_module().get_contents()+ clipboard = self._clipboard_module()+ text, image = getattr(clipboard, "read_contents", clipboard.get_contents)()except Exception:LOGGER.exception("Failed to read the local clipboard for %s", self._name(peer))- return+ return Falseif generation is not None and (self._owner.on != peer or self._owner._visit_route != generation or(stamp is not None and self._clipboard_stamp_now() != stamp)):- return+ return Falsewith self._clip_lock:if self._clip_wait.get(peer) is not waiting:- return+ return Falsecaps = self.links.caps(peer)if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:LOGGER.warning("Local clipboard text is too large; skipping the text")@@ -1408,7 +1457,7 @@ class LinkSender:if "clipboard_image" not in caps:image = Noneif not text and image is None:- return+ return Nonereturn self.links.post(peer, protocol.clipboard_msg(text or None, image))def _set_clipboard(self, message: dict) -> None:diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.pyindex c5e26dd..1b8f8f9 100644--- a/win_app/tests/test_app_config.py+++ b/win_app/tests/test_app_config.py@@ -20,6 +20,20 @@ BASE = {"host": "192.168.1.3", "port": 51820, "auth_token": "shared-token"}class PeerAddressConfigTests(unittest.TestCase):+ def test_explicitly_saving_the_same_learnt_host_pins_it(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "settings.json"+ config = config_from_dict({**BASE, "mac_host": "192.0.2.10"})+ app_config.save_config(path, config)+ settings = app_config.load_settings(path)+ settings["peers"][0]["host_pinned"] = False+ app_config.write_settings(path, settings)+ config = app_config.load_config(path)+ app_config.save_config(path, config)+ self.assertIs(app_config.load_settings(path)["peers"][0]["host_pinned"], False)+ app_config.save_config(path, config, pin_address=True)+ self.assertIs(app_config.load_settings(path)["peers"][0]["host_pinned"], True)+def test_editing_a_learnt_host_pins_it_and_survives_reload(self):with tempfile.TemporaryDirectory() as directory:path = Path(directory) / "settings.json"diff --git a/win_app/tests/test_capture_win_recovery.py b/win_app/tests/test_capture_win_recovery.pynew file mode 100644index 0000000..ac91dc8--- /dev/null+++ b/win_app/tests/test_capture_win_recovery.py@@ -0,0 +1,232 @@+"""Secure desktop returns repair translation state without inventing wire events."""++import ctypes+import unittest+from unittest.mock import Mock, patch++import capture_win+import desktop_win+++class ModifierRecoveryTests(unittest.TestCase):+ class HookData(ctypes.Structure):+ _fields_ = [+ ("vkCode", ctypes.c_ulong),+ ("scanCode", ctypes.c_ulong),+ ("flags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ctypes.c_size_t),+ ]++ def setUp(self):+ self.events = []+ self.hooks = capture_win.Hooks(lambda *event: self.events.append(event) or True, Mock(), Mock())+ self.user32 = Mock()+ self.user32.CallNextHookEx.return_value = 99+ self.user32.GetKeyState.return_value = 0+ self.user32.GetAsyncKeyState.side_effect = lambda vk: 0x8000 if vk in self.held else 0+ self.held = set()+ self.default_desktop = True+ self.enterContext(patch.object(capture_win, "user32", self.user32))+ self.enterContext(patch.object(capture_win, "KBDLLHOOKSTRUCT", self.HookData))+ self.enterContext(patch.object(desktop_win, "_on_default_desktop", side_effect=lambda: self.default_desktop))++ def tick(self, default):+ self.default_desktop = default+ self.hooks._window_proc(10, 0x8001, 0, 0)++ def key(self, vk, scan, down=True):+ data = self.HookData(vk, scan, 0, 0, 0)+ return self.hooks._keyboard_proc(+ capture_win.HC_ACTION, capture_win.WM_KEYDOWN if down else capture_win.WM_KEYUP, ctypes.byref(data),+ )++ def run_hooks(self):+ with patch.object(capture_win, "kernel32", Mock()), \+ patch.object(capture_win, "_LL_HOOK_PROC", side_effect=lambda callback: callback), \+ patch.object(capture_win, "_WNDPROC", side_effect=lambda callback: callback), \+ patch.object(capture_win, "_WINEVENTPROC", side_effect=lambda callback: callback, create=True), \+ patch.object(capture_win, "MSG", ctypes.c_long), \+ patch.object(capture_win, "_create_message_window", return_value=10), \+ patch.object(capture_win, "_register_raw_mouse"), \+ patch.object(capture_win, "_unregister_window_class"):+ self.hooks._run()++ def test_return_repairs_lost_ctrl_and_altgr_releases_before_another_key(self):+ self.key(0xA2, 0x1D)+ self.key(0xA5, 0x38)+ before = list(self.events)++ self.tick(False)+ self.tick(True)++ self.assertEqual(self.hooks._state.ctrl_down, set())+ self.assertFalse(self.hooks._state.altgr_down)+ self.assertEqual(self.events, before)++ def test_secure_desktop_zeroes_do_not_release_genuinely_held_modifiers(self):+ self.key(0xA2, 0x1D)+ self.key(0xA3, 0x1D)+ self.key(0xA5, 0x38)+ before = list(self.events)++ self.tick(False)+ self.tick(False)++ self.assertEqual(self.hooks._state.ctrl_down, {0xA2, 0xA3})+ self.assertTrue(self.hooks._state.altgr_down)+ self.assertEqual(self.events, before)+ self.user32.GetAsyncKeyState.assert_not_called()++ def test_return_preserves_held_ctrl_side_and_its_eventual_real_release(self):+ self.key(0xA2, 0x1D)+ self.key(0xA3, 0x1D)+ self.tick(False)+ self.held = {0xA3}++ self.tick(True)+ self.assertEqual(self.hooks._state.ctrl_down, {0xA3})+ self.key(0xA3, 0x1D, False)++ self.assertEqual(self.events, [+ ("cmd", True, 0xA2, None), ("cmd_r", True, 0xA3, None), ("cmd_r", False, 0xA3, None),+ ])+ self.assertEqual(self.hooks._state.ctrl_down, set())++ def test_return_with_held_altgr_does_not_promote_its_synthetic_ctrl(self):+ self.key(0xA2, 0x21D)+ self.key(0xA5, 0x38)+ self.tick(False)+ self.held = {0xA2, 0xA5}++ self.tick(True)+ self.assertEqual(self.hooks._state.ctrl_down, set())+ self.assertTrue(self.hooks._state.altgr_down)+ self.key(0xA5, 0x38, False)++ self.assertEqual(self.events, [("alt_r", True, 0xA5, None), ("alt_r", False, 0xA5, None)])++ def test_return_restores_dead_key_composition_after_a_lost_ctrl_release(self):+ self.key(0xA2, 0x1D)+ self.tick(False)+ self.tick(True)+ self.events.clear()++ def french(vk, _scan, _state):+ return capture_win.DeadKey("^") if vk == 0xDD else "e"++ with patch.object(capture_win, "_to_unicode", side_effect=french):+ self.key(0xDD, 0x1A)+ self.key(0xDD, 0x1A, False)+ self.key(0x45, 0x12)+ self.key(0x45, 0x12, False)++ self.assertIsInstance(self.events[0][0], capture_win.DeadKey)+ self.assertEqual(self.events[2:], [("ê", True, 0x45, "e"), ("ê", False, 0x45, "e")])++ def test_return_restores_plain_text_after_a_lost_altgr_release(self):+ self.key(0xA5, 0x38)+ self.tick(False)+ self.tick(True)+ self.events.clear()++ def layout(_vk, _scan, state):+ return "@" if state.get(0xA5) else "q"++ with patch.object(capture_win, "_to_unicode", side_effect=layout):+ self.key(0x51, 0x10)+ self.key(0x51, 0x10, False)++ self.assertEqual(self.events, [("q", True, 0x51, "q"), ("q", False, 0x51, "q")])++ def test_unrelated_window_message_does_not_resample_suppressed_modifier_presses(self):+ self.key(0xA2, 0x1D)+ self.key(0xA5, 0x38)++ self.hooks._window_proc(10, 0x0113, 1, 0)++ self.assertEqual(self.hooks._state.ctrl_down, {0xA2})+ self.assertTrue(self.hooks._state.altgr_down)+ self.user32.GetAsyncKeyState.assert_not_called()++ def test_hook_lifecycle_listens_for_desktop_return_and_releases_the_listener(self):+ notifications = []+ lifetime = []++ def listen(first, last, module, callback, process, thread, flags):+ self.assertEqual((first, last, module, process, thread, flags), (0x20, 0x20, None, 0, 0, 0))+ notifications.append(callback)+ return 30++ def dispatch(_message, _window, _first, _last):+ if notifications:+ self.key(0xA2, 0x1D)+ self.key(0xA5, 0x38)+ self.default_desktop = False+ notifications[0](30, 0x20, None, 0, 0, 0, 0)+ self.default_desktop = True+ notifications[0](30, 0x20, None, 0, 0, 0, 0)+ return 0++ self.user32.SetWindowsHookExW.side_effect = (20, 21)+ self.user32.SetWinEventHook.side_effect = listen+ self.user32.GetMessageW.side_effect = dispatch+ self.user32.PostMessageW.side_effect = lambda *args: self.hooks._window_proc(*args) or 1+ self.user32.UnhookWinEvent.side_effect = lambda handle: lifetime.append(+ ("unhook", handle, notifications[0] in self.hooks._callbacks),+ )+ self.user32.DestroyWindow.side_effect = lambda handle: lifetime.append(("destroy", handle))+ self.run_hooks()++ self.assertEqual(len(notifications), 1)+ self.assertIsNone(self.hooks._failure)+ self.assertEqual(self.hooks._state.ctrl_down, set())+ self.assertFalse(self.hooks._state.altgr_down)+ self.assertEqual(self.events, [("cmd", True, 0xA2, None), ("alt_r", True, 0xA5, None)])+ self.assertEqual(lifetime, [("unhook", 30, True), ("destroy", 10)])+ self.assertEqual(self.hooks._callbacks, [])++ def test_failed_desktop_listener_registration_removes_input_hooks(self):+ self.user32.SetWindowsHookExW.side_effect = (20, 21)+ self.user32.SetWinEventHook.return_value = 0+ self.user32.GetMessageW.return_value = 0++ with self.assertLogs(capture_win.LOGGER, level="ERROR"):+ self.run_hooks()++ self.assertIsInstance(self.hooks._failure, RuntimeError)+ self.assertTrue(self.hooks._ready.is_set())+ self.assertEqual([call.args for call in self.user32.UnhookWindowsHookEx.call_args_list], [(20,), (21,)])+ self.user32.UnhookWinEvent.assert_not_called()+ self.user32.DestroyWindow.assert_called_once_with(10)+ self.assertEqual(self.hooks._callbacks, [])++ def test_unavailable_desktop_listener_api_removes_input_hooks(self):+ self.user32.SetWindowsHookExW.side_effect = (20, 21)+ del self.user32.SetWinEventHook+ self.user32.GetMessageW.return_value = 0++ with self.assertLogs(capture_win.LOGGER, level="ERROR"):+ self.run_hooks()++ self.assertIsInstance(self.hooks._failure, AttributeError)+ self.assertEqual([call.args for call in self.user32.UnhookWindowsHookEx.call_args_list], [(20,), (21,)])+ self.user32.DestroyWindow.assert_called_once_with(10)+ self.assertEqual(self.hooks._callbacks, [])++ def test_message_loop_failure_releases_the_desktop_listener(self):+ self.user32.SetWindowsHookExW.side_effect = (20, 21)+ self.user32.SetWinEventHook.return_value = 30+ self.user32.GetMessageW.side_effect = RuntimeError("message pump failed")++ with self.assertLogs(capture_win.LOGGER, level="ERROR"):+ self.run_hooks()++ self.assertEqual(str(self.hooks._failure), "message pump failed")+ self.user32.UnhookWinEvent.assert_called_once_with(30)+ self.user32.DestroyWindow.assert_called_once_with(10)+ self.assertEqual(self.hooks._callbacks, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_clipboard_portal.py b/win_app/tests/test_clipboard_portal.pyindex 5493991..bd153e5 100644--- a/win_app/tests/test_clipboard_portal.py+++ b/win_app/tests/test_clipboard_portal.py@@ -83,5 +83,30 @@ class SetContentsTest(unittest.TestCase):self.assertEqual(clipboard_portal._synced, 5)+class ReadContentsTest(unittest.TestCase):+ def test_strict_read_distinguishes_an_unavailable_session_from_empty(self):+ stub = StubRemote(ready=True)+ stub.session.offered = []+ stub.session.ours = False+ with mock.patch.object(inject_portal, "remote", return_value=stub):+ self.assertEqual(clipboard_portal.read_contents(), (None, None))+ with mock.patch.object(inject_portal, "remote") as remote:+ remote.return_value.ask.side_effect = lambda work, default=None, **kwargs: default+ with self.assertRaises(OSError):+ clipboard_portal.read_contents()+ self.assertEqual(clipboard_portal.get_contents(), (None, None))++ def test_strict_read_distinguishes_a_failed_transfer_from_empty_text(self):+ with mock.patch.object(clipboard_portal, "_offered", return_value=(["text/plain"], False, 5)), \+ mock.patch.object(inject_portal, "remote") as remote:+ remote.return_value.ask.return_value = None+ with self.assertRaises(OSError):+ clipboard_portal.read_contents()+ self.assertEqual(clipboard_portal.get_contents(), (None, None))+ with mock.patch.object(clipboard_portal, "_offered", return_value=(["text/plain"], False, 5)), \+ mock.patch.object(clipboard_portal, "_read", return_value=b""):+ self.assertEqual(clipboard_portal.read_contents(), (None, None))++if __name__ == "__main__":unittest.main()diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.pyindex bbe305c..d5def5b 100644--- a/win_app/tests/test_clipboard_win.py+++ b/win_app/tests/test_clipboard_win.py@@ -217,6 +217,9 @@ class FakeWin32:def GetClipboardData(self, clipboard_format):return self.formats.get(clipboard_format, 0)+ def IsClipboardFormatAvailable(self, clipboard_format):+ return clipboard_format in self.formats+def SetClipboardData(self, clipboard_format, handle):self.formats[clipboard_format] = handlereturn handle@@ -244,6 +247,46 @@ class ClipboardOrchestrationTests(unittest.TestCase):self.addCleanup(patch.stop)self.mem32 = FakeMem32()+ def test_strict_read_retries_native_contention_without_another_copy(self):+ win32 = FakeWin32(self.mem32, {CF_UNICODETEXT: self.mem32.handle_for("copied")})+ with mock.patch.multiple(clipboard_win, _IS_WINDOWS=True, user32=win32, kernel32=self.mem32), \+ mock.patch.object(clipboard_win, "_open_clipboard", return_value=False):+ with self.assertRaises(OSError):+ clipboard_win.read_contents()+ self.assertEqual(clipboard_win.get_contents(), (None, None))+ with mock.patch.multiple(clipboard_win, _IS_WINDOWS=True, user32=win32, kernel32=self.mem32):+ self.assertEqual(clipboard_win.read_contents(), ("copied", None))++ def test_strict_read_distinguishes_a_native_exception_from_empty(self):+ win32 = FakeWin32(self.mem32)+ with mock.patch.multiple(clipboard_win, _IS_WINDOWS=True, user32=win32, kernel32=self.mem32):+ self.assertEqual(clipboard_win.read_contents(), (None, None))+ with mock.patch.object(win32, "GetClipboardData", side_effect=OSError("provider busy")):+ with self.assertRaises(OSError):+ clipboard_win.read_contents()+ self.assertEqual(clipboard_win.get_contents(), (None, None))++ def test_strict_read_preserves_valid_text_when_the_image_provider_fails(self):+ win32 = FakeWin32(self.mem32, {CF_UNICODETEXT: self.mem32.handle_for("copied")})+ original = win32.GetClipboardData+ def read(kind):+ if kind == CF_DIB:+ raise OSError("image provider busy")+ return original(kind)+ with mock.patch.multiple(clipboard_win, _IS_WINDOWS=True, user32=win32, kernel32=self.mem32), \+ mock.patch.object(win32, "GetClipboardData", side_effect=read):+ self.assertEqual(clipboard_win.read_contents(), ("copied", None))++ def test_strict_read_reports_an_offered_format_that_cannot_be_read(self):+ win32 = FakeWin32(self.mem32, {CF_UNICODETEXT: self.mem32.handle_for("copied")})+ with mock.patch.multiple(clipboard_win, _IS_WINDOWS=True, user32=win32, kernel32=self.mem32):+ with mock.patch.object(win32, "GetClipboardData", return_value=0):+ with self.assertRaises(OSError):+ clipboard_win.read_contents()+ with mock.patch.object(self.mem32, "GlobalLock", return_value=0):+ with self.assertRaises(OSError):+ clipboard_win.read_contents()+def test_get_contents_reads_text_and_converts_the_dib(self):win32 = FakeWin32(self.mem32,diff --git a/win_app/tests/test_clipboard_x11.py b/win_app/tests/test_clipboard_x11.pyindex 831ddfb..acdc227 100644--- a/win_app/tests/test_clipboard_x11.py+++ b/win_app/tests/test_clipboard_x11.py@@ -4,6 +4,7 @@ import sysimport threadingimport timeimport unittest+from unittest import mockfrom pathlib import Pathtry:@@ -107,6 +108,27 @@ class ClipboardX11Test(unittest.TestCase):def test_empty_clipboard_reads_as_nothing(self):self.assertEqual(self.cb.get_contents(), (None, None))+ def test_strict_read_distinguishes_gui_failure_from_empty(self):+ self.assertEqual(self.cb.read_contents(), (None, None))+ with mock.patch.object(self.cb, "_read", side_effect=OSError("selection busy")):+ with self.assertRaises(OSError):+ self.cb.read_contents()+ self.assertEqual(self.cb.get_contents(), (None, None))++ def test_strict_read_reports_a_worker_timeout(self):+ self.cb.TIMEOUT_SECONDS = 0.01+ outcome = []+ def read():+ try:+ self.cb.read_contents()+ except OSError:+ outcome.append("failed")+ thread = threading.Thread(target=read)+ thread.start()+ thread.join(1)+ self.assertFalse(thread.is_alive())+ self.assertEqual(outcome, ["failed"])+def test_changed_contents_after_an_outside_change(self):self.outside_text("from another app")self.assertEqual(self.cb.changed_contents(), ("from another app", None))diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.pyindex f04997e..2fa1fb5 100644--- a/win_app/tests/test_firewall_win.py+++ b/win_app/tests/test_firewall_win.py@@ -53,6 +53,65 @@ def payload(rules=(), networks=(network(),)):class InterpretTests(unittest.TestCase):+ def test_existing_rules_on_another_profile_do_not_trigger_automatic_repair(self):+ rules = [rule(), pairing_rule(), pairing_tcp_rule(), pairing_tcp_rule(action="Block", profile="Domain")]+ status = interpret(payload(rules, [network("Public")]), EXE, PORT)+ self.assertFalse(firewall_win.missing_rule(status))+ self.assertFalse(status.blocked)+ self.assertEqual(advise(status).action, "trust")++ def test_existing_misprofiled_pairing_rules_require_a_manual_repair(self):+ rules = [rule(), pairing_rule(profile="Public"), pairing_tcp_rule(profile="Public")]+ status = interpret(payload(rules), EXE, PORT)+ self.assertFalse(firewall_win.missing_rule(status))+ self.assertEqual(advise(status).action, "repair")++ def test_pairing_only_blocks_are_reported_and_never_auto_repaired(self):+ for transport in ("TCP", "UDP"):+ with self.subTest(transport=transport):+ rules = [rule(), pairing_rule(), pairing_tcp_rule(),+ rule(action="Block", port=str(firewall_win.PAIRING_PORT), protocol=transport)]+ status = interpret(payload(rules), EXE, PORT)+ self.assertTrue(status.blocked)+ self.assertEqual(advise(status).action, "repair")+ self.assertIn("pairing", advise(status).sentence)+ self.assertFalse(firewall_win.missing_rule(status))++ def test_pairing_rules_must_cover_every_lan_profile(self):+ for transport in ("TCP", "UDP"):+ with self.subTest(transport=transport):+ rules = [rule(), pairing_rule(profile="Public" if transport == "UDP" else "Private"),+ pairing_tcp_rule(profile="Public" if transport == "TCP" else "Private")]+ status = interpret(payload(rules), EXE, PORT)+ self.assertFalse(status.pairing_tcp_covered if transport == "TCP" else status.pairing_covered)+ self.assertEqual(advise(status).action, "repair")+ self.assertFalse(firewall_win.missing_rule(status))++ def test_public_lan_with_private_pairing_rules_offers_trust(self):+ rules = [rule(profile="Any"), pairing_rule(), pairing_tcp_rule()]+ status = interpret(payload(rules, [network("Public")]), EXE, PORT)+ self.assertFalse(status.pairing_covered)+ self.assertFalse(status.pairing_tcp_covered)+ self.assertEqual(advise(status).action, "trust")++ def test_pairing_block_on_an_inactive_profile_does_not_hide_healthy_rules(self):+ rules = [rule(), pairing_rule(), pairing_tcp_rule(),+ pairing_rule(action="Block", profile="Public"),+ pairing_tcp_rule(action="Block", profile="Public")]+ status = interpret(payload(rules), EXE, PORT)+ self.assertFalse(status.blocked)+ self.assertTrue(status.pairing_allowed)+ self.assertTrue(status.pairing_tcp_allowed)+ self.assertEqual(advise(status).action, "check")++ def test_domain_authenticated_network_matches_domain_pairing_rules(self):+ rules = [rule(profile="Domain"), pairing_rule(profile="Domain"), pairing_tcp_rule(profile="Domain")]+ status = interpret(payload(rules, [network("DomainAuthenticated")]), EXE, PORT)+ self.assertTrue(status.covered)+ self.assertTrue(status.pairing_allowed)+ self.assertTrue(status.pairing_tcp_allowed)+ self.assertEqual(advise(status).action, "check")+def test_no_rule_at_all(self):status = interpret(payload(), EXE, PORT)self.assertFalse(status.allowed)diff --git a/win_app/tests/test_identify_screens_qt.py b/win_app/tests/test_identify_screens_qt.pyindex 7c0b0cb..0490392 100644--- a/win_app/tests/test_identify_screens_qt.py+++ b/win_app/tests/test_identify_screens_qt.py@@ -74,7 +74,8 @@ class IdentifyOverlayTests(unittest.TestCase):controller._fallback()native.assert_not_called()- def test_flags_geometry_repeated_invocation_and_three_second_expiry(self):+ @patch("time.monotonic", return_value=0.0)+ def test_flags_geometry_repeat_does_not_replace_or_extend_three_second_expiry(self, clock):controller = identify_overlay.IdentifyScreens()self.addCleanup(controller.stop)screen = self.app.primaryScreen()@@ -90,12 +91,45 @@ class IdentifyOverlayTests(unittest.TestCase):self.assertTrue(first.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating))self.assertTrue(first.testAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents))self.assertEqual(controller._expiry.interval(), 3000)- controller.show_numbers({"0": 2}, display)- self.assertFalse(first.isVisible())+ clock.return_value = 2.9+ remaining = controller._expiry.remainingTime()+ for _ in range(100):+ controller.show_numbers({"0": 2}, display)+ self.assertIs(controller.windows[0], first)+ self.assertTrue(first.isVisible())self.assertEqual(len(controller.windows), 1)- self.assertEqual(controller.windows[0].number, 2)+ self.assertEqual(controller.windows[0].number, 1)+ self.assertLessEqual(controller._expiry.remainingTime(), remaining)QTest.qWait(3150)self.assertFalse(controller.windows)+ clock.return_value = 3.0+ controller.show_numbers({"0": 2}, display)+ self.assertEqual(controller.windows[0].number, 2)++ @patch("time.monotonic", return_value=0.0)+ def test_wayland_helper_flood_is_limited_even_after_failure_and_stop(self, clock):+ controller = identify_overlay.IdentifyScreens()+ self.addCleanup(controller.stop)+ screen = self.fake_screen(0, 0)+ with patch.object(identify_overlay.QGuiApplication, "platformName", return_value="wayland"), \+ patch.object(identify_overlay.QGuiApplication, "screens", return_value=[screen]), \+ patch.object(identify_overlay.sys, "platform", "linux"), \+ patch.dict(identify_overlay.os.environ, {"DISPLAY": ""}), \+ patch.object(controller, "_start_layer_shell") as start:+ controller.show_numbers({"0": 1}, {"0": Rect(0, 0, 1920, 1080)})+ controller._backend = "layer-shell"+ process = Mock()+ process.readAllStandardError.return_value = b"unavailable"+ controller._process = process+ controller._helper_finished(process)+ controller.stop()+ clock.return_value = 2.9+ for _ in range(100):+ controller.show_numbers({"0": 2}, {"0": Rect(0, 0, 1920, 1080)})+ self.assertEqual(start.call_count, 1)+ clock.return_value = 3.0+ controller.show_numbers({"0": 2}, {"0": Rect(0, 0, 1920, 1080)})+ self.assertEqual(start.call_count, 2)def test_helper_failed_start_and_timeout_both_fall_back(self):controller = identify_overlay.IdentifyScreens()@@ -206,6 +240,46 @@ class IdentifyPageTests(unittest.TestCase):_close_window = fixture.CrossingPageParityTests._close_window_stop_patches = fixture.CrossingPageParityTests._stop_patches+ def test_both_receive_links_ignore_phone_and_unknown_peer_before_overlay(self):+ window = self.window+ desktop = protocol.read_id(self.peers[0]["id"])+ phone, unknown = bytes([90]) * 16, bytes([91]) * 16+ peers = self.peers + [{"id": protocol.id_text(phone), "port": 0}]+ with patch.object(window.book, "peers", return_value=peers), \+ patch.object(window.identify_screens, "show_numbers") as show:+ for callback in (window.sender.identify_callback, window.server._callbacks["identify"]):+ with self.subTest(callback=callback):+ callback(phone, {"0": 1})+ callback(unknown, {"0": 1})+ QApplication.processEvents()+ show.assert_not_called()+ callback(desktop, {"0": 1})+ QApplication.processEvents()+ show.assert_called_once()+ show.reset_mock()++ @patch("time.monotonic", return_value=0.0)+ def test_local_button_and_both_receive_links_share_overlay_limit(self, clock):+ window = self.window+ peer = protocol.read_id(self.peers[0]["id"])+ geometry = self.app.primaryScreen().geometry()+ displays = {"0": Rect(geometry.x(), geometry.y(), geometry.width(), geometry.height())}+ with patch.object(window, "_peer_caps", return_value={}), \+ patch.object(window, "_displays_changed"), \+ patch.object(window, "_refresh_own_displays"), \+ patch.object(window, "_own_displays", return_value=displays), \+ patch.object(window.identify_screens, "_show_qt") as show:+ window._identify_screens()+ clock.return_value = 2.9+ for callback in (window.sender.identify_callback, window.server._callbacks["identify"]):+ callback(peer, {"0": 1})+ window._identify_screens()+ QApplication.processEvents()+ self.assertEqual(show.call_count, 1)+ clock.return_value = 3.0+ window._identify_screens()+ self.assertEqual(show.call_count, 2)+def test_button_identifies_local_and_all_capable_linked_peers(self):window = self.windowself.assertIn("identify_screens", window._identity()["caps"])diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.pyindex fa74875..3978539 100644--- a/win_app/tests/test_links.py+++ b/win_app/tests/test_links.py@@ -811,8 +811,7 @@ class ReviewTests(unittest.TestCase):self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == B and m["type"] == "keydown"]))self.assertEqual([m["type"] for t, m in rig.links.sent if t == B], ["focus", "clipboard", "keydown"])- def test_pointer_moves_made_during_a_clipboard_read_go_one_by_one_as_made(self):- # Never summed: the far machine's edge feels each move where its pointer is (return_edge).+ def test_pointer_moves_during_a_clipboard_read_keep_their_relative_travel(self):rig = self.two()rig.clipboard.slow_get = 0.3self.start_worker(rig)@@ -822,7 +821,7 @@ class ReviewTests(unittest.TestCase):self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == B and m["type"] == "mousemove"]))self.assertTrue(self.wait(lambda: not rig.sender._clip_wait))moves = [m["data"] for t, m in rig.links.sent if t == B and m["type"] == "mousemove"]- self.assertEqual([(m["dx"], m["dy"]) for m in moves], [(3, 1), (4, -2), (5, 0)])+ self.assertEqual((sum(m["dx"] for m in moves), sum(m["dy"] for m in moves)), (12, -1))def test_a_link_lost_during_a_clipboard_read_drops_what_waited_and_a_retake_sends_the_clipboard_after_its_focus(self):rig = self.two()@@ -952,6 +951,32 @@ class MouseTests(unittest.TestCase):class ClipboardReliabilityTests(unittest.TestCase):+ def test_unsendable_clipboards_are_read_once_until_the_next_local_copy(self):+ for text, image, caps in ((None, None, CAPS), ("", None, CAPS),+ ("x" * (protocol.CLIPBOARD_MAX_BYTES + 1), None, CAPS),+ (None, b"not a PNG", CAPS), ("unsupported", None, ())):+ with self.subTest(text_length=len(text or ""), image=image, caps=caps):+ rig = Rig()+ rig.links.caps_of[B] = frozenset(caps)+ rig.clipboard.copy(text)+ rig.clipboard.image = image+ with mock.patch.object(rig.clipboard, "get_contents", wraps=rig.clipboard.get_contents) as read:+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.set_redirecting(False)+ rig.flush()+ rig.sender.set_redirecting(True)+ rig.flush()+ rig.accept_take()+ self.assertEqual(read.call_count, 1)+ self.assertEqual(rig.sent(B, "clipboard"), [])+ rig.clipboard.copy("new copy")+ rig.sender.tick()+ rig.flush()+ self.assertEqual(read.call_count, 2)+ if "clipboard" in caps:+ self.assertEqual(rig.sent(B, "clipboard"), [protocol.clipboard_msg("new copy")])+def test_a_read_finishing_after_home_never_posts_private_local_text(self):rig = Rig()rig.sender.set_redirecting(True)@@ -998,7 +1023,7 @@ class ClipboardReliabilityTests(unittest.TestCase):rig = Rig()rig.sender.set_redirecting(True)rig.accept_take()- for failure in ("read", "read_exception", "post", "post_exception"):+ for failure in ("read_exception", "post", "post_exception"):with self.subTest(failure=failure):text = "new local copy: " + failurerig.clipboard.copy(text)@@ -1009,7 +1034,7 @@ class ClipboardReliabilityTests(unittest.TestCase):if len(calls) == 1:if failure.endswith("exception"):raise OSError("clipboard temporarily busy")- return (None, None) if failure == "read" else False+ return Falsereturn read() if failure.startswith("read") else post(*args)target, name = (rig.clipboard, "get_contents") if failure.startswith("read") else (rig.links, "post")with mock.patch.object(target, name, side_effect=attempt):@@ -1023,7 +1048,7 @@ class ClipboardReliabilityTests(unittest.TestCase):rig.sender.set_redirecting(True)rig.accept_take()rig.clipboard.copy("temporarily unreadable")- with mock.patch.object(rig.clipboard, "get_contents", return_value=(None, None)) as read:+ with mock.patch.object(rig.clipboard, "get_contents", side_effect=OSError("clipboard busy")) as read:rig.sender.tick()rig.sender.on_key("a", True, 0x41, "a")rig.flush()@@ -1073,7 +1098,7 @@ class ClipboardReliabilityTests(unittest.TestCase):rig = Rig()read, post = rig.clipboard.get_contents, rig.links.postif failure == "read":- rig.clipboard.get_contents = lambda: (None, None)+ rig.clipboard.get_contents = mock.Mock(side_effect=OSError("clipboard busy"))else:rig.links.post = lambda peer, message: False if message["type"] == protocol.MSG_CLIPBOARD else post(peer, message)rig.sender.set_redirecting(True)diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.pyindex 9d8d9d1..a39aee2 100644--- a/win_app/tests/test_pairing_window.py+++ b/win_app/tests/test_pairing_window.py@@ -135,6 +135,20 @@ class MachinesWindowTest(unittest.TestCase):row.directions.click()self.assertFalse(row.direction_group.isHidden())+ def test_windows_receiving_switch_is_under_directions_even_when_receiving_is_off(self):+ entry = peer(ID_A, "Other PC", TOKEN_A, "192.0.2.10", platform="windows")+ entry["allow_drive"] = False+ window = self.open(entry)+ row = window.machines.rows[TOKEN_A]+ self.assertTrue(row.direction_group.isHidden())+ self.assertEqual(row.directions.text(), "Directions")+ row.directions.click()+ self.assertFalse(row.direction_group.isHidden())+ self.assertEqual(row.allow.text(), "It drives this PC")+ self.assertFalse(row.allow.isChecked())+ row.allow.click()+ self.assertTrue(self.settings()["peers"][0]["allow_drive"])+def test_the_send_button_names_the_only_machine_in_use(self):window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"),peer(ID_B, "Inactive", TOKEN_B, "192.0.2.11", in_use=False))@@ -647,6 +661,20 @@ class PairingSheetWindowTest(unittest.TestCase):self.window.sheet.set_machines([dict(first, pair_id="new")])self.assertEqual(self.window.sheet.chosen_machine()["pair_id"], "new")+ def test_installed_and_portable_on_one_ip_keep_separate_selection(self):+ installed = dict(self.STUDIO, pair_id="installed")+ portable = dict(self.STUDIO, name="Studio (Portable)", port=53000,+ reply_port=53001, pair_id="portable")+ sheet = self.window.sheet+ sheet.set_machines([installed, portable])+ sheet.group.buttons()[1].click()+ self.assertEqual(sheet.chosen_machine(), portable)+ refreshed = dict(portable, pair_id="new-portable")+ sheet.set_machines([dict(installed, pair_id="new-installed"), refreshed])+ self.assertEqual(sheet.chosen_machine(), refreshed)+ sheet.group.buttons()[0].click()+ self.assertEqual(sheet.chosen_machine()["pair_id"], "new-installed")+def test_pair_stays_off_while_a_pairing_is_under_way(self):sheet = self.window.sheetsheet.address.setText("192.0.2.70")diff --git a/win_app/tests/test_portable.py b/win_app/tests/test_portable.pynew file mode 100644index 0000000..b9b025a--- /dev/null+++ b/win_app/tests/test_portable.py@@ -0,0 +1,447 @@+"""Synthetic portable acceptance cases; run offscreen from Claude, one module per process."""++import json+import os+from pathlib import Path+import sys+import tempfile+from types import SimpleNamespace+import unittest+from unittest import mock++os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')+sys.path[:0] = [str(Path(__file__).resolve().parents[1]), str(Path(__file__).resolve().parents[2])]++from PySide6.QtWidgets import QApplication+import app_config+import autostart_win+import input_injector+import kvm_bridge_win as kvm+import theme+from core import portable_runtime, protocol, updates+from core.portable_store import PortableStore+from core.tests import responder_harness as h+++PASSWORD = 'Synthetic portable passphrase'+VERSION = '1.5.11'+PAGE = 'https://github.com/kalkman-code/beamer/releases/tag/v1.5.11'+DOWNLOAD = ('https://github.com/kalkman-code/beamer/releases/download/v1.5.11/'+ 'Beamer-Portable-1.5.11-windows-x64.zip')+++class PortableTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.app = QApplication.instance() or QApplication([])+ theme.init_fonts()++ def setUp(self):+ scratch = Path.home() / 'hub' / 'Scratch'+ scratch.mkdir(parents=True, exist_ok=True)+ directory = tempfile.TemporaryDirectory(prefix='port2-native-', dir=scratch)+ self.addCleanup(directory.cleanup)+ self.root = Path(directory.name) / 'portable'+ (self.root / 'data').mkdir(parents=True)+ self.path = self.root / 'data' / 'settings.beamer'+ self.vault = PortableStore(self.path)+ self.vault.unlock(PASSWORD)+ for blocker in (+ mock.patch.object(portable_runtime, '_root', self.root),+ mock.patch.object(portable_runtime, 'store', self.vault),+ mock.patch.object(portable_runtime, 'reserve_listener', return_value=51234),+ mock.patch('core.locale.is_us_region', return_value=False),+ ):+ blocker.start()+ self.addCleanup(blocker.stop)+ self.addCleanup(self.vault.lock)+ self.addCleanup(lambda: portable_runtime.store.lock() if portable_runtime.store else None)++ def test_paths_ignore_host_settings_and_remain_beside_executable(self):+ with mock.patch.dict(os.environ, {'LOCALAPPDATA': str(self.root.parent / 'host')}):+ self.assertEqual(app_config.default_config_path(), self.path)++ def test_pairing_round_trip_is_encrypted_and_preserves_settings(self):+ settings = app_config.load_settings(self.path)+ settings['peers'] = [h.entry(h.B, 'Synthetic peer')]+ settings['hide_addresses'] = True+ app_config.write_settings(self.path, settings)+ self.vault.lock()+ self.vault.unlock(PASSWORD)+ loaded = app_config.load_settings(self.path)+ self.assertEqual(loaded['schema'], settings['schema'])+ self.assertEqual(loaded['peers'][0]['token'], h.TOKENS[h.B])+ self.assertTrue(loaded['hide_addresses'])+ self.assertEqual(loaded['port'], 51234)+ for path in self.root.rglob('*'):+ if path.is_file():+ self.assertNotIn(h.TOKENS[h.B].encode(), path.read_bytes())+ self.assertNotIn(b'Synthetic peer', path.read_bytes())+ self.assertEqual({path.name for path in self.path.parent.iterdir()}, {'settings.beamer'})++ def test_legacy_settings_are_never_imported_or_rewritten(self):+ legacy = app_config.legacy_config_path(self.path)+ original = json.dumps({'host': '192.0.2.99', 'port': protocol.DEFAULT_PORT,+ 'auth_token': 'legacy-secret-must-stay-out'}).encode()+ legacy.write_bytes(original)+ settings = app_config.load_settings(self.path)+ self.assertEqual(settings['peers'], [])+ self.assertEqual(legacy.read_bytes(), original)+ self.assertNotIn(b'legacy-secret-must-stay-out', self.path.read_bytes())++ def test_locked_state_fails_closed_without_replacing_existing_vault(self):+ before = self.path.read_bytes()+ self.vault.lock()+ with self.assertRaises(app_config.SettingsFileError):+ app_config.load_settings(self.path)+ with self.assertRaises(app_config.SettingsFileError):+ app_config.write_settings(self.path, app_config.migrate(None))+ self.assertEqual(self.path.read_bytes(), before)++ def test_settings_cannot_be_written_to_a_host_path(self):+ outside = self.root.parent / 'host-settings.json'+ with self.assertRaises(app_config.SettingsFileError):+ app_config.write_settings(outside, app_config.migrate(None))+ self.assertFalse(outside.exists())++ def test_logging_failure_never_falls_back_to_host_temp(self):+ with mock.patch.object(kvm, 'RotatingFileHandler', side_effect=PermissionError('read only')) as handler, \+ mock.patch.object(kvm.tempfile, 'gettempdir', side_effect=AssertionError('host temp fallback')):+ with self.assertRaises(PermissionError):+ kvm.configure_logging()+ self.assertEqual(Path(handler.call_args.args[0]).parent, self.path.parent)+ self.assertEqual(handler.call_count, 1)++ def test_profile_upgrade_never_creates_a_plaintext_backup(self):+ app_config._backup_before_profile_upgrade(self.path)+ self.assertEqual({path.name for path in self.path.parent.iterdir()}, {'settings.beamer'})++ def test_cancel_unlock_leaves_pairings_locked_and_unchanged(self):+ before = self.path.read_bytes()+ portable_runtime.store = None+ with mock.patch.object(kvm.QInputDialog, 'getText', return_value=('', False)):+ self.assertFalse(kvm.unlock_portable())+ self.assertIsNone(portable_runtime.store)+ self.assertEqual(self.path.read_bytes(), before)++ def test_cancel_bootstrap_never_constructs_native_application(self):+ args = SimpleNamespace(config=self.path, hidden=True, relaunched=False, identify_x11=None)+ release = mock.Mock()+ app = mock.Mock()+ with mock.patch.object(portable_runtime, 'initialise'), \+ mock.patch.object(portable_runtime, 'close'), \+ mock.patch.object(kvm, 'parse_args', return_value=args), \+ mock.patch.object(kvm, 'prepare_windows_startup'), \+ mock.patch.object(kvm, '_claim_instance', return_value=release), \+ mock.patch.object(kvm, 'configure_logging', return_value=None), \+ mock.patch.object(kvm, '_windows_kernel32', return_value=mock.Mock()), \+ mock.patch.object(kvm, '_stay_unthrottled'), \+ mock.patch.object(kvm, 'QApplication', return_value=app), \+ mock.patch.object(kvm.theme, 'init_fonts'), \+ mock.patch.object(kvm, 'unlock_portable', return_value=False), \+ mock.patch.object(kvm.app_config, 'load_config') as load, \+ mock.patch.object(kvm, 'WindowsApplication') as native:+ kvm.main()+ native.assert_not_called()+ load.assert_not_called()+ app.exec.assert_not_called()+ release.assert_called_once()++ def test_wrong_passphrase_can_retry_without_resetting_pairings(self):+ settings = app_config.load_settings(self.path)+ settings['peers'] = [h.entry(h.B, 'Synthetic peer')]+ app_config.write_settings(self.path, settings)+ before = self.path.read_bytes()+ portable_runtime.store = None+ with mock.patch.object(kvm.QInputDialog, 'getText', side_effect=[('incorrect', True), (PASSWORD, True)]), \+ mock.patch.object(kvm.QMessageBox, 'warning') as warning:+ self.assertTrue(kvm.unlock_portable())+ warning.assert_called_once()+ self.assertEqual(self.path.read_bytes(), before)+ self.assertEqual(portable_runtime.store.read()['peers'][0]['token'], h.TOKENS[h.B])++ def test_creation_requires_confirmation_and_cancel_creates_nothing(self):+ self.vault.lock()+ self.path.unlink()+ portable_runtime.store = None+ with mock.patch.object(kvm.QInputDialog, 'getText', side_effect=[(PASSWORD, True), ('', False)]):+ self.assertFalse(kvm.unlock_portable())+ self.assertIsNone(portable_runtime.store)+ self.assertFalse(self.path.exists())++ def test_creation_retries_short_and_mismatched_passphrases(self):+ self.vault.lock()+ self.path.unlink()+ portable_runtime.store = None+ answers = [('short', True), (PASSWORD, True), ('different long passphrase', True),+ (PASSWORD, True), (PASSWORD, True)]+ with mock.patch.object(kvm.QInputDialog, 'getText', side_effect=answers), \+ mock.patch.object(kvm.QMessageBox, 'warning') as warning:+ self.assertTrue(kvm.unlock_portable())+ self.assertEqual(warning.call_count, 2)+ self.assertEqual(portable_runtime.store.read(), {})+ self.assertNotIn(PASSWORD.encode(), self.path.read_bytes())++ def test_startup_and_autostart_controls_never_touch_tasks(self):+ runner = mock.Mock(side_effect=AssertionError('task command attempted'))+ with mock.patch.object(kvm.sys, 'platform', 'win32'), \+ mock.patch.object(kvm.sys, 'frozen', True, create=True), \+ mock.patch.object(autostart_win, 'migrate_legacy_task') as migrate:+ kvm.prepare_windows_startup()+ self.assertIsNone(autostart_win.installed_exe())+ self.assertFalse(autostart_win.is_enabled(run=runner))+ migrate.assert_not_called()+ autostart_win.migrate_legacy_task(run=runner)+ autostart_win.remove_legacy_task(run=runner)+ for enabled in (True, False):+ with self.assertRaisesRegex(OSError, 'Portable'):+ autostart_win.set_enabled(enabled, str(self.root / 'Beamer.exe'), run=runner)+ runner.assert_not_called()++ def test_installer_entry_points_leave_tasks_and_firewall_untouched(self):+ with mock.patch.object(autostart_win, 'set_enabled') as task, \+ mock.patch.object(autostart_win, 'remove_legacy_task') as legacy, \+ mock.patch.object(autostart_win, '_run') as run:+ self.assertEqual(kvm.register_autostart_for_setup(), 1)+ self.assertEqual(kvm.cleanup_for_uninstall(), 1)+ task.assert_not_called()+ legacy.assert_not_called()+ run.assert_not_called()++ def test_gameinput_service_is_not_queried_or_restarted_in_portable_mode(self):+ after = mock.Mock()+ with mock.patch.object(input_injector, 'foreground_class') as foreground, \+ mock.patch.object(input_injector.windows_tools, 'run') as run, \+ mock.patch.object(input_injector.threading, 'Thread') as thread:+ self.assertFalse(input_injector.release_gameinput_foreground(after=after))+ foreground.assert_not_called()+ run.assert_not_called()+ thread.assert_not_called()+ after.assert_not_called()++ def test_manual_automatic_and_startup_firewall_paths_never_mutate_host(self):+ owner = SimpleNamespace(+ update_checker=SimpleNamespace(start=mock.Mock()), _listen=mock.Mock(),+ bridge=SimpleNamespace(rules_ready=SimpleNamespace(emit=mock.Mock())),+ firewall_note=mock.Mock(), firewall_button=mock.Mock(), _run_firewall=mock.Mock(),+ _firewall_advice=SimpleNamespace(action='repair', rule_profiles=('Private',)),+ )+ with mock.patch.object(kvm.sys, 'frozen', True, create=True), \+ mock.patch.object(kvm.firewall_win, 'is_elevated', return_value=True), \+ mock.patch.object(kvm.firewall_win, 'repair') as repair, \+ mock.patch.object(kvm.firewall_win, 'trust_network') as trust, \+ mock.patch.object(kvm.firewall_win, 'status') as status, \+ mock.patch.object(kvm.threading, 'Thread') as thread:+ kvm.WindowsApplication.start(owner)+ kvm.WindowsApplication._rules_then_listen(owner)+ kvm.WindowsApplication._firewall_action(owner)+ kvm.WindowsApplication._on_firewall(owner, SimpleNamespace(elevated=True))+ kvm.WindowsApplication._check_firewall(owner)+ owner._listen.assert_called_once()+ owner.bridge.rules_ready.emit.assert_called_once()+ owner._run_firewall.assert_not_called()+ owner.firewall_button.hide.assert_called_once()+ for operation in (repair, trust, status, thread):+ operation.assert_not_called()++ def test_windows_mutex_and_activation_names_do_not_clash_with_installed_app(self):+ kernel = mock.Mock()+ kernel.CreateMutexW.return_value = 42++ def session(_pid, pointer):+ pointer._obj.value = 7+ return True++ kernel.ProcessIdToSessionId.side_effect = session+ with mock.patch.object(kvm.sys, 'platform', 'win32'), \+ mock.patch.object(kvm, '_windows_kernel32', return_value=kernel), \+ mock.patch.object(kvm.ctypes, 'get_last_error', return_value=0, create=True):+ portable_name = kvm._instance_server_name()+ release = kvm._claim_instance()+ portable_mutex = kernel.CreateMutexW.call_args.args[2]+ release()+ with mock.patch.object(portable_runtime, '_root', None), \+ mock.patch.object(portable_runtime, 'portable_root', return_value=None):+ installed_name = kvm._instance_server_name()+ release = kvm._claim_instance()+ installed_mutex = kernel.CreateMutexW.call_args.args[2]+ release()+ self.assertEqual(installed_name, 'Beamer.Receiver.7')+ self.assertEqual(installed_mutex, 'Local\\Beamer.Receiver')+ self.assertNotEqual(portable_name, installed_name)+ self.assertNotEqual(portable_mutex, installed_mutex)+ self.assertTrue(portable_name.endswith(portable_runtime.instance_suffix()))+ self.assertTrue(portable_mutex.endswith(portable_runtime.instance_suffix()))++ def test_legacy_installed_instance_prevents_portable_input_lease(self):+ kernel = mock.Mock()+ kernel.OpenMutexW.return_value = 77+ with mock.patch.object(kvm, '_windows_kernel32', return_value=kernel), \+ mock.patch.object(kvm.ctypes, 'get_last_error', return_value=0, create=True):+ self.assertIsNone(kvm._claim_input_controller())+ kernel.OpenMutexW.assert_called_once_with(0x00100000, False, 'Local\\Beamer.Receiver')+ kernel.CloseHandle.assert_called_once_with(77)+ kernel.CreateMutexW.assert_not_called()++ def test_inaccessible_legacy_instance_also_blocks_portable_input(self):+ kernel = mock.Mock()+ kernel.OpenMutexW.return_value = 0+ with mock.patch.object(kvm, '_windows_kernel32', return_value=kernel), \+ mock.patch.object(kvm.ctypes, 'get_last_error', return_value=5, create=True):+ self.assertIsNone(kvm._claim_input_controller())+ kernel.CreateMutexW.assert_not_called()+ kernel.CloseHandle.assert_not_called()++ def test_existing_shared_input_lease_is_refused_and_handle_closed(self):+ kernel = mock.Mock()+ kernel.OpenMutexW.return_value = 0+ kernel.CreateMutexW.return_value = 99+ with mock.patch.object(kvm, '_windows_kernel32', return_value=kernel), \+ mock.patch.object(kvm.ctypes, 'get_last_error', side_effect=[2, 183], create=True):+ self.assertIsNone(kvm._claim_input_controller())+ kernel.CreateMutexW.assert_called_once_with(None, False, 'Local\\Beamer.InputController')+ kernel.CloseHandle.assert_called_once_with(99)++ def test_available_input_lease_returns_a_release_for_its_own_handle(self):+ kernel = mock.Mock()+ kernel.OpenMutexW.return_value = 0+ kernel.CreateMutexW.return_value = 99+ with mock.patch.object(kvm, '_windows_kernel32', return_value=kernel), \+ mock.patch.object(kvm.ctypes, 'get_last_error', side_effect=[2, 0], create=True):+ release = kvm._claim_input_controller()+ self.assertTrue(callable(release))+ kernel.CloseHandle.assert_not_called()+ release()+ kernel.CloseHandle.assert_called_once_with(99)++ def test_blocked_input_keeps_pairing_available_and_retries_without_hooks(self):+ owner = SimpleNamespace(+ _closing=False, pairing=mock.Mock(), _input_controller_blocked=True,+ _config=SimpleNamespace(port=51234), _paired=True,+ _set_status=mock.Mock(), _listen=mock.Mock(), _start_receiver=mock.Mock(),+ _start_sending=mock.Mock(), _make_idle_pointer=mock.Mock(), _check_firewall=mock.Mock(),+ )+ with mock.patch.object(kvm.sys, 'platform', 'win32'), \+ mock.patch.object(kvm, '_claim_input_controller', return_value=None), \+ mock.patch.object(kvm.QTimer, 'singleShot') as retry, \+ mock.patch.object(kvm.platform_parts.injector, 'start', create=True) as injector:+ kvm.WindowsApplication._listen(owner)+ owner.pairing.start.assert_called_once()+ owner._set_status.assert_called_once()+ self.assertEqual(owner._set_status.call_args.args[0], kvm.ServerState.ERROR)+ self.assertIn('Another Beamer copy controls input', owner._set_status.call_args.args[1])+ retry.assert_called_once_with(1000, owner._listen)+ for blocked in (owner._start_receiver, owner._start_sending, owner._make_idle_pointer, injector):+ blocked.assert_not_called()+ self.assertTrue(owner._input_controller_blocked)++ def test_retry_after_input_lease_release_starts_this_copys_input(self):+ release, idle_pointer = mock.Mock(), object()+ owner = SimpleNamespace(+ _closing=False, pairing=mock.Mock(), _input_controller_blocked=True,+ _config=SimpleNamespace(port=51234), _paired=True,+ _set_status=mock.Mock(), _listen=mock.Mock(), _start_receiver=mock.Mock(),+ _start_sending=mock.Mock(), _make_idle_pointer=mock.Mock(return_value=idle_pointer),+ _check_firewall=mock.Mock(),+ )+ with mock.patch.object(kvm.sys, 'platform', 'win32'), \+ mock.patch.object(kvm, '_claim_input_controller', return_value=release), \+ mock.patch.object(kvm.QTimer, 'singleShot') as retry, \+ mock.patch.object(kvm.platform_parts.injector, 'start', create=True) as injector:+ kvm.WindowsApplication._listen(owner)+ self.assertFalse(owner._input_controller_blocked)+ self.assertIs(owner._input_controller_release, release)+ self.assertIs(owner._idle_pointer, idle_pointer)+ owner._start_receiver.assert_called_once_with(owner._config)+ owner._start_sending.assert_called_once_with(owner._config)+ owner._check_firewall.assert_called_once()+ injector.assert_called_once()+ retry.assert_not_called()+ release.assert_not_called()++ def test_direct_input_start_methods_respect_blocked_controller(self):+ owner = SimpleNamespace(_input_controller_blocked=True,+ server=mock.Mock(), sender=mock.Mock(), hooks=mock.Mock())+ config = SimpleNamespace(port=51234)+ kvm.WindowsApplication._start_receiver(owner, config)+ kvm.WindowsApplication._start_sending(owner, config)+ owner.server.start.assert_not_called()+ owner.sender.start.assert_not_called()+ owner.hooks.start.assert_not_called()+ with mock.patch.object(portable_runtime, 'enabled', return_value=False), \+ mock.patch.object(kvm.desktop_win, 'restore_pointer') as restore, \+ mock.patch.object(kvm.idle_pointer, 'IdlePointer') as pointer:+ self.assertIsNone(kvm.WindowsApplication._make_idle_pointer(owner))+ restore.assert_not_called()+ pointer.assert_not_called()++ def test_link_identity_and_pairing_beacon_use_the_same_portable_name(self):+ settings = app_config.load_settings(self.path)+ settings['name'] = ''+ app_config.write_settings(self.path, settings)+ owner = SimpleNamespace(+ config_path=self.path,+ _config=SimpleNamespace(name='', machine_id=settings['machine_id']),+ _settings_port=51234, _announced_port=lambda: 51234,+ book=SimpleNamespace(peers=lambda: []), _store_peer=mock.Mock(),+ bridge=SimpleNamespace(paired=SimpleNamespace(emit=mock.Mock())),+ )+ service = SimpleNamespace(active_discovery=False)+ with mock.patch.object(kvm.pairing, 'machine_name', return_value='Synthetic PC'), \+ mock.patch.object(kvm, 'PairingService', return_value=service) as factory:+ identity = kvm.WindowsApplication._identity(owner)+ self.assertIs(kvm.WindowsApplication._make_pairing(owner), service)+ self.assertEqual(identity['name'], 'Synthetic PC (Portable)')+ self.assertEqual(factory.call_args.args[0], identity['name'])+ self.assertTrue(service.active_discovery)++ def test_portable_yields_when_legacy_installed_copy_starts_later(self):+ events = []+ owner = SimpleNamespace(+ _closing=False, _input_controller_blocked=False,+ _input_controller_release=lambda: events.append('release'),+ server=SimpleNamespace(stop=lambda: events.append('stop receiver')),+ _stop_sending=lambda: events.append('stop sender'),+ _listen=lambda: events.append('wait for input'),+ )+ with mock.patch.object(kvm, '_installed_instance_running', return_value=True):+ kvm.WindowsApplication._check_input_controller(owner)+ self.assertEqual(events, ['stop receiver', 'stop sender', 'release', 'wait for input'])+ self.assertTrue(owner._input_controller_blocked)+ self.assertIsNone(owner._input_controller_release)++ def test_about_identifies_portable_passphrase_storage_and_uipi_limit(self):+ box = mock.Mock()+ box.findChildren.return_value = []+ with mock.patch.object(kvm, 'QMessageBox', return_value=box):+ kvm.WindowsApplication.show_about(object())+ text = box.setInformativeText.call_args.args[0]+ self.assertIn('Portable', text)+ self.assertIn('passphrase', text)+ self.assertIn('Administrator apps cannot be controlled', text)++ def test_download_opens_portable_asset_and_notes_keep_release_page(self):+ payload = {'tag_name': 'v' + VERSION, 'html_url': PAGE,+ 'assets': [{'name': 'Beamer-Portable-' + VERSION + '-windows-x64.zip',+ 'browser_download_url': DOWNLOAD}]}+ checker = updates.Checker('1.5.10', lambda: True, lambda result: None,+ fetcher=lambda: json.dumps(payload).encode(), portable=True)+ checker.check_once()+ owner = SimpleNamespace(_update=checker.latest, update_checker=checker)+ with mock.patch.object(kvm.QDesktopServices, 'openUrl') as opened:+ kvm.WindowsApplication.download_update(owner)+ self.assertEqual(opened.call_args.args[0].toString(), DOWNLOAD)+ kvm.WindowsApplication.open_update(owner)+ self.assertEqual(opened.call_args.args[0].toString(), PAGE)+ self.assertEqual(opened.call_count, 2)++ def test_missing_portable_asset_does_not_open_installer_or_release_page(self):+ owner = SimpleNamespace(_update=(VERSION, PAGE),+ update_checker=SimpleNamespace(download_url=None))+ with mock.patch.object(kvm.QDesktopServices, 'openUrl') as opened:+ kvm.WindowsApplication.download_update(owner)+ opened.assert_not_called()+++if __name__ == '__main__':+ unittest.main()diff --git a/win_app/tests/test_sender_motion_flow.py b/win_app/tests/test_sender_motion_flow.pynew file mode 100644index 0000000..e5df633--- /dev/null+++ b/win_app/tests/test_sender_motion_flow.py@@ -0,0 +1,95 @@+"""GH15 sender batching: preserve travel and barriers before any socket work."""++import unittest+import collections+from unittest import mock++from links_rig import B, Rig+from core import owner, protocol+import sender+++class SenderMotionFlowTests(unittest.TestCase):+ def rig(self):+ rig = Rig()+ rig.links.caps_of[B] = rig.links.caps(B) | {"motion_path"}+ return rig++ def test_motion_waiting_for_clipboard_is_bounded_and_controls_keep_their_place(self):+ rig = self.rig()+ rig.sender._clip_wait[B] = collections.deque()+ for index in range(1000):+ rig.sender._deliver(owner.Send(B, protocol.mousemove_msg(1, 1 if index % 2 else -1)))+ rig.sender._deliver(owner.Send(B, protocol.key_msg("keydown", "a")))+ rig.sender._deliver(owner.Send(B, protocol.mousemove_msg(2, 3)))+ waiting = rig.sender._clip_wait[B]+ self.assertLessEqual(len(waiting), 18)+ self.assertEqual(sum(a.message["data"]["dx"] for a in list(waiting)[:-2]), 1000)+ self.assertEqual(sum(a.message["data"]["dy"] for a in list(waiting)[:-2]), 0)+ self.assertEqual(waiting[-2].message["type"], "keydown")++ def test_worker_sends_first_immediately_and_flushes_trailing_motion_when_idle(self):+ rig = self.rig()+ sent = []+ clock = [10.0]+ sleeps = []++ def deliver(action):+ sent.append(action.message)+ if len(sent) == 1:+ rig.sender._queue([owner.Send(B, protocol.mousemove_msg(2, 3))])+ else:+ rig.sender._stop_event.set()++ def sleep(delay):+ sleeps.append(delay)+ clock[0] += delay+ rig.sender._queue([owner.Send(B, protocol.mousemove_msg(4, 5))])++ rig.sender._deliver = deliver+ rig.sender._queue([owner.Send(B, protocol.mousemove_msg(1, 1))])+ with mock.patch.object(sender.time, "monotonic", side_effect=lambda: clock[0]), mock.patch.object(sender.time, "sleep", side_effect=sleep):+ rig.sender._outbound_worker()+ self.assertEqual([(m["data"]["dx"], m["data"]["dy"]) for m in sent], [(1, 1), (6, 8)])+ self.assertEqual(len(sleeps), 1)+ self.assertAlmostEqual(sleeps[0], .002)+ self.assertEqual(rig.sender._outbound.unfinished_tasks, 0)++ def test_pending_high_polling_samples_are_bounded_relative_batches(self):+ rig = self.rig()+ rig.sender.set_redirecting(True)+ rig.flush()+ for _ in range(1000):+ rig.sender.on_motion(1, 2)+ self.assertLessEqual(rig.sender._outbound.qsize(), 16)+ moves = rig.sent(B, "mousemove")+ self.assertEqual((sum(m["data"]["dx"] for m in moves), sum(m["data"]["dy"] for m in moves)), (1000, 2000))++ def test_buttons_are_batch_boundaries_and_reversing_jitter_is_summed(self):+ rig = self.rig()+ rig.sender.set_redirecting(True)+ rig.flush()+ rig.links.sent.clear()+ rig.sender.on_motion(1, 0)+ rig.sender.on_motion(0, 2)+ rig.sender.on_button("left", True)+ rig.sender.on_motion(3, 4)+ rig.sender.on_motion(-2, -1)+ messages = rig.sent(B)+ self.assertEqual([m["type"] for m in messages], ["mousemove", "mousedown", "mousemove"])+ self.assertEqual((messages[0]["data"]["dx"], messages[0]["data"]["dy"]), (1, 2))+ self.assertEqual((messages[2]["data"]["dx"], messages[2]["data"]["dy"]), (1, 3))++ def test_high_polling_sign_jitter_is_bounded_and_keeps_net_travel(self):+ rig = self.rig()+ rig.sender.set_redirecting(True)+ rig.flush()+ for index in range(1000):+ rig.sender.on_motion(1, 1 if index % 2 else -1)+ self.assertLessEqual(rig.sender._outbound.qsize(), 16)+ moves = rig.sent(B, "mousemove")+ self.assertEqual((sum(m["data"]["dx"] for m in moves), sum(m["data"]["dy"] for m in moves)), (1000, 0))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_update_notice.py b/win_app/tests/test_update_notice.pyindex e365613..8fcb738 100644--- a/win_app/tests/test_update_notice.py+++ b/win_app/tests/test_update_notice.py@@ -78,6 +78,12 @@ class UpdateNoticeTest(unittest.TestCase):self.assertIn("software store", self.window.update_notice_text.text())self.assertTrue(self.window.update_button.isHidden())self.assertFalse(self.window.update_notes.isHidden())+ self.assertFalse(self.window.header_action.isEnabled())++ def test_desktop_update_header_remains_a_download_action(self):+ with patch.object(kvm.portal, "sandboxed", return_value=False):+ self.window._on_update(FOUND)+ self.assertTrue(self.window.header_action.isEnabled())def test_linux_start_checks_for_updates_without_waiting_for_a_toggle(self):events = []