Refine verified update notices and Windows installation lifecycle

This commit is contained in:
2026-11-26 19:09:17 -06:00
parent f9fa7c258d
commit 2e93b7587d
19 changed files with 744 additions and 81 deletions

View File

@@ -1,5 +1,11 @@
# Changelog # 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 ## v0.6.1.1_alpha — 2026-11-26
- Added signed update discovery, verified downloads and authorized installation for installed and portable Windows x64 editions. - Added signed update discovery, verified downloads and authorized installation for installed and portable Windows x64 editions.

View File

@@ -1,5 +1,19 @@
# Adaptive Resource Monitor implementation report # 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 ## 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) [Adaptive Resource Monitor v0.6.1.1_alpha](https://phantom.zapto.org/gitea/sonja/Adaptive_Resource_Monitor/releases/tag/v0.6.1.1_alpha)

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 size, verification status, progress and signed release notes. ARM defaults to
manual checks. Settings offers a startup check and periodic checks every 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 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 **Download Update** stores the signed envelope and verified package in the
application's per-user updates directory. Cancel leaves a partial file. A retry 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 requests a byte range and validates the server's response. If the server
returns a complete response, ARM starts the file over. **Install Later** 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 ## 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 installed variant is identified from Windows' uninstall registration.
The maintenance launcher verifies the download, starts from a staged copy The maintenance launcher verifies the download, starts from a staged copy
outside the installed directory and waits for the monitor to close. The outside the installed directory. It verifies the requesting process's
monitor closes its collectors and drains pending history writes. The launcher 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 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 verifies and extracts the ZIP into staging on the same volume and replaces
only distribution-owned entries. Existing files outside those entries stay only distribution-owned entries. Existing files outside those entries stay
in place. Before restarting ARM, the launcher verifies the new executable, 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 ## 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 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 transaction and its backup remain available. The About panel reads the most
recent update result. Details are in maintenance.log and, for Setup, recent update result. Details are in maintenance.log and, for Setup,
installer.log under the transaction directory. Keep transaction files while an installer.log under the transaction directory. If an automated restore fails,
installation is pending. Profiles, the Credential Manager, SSH trust and 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. 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 winreg
import psutil 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.QtGui import QDesktopServices
from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QSystemTrayIcon from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QSystemTrayIcon
@@ -82,12 +82,18 @@ class Application(QObject):
self.icons = {} self.icons = {}
self.menus = {} self.menus = {}
self.about_page = AboutPage(self.root) 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.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.expanded = Monitor(self.dashboard, True, self.request_archive, self.open_expanded,
self.set_pin, self.about_page) self.set_pin, self.about_page)
self.expanded.setWindowIcon(self.brand_icon) self.expanded.setWindowIcon(self.brand_icon)
self.popup = Monitor(self.dashboard, False, self.request_archive, self.open_expanded, self.set_pin) 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) self.hover = HoverMonitor(self.popup, self.dashboard, self.icons)
for view in (self.popup, self.expanded): for view in (self.popup, self.expanded):
view.machine.currentIndexChanged.connect(partial(self.monitor_selected, view)) 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.brand_colors = DARK if scheme == Qt.ColorScheme.Dark else LIGHT
self.about_page.theme(self.brand_colors) self.about_page.theme(self.brand_colors)
self.expanded.brand_tabs(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(): for menu in self.menus.values():
menu.theme(self.brand_colors) menu.theme(self.brand_colors)
@@ -193,10 +201,11 @@ class Application(QObject):
icon = QSystemTrayIcon(self) icon = QSystemTrayIcon(self)
icon.setIcon(self.brand_icon) icon.setIcon(self.brand_icon)
icon.activated.connect(partial(self.activate_icon, machine)) 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.icons[machine] = icon
self.menus[machine] = TrayMenu(self, machine) self.menus[machine] = TrayMenu(self, machine)
self.menus[machine].theme(self.brand_colors) self.menus[machine].theme(self.brand_colors)
self.set_menu_update(self.menus[machine])
icon.setContextMenu(self.menus[machine]) icon.setContextMenu(self.menus[machine])
icon.show() icon.show()
self.sync_menus() self.sync_menus()
@@ -497,10 +506,56 @@ class Application(QObject):
self.about() self.about()
self.about_page.updates.check_now() 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) icon = self.icons.get(self.settings.tray_machine)
if icon: if icon and icon.supportsMessages():
icon.showMessage(NAME, f"Verified update {version} is available. Open About for details.") 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): def open_website(self):
QDesktopServices.openUrl(QUrl(WEBSITE)) QDesktopServices.openUrl(QUrl(WEBSITE))
@@ -509,7 +564,7 @@ class Application(QObject):
if self._closed: if self._closed:
return return
self._closed = True 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): for timer in (self.tray_timer, self.hover_timer, self.view_timer):
timer.stop() timer.stop()
for icon in self.icons.values(): for icon in self.icons.values():
@@ -524,9 +579,13 @@ class Application(QObject):
LOG.info("%s stopped", NAME) LOG.info("%s stopped", NAME)
logging.getLogger().removeHandler(self.logger) logging.getLogger().removeHandler(self.logger)
self.logger.close() self.logger.close()
return updates_stopped
def main(): def main():
from .update_worker import ACK, acknowledge_shutdown, presentation, signal_ready, updates_locked
from .update_state import transaction_from_ack
set_windows_identity() set_windows_identity()
app = QApplication(sys.argv) app = QApplication(sys.argv)
app.setApplicationName(NAME) app.setApplicationName(NAME)
@@ -542,13 +601,29 @@ def main():
return 0 return 0
controller = None controller = None
try: try:
transaction = transaction_from_ack(root, os.environ.get(ACK))
if not transaction and updates_locked(root):
return 0
controller = Application(app, root) 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() controller.open_expanded()
from .update_worker import signal_ready if geometry := state.get("geometry"):
signal_ready() 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() return app.exec()
finally: finally:
if controller is not None: closed = False
controller.close() try:
lock.unlock() 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" log_level: str = "INFO"
update_startup: bool = False update_startup: bool = False
update_interval: int = 0 update_interval: int = 0
update_notifications: bool = True
targets: list[Target] = field(default_factory=list) targets: list[Target] = field(default_factory=list)
@classmethod @classmethod
@@ -158,6 +159,8 @@ class Settings:
cfg.update_startup = False cfg.update_startup = False
if type(cfg.update_interval) is not int or cfg.update_interval not in (0, 4, 12, 24, 168): if type(cfg.update_interval) is not int or cfg.update_interval not in (0, 4, 12, 24, 168):
cfg.update_interval = 0 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 = [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()) cfg.targets = list({target.identifier: target for target in cfg.targets}.values())
legacy_tray = source.get("tray_mode") 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, "Theme", "theme", [(value, value) for value in ("System", "Light", "Dark")])
self.select(form, "Default machine", "default_machine", machine_choices(self.app.dashboard)) 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, "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", self.select(form, "Check for updates periodically", "update_interval",
[("Off", 0), ("Every 4 hours", 4), ("Every 12 hours", 12), [("Off", 0), ("Every 4 hours", 4), ("Every 12 hours", 12),
("Daily", 24), ("Weekly", 168)]) ("Daily", 24), ("Weekly", 168)])

View File

@@ -1,6 +1,6 @@
"""Design Creations tray commands for each visible ARM icon.""" """Design Creations tray commands for each visible ARM icon."""
from PySide6.QtCore import QSize from PySide6.QtCore import QSize, Qt
from PySide6.QtGui import QActionGroup, QFont, QIcon from PySide6.QtGui import QActionGroup, QColor, QFont, QIcon, QPainter, QPen, QPixmap
from PySide6.QtWidgets import QHBoxLayout, QLabel, QMenu, QStyle, QVBoxLayout, QWidget, QWidgetAction from PySide6.QtWidgets import QHBoxLayout, QLabel, QMenu, QStyle, QVBoxLayout, QWidget, QWidgetAction
from .about import BrandImage from .about import BrandImage
@@ -17,6 +17,11 @@ class TrayMenu(QMenu):
self.app, self.scope = app, scope self.app, self.scope = app, scope
self.setAccessibleName(f"{NAME} tray menu") self.setAccessibleName(f"{NAME} tray menu")
self.add_header() 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() self.addSeparator()
open_monitor = self.action(self, "Open Resource Monitor", SP.SP_ComputerIcon, open_monitor = self.action(self, "Open Resource Monitor", SP.SP_ComputerIcon,
app.open_expanded) app.open_expanded)
@@ -120,6 +125,23 @@ class TrayMenu(QMenu):
self.start.setChecked(app.startup_enabled()) self.start.setChecked(app.startup_enabled())
def theme(self, colors): 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""" self.setStyleSheet(f"""
QMenu {{ QMenu {{
background-color: {colors.background}; color: {colors.text}; background-color: {colors.background}; color: {colors.text};

View File

@@ -118,6 +118,7 @@ class ReleaseClient:
folder.mkdir(parents=True, exist_ok=True) folder.mkdir(parents=True, exist_ok=True)
output = folder / package.name output = folder / package.name
part = output.with_suffix(output.suffix + ".part") part = output.with_suffix(output.suffix + ".part")
write_atomic(folder / MANIFEST, signed.envelope)
if output.is_file(): if output.is_file():
try: try:
verify_file(output, package) verify_file(output, package)
@@ -136,7 +137,6 @@ class ReleaseClient:
raise raise
except (URLError, OSError) as exc: except (URLError, OSError) as exc:
raise UpdateError(f"Download interrupted: {exc}. Retry to resume.") from None raise UpdateError(f"Download interrupted: {exc}. Retry to resume.") from None
write_atomic(folder / MANIFEST, signed.envelope)
return output return output
def fetch(self, address, part, size, progress, cancelled): 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 json
import logging import logging
from threading import Event, Thread from threading import Event, Thread
from time import monotonic
from PySide6.QtCore import Qt, QTimer, Signal from PySide6.QtCore import Qt, QTimer, Signal
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
@@ -12,6 +13,7 @@ from PySide6.QtWidgets import (
from .update_client import ReleaseClient, UpdateCancelled, write_atomic from .update_client import ReleaseClient, UpdateCancelled, write_atomic
from .update_release import MANIFEST, UpdateError, eligible, verify_file, verify_manifest 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 from .version import VERSION, version_key
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@@ -20,9 +22,10 @@ PACKAGE_LABELS = {"installed": "Windows x64 installer", "portable": "Windows x64
class UpdatePanel(QGroupBox): class UpdatePanel(QGroupBox):
notify = Signal(str) notify = Signal(str)
changed = Signal(str, bool)
result = Signal(str, object) result = Signal(str, object)
transferred = Signal(int, int) transferred = Signal(int, int)
quit_requested = Signal() quit_requested = Signal(object)
def __init__(self, root, installation_kind): def __init__(self, root, installation_kind):
super().__init__("Application Update") super().__init__("Application Update")
@@ -32,7 +35,12 @@ class UpdatePanel(QGroupBox):
self.client = ReleaseClient() self.client = ReleaseClient()
self.job = None self.job = None
self.release = self.downloaded = self.plan = 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.cancel = Event()
self.closing = False self.closing = False
self.policy = None self.policy = None
@@ -80,12 +88,14 @@ class UpdatePanel(QGroupBox):
self.periodic.timeout.connect(self.check_now) self.periodic.timeout.connect(self.check_now)
self.handoff = QTimer(self, interval=250) self.handoff = QTimer(self, interval=250)
self.handoff.timeout.connect(self.poll_worker) 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.result.connect(self.finished)
self.transferred.connect(self.update_progress) self.transferred.connect(self.update_progress)
self.set_controls() self.set_controls()
def configure(self, settings): 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: if self.policy == policy:
return return
first = self.policy is None first = self.policy is None
@@ -95,6 +105,8 @@ class UpdatePanel(QGroupBox):
self.periodic.start(settings.update_interval * 3_600_000) self.periodic.start(settings.update_interval * 3_600_000)
if first: if first:
QTimer.singleShot(900, self.initialize) QTimer.singleShot(900, self.initialize)
else:
self.set_controls()
def initialize(self): def initialize(self):
if self.job: if self.job:
@@ -113,7 +125,7 @@ class UpdatePanel(QGroupBox):
plans = sorted((self.root / "transactions").glob("*/status.json"), plans = sorted((self.root / "transactions").glob("*/status.json"),
key=lambda path: path.stat().st_mtime, reverse=True) key=lambda path: path.stat().st_mtime, reverse=True)
if plans: if plans:
status = json.loads(plans[0].read_bytes()).get("message") status = result_for(plans[0].parent)
verified = [] verified = []
for manifest in (self.root / "downloads").glob(f"*/{MANIFEST}"): for manifest in (self.root / "downloads").glob(f"*/{MANIFEST}"):
try: try:
@@ -121,11 +133,39 @@ class UpdatePanel(QGroupBox):
if eligible(release.version, VERSION) and release.version != VERSION: if eligible(release.version, VERSION) and release.version != VERSION:
package = release.packages[self.kind] package = release.packages[self.kind]
artifact = manifest.parent / package.name artifact = manifest.parent / package.name
verify_file(artifact, package) if artifact.is_file():
verified.append((release, artifact)) 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): except (OSError, UpdateError):
continue 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): def start(self, operation, action):
if self.closing or self.job or self.plan: if self.closing or self.job or self.plan:
@@ -147,7 +187,8 @@ class UpdatePanel(QGroupBox):
if not self.closing: if not self.closing:
self.result.emit(*operation_result) 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): def check_now(self):
if self.job or self.plan: if self.job or self.plan:
@@ -165,16 +206,21 @@ class UpdatePanel(QGroupBox):
self.notes.setPlainText(release.notes) self.notes.setPlainText(release.notes)
def finished(self, operation, value): def finished(self, operation, value):
previous_job = self.job
self.job = None self.job = None
self.progress.hide() self.progress.hide()
if operation == "restore": if operation == "restore":
message, (release, artifact) = value outcome, (release, artifact, self.paused) = value
if release: if release:
self.set_release(release) self.set_release(release)
self.downloaded = artifact self.downloaded = artifact
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified") if artifact:
if message or artifact: self.fields["Verification"].setText("Manifest signature and package SHA-256 verified")
self.status.setText(message or "Verified package saved. Install it when ready.") 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]: if self.policy and self.policy[0]:
self.check_now() self.check_now()
elif operation == "check": elif operation == "check":
@@ -182,6 +228,7 @@ class UpdatePanel(QGroupBox):
if value.release: if value.release:
if not self.release or value.release.envelope != self.release.envelope: if not self.release or value.release.envelope != self.release.envelope:
self.downloaded = None self.downloaded = None
self.paused = False
self.set_release(value.release) self.set_release(value.release)
if self.release.version == VERSION: if self.release.version == VERSION:
self.status.setText("This is the latest verified 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.") self.status.setText("A verified update is available." if self.downloaded is None else "Verified package saved.")
if self.downloaded: if self.downloaded:
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified") 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: else:
if not self.downloaded: if not self.downloaded:
self.release = None self.release = None
self.paused = False
self.notes.clear() self.notes.clear()
self.fields["Latest eligible verified"].setText("None") self.fields["Latest eligible verified"].setText("None")
self.fields["Download size"].setText("—") self.fields["Download size"].setText("—")
@@ -209,6 +254,7 @@ class UpdatePanel(QGroupBox):
except OSError: except OSError:
LOG.exception("Could not save the last successful ARM update check") LOG.exception("Could not save the last successful ARM update check")
elif operation == "download": elif operation == "download":
self.paused = False
self.downloaded = value self.downloaded = value
self.fields["Verification"].setText("Manifest signature and package SHA-256 verified") self.fields["Verification"].setText("Manifest signature and package SHA-256 verified")
self.status.setText("Verified package saved. Install it when ready.") self.status.setText("Verified package saved. Install it when ready.")
@@ -218,6 +264,12 @@ class UpdatePanel(QGroupBox):
self.handoff.start() self.handoff.start()
else: else:
self.status.setText(("Update unavailable. " if operation == "error" else "") + value) 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() self.set_controls()
def download_now(self): def download_now(self):
@@ -248,6 +300,7 @@ class UpdatePanel(QGroupBox):
from .about import installation from .about import installation
from .update_worker import prepare from .update_worker import prepare
release, artifact, target = self.release, self.downloaded, installation()[1] release, artifact, target = self.release, self.downloaded, installation()[1]
self.outcome = None
self.status.setText("Revalidating the package and preparing the maintenance launcher…") self.status.setText("Revalidating the package and preparing the maintenance launcher…")
self.progress.setRange(0, 0) self.progress.setRange(0, 0)
self.progress.show() self.progress.show()
@@ -258,19 +311,23 @@ class UpdatePanel(QGroupBox):
def poll_worker(self): def poll_worker(self):
self.elapsed += 250 self.elapsed += 250
try: status = read_json(self.plan / "status.json", {})
status = json.loads((self.plan / "status.json").read_bytes())
except (OSError, ValueError):
status = {}
if status.get("state") == "waiting": if status.get("state") == "waiting":
self.handoff.stop() self.handoff.stop()
self.quit_requested.emit() self.quit_requested.emit(self.plan)
elif status.get("state") == "failed" or self.elapsed > 70_000: elif status.get("state") == "failed" or self.elapsed > 70_000:
self.handoff.stop() 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.plan = None
self.status.setText(status.get("message") or "The maintenance launcher did not become ready. Installation was deferred.") self.accept_outcome((Phase.FAILED, message))
self.set_controls()
def set_controls(self): def set_controls(self):
available = self.release is not None and self.release.version != VERSION 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) idle and self.downloaded is not None)
for button, enabled in zip(self.buttons.values(), states): for button, enabled in zip(self.buttons.values(), states):
button.setEnabled(enabled) 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): def stop(self):
self.closing = True self.closing = True
self.cancel.set() self.cancel.set()
self.handoff.stop() self.handoff.stop()
self.periodic.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.""" """Independent Windows updater. Transaction data never includes the ARM user profile."""
import argparse import argparse
from contextlib import contextmanager
import json import json
import logging import logging
import msvcrt
import os import os
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
import re import re
@@ -21,6 +23,7 @@ from .branding import INSTALL_ID, PUBLISHER
from .config import data_path from .config import data_path
from .update_client import write_atomic from .update_client import write_atomic
from .update_release import MANIFEST, UpdateError, eligible, source_config, verify_file, verify_manifest 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 from .version import VERSION, read_version, version_key
EXE = "AdaptiveResourceMonitor.exe" EXE = "AdaptiveResourceMonitor.exe"
@@ -119,6 +122,45 @@ def set_status(plan_dir, state, message):
LOG.info("%s. %s", 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): def prepare(release, artifact, target, kind, root):
config = source_config() config = source_config()
signed = verify_manifest(release.envelope, config["public_key"], release.version) signed = verify_manifest(release.envelope, config["public_key"], release.version)
@@ -192,25 +234,45 @@ def remove_managed(path):
path.unlink() path.unlink()
def wait_parent(data, target, plan_dir): def requesting_process(data, target):
limit = monotonic() + 75 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: 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: try:
parent = psutil.Process(data["parent"]) parent = psutil.Process(data["parent"])
if abs(parent.create_time() - data["created"]) > 0.01: alive = 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")
except psutil.NoSuchProcess: except psutil.NoSuchProcess:
alive = False
if not alive:
if not acknowledged:
raise UpdateError("ARM exited without confirming that settings and history were closed. Installation stopped.")
return return
if (plan_dir / "abort").exists(): if Path(parent.exe()).resolve() != target / EXE:
raise UpdateError("Installation canceled before touching the application") raise UpdateError("The requesting process is not this Adaptive Resource Monitor installation.")
sleep(.25) 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): def restart(target, version, plan_dir):
ready = plan_dir / "ready.json" 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)})) child = subprocess.Popen([str(target / EXE)], cwd=target, env=dict(os.environ, **{ACK: str(ready)}))
try: try:
deadline = monotonic() + 35 deadline = monotonic() + 35
@@ -253,13 +315,17 @@ def transact(plan_dir, recover=False):
if journal.get("committed"): if journal.get("committed"):
remove_managed(work) remove_managed(work)
recovery_entry(plan_dir, False) recovery_entry(plan_dir, False)
set_status(plan_dir, "complete", f"Updated and restarted Adaptive Resource Monitor {data['new']}.")
return return
set_status(plan_dir, "recovering", "Restoring the previous application after an interrupted installation…")
rollback(target, work, journal) 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) 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 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"]) release = verify_manifest((plan_dir / MANIFEST).read_bytes(), source_config()["public_key"], data["new"])
view = registered_view(target) view = registered_view(target)
kind = "installed" if view is not None else "portable" 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) shutil.copy2(artifact, payload / package.name)
verify_file(payload / package.name, package) verify_file(payload / package.name, package)
verify_executable(payload / package.name, release.version) 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) 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): for name in managed_entries(target, view is not None):
safe_entry(target / name) safe_entry(target / name)
originals = managed_entries(target, view is not None) 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: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_READ | view) as key:
if winreg.QueryValueEx(key, "DisplayVersion")[0] != release.version: if winreg.QueryValueEx(key, "DisplayVersion")[0] != release.version:
raise UpdateError("Windows installer registration did not report the expected 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) verify_payload(target, release.version)
build = json.loads((target / "BUILD.json").read_bytes()) build = json.loads((target / "BUILD.json").read_bytes())
if (build.get("source_revision"), build.get("jenkins_build")) != (release.commit, release.build): if (build.get("source_revision"), build.get("jenkins_build")) != (release.commit, release.build):
raise UpdateError("Installed build identity does not match the signed manifest") 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) restart(target, release.version, plan_dir)
except Exception as exc: 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) 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) 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 return
journal["committed"] = True journal["committed"] = True
write_atomic(checkpoint, json.dumps(journal).encode()) write_atomic(checkpoint, json.dumps(journal).encode())
@@ -332,12 +406,9 @@ def transact(plan_dir, recover=False):
remove_managed(work) remove_managed(work)
def signal_ready(): def signal_ready(root=None):
if value := os.environ.pop(ACK, None): if directory := transaction_from_ack(root or data_path(), os.environ.pop(ACK, None)):
path = Path(value) write_atomic(directory / "ready.json", json.dumps({"version": VERSION, "pid": os.getpid()}).encode())
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 main(): def main():
@@ -351,10 +422,26 @@ def main():
return 2 return 2
logging.basicConfig(filename=plan_dir / "maintenance.log", level=logging.INFO, encoding="utf-8", logging.basicConfig(filename=plan_dir / "maintenance.log", level=logging.INFO, encoding="utf-8",
format="%(asctime)s %(levelname)s %(message)s") format="%(asctime)s %(levelname)s %(message)s")
try: def run():
transact(plan_dir, args.recover) try:
except Exception as exc: with update_lock(data_path()):
LOG.exception("Maintenance failed") set_status(plan_dir, "preparing", "Preparing the Adaptive Resource Monitor update…")
set_status(plan_dir, "failed", str(exc)) transact(plan_dir, args.recover)
return 1 except Exception as exc:
return 0 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) 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): class Monitor(QWidget):
def __init__(self, dashboard, expanded, request_archive, switch_expanded, set_pin, about_page=None): def __init__(self, dashboard, expanded, request_archive, switch_expanded, set_pin, about_page=None):
flags = Qt.WindowType.Window if expanded else ( flags = Qt.WindowType.Window if expanded else (
@@ -277,12 +305,18 @@ class Monitor(QWidget):
def popup_size(self): def popup_size(self):
cfg = self.dashboard.settings 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: 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 # Cap in HoverMonitor against the work area. The scroll area keeps
# six columns together even on a narrow monitor. # six columns together even on a narrow monitor.
rows_height = sum(max(138, section.sizeHint().height()) for section in self.sections.values()) 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): def sync_devices(self):
if not self.expanded: if not self.expanded:

View File

@@ -2,7 +2,8 @@
The Windows package includes CPython, Qt 6 and its PySide6 Python bindings, The Windows package includes CPython, Qt 6 and its PySide6 Python bindings,
psutil, Paramiko and its cryptographic dependencies, NVIDIA's NVML Python 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 provided by the driver. License text distributed by the dependency wheels
is included in this directory. is included in this directory.

View File

@@ -34,6 +34,8 @@ SetupIconFile={#AppIcon}
WizardImageFile={#WizardImage} WizardImageFile={#WizardImage}
WizardSmallImageFile={#WizardEmblem} WizardSmallImageFile={#WizardEmblem}
UninstallDisplayIcon={app}\{#Executable} UninstallDisplayIcon={app}\{#Executable}
CloseApplications=no
RestartApplications=no
[Tasks] [Tasks]
Name: "desktopicon"; Description: "Create a desktop shortcut"; Flags: unchecked 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 Filename: "{app}\{#Executable}"; Description: "Open Adaptive Resource Monitor"; Flags: nowait postinstall skipifsilent
[Code] [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; function ArmUpdate: Boolean;
begin begin
Result := ExpandConstant('{param:ARMUPDATE|0}') = '1'; Result := ExpandConstant('{param:ARMUPDATE|0}') = '1';

View File

@@ -9,6 +9,7 @@ import unittest
from unittest.mock import patch from unittest.mock import patch
from urllib.error import URLError from urllib.error import URLError
from zipfile import ZipFile from zipfile import ZipFile
import psutil
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey 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.config import Settings
from arm.update_client import ReleaseClient, UpdateCancelled from arm.update_client import ReleaseClient, UpdateCancelled
from arm.update_release import MANIFEST, UpdateError, artifact_name, canonical, verify_manifest 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 from arm.version import VERSION, version_key
COUNTERS = version_key(VERSION) COUNTERS = version_key(VERSION)
@@ -150,3 +152,49 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(Settings.from_dict({"update_startup": True, "update_interval": 168}).update_interval, 168) self.assertEqual(Settings.from_dict({"update_startup": True, "update_interval": 168}).update_interval, 168)
default = Settings.from_dict({"update_startup": "yes", "update_interval": 169}) default = Settings.from_dict({"update_startup": "yes", "update_interval": 169})
self.assertEqual((default.update_startup, default.update_interval), (False, 0)) 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.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 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): def evaluate_app(work, results, short=False, captures=None):
import psutil import psutil
from PySide6.QtCore import QEventLoop, QTimer 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 update.fields["Latest published"].text() == "No public releases"
assert "UTC" in update.fields["Last successful check"].text() assert "UTC" in update.fields["Last successful check"].text()
session.expanded.close() session.expanded.close()
verify_update_notices(session, wait_for, results, captures)
results["asynchronous_update_check_with_live_telemetry"] = True results["asynchronous_update_check_with_live_telemetry"] = True
modes = {} modes = {}
for mode in ("Stacked", STATIC_TRAY_MODE, "Overlay", "Composite"): 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" python_license = Path(sys.base_prefix) / "LICENSE.txt"
if python_license.is_file(): if python_license.is_file():
shutil.copyfile(python_license, notices / "Python-LICENSE.txt") 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") 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"), "--name", worker_name, "--paths", str(ROOT), "--workpath", str(temporary / "work"),
"--distpath", str(temporary / "maintenance"), "--specpath", str(temporary), "--distpath", str(temporary / "maintenance"), "--specpath", str(temporary),
"--version-file", str(version_file), "--manifest", str(ROOT / "packaging" / "windows.manifest"), "--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([ run([
sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed", sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed",