4 Commits

Author SHA1 Message Date
035fb8ddc9 Handle shutdown acknowledgement when the parent exits during polling 2026-11-26 19:14:20 -06:00
2e93b7587d Refine verified update notices and Windows installation lifecycle 2026-11-26 19:09:17 -06:00
f9fa7c258d Document v0.6.1.1 release and upgrade
Record the public release verification, production upgrade results, and validation cleanup in the implementation report.
2026-11-26 18:11:20 -06:00
48beab4671 Scope Jenkins archive access to the sibling release job 2026-11-26 17:45:29 -06:00
21 changed files with 930 additions and 83 deletions

View File

@@ -1,5 +1,11 @@
# Changelog
## v0.6.2.1_alpha — 2026-11-26
- Show verified update availability and installation readiness in the hover monitor, main window, and tray menu. Windows notifications can be turned off and repeat checks do not repeat them.
- Wait for ARM to finish saving settings and history and exit before replacing any application files. Show independent installation progress and report restart or recovery results.
- Restore the prior tray-only or expanded presentation after an update and let users open the changelog from the success confirmation.
## v0.6.1.1_alpha — 2026-11-26
- Added signed update discovery, verified downloads and authorized installation for installed and portable Windows x64 editions.

View File

@@ -1,5 +1,200 @@
# Adaptive Resource Monitor implementation report
## v0.6.2.1_alpha — Update notifications and installation lifecycle
The Minor counter advanced. The hover monitor, expanded window and tray menu
use the About updater's verified-release state. Install Later retains the
download and its ready notice. A Windows notification preference controls
one-time notifications. The maintenance launcher waits for a clean ARM
shutdown and process exit, shows independent installation progress and
checks the restarted version before reporting success. The release uses
the existing Jenkins build and authorized publication jobs.
Production self-update acceptance follows authorized publication using the
installed v0.6.1.1_alpha updater. Its maintenance launcher handles the first
upgrade. The newly installed application reads the legacy completion receipt.
## Initial public release and production upgrade — 2026-11-26
[Adaptive Resource Monitor v0.6.1.1_alpha](https://phantom.zapto.org/gitea/sonja/Adaptive_Resource_Monitor/releases/tag/v0.6.1.1_alpha)
was published by [Publish Release #6](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Publish-Release/6/).
The job used [Build and Archive #3](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Build-and-Archive/3/)
at 6b333b6e930399c73873911197ce1e63d567c034, the archive previously verified by
[Publish Release #4](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Publish-Release/4/).
The build job remained at #4 and its H/5 main-branch SCM trigger was
still configured. Build #4 had an SCM-trigger cause. Publication #5
records the prior rejection without authorization. Publication #6 recorded
explicit authorization and archive #3 as its selected build.
### Public readback
The release tag resolves to the pinned commit. All seven files were downloaded
over anonymous HTTPS and matched the pinned archive by byte count and SHA-256.
The signed manifest matched the exact bytes in Jenkins build #3. Its Ed25519
signature, application ID, version, build number, commit, package types and
Windows x64 architecture verified. Native PE and ZIP payload checks passed.
The release body and attached notes match the signed notes. The complete
changelog is in both distributions and at the
[public version tag](https://phantom.zapto.org/gitea/sonja/Adaptive_Resource_Monitor/src/tag/v0.6.1.1_alpha/CHANGELOG.md).
| Anonymous attachment | Bytes | SHA-256 |
| --- | ---: | --- |
| AdaptiveResourceMonitor-v0.6.1.1_alpha-windows-x64-setup.exe | 57,131,180 | c4aad237a9e92668c278d08b7887f1bea16a72850c25e7c01e7aea85e6692474 |
| AdaptiveResourceMonitor-v0.6.1.1_alpha-windows-x64-portable.zip | 71,478,426 | d7fe934beb75cf96f7aad70012a31bc958a7657f8a04fc82717111d305da9d53 |
| SHA256SUMS.txt | 257 | 537884b587d76e13a7ccaab0fd2c30bf38f010cc5e13acc803969830f624e1de |
| arm-update-windows-x64.json | 935 | 33ee001c4a4c6154cfb185ea381cf3e975ff3c10b780dc01b0e58c841c86f498 |
| arm-ed25519.pub | 45 | 6127dc67b0f49479fe8a7924b1dc2fc5597da2e4c066f246925fce1c8097ba17 |
| release-build.json | 561 | b953ec28642b906b43f7af1ed01637c63d7029186cf400a0162b1c4e019769e2 |
| RELEASE_NOTES.md | 250 | fd25e23c01bc35099c1686ef9370024cf57f5d24b3e7c0ed643e38f0d3872734 |
### Production upgrade and checks
- The v0.4.1.1_alpha process closed cleanly. The anonymously downloaded
and verified Setup performed the in-place upgrade and completed without
a Windows restart. The production registry and running binary report
v0.6.1.1_alpha. All 297 installed payload files matched build #3.
The first launch logged a clean exit. A subsequent instance stayed
running through validation.
- The settings file and pinned SSH host-key file matched byte for byte.
The three Windows Credential Manager entries and their references
matched, as did the Start with Windows registration. Saved machine
selections, graph colors, display mode, hover range, popup dimensions and
theme were preserved. ARM positions the popup from the live tray icon.
Recording was off and the configured profile had no retained SQLite
history. In-memory graph history began again at restart.
- The production process had established SSH sessions to Rain, Phantom
and LAMP. In a private native Windows desktop, the same profiles
produced fresh samples for all three remotes and Local Machine.
Both All Systems views showed six per-machine graphs, with separate
plotted network IN and OUT traces. Explorer returned an on-screen
rectangle for the installed tray icon, and six passive samples showed
six distinct rendered images. The hover path passed in
isolation using that rectangle, and the user confirmed the popup
appeared when hovering over the real Explorer icon.
- Both Check for Updates controls were invoked in the actual installed
executable on a private Windows desktop using a disposable profile.
Each queried the live public repository, verified the release and
displayed “This is the latest verified version.” The production
profile's startup and periodic update checking remained off.
### Production validation cleanup
Removed the duplicate anonymous downloads, expanded verification payload,
temporary installer log, private desktop profiles and diagnostic scripts.
Manual cleanup removed 283,979,051 bytes by logical file size, and the
package verifier removed another 155,163,584 bytes of temporary extraction.
Jenkins reported that it cleared the publication workspace. The installed
application, user profile, public release, pinned local candidate and
historical releases were kept. The local report is the only worktree edit.
## v0.6.1.1_alpha — Signed updates and release automation
The Feature counter advanced twice for the updater and the build and
release infrastructure. The accepted v0.4.1.1_alpha monitoring behavior
carries forward. VERSION.md now supplies the application and package
version. The build number is a separate part of the Jenkins receipt.
The About and tray actions check the public ARM Releases index on a
background thread. Startup and periodic checking are opt-in. Downloads
can be paused and resumed, and the verified installer or portable ZIP can
be used later. Install requires confirmation. An independent Windows
launcher waits for the monitor to save history and exit, verifies the
package again, applies the update and waits for the new process to report
readiness. Its transaction journal supports recovery and rollback.
### Repository access
The existing ARM repository serves the source and release endpoint. Before
making it anonymously accessible, the three historical commits were
sanitized to remove monitoring screenshots, identifying machine labels and
personal commit email. The prior objects were pruned from the ARM repository
on the server. Old commit and screenshot requests returned 404. The owner
account now permits anonymous ARM access, while all 55 other repositories
under that owner returned 404 anonymously. The original local screenshots
remain with the user. The unused temporary binary repository was removed.
### Validation
- Twenty-five automated tests passed. Update fixtures covered valid and
invalid signatures, missing signatures, release selection, downgrade
rejection, server failure, package size and hash checks, interrupted
downloads, cancel and resume, and unsafe portable archive paths.
- Native tests on a private Windows desktop exercised the About and tray
check actions, the startup policy, periodic scheduling and continuing
resource collection during a pending check. The live tray graph, separate
machine views, networking directions and branding passed regression checks.
- The native About controls showed signed release notes and live progress.
Telemetry continued while a download was blocked. Install Later kept the
verified package across a fresh application instance. A separate loopback
HTTPS test downloaded and verified a package anonymously with certificate
validation enabled.
- Controlled installed and portable updates ran on private Windows desktops
using disposable builds and profiles. Both restarted the updated executable
and received its readiness acknowledgement. An injected mismatch after
replacement restored the previous portable files. An interrupted journal
restored the previous executable. The test settings, saved Windows
credential, SSH trust file and existing SQLite row survived. The native
installer used a disposable AppId. An independent frozen maintenance
launcher also performed a signed portable update, restarted the monitor
and cleared its temporary recovery registration.
- ARM's production release index was anonymously reachable and empty.
The accepted installation was outside the test runs. Public production
artifact retrieval awaits release authorization.
### Jenkins release candidate
[Build and Archive #3](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Build-and-Archive/3/)
was triggered by an SCM change and completed successfully on inkiron-windows.
It built commit 6b333b6e930399c73873911197ce1e63d567c034 and archived seven
files. Native validation verified x64 PE resources, installer metadata, ZIP
integrity and two portable launches. The archived manifest signature matched
the trusted ARM-specific key. The downloaded archive passed offline revalidation.
An attempted verification with an incorrect build number was rejected.
[Publish Release #4](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Publish-Release/4/)
copied all seven files from build #3 and verified its exact version, commit,
signature and hashes. The public upload stage was skipped in verification-only
mode. A disposable Inno upgrade installed all 297 files from the archived
payload byte for byte. Its native wizard, frozen startup, shutdown and
uninstall passed. The production registration still showed v0.4.1.1_alpha.
[Publish Release #5](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Publish-Release/5/)
deliberately requested publication without authorization. Jenkins rejected
it before retrieving the archive or entering the publishing stage.
The anonymous Gitea endpoint has zero releases and zero tags.
[Build and Archive #4](https://192.168.1.164:8080/jenkins/job/Adaptive-Resource-Monitor/job/Build-and-Archive/4/)
also succeeded after the publication job permission change at
48beab46711ffc9b25a7643f46ab9a578cf43fee. Build #3 remains the selected
candidate and is the archive copied during publication verification.
| Candidate file | Bytes | SHA-256 |
| --- | ---: | --- |
| [Windows installer](release/v0.6.1.1_alpha/AdaptiveResourceMonitor-v0.6.1.1_alpha-windows-x64-setup.exe) | 57,131,180 | c4aad237a9e92668c278d08b7887f1bea16a72850c25e7c01e7aea85e6692474 |
| [Portable ZIP](release/v0.6.1.1_alpha/AdaptiveResourceMonitor-v0.6.1.1_alpha-windows-x64-portable.zip) | 71,478,426 | d7fe934beb75cf96f7aad70012a31bc958a7657f8a04fc82717111d305da9d53 |
The release directory also contains SHA256SUMS.txt, the Ed25519 manifest,
public key, release notes and build receipt. The signature authenticates
the package bytes through the manifest. The executables would require
separate Authenticode signing for Windows publisher verification.
### Cleanup and remaining authorization
Removed the disposable Windows installations, temporary profiles and
credentials, staged compiler and Python dependencies, extracted payloads,
test TLS certificates and keys, Git sanitization checkout, failed build
output and local diagnostics. The local build and QA cleanup accounted for
**2,463,578,942 bytes** measured by logical file size. Build #3 independently
reported **482,337,392 bytes** removed from its measured packaging and native
QA directories. Build #4 reported another **482,329,896 bytes** of measured
cleanup. Both Jenkins pipelines cleaned their workspaces after
execution. The selected packages and verification metadata are retained
locally and in the Jenkins archive. Earlier accepted releases and original
local screenshots are retained as user data.
Public release publication and any in-place production installation
require separate authorization. The production index can be read anonymously.
Anonymous downloads were tested using an isolated signed update fixture.
Interrupted-installation recovery was exercised with a saved journal. The
Windows sign-in path following an actual reboot was outside that test.
## v0.4.1.1_alpha — Independent tray machine
The Minor counter advanced from 0 to 1. The existing Major, Feature and

2
Jenkinsfile vendored
View File

@@ -4,7 +4,7 @@ pipeline {
skipDefaultCheckout()
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '15', artifactNumToKeepStr: '6'))
copyArtifactPermission('Adaptive-Resource-Monitor/Publish-Release')
copyArtifactPermission('Publish-Release')
timeout(time: 35, unit: 'MINUTES')
}
triggers { pollSCM('H/5 * * * *') }

View File

@@ -3,6 +3,7 @@ pipeline {
options {
skipDefaultCheckout()
disableConcurrentBuilds()
disableRestartFromStage()
buildDiscarder(logRotator(numToKeepStr: '20'))
timeout(time: 30, unit: 'MINUTES')
}
@@ -41,7 +42,7 @@ pipeline {
steps {
deleteDir()
checkout scm
copyArtifacts projectName: '/Adaptive-Resource-Monitor/Build-and-Archive',
copyArtifacts projectName: 'Build-and-Archive',
selector: specific("${env.ARM_PIN_BUILD}"), filter: 'release/candidate/*',
target: 'release/pinned', flatten: true, fingerprintArtifacts: true
bat 'py -3.12 -m venv .ci\\python'

View File

@@ -6,13 +6,19 @@ the time of the last successful check in the local timezone, package type and
size, verification status, progress and signed release notes. ARM defaults to
manual checks. Settings offers a startup check and periodic checks every
4 hours, 12 hours, day or week. A verified update uses the existing tray icon
for its notification. Checks and downloads run separately from collection.
for its Windows notification once per verified version, including across
restarts. **Show Windows update notifications** controls these transient
messages. Verified releases also appear below the hover monitor's machine
and connection controls, in the expanded window and below the tray menu's
version. These entries open the About tab. No row appears when there is no
eligible verified update. Checks and downloads run separately from collection.
**Download Update** stores the signed envelope and verified package in the
application's per-user updates directory. Cancel leaves a partial file. A retry
requests a byte range and validates the server's response. If the server
returns a complete response, ARM starts the file over. **Install Later**
keeps the package. **Install Update** asks for approval.
keeps the package and its ready-to-install notice. **Install Update** asks for
approval.
## Release contract
@@ -29,13 +35,22 @@ and eligible stable releases. A package for installation must be strictly newer.
The installed variant is identified from Windows' uninstall registration.
The maintenance launcher verifies the download, starts from a staged copy
outside the installed directory and waits for the monitor to close. The
monitor closes its collectors and drains pending history writes. The launcher
outside the installed directory. It verifies the requesting process's
executable path, PID and creation time. ARM saves its presentation, removes
its tray icons, stops workers and drains pending history writes. The launcher
requires ARM's shutdown acknowledgement and waits for the process to exit
before replacing files. It reports progress in its own branded window.
A directly launched installer asks the user to close ARM if the destination
executable is in use. The launcher
uses the native installer for an installed copy. For portable copies it
verifies and extracts the ZIP into staging on the same volume and replaces
only distribution-owned entries. Existing files outside those entries stay
in place. Before restarting ARM, the launcher verifies the new executable,
version and build metadata. The restarted process signals readiness.
version and build metadata. The launcher restarts ARM in the invoking user
session with the previous tray-only or expanded presentation. The restarted
process signals readiness before ARM reports success and offers the changelog.
An upgrade initiated by v0.6.1.1 uses that version's launcher and progress
behavior. The newer application still reads its completion receipt.
## Recovery
@@ -46,6 +61,7 @@ interrupted transaction can recover from the independently staged launcher
through the per-user Windows RunOnce entry. If a file is still locked, the
transaction and its backup remain available. The About panel reads the most
recent update result. Details are in maintenance.log and, for Setup,
installer.log under the transaction directory. Keep transaction files while an
installation is pending. Profiles, the Credential Manager, SSH trust and
installer.log under the transaction directory. If an automated restore fails,
close ARM and use the previous verified installer or restore the previous
portable payload. Keep the ARM profile and transaction logs. Profiles, the Credential Manager, SSH trust and
telemetry history are outside the file-replacement transaction.

View File

@@ -1 +1 @@
v0.6.1.1_alpha
v0.6.2.1_alpha

View File

@@ -11,7 +11,7 @@ from time import time
import winreg
import psutil
from PySide6.QtCore import QLockFile, QObject, QSignalBlocker, Qt, QTimer, QUrl, Signal
from PySide6.QtCore import QLockFile, QObject, QRect, QSignalBlocker, Qt, QTimer, QUrl, Signal
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QSystemTrayIcon
@@ -82,12 +82,18 @@ class Application(QObject):
self.icons = {}
self.menus = {}
self.about_page = AboutPage(self.root)
self.update_label = ""
self.update_notice_changelog = False
self.update_shutdown = None
self.about_page.updates.notify.connect(self.update_notice)
self.about_page.updates.quit_requested.connect(self.qt.quit)
self.about_page.updates.changed.connect(self.sync_update_notice)
self.about_page.updates.quit_requested.connect(self.close_for_update)
self.expanded = Monitor(self.dashboard, True, self.request_archive, self.open_expanded,
self.set_pin, self.about_page)
self.expanded.setWindowIcon(self.brand_icon)
self.popup = Monitor(self.dashboard, False, self.request_archive, self.open_expanded, self.set_pin)
for view in (self.popup, self.expanded):
view.add_update_banner(self.open_update)
self.hover = HoverMonitor(self.popup, self.dashboard, self.icons)
for view in (self.popup, self.expanded):
view.machine.currentIndexChanged.connect(partial(self.monitor_selected, view))
@@ -115,6 +121,8 @@ class Application(QObject):
self.brand_colors = DARK if scheme == Qt.ColorScheme.Dark else LIGHT
self.about_page.theme(self.brand_colors)
self.expanded.brand_tabs(self.brand_colors)
for view in (self.popup, self.expanded):
view.update_banner.theme(self.brand_colors)
for menu in self.menus.values():
menu.theme(self.brand_colors)
@@ -193,10 +201,11 @@ class Application(QObject):
icon = QSystemTrayIcon(self)
icon.setIcon(self.brand_icon)
icon.activated.connect(partial(self.activate_icon, machine))
icon.messageClicked.connect(self.about)
icon.messageClicked.connect(lambda: self.open_update(self.update_notice_changelog))
self.icons[machine] = icon
self.menus[machine] = TrayMenu(self, machine)
self.menus[machine].theme(self.brand_colors)
self.set_menu_update(self.menus[machine])
icon.setContextMenu(self.menus[machine])
icon.show()
self.sync_menus()
@@ -497,10 +506,56 @@ class Application(QObject):
self.about()
self.about_page.updates.check_now()
def update_notice(self, version):
def open_update(self, changelog=False):
if not self.popup.pinned:
self.popup.hide()
self.about()
if changelog:
self.about_page.show_document("CHANGELOG.md")
self.about_page.browser.setFocus()
else:
self.about_page.updates.buttons["Check for Updates"].setFocus()
def set_menu_update(self, menu):
menu.update.setText(self.update_label)
menu.update.setVisible(bool(self.update_label))
def sync_update_notice(self, message, success):
if not success:
self.update_label = message
else:
self.update_label = ""
for menu in self.menus.values():
self.set_menu_update(menu)
for view in (self.popup, self.expanded):
view.update_banner.update_notice(message, success)
if self.popup.isVisible():
self.hover.reposition()
def update_notice(self, message):
icon = self.icons.get(self.settings.tray_machine)
if icon:
icon.showMessage(NAME, f"Verified update {version} is available. Open About for details.")
if icon and icon.supportsMessages():
self.update_notice_changelog = message.startswith(f"{NAME} successfully updated")
icon.showMessage(NAME, message, self.brand_icon)
def update_presentation(self):
rect = self.expanded.geometry()
return {"expanded": self.expanded.isVisible() and not self.expanded.isMinimized(),
"geometry": [rect.x(), rect.y(), rect.width(), rect.height()],
"about": self.expanded.tabs.currentWidget() is self.about_page}
def close_for_update(self, directory):
updates = self.about_page.updates
try:
if self.store.load() != self.settings:
self.store.save(self.settings)
from .update_worker import save_presentation
save_presentation(directory, self.update_presentation())
except OSError as exc:
updates.abort_install(f"Could not save application state. {exc}")
return
self.update_shutdown = directory
self.qt.quit()
def open_website(self):
QDesktopServices.openUrl(QUrl(WEBSITE))
@@ -509,7 +564,7 @@ class Application(QObject):
if self._closed:
return
self._closed = True
self.about_page.updates.stop()
updates_stopped = self.about_page.updates.stop()
for timer in (self.tray_timer, self.hover_timer, self.view_timer):
timer.stop()
for icon in self.icons.values():
@@ -524,9 +579,13 @@ class Application(QObject):
LOG.info("%s stopped", NAME)
logging.getLogger().removeHandler(self.logger)
self.logger.close()
return updates_stopped
def main():
from .update_worker import ACK, acknowledge_shutdown, presentation, signal_ready, updates_locked
from .update_state import transaction_from_ack
set_windows_identity()
app = QApplication(sys.argv)
app.setApplicationName(NAME)
@@ -542,13 +601,29 @@ def main():
return 0
controller = None
try:
transaction = transaction_from_ack(root, os.environ.get(ACK))
if not transaction and updates_locked(root):
return 0
controller = Application(app, root)
if not controller.settings.minimized:
state = presentation(transaction) if transaction else {}
if state.get("expanded", not controller.settings.minimized):
controller.open_expanded()
from .update_worker import signal_ready
signal_ready()
if geometry := state.get("geometry"):
rect = QRect(*geometry)
if any(screen.availableGeometry().intersects(rect) for screen in app.screens()):
controller.expanded.setGeometry(rect)
if state.get("about"):
controller.expanded.tabs.setCurrentWidget(controller.about_page)
if transaction:
controller.about_page.updates.follow_restart(transaction)
signal_ready(root)
return app.exec()
finally:
if controller is not None:
controller.close()
lock.unlock()
closed = False
try:
if controller is not None:
closed = controller.close()
finally:
lock.unlock()
if closed and controller.update_shutdown:
acknowledge_shutdown(controller.update_shutdown)

View File

@@ -114,6 +114,7 @@ class Settings:
log_level: str = "INFO"
update_startup: bool = False
update_interval: int = 0
update_notifications: bool = True
targets: list[Target] = field(default_factory=list)
@classmethod
@@ -158,6 +159,8 @@ class Settings:
cfg.update_startup = False
if type(cfg.update_interval) is not int or cfg.update_interval not in (0, 4, 12, 24, 168):
cfg.update_interval = 0
if not isinstance(cfg.update_notifications, bool):
cfg.update_notifications = True
cfg.targets = [Target.from_dict(item) for item in cfg.targets if isinstance(item, dict)] if isinstance(cfg.targets, list) else []
cfg.targets = list({target.identifier: target for target in cfg.targets}.values())
legacy_tray = source.get("tray_mode")

View File

@@ -161,6 +161,7 @@ class SettingsDialog(QDialog):
self.select(form, "Theme", "theme", [(value, value) for value in ("System", "Light", "Dark")])
self.select(form, "Default machine", "default_machine", machine_choices(self.app.dashboard))
self.check(form, "Check for updates at startup", "update_startup")
self.check(form, "Show Windows update notifications", "update_notifications")
self.select(form, "Check for updates periodically", "update_interval",
[("Off", 0), ("Every 4 hours", 4), ("Every 12 hours", 12),
("Daily", 24), ("Weekly", 168)])

View File

@@ -1,6 +1,6 @@
"""Design Creations tray commands for each visible ARM icon."""
from PySide6.QtCore import QSize
from PySide6.QtGui import QActionGroup, QFont, QIcon
from PySide6.QtCore import QSize, Qt
from PySide6.QtGui import QActionGroup, QColor, QFont, QIcon, QPainter, QPen, QPixmap
from PySide6.QtWidgets import QHBoxLayout, QLabel, QMenu, QStyle, QVBoxLayout, QWidget, QWidgetAction
from .about import BrandImage
@@ -17,6 +17,11 @@ class TrayMenu(QMenu):
self.app, self.scope = app, scope
self.setAccessibleName(f"{NAME} tray menu")
self.add_header()
self.update = self.action(self, "", None, app.open_update)
self.update.setVisible(False)
font = self.update.font()
font.setBold(True)
self.update.setFont(font)
self.addSeparator()
open_monitor = self.action(self, "Open Resource Monitor", SP.SP_ComputerIcon,
app.open_expanded)
@@ -120,6 +125,23 @@ class TrayMenu(QMenu):
self.start.setChecked(app.startup_enabled())
def theme(self, colors):
icon = QIcon()
for size in (16, 24, 32):
pixels = QPixmap(size, size)
pixels.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixels)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.scale(size / 16, size / 16)
pen = QPen(QColor(colors.accent), 1.7)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(pen)
painter.drawLine(8, 2, 8, 10)
painter.drawLine(5, 7, 8, 10)
painter.drawLine(11, 7, 8, 10)
painter.drawLine(3, 13, 13, 13)
painter.end()
icon.addPixmap(pixels)
self.update.setIcon(icon)
self.setStyleSheet(f"""
QMenu {{
background-color: {colors.background}; color: {colors.text};

View File

@@ -118,6 +118,7 @@ class ReleaseClient:
folder.mkdir(parents=True, exist_ok=True)
output = folder / package.name
part = output.with_suffix(output.suffix + ".part")
write_atomic(folder / MANIFEST, signed.envelope)
if output.is_file():
try:
verify_file(output, package)
@@ -136,7 +137,6 @@ class ReleaseClient:
raise
except (URLError, OSError) as exc:
raise UpdateError(f"Download interrupted: {exc}. Retry to resume.") from None
write_atomic(folder / MANIFEST, signed.envelope)
return output
def fetch(self, address, part, size, progress, cancelled):

70
arm/update_progress.py Normal file
View File

@@ -0,0 +1,70 @@
"""A small, independent Windows window for the frozen maintenance launcher."""
import logging
from tkinter import Button, Frame, Label, Tk, TclError
from tkinter.ttk import Progressbar
from threading import Thread
from .branding import APPLICATION_ICON, asset
from .update_state import read_json
LOG = logging.getLogger(__name__)
def show_progress(directory, run):
window = Tk()
window.title("Adaptive Resource Monitor Update")
window.resizable(False, False)
icon = asset(APPLICATION_ICON)
if icon.is_file():
window.iconbitmap(str(icon))
background, text, amber = "#211c19", "#f0e5d7", "#e9b46b"
window.configure(background=background)
panel = Frame(window, background=background, padx=20, pady=16)
panel.pack(fill="both", expand=True)
Label(panel, text="Adaptive Resource Monitor", font=("Georgia", 18, "bold"),
background=background, foreground=amber, anchor="w").pack(fill="x")
Label(panel, text="Design Creations", font=("Segoe UI", 10), background=background,
foreground=text, anchor="w").pack(fill="x", pady=(0, 12))
message = Label(panel, text="Preparing update…", wraplength=440, justify="left",
background=background, foreground=text, font=("Segoe UI", 11), anchor="w")
message.pack(fill="x", pady=(0, 12))
progress = Progressbar(panel, mode="indeterminate", length=440)
progress.pack(fill="x")
progress.start(15)
window.protocol("WM_DELETE_WINDOW", lambda: None)
result = []
def perform():
try:
result.append((run(), ""))
except Exception as exc:
LOG.exception("Maintenance reporting failed")
result.append((1, f"{exc}\nDiagnostics: {directory / 'maintenance.log'}"))
def refresh():
status = read_json(directory / "status.json", {})
if text := status.get("message"):
message.configure(text=text)
if not result:
window.after(140, refresh)
return
progress.stop()
progress.pack_forget()
window.protocol("WM_DELETE_WINDOW", window.destroy)
code, error = result[0]
if error:
message.configure(text=error)
if code or status.get("state") == "rolled_back":
Button(panel, text="Close", command=window.destroy).pack(anchor="e")
else:
window.after(2400, window.destroy)
worker = Thread(target=perform, name="ARM update installation")
worker.start()
window.after(140, refresh)
try:
window.mainloop()
except TclError:
pass
worker.join()
return result[0][0]

82
arm/update_state.py Normal file
View File

@@ -0,0 +1,82 @@
"""Presentation and persisted outcomes for the shared updater."""
from enum import Enum, auto
import json
from pathlib import Path
import re
from .update_client import write_atomic
from .version import VERSION, version_key
class Phase(Enum):
CURRENT = auto()
CHECKING = auto()
AVAILABLE = auto()
DOWNLOADING = auto()
PAUSED = auto()
READY = auto()
INSTALLING = auto()
SUCCESS = auto()
FAILED = auto()
RESTORED = auto()
def notice(phase, version, ready=False):
if not version:
return ""
if phase is Phase.SUCCESS:
return f"Adaptive Resource Monitor successfully updated to {version}."
if phase is not Phase.INSTALLING:
title = "Update Ready to Install" if ready else "Update Available"
return f"{title}: {version}"
return ""
def read_json(path, default=None):
try:
return json.loads(path.read_bytes())
except (OSError, ValueError):
return default
def notify_once(path, key, enabled):
if not enabled:
return False
cached = read_json(path, [])
keys = cached if isinstance(cached, list) else []
if key in keys:
return False
write_atomic(path, json.dumps([*keys, key]).encode())
return True
def result_for(directory, running=VERSION):
plan = read_json(directory / "plan.json")
status = read_json(directory / "status.json")
if not isinstance(plan, dict) or not isinstance(status, dict):
return None
try:
version_key(plan["new"])
version_key(plan["old"])
except (KeyError, ValueError, TypeError):
return None
state, message = status.get("state"), status.get("message")
if not isinstance(message, str):
return None
if state == "complete" and plan["new"] == running:
ready = read_json(directory / "ready.json", {})
if (isinstance(ready, dict) and ready.get("version") == running
and type(ready.get("pid")) is int and ready["pid"] > 0):
return Phase.SUCCESS, notice(Phase.SUCCESS, running)
if state in ("rolled_back", "failed") and plan["old"] == running:
return (Phase.RESTORED if state == "rolled_back" else Phase.FAILED), message
return None
def transaction_from_ack(root, value):
if value:
path = Path(value).resolve()
if (path.name == "ready.json" and re.fullmatch(r"[0-9a-f]{32}", path.parent.name)
and path.parent.parent == (root / "updates" / "transactions").resolve()):
return path.parent
return None

View File

@@ -3,6 +3,7 @@ from datetime import datetime
import json
import logging
from threading import Event, Thread
from time import monotonic
from PySide6.QtCore import Qt, QTimer, Signal
from PySide6.QtWidgets import (
@@ -12,6 +13,7 @@ from PySide6.QtWidgets import (
from .update_client import ReleaseClient, UpdateCancelled, write_atomic
from .update_release import MANIFEST, UpdateError, eligible, verify_file, verify_manifest
from .update_state import Phase, notice, notify_once, read_json, result_for
from .version import VERSION, version_key
LOG = logging.getLogger(__name__)
@@ -20,9 +22,10 @@ PACKAGE_LABELS = {"installed": "Windows x64 installer", "portable": "Windows x64
class UpdatePanel(QGroupBox):
notify = Signal(str)
changed = Signal(str, bool)
result = Signal(str, object)
transferred = Signal(int, int)
quit_requested = Signal()
quit_requested = Signal(object)
def __init__(self, root, installation_kind):
super().__init__("Application Update")
@@ -32,7 +35,12 @@ class UpdatePanel(QGroupBox):
self.client = ReleaseClient()
self.job = None
self.release = self.downloaded = self.plan = None
self.announced = set()
self.phase = Phase.CURRENT
self.outcome = None
self.success_banner = False
self.message = ""
self.paused = False
self.worker = None
self.cancel = Event()
self.closing = False
self.policy = None
@@ -80,12 +88,14 @@ class UpdatePanel(QGroupBox):
self.periodic.timeout.connect(self.check_now)
self.handoff = QTimer(self, interval=250)
self.handoff.timeout.connect(self.poll_worker)
self.receipt = QTimer(self, interval=350)
self.receipt.timeout.connect(self.poll_receipt)
self.result.connect(self.finished)
self.transferred.connect(self.update_progress)
self.set_controls()
def configure(self, settings):
policy = (settings.update_startup, settings.update_interval)
policy = (settings.update_startup, settings.update_interval, settings.update_notifications)
if self.policy == policy:
return
first = self.policy is None
@@ -95,6 +105,8 @@ class UpdatePanel(QGroupBox):
self.periodic.start(settings.update_interval * 3_600_000)
if first:
QTimer.singleShot(900, self.initialize)
else:
self.set_controls()
def initialize(self):
if self.job:
@@ -113,7 +125,7 @@ class UpdatePanel(QGroupBox):
plans = sorted((self.root / "transactions").glob("*/status.json"),
key=lambda path: path.stat().st_mtime, reverse=True)
if plans:
status = json.loads(plans[0].read_bytes()).get("message")
status = result_for(plans[0].parent)
verified = []
for manifest in (self.root / "downloads").glob(f"*/{MANIFEST}"):
try:
@@ -121,11 +133,39 @@ class UpdatePanel(QGroupBox):
if eligible(release.version, VERSION) and release.version != VERSION:
package = release.packages[self.kind]
artifact = manifest.parent / package.name
verify_file(artifact, package)
verified.append((release, artifact))
if artifact.is_file():
verify_file(artifact, package)
verified.append((release, artifact, False))
elif artifact.with_suffix(artifact.suffix + ".part").is_file():
verified.append((release, None, True))
except (OSError, UpdateError):
continue
return status, max(verified, key=lambda pair: version_key(pair[0].version), default=(None, None))
return status, max(verified, key=lambda entry: version_key(entry[0].version),
default=(None, None, False))
def follow_restart(self, directory):
self.restart_result = directory
self.receipt_deadline = monotonic() + 45
self.receipt.start()
def poll_receipt(self):
result = result_for(self.restart_result)
if result:
self.receipt.stop()
self.accept_outcome(result)
elif monotonic() > self.receipt_deadline:
self.receipt.stop()
def accept_outcome(self, result):
self.outcome, self.message = result
if self.outcome is Phase.SUCCESS:
try:
self.success_banner |= notify_once(self.root / "confirmation.json", VERSION, True)
except OSError:
self.success_banner = True
LOG.exception("Could not persist the ARM update confirmation")
self.status.setText(self.message)
self.set_controls()
def start(self, operation, action):
if self.closing or self.job or self.plan:
@@ -147,7 +187,8 @@ class UpdatePanel(QGroupBox):
if not self.closing:
self.result.emit(*operation_result)
Thread(target=work, name=f"ARM update {operation}", daemon=True).start()
self.worker = Thread(target=work, name=f"ARM update {operation}", daemon=True)
self.worker.start()
def check_now(self):
if self.job or self.plan:
@@ -165,16 +206,21 @@ class UpdatePanel(QGroupBox):
self.notes.setPlainText(release.notes)
def finished(self, operation, value):
previous_job = self.job
self.job = None
self.progress.hide()
if operation == "restore":
message, (release, artifact) = value
outcome, (release, artifact, self.paused) = value
if release:
self.set_release(release)
self.downloaded = artifact
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified")
if message or artifact:
self.status.setText(message or "Verified package saved. Install it when ready.")
if artifact:
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified")
self.status.setText("Verified package saved. Install it when ready.")
else:
self.status.setText("Download paused. Retry to resume.")
if outcome:
self.accept_outcome(outcome)
if self.policy and self.policy[0]:
self.check_now()
elif operation == "check":
@@ -182,6 +228,7 @@ class UpdatePanel(QGroupBox):
if value.release:
if not self.release or value.release.envelope != self.release.envelope:
self.downloaded = None
self.paused = False
self.set_release(value.release)
if self.release.version == VERSION:
self.status.setText("This is the latest verified version.")
@@ -189,12 +236,10 @@ class UpdatePanel(QGroupBox):
self.status.setText("A verified update is available." if self.downloaded is None else "Verified package saved.")
if self.downloaded:
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified")
if self.release.version not in self.announced:
self.announced.add(self.release.version)
self.notify.emit(self.release.version)
else:
if not self.downloaded:
self.release = None
self.paused = False
self.notes.clear()
self.fields["Latest eligible verified"].setText("None")
self.fields["Download size"].setText("—")
@@ -209,6 +254,7 @@ class UpdatePanel(QGroupBox):
except OSError:
LOG.exception("Could not save the last successful ARM update check")
elif operation == "download":
self.paused = False
self.downloaded = value
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified")
self.status.setText("Verified package saved. Install it when ready.")
@@ -218,6 +264,12 @@ class UpdatePanel(QGroupBox):
self.handoff.start()
else:
self.status.setText(("Update unavailable. " if operation == "error" else "") + value)
if previous_job == "download":
self.paused = True
elif previous_job == "prepare":
self.downloaded = None
self.outcome = Phase.FAILED
self.message = self.status.text()
self.set_controls()
def download_now(self):
@@ -248,6 +300,7 @@ class UpdatePanel(QGroupBox):
from .about import installation
from .update_worker import prepare
release, artifact, target = self.release, self.downloaded, installation()[1]
self.outcome = None
self.status.setText("Revalidating the package and preparing the maintenance launcher…")
self.progress.setRange(0, 0)
self.progress.show()
@@ -258,19 +311,23 @@ class UpdatePanel(QGroupBox):
def poll_worker(self):
self.elapsed += 250
try:
status = json.loads((self.plan / "status.json").read_bytes())
except (OSError, ValueError):
status = {}
status = read_json(self.plan / "status.json", {})
if status.get("state") == "waiting":
self.handoff.stop()
self.quit_requested.emit()
self.quit_requested.emit(self.plan)
elif status.get("state") == "failed" or self.elapsed > 70_000:
self.handoff.stop()
(self.plan / "abort").touch()
self.abort_install(status.get("message") or
"The maintenance launcher did not become ready. Installation was deferred.")
def abort_install(self, message):
if self.plan:
try:
(self.plan / "abort").touch()
except OSError:
LOG.exception("Could not signal that ARM canceled the installation")
self.plan = None
self.status.setText(status.get("message") or "The maintenance launcher did not become ready. Installation was deferred.")
self.set_controls()
self.accept_outcome((Phase.FAILED, message))
def set_controls(self):
available = self.release is not None and self.release.version != VERSION
@@ -280,9 +337,41 @@ class UpdatePanel(QGroupBox):
idle and self.downloaded is not None)
for button, enabled in zip(self.buttons.values(), states):
button.setEnabled(enabled)
if self.plan or self.job == "prepare":
self.phase = Phase.INSTALLING
elif self.job == "download":
self.phase = Phase.DOWNLOADING
elif self.job == "check":
self.phase = Phase.CHECKING
elif self.outcome in (Phase.FAILED, Phase.RESTORED):
self.phase = self.outcome
elif self.downloaded:
self.phase = Phase.READY
elif self.paused:
self.phase = Phase.PAUSED
elif available:
self.phase = Phase.AVAILABLE
else:
self.phase = self.outcome or Phase.CURRENT
version = self.release.version if available else None
show_success = self.phase is Phase.SUCCESS and self.success_banner
label = notice(self.phase, VERSION if show_success else version, bool(self.downloaded))
self.changed.emit(label, self.phase is Phase.SUCCESS)
key = f"success:{VERSION}" if self.phase is Phase.SUCCESS else f"available:{version}"
if label and self.policy:
try:
if notify_once(self.root / "notifications.json", key, self.policy[2]):
self.notify.emit(label)
except OSError:
LOG.exception("Could not persist the ARM update notification")
def stop(self):
self.closing = True
self.cancel.set()
self.handoff.stop()
self.periodic.stop()
self.receipt.stop()
if self.worker:
self.worker.join(timeout=20)
return not self.worker.is_alive()
return True

View File

@@ -1,7 +1,9 @@
"""Independent Windows updater. Transaction data never includes the ARM user profile."""
import argparse
from contextlib import contextmanager
import json
import logging
import msvcrt
import os
from pathlib import Path, PurePosixPath
import re
@@ -21,6 +23,7 @@ from .branding import INSTALL_ID, PUBLISHER
from .config import data_path
from .update_client import write_atomic
from .update_release import MANIFEST, UpdateError, eligible, source_config, verify_file, verify_manifest
from .update_state import read_json, transaction_from_ack
from .version import VERSION, read_version, version_key
EXE = "AdaptiveResourceMonitor.exe"
@@ -119,6 +122,45 @@ def set_status(plan_dir, state, message):
LOG.info("%s. %s", state, message)
@contextmanager
def update_lock(root):
with (root / "updates" / "maintenance.lock").open("a+b") as lock:
try:
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
except OSError as exc:
raise UpdateError("Another update is already running.") from exc
yield
def updates_locked(root):
if not (root / "updates").is_dir():
return False
try:
with update_lock(root):
return False
except UpdateError:
return True
def save_presentation(plan_dir, state):
write_atomic(plan_dir / "presentation.json", json.dumps(state).encode())
def presentation(plan_dir):
state = read_json(plan_dir / "presentation.json", {})
if not isinstance(state, dict) or type(state.get("expanded")) is not bool:
return {}
rect = state.get("geometry")
if (not isinstance(rect, list) or len(rect) != 4 or any(type(value) is not int for value in rect)
or any(abs(value) > 32768 for value in rect) or min(rect[2:]) <= 0):
state.pop("geometry", None)
return state
def acknowledge_shutdown(plan_dir):
write_atomic(plan_dir / "closed.json", json.dumps({"pid": os.getpid(), "version": VERSION}).encode())
def prepare(release, artifact, target, kind, root):
config = source_config()
signed = verify_manifest(release.envelope, config["public_key"], release.version)
@@ -192,25 +234,45 @@ def remove_managed(path):
path.unlink()
def wait_parent(data, target, plan_dir):
limit = monotonic() + 75
def requesting_process(data, target):
try:
parent = psutil.Process(data["parent"])
if abs(parent.create_time() - data["created"]) <= 0.01 and Path(parent.exe()).resolve() == target / EXE:
return parent
except psutil.NoSuchProcess:
pass
raise UpdateError("The requesting process is not this Adaptive Resource Monitor installation.")
def wait_parent(data, target, plan_dir, timeout=75):
expected = {"pid": data["parent"], "version": data["old"]}
limit = monotonic() + timeout
closing = False
while monotonic() < limit:
if (plan_dir / "abort").exists():
raise UpdateError("Installation canceled before touching the application.")
acknowledged = read_json(plan_dir / "closed.json") == expected
if acknowledged and not closing:
set_status(plan_dir, "closing", "Closing Adaptive Resource Monitor…")
closing = True
try:
parent = psutil.Process(data["parent"])
if abs(parent.create_time() - data["created"]) > 0.01:
return
if Path(parent.exe()).resolve() != target / EXE:
raise UpdateError("The requesting process is not this ARM executable")
alive = abs(parent.create_time() - data["created"]) <= 0.01
if alive and Path(parent.exe()).resolve() != target / EXE:
raise UpdateError("The requesting process is not this Adaptive Resource Monitor installation.")
except psutil.NoSuchProcess:
alive = False
if not alive:
if read_json(plan_dir / "closed.json") != expected:
raise UpdateError("ARM exited without confirming that settings and history were closed. Installation stopped.")
return
if (plan_dir / "abort").exists():
raise UpdateError("Installation canceled before touching the application")
sleep(.25)
raise UpdateError("The application did not exit. Installation was deferred.")
raise UpdateError("ARM did not shut down in time. To retry, close any open ARM dialogs and start the update again.")
def restart(target, version, plan_dir):
ready = plan_dir / "ready.json"
ready.unlink(missing_ok=True)
child = subprocess.Popen([str(target / EXE)], cwd=target, env=dict(os.environ, **{ACK: str(ready)}))
try:
deadline = monotonic() + 35
@@ -253,13 +315,17 @@ def transact(plan_dir, recover=False):
if journal.get("committed"):
remove_managed(work)
recovery_entry(plan_dir, False)
set_status(plan_dir, "complete", f"Updated and restarted Adaptive Resource Monitor {data['new']}.")
return
set_status(plan_dir, "recovering", "Restoring the previous application after an interrupted installation…")
rollback(target, work, journal)
remove_managed(work)
recovery_entry(plan_dir, False)
set_status(plan_dir, "rolled_back", "Restored the previous application after an interrupted installation.")
restart(target, data["old"], plan_dir)
set_status(plan_dir, "rolled_back", "Restored the previous application after an interrupted installation.")
recovery_entry(plan_dir, False)
remove_managed(work)
return
requesting_process(data, target)
set_status(plan_dir, "verifying", "Verifying the signed update package…")
release = verify_manifest((plan_dir / MANIFEST).read_bytes(), source_config()["public_key"], data["new"])
view = registered_view(target)
kind = "installed" if view is not None else "portable"
@@ -281,9 +347,13 @@ def transact(plan_dir, recover=False):
shutil.copy2(artifact, payload / package.name)
verify_file(payload / package.name, package)
verify_executable(payload / package.name, release.version)
set_status(plan_dir, "waiting", "Verified the update. Waiting for the monitor to close and save its history.")
set_status(plan_dir, "waiting", "Saving application settings and pending telemetry…")
wait_parent(data, target, plan_dir)
verify_file(artifact, package)
set_status(plan_dir, "verifying", "Rechecking the update package before installation…")
signed = verify_manifest((plan_dir / MANIFEST).read_bytes(), source_config()["public_key"], data["new"])
if signed.envelope != release.envelope:
raise UpdateError("The signed update manifest changed during shutdown.")
verify_file(artifact, signed.packages[kind])
for name in managed_entries(target, view is not None):
safe_entry(target / name)
originals = managed_entries(target, view is not None)
@@ -310,16 +380,20 @@ def transact(plan_dir, recover=False):
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_READ | view) as key:
if winreg.QueryValueEx(key, "DisplayVersion")[0] != release.version:
raise UpdateError("Windows installer registration did not report the expected version")
set_status(plan_dir, "verifying_installation", "Verifying installed files and application version…")
verify_payload(target, release.version)
build = json.loads((target / "BUILD.json").read_bytes())
if (build.get("source_revision"), build.get("jenkins_build")) != (release.commit, release.build):
raise UpdateError("Installed build identity does not match the signed manifest")
set_status(plan_dir, "restarting", "Restarting Adaptive Resource Monitor…")
restart(target, release.version, plan_dir)
except Exception as exc:
LOG.exception("Installation or startup failed")
set_status(plan_dir, "recovering", "Update failed. Restoring the previous release…")
rollback(target, work, journal)
set_status(plan_dir, "rolled_back", f"Installed update failed. Restored the previous application. {exc}")
recovery_entry(plan_dir, False)
restart(target, data["old"], plan_dir)
set_status(plan_dir, "rolled_back", f"Update failed. The previous version was restored and restarted. {exc}")
recovery_entry(plan_dir, False)
return
journal["committed"] = True
write_atomic(checkpoint, json.dumps(journal).encode())
@@ -332,12 +406,9 @@ def transact(plan_dir, recover=False):
remove_managed(work)
def signal_ready():
if value := os.environ.pop(ACK, None):
path = Path(value)
transactions = data_path() / "updates" / "transactions"
if path.name == "ready.json" and path.parent.parent.resolve() == transactions.resolve():
write_atomic(path, json.dumps({"version": VERSION, "pid": os.getpid()}).encode())
def signal_ready(root=None):
if directory := transaction_from_ack(root or data_path(), os.environ.pop(ACK, None)):
write_atomic(directory / "ready.json", json.dumps({"version": VERSION, "pid": os.getpid()}).encode())
def main():
@@ -351,10 +422,26 @@ def main():
return 2
logging.basicConfig(filename=plan_dir / "maintenance.log", level=logging.INFO, encoding="utf-8",
format="%(asctime)s %(levelname)s %(message)s")
try:
transact(plan_dir, args.recover)
except Exception as exc:
LOG.exception("Maintenance failed")
set_status(plan_dir, "failed", str(exc))
return 1
return 0
def run():
try:
with update_lock(data_path()):
set_status(plan_dir, "preparing", "Preparing the Adaptive Resource Monitor update…")
transact(plan_dir, args.recover)
except Exception as exc:
LOG.exception("Maintenance failed")
message = f"{exc}\nDiagnostics: {plan_dir / 'maintenance.log'}"
journal = read_json(plan_dir / "journal.json", {})
if journal and not journal.get("committed"):
message += ("\nClose ARM before attempting recovery again. If it still fails, use the previous "
"version's installer or restore the portable files from the previous verified package. "
"Leave the ARM profile directory in place.")
try:
recovery_entry(plan_dir, False)
except OSError:
LOG.exception("Could not remove the scheduled recovery entry")
set_status(plan_dir, "failed", message)
return 1
return 0
from .update_progress import show_progress
return show_progress(plan_dir, run)

View File

@@ -154,6 +154,34 @@ class MachineSection(QFrame):
header.addWidget(details)
class UpdateBanner(QFrame):
def __init__(self, open_update):
super().__init__()
self.setObjectName("armUpdateBanner")
row = QHBoxLayout(self)
row.setContentsMargins(8, 3, 6, 3)
self.label = plain()
row.addWidget(self.label, 1)
self.action = QPushButton("View Update")
self.action.clicked.connect(lambda: open_update(self.success))
row.addWidget(self.action)
self.success = False
self.hide()
def update_notice(self, message, success):
self.success = success
self.label.setText(message)
self.action.setText("View Changelog" if success else "View Update")
self.setVisible(bool(message))
def theme(self, colors):
self.setStyleSheet(f"""
QFrame#armUpdateBanner {{ background: {colors.highlight}; border: 1px solid {colors.border}; border-radius: 4px; }}
QFrame#armUpdateBanner QLabel {{ color: {colors.accent}; font-weight: 600; }}
QFrame#armUpdateBanner QPushButton {{ color: {colors.accent}; padding: 2px 8px; }}
""")
class Monitor(QWidget):
def __init__(self, dashboard, expanded, request_archive, switch_expanded, set_pin, about_page=None):
flags = Qt.WindowType.Window if expanded else (
@@ -277,12 +305,18 @@ class Monitor(QWidget):
def popup_size(self):
cfg = self.dashboard.settings
banner = self.update_banner.sizeHint().height() + self.layout().spacing() if (
hasattr(self, "update_banner") and not self.update_banner.isHidden()) else 0
if self.selected_machine != ALL:
return QSize(cfg.popup_width, cfg.popup_height)
return QSize(cfg.popup_width, cfg.popup_height + banner)
# Cap in HoverMonitor against the work area. The scroll area keeps
# six columns together even on a narrow monitor.
rows_height = sum(max(138, section.sizeHint().height()) for section in self.sections.values())
return QSize(max(cfg.popup_width, 875), max(cfg.popup_height, rows_height + 72))
return QSize(max(cfg.popup_width, 875), max(cfg.popup_height, rows_height + 72) + banner)
def add_update_banner(self, open_update):
self.update_banner = UpdateBanner(open_update)
self.layout().insertWidget(0 if self.expanded else 2, self.update_banner)
def sync_devices(self):
if not self.expanded:

View File

@@ -2,7 +2,8 @@
The Windows package includes CPython, Qt 6 and its PySide6 Python bindings,
psutil, Paramiko and its cryptographic dependencies, NVIDIA's NVML Python
bindings, and the PyInstaller bootloader. The NVIDIA display driver's NVML DLL
bindings, Tcl/Tk for the maintenance window, and the PyInstaller bootloader.
The NVIDIA display driver's NVML DLL
is provided by the driver. License text distributed by the dependency wheels
is included in this directory.

View File

@@ -34,6 +34,8 @@ SetupIconFile={#AppIcon}
WizardImageFile={#WizardImage}
WizardSmallImageFile={#WizardEmblem}
UninstallDisplayIcon={app}\{#Executable}
CloseApplications=no
RestartApplications=no
[Tasks]
Name: "desktopicon"; Description: "Create a desktop shortcut"; Flags: unchecked
@@ -53,6 +55,31 @@ Root: HKCU; Subkey: "{#RunKey}"; ValueType: string; ValueName: "AdaptiveResource
Filename: "{app}\{#Executable}"; Description: "Open Adaptive Resource Monitor"; Flags: nowait postinstall skipifsilent
[Code]
function OpenPayloadFile(Name: String; Access, Share: Cardinal; Security: Integer;
Creation, Flags: Cardinal; Template: THandle): THandle;
external 'CreateFileW@kernel32.dll stdcall';
function ClosePayloadFile(Handle: THandle): Boolean;
external 'CloseHandle@kernel32.dll stdcall';
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
Target: String;
Handle: THandle;
begin
Result := '';
Target := ExpandConstant('{app}\{#Executable}');
if FileExists(Target) then
begin
{ An executable loaded as a Windows image cannot be opened for writing. }
Handle := OpenPayloadFile(Target, 2, 7, 0, 3, 0, 0);
if Handle = THandle(-1) then
Result := 'Close Adaptive Resource Monitor from its notification-area menu, then run Setup again.'
else
ClosePayloadFile(Handle);
end;
end;
function ArmUpdate: Boolean;
begin
Result := ExpandConstant('{param:ARMUPDATE|0}') = '1';

View File

@@ -9,6 +9,7 @@ import unittest
from unittest.mock import patch
from urllib.error import URLError
from zipfile import ZipFile
import psutil
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
@@ -16,7 +17,8 @@ from arm.branding import APP_MODEL_ID
from arm.config import Settings
from arm.update_client import ReleaseClient, UpdateCancelled
from arm.update_release import MANIFEST, UpdateError, artifact_name, canonical, verify_manifest
from arm.update_worker import unpack_portable
from arm.update_state import Phase, notice, notify_once, result_for, transaction_from_ack
from arm.update_worker import unpack_portable, wait_parent
from arm.version import VERSION, version_key
COUNTERS = version_key(VERSION)
@@ -150,3 +152,51 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(Settings.from_dict({"update_startup": True, "update_interval": 168}).update_interval, 168)
default = Settings.from_dict({"update_startup": "yes", "update_interval": 169})
self.assertEqual((default.update_startup, default.update_interval), (False, 0))
def test_notification_only_once_across_checks_and_restarts(self):
path = self.work / "notices.json"
self.assertFalse(notify_once(path, NEW, False))
self.assertFalse(path.exists())
self.assertTrue(notify_once(path, NEW, True))
self.assertFalse(notify_once(path, NEW, True))
self.assertEqual(notice(Phase.CHECKING, None), "")
self.assertEqual(notice(Phase.INSTALLING, NEW, True), "")
self.assertEqual(notice(Phase.AVAILABLE, NEW), f"Update Available: {NEW}")
self.assertEqual(notice(Phase.READY, NEW, True), f"Update Ready to Install: {NEW}")
def test_update_result_requires_successful_restart_receipt(self):
directory = self.work / "updates" / "transactions" / ("a" * 32)
directory.mkdir(parents=True)
(directory / "plan.json").write_text(json.dumps({"old": VERSION, "new": NEW}))
status = directory / "status.json"
status.write_text(json.dumps({"state": "complete", "message": "Legacy completion status"}))
ready = directory / "ready.json"
self.assertEqual(transaction_from_ack(self.work, str(ready)), directory)
self.assertIsNone(transaction_from_ack(self.work, str(status)))
self.assertIsNone(result_for(directory, NEW))
ready.write_text(json.dumps({"version": NEW, "pid": 10}))
self.assertEqual(result_for(directory, NEW), (Phase.SUCCESS, notice(Phase.SUCCESS, NEW)))
self.assertIsNone(result_for(directory, VERSION))
status.write_text(json.dumps({"state": "rolled_back", "message": "Restored prior application"}))
self.assertEqual(result_for(directory, VERSION), (Phase.RESTORED, "Restored prior application"))
self.assertIsNone(result_for(directory, NEW))
def test_shutdown_requires_acknowledgement_and_confirmed_process_exit(self):
target = self.work
plan = {"parent": 10, "created": 1, "old": VERSION}
with patch("arm.update_worker.psutil.Process", side_effect=psutil.NoSuchProcess(10)):
with self.assertRaisesRegex(UpdateError, "without confirming"):
wait_parent(plan, target, self.work)
(self.work / "closed.json").write_text(json.dumps({"pid": 10, "version": VERSION}))
wait_parent(plan, target, self.work)
with patch("arm.update_worker.read_json", side_effect=[None, {"pid": 10, "version": VERSION}]):
wait_parent(plan, target, self.work)
with patch("arm.update_worker.psutil.Process") as process:
process.return_value.create_time.return_value = 1
process.return_value.exe.return_value = str(target / "AdaptiveResourceMonitor.exe")
with self.assertRaisesRegex(UpdateError, "shut down in time"):
wait_parent(plan, target, self.work, timeout=.05)
self.assertEqual(process.return_value.exe.call_count, 1)
(self.work / "abort").touch()
with self.assertRaisesRegex(UpdateError, "canceled"):
wait_parent(plan, target, self.work)

View File

@@ -428,6 +428,89 @@ def verify_branding(session, results, captures=None):
results["verified_about_and_tray_actions"] = True
def verify_update_notices(session, wait_for, results, captures):
from PySide6.QtCore import QPoint
from unittest.mock import patch
from arm.model import ALL, LOCAL
from arm.update_client import Check
from arm.update_release import verify_manifest
from arm.update_state import Phase
from test_updates import NEW, PACKAGE, Response, UpdateTests
def capture(widget, filename):
session.qt.processEvents()
if captures:
assert widget.grab().save(str(captures / filename))
menu = session.menus[LOCAL]
hover, expanded = session.popup, session.expanded
update = session.about_page.updates
assert not menu.update.isVisible() and hover.update_banner.isHidden()
initial_size = hover.popup_size()
notices = []
update.notify.connect(notices.append)
rejected = Check(NEW, None, ("Fixture signature rejected",))
with patch.object(update.client, "check", return_value=rejected):
update.check_now()
wait_for(lambda: update.job is None)
assert not menu.update.isVisible() and not notices
fixture = UpdateTests()
try:
fixture.setUp()
release = verify_manifest(fixture.sign(fixture.metadata()), fixture.public)
checked = Check(NEW, release, ())
with patch.object(update.client, "check", return_value=checked):
for _ in range(2):
update.check_now()
wait_for(lambda: update.job is None)
available = f"Update Available: {NEW}"
assert update.phase is Phase.AVAILABLE and notices == [available]
assert menu.actions()[1] is menu.update and menu.update.text() == available
session.hover.show(LOCAL)
assert hover.popup_size().height() > initial_size.height()
assert hover.update_banner.label.text() == available
capture(hover, "update-hover.png")
session.select_machine(ALL, LOCAL)
session.hover.pin(True, LOCAL)
assert hover.update_banner.isVisible() and hover.selected_machine == ALL
session.hover.pin(False)
session.select_machine(LOCAL, LOCAL)
hover.hide()
session.open_expanded()
assert expanded.update_banner.isVisible() and expanded.monitor_visible
capture(expanded, "update-expanded.png")
menu.popup(QPoint(20, 20))
capture(menu, "update-tray-menu.png")
menu.hide()
menu.update.trigger()
assert expanded.tabs.currentWidget() == session.about_page and expanded.update_banner.isVisible()
capture(expanded, "update-about.png")
with patch.object(update.client, "open", return_value=Response(PACKAGE)):
update.client.source["public_key"], original_key = fixture.public, update.client.source["public_key"]
try:
update.download_now()
wait_for(lambda: update.job is None)
assert update.phase is Phase.READY and update.downloaded.is_file()
update.defer_install()
assert menu.update.text() == f"Update Ready to Install: {NEW}"
assert update.restore()[1][1] == update.downloaded
finally:
update.client.source["public_key"] = original_key
update.downloaded.unlink()
update.downloaded = None
with patch.object(update.client, "check", return_value=rejected):
update.check_now()
wait_for(lambda: update.job is None)
assert not menu.update.isVisible() and expanded.update_banner.isHidden()
assert hover.popup_size() == initial_size
expanded.close()
finally:
fixture.doCleanups()
results["verified_shared_update_notices"] = "Verified, ready, rejected, deferred and duplicate notification states"
def evaluate_app(work, results, short=False, captures=None):
import psutil
from PySide6.QtCore import QEventLoop, QTimer
@@ -536,6 +619,7 @@ def evaluate_app(work, results, short=False, captures=None):
assert update.fields["Latest published"].text() == "No public releases"
assert "UTC" in update.fields["Last successful check"].text()
session.expanded.close()
verify_update_notices(session, wait_for, results, captures)
results["asynchronous_update_check_with_live_telemetry"] = True
modes = {}
for mode in ("Stacked", STATIC_TRAY_MODE, "Overlay", "Composite"):

View File

@@ -68,6 +68,9 @@ def copy_notices(payload):
python_license = Path(sys.base_prefix) / "LICENSE.txt"
if python_license.is_file():
shutil.copyfile(python_license, notices / "Python-LICENSE.txt")
tcl_tk_license = next(Path(sys.base_prefix).glob("tcl/tk*/license.terms"), None)
if tcl_tk_license:
shutil.copyfile(tcl_tk_license, notices / "Tcl-Tk-license.terms")
shutil.copyfile(ROOT / "packaging" / "THIRD_PARTY.md", notices / "README.md")
@@ -125,7 +128,8 @@ def build(compiler, output):
"--name", worker_name, "--paths", str(ROOT), "--workpath", str(temporary / "work"),
"--distpath", str(temporary / "maintenance"), "--specpath", str(temporary),
"--version-file", str(version_file), "--manifest", str(ROOT / "packaging" / "windows.manifest"),
"--icon", str(ICON), "--exclude-module", "PySide6", *update_data, str(ROOT / "tools" / "maintenance.py"),
"--icon", str(ICON), "--exclude-module", "PySide6", "--add-data", f"{ICON};branding",
*update_data, str(ROOT / "tools" / "maintenance.py"),
])
run([
sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed",