Add release packaging and automatic update support

This commit is contained in:
Elijah 2026-10-03 19:07:11 -07:00
parent 94cd6b984b
commit f971c374f8
20 changed files with 722 additions and 16 deletions

10
.config/dotnet-tools.json Normal file
View file

@ -0,0 +1,10 @@
{
"version": 1,
"isRoot": true,
"tools": {
"vpk": {
"version": "1.2.161",
"commands": ["vpk"]
}
}
}

2
.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
*.sh text eol=lf
*.ps1 text eol=crlf

View file

@ -1,17 +1,22 @@
param([switch]$Publish,[switch]$Test)
param([switch]$Publish,[switch]$Test,[switch]$Package)
$ErrorActionPreference='Stop'
Set-Location $PSScriptRoot
$env:DOTNET_CLI_HOME=Join-Path $PSScriptRoot '.tools/home'
$env:NUGET_PACKAGES=Join-Path $PSScriptRoot '.tools/packages'
$env:DOTNET_CLI_TELEMETRY_OPTOUT='1'
New-Item -ItemType Directory -Force '.tools/feed' | Out-Null
$sdk=Join-Path $PSScriptRoot '.tools/dotnet/dotnet.exe'
if (!(Test-Path $sdk)) { $sdk='dotnet' }
& $sdk build src/AstroFrame.Desktop -c Release
if ($LASTEXITCODE) { throw 'Build failed' }
& $sdk build tests/AstroFrame.Validation -c Release
if ($LASTEXITCODE) { throw 'Validation build failed' }
if ($Test) { & $sdk run --project tests/AstroFrame.Validation -c Release --no-build; if ($LASTEXITCODE) {throw 'Validation failed'} }
if ($Test) {
& $sdk run --project tests/AstroFrame.Validation -c Release --no-build; if ($LASTEXITCODE) {throw 'Validation failed'}
& $sdk run --project tests/AstroFrame.Updates.Validation -c Release; if ($LASTEXITCODE) {throw 'Update validation failed'}
}
if ($Publish) {
& $sdk publish src/AstroFrame.Desktop -c Release -r win-x64 --self-contained true -o artifacts/AstroFrame
if ($LASTEXITCODE) { throw 'Publish failed' }
}
if ($Package) { & ./packaging/Release.ps1; if ($LASTEXITCODE) { throw 'Packaging failed' } }

7
Directory.Build.props Normal file
View file

@ -0,0 +1,7 @@
<Project>
<PropertyGroup>
<Version>1.0.0</Version>
<Authors>Elijah Kuntz</Authors>
<Product>AstroFrame</Product>
</PropertyGroup>
</Project>

View file

@ -4,6 +4,10 @@ An independent Windows/Linux desktop application for selecting astrophotography
## Run on Windows
For packaged installations, run `AstroFrame-win-x64-Setup.exe`. Linux users can use `AstroFrame-linux-x64.AppImage` and the accompanying `install-linux.sh` for an application-menu entry. Both target x64 PCs. See [installation and releases](docs/releases.md) for Debian/Arch prerequisites and package-building instructions.
**Settings → Updates** shows the installed version and update status, with automatic and manual checks. Installed packages check the [public repository releases](https://git.elijahkuntz.com/Elijah/AstroFrame/releases) on startup and every six hours. A newer stable release adds an update indicator to Settings. **Install update and restart** downloads the release package and restarts after saving; active analysis/export must finish first. Preferences and projects survive updates. Git pushes become app updates only after a versioned release and its packages are published.
Open `artifacts/AstroFrame/AstroFrame.Desktop.exe`. This self-contained build does not require Python, a GPU, or a separate .NET installation. Keep the entire application folder together.
Windows enforces a **6 GiB process allocation limit** and a **3 GiB managed-heap limit**. Only one desktop instance can run at a time. Analysis uses up to four workers, leaving at least two logical processors unused where available. It rejects images exceeding a 256 MiB per-frame budget and pauses when it cannot leave roughly 25% of physical RAM free (up to 8 GiB). If pressure persists for 20 seconds, completed measurements are saved for resuming. The page file is not counted as available physical RAM. Windows software rendering is used during this release. The larger limit provides headroom; it does not allocate 6 GiB in advance.
@ -43,6 +47,7 @@ Requires a .NET 8 SDK. `Build.ps1` uses the workspace-local SDK if present, othe
```powershell
./Build.ps1 -Test
./Build.ps1 -Publish
./Build.ps1 -Package
```
Standard builds on Windows or Linux:
@ -53,7 +58,7 @@ dotnet run --project tests/AstroFrame.Validation -c Release
dotnet publish src/AstroFrame.Desktop -c Release -r linux-x64 --self-contained true -o artifacts/AstroFrame-linux
```
The Windows build and rendered layout were tested here. Linux uses Avalonia's X11 backend and bundled Skia/Harfbuzz binaries; actual Linux execution remains untested. A Linux desktop with the usual X11/font libraries is required.
The Windows build and rendered layout were tested here. Linux uses Avalonia's X11 backend and bundled Skia/Harfbuzz binaries; packaged Linux startup, settings rendering, installation and self-updates were also exercised under Ubuntu WSL. Debian/Arch desktop acceptance remains to be checked directly. A Linux desktop with the usual X11/font/ICU libraries is required; see [installation and releases](docs/releases.md).
Prebuilt Linux files are in `artifacts/AstroFrame-linux`. On Linux, run `chmod +x AstroFrame.Desktop` before launching if executable permissions were lost during transfer. The managed-heap limit and RAM-pressure monitoring also apply on Linux; the Windows kernel job limit does not.

107
docs/releases.md Normal file
View file

@ -0,0 +1,107 @@
# Installing and releasing AstroFrame
## First release
Version **1.0.0** targets x64 Windows and Linux desktops. Windows uses a per-user Velopack installer. Linux uses one self-contained AppImage plus an optional per-user application-menu installer; the same binary targets both Debian and Arch. No Git client, Python, .NET runtime installation or administrator access is required to install AstroFrame itself.
### Windows
Run `AstroFrame-win-x64-Setup.exe`. Setup creates application-menu and desktop shortcuts and an uninstall entry. Installations live under the user's local application-data directory. Updates replace the application files while leaving projects and preferences in their separate data directory.
These first packages are unsigned; Windows may display its unknown-publisher/SmartScreen prompt. Signing requires the maintainer's own signing certificate or signing service, and can be added to the Velopack pack command later.
### Linux: Debian and Arch
Use a current x64 desktop with X11, or a Wayland desktop with XWayland. The AppImage bundles .NET and Avalonia; it still uses normal Linux system libraries. Debian 12/13 and current Arch are the intended targets. Minimal/server installations may need the following prerequisites.
Debian 12:
```sh
sudo apt install libicu72 libx11-6 libice6 libsm6 libfontconfig1 libxrandr2 libxi6 libxcursor1 libxrender1 libxext6 libfuse2 ca-certificates
```
Debian 13 uses `libicu76` and `libfuse2t64` instead of `libicu72` and `libfuse2`. On Arch:
```sh
sudo pacman -Syu --needed icu libx11 libice libsm fontconfig libxrandr libxi libxcursor libxrender libxext fuse2 ca-certificates
```
AppImage runtimes may fall back to extraction when FUSE is unavailable. `APPIMAGE_EXTRACT_AND_RUN=1 ./AstroFrame-linux-x64.AppImage` explicitly requests that mode.
The Windows build also creates `AstroFrame-<version>-linux-x64.zip` containing the AppImage and installation helpers. Extract it, or download `AstroFrame-linux-x64.AppImage`, `install-linux.sh` and `astroframe.png` into the same folder. Then:
```sh
bash install-linux.sh ./AstroFrame-linux-x64.AppImage
```
This puts the AppImage in `$XDG_DATA_HOME/AstroFrame/app/` (normally `~/.local/share/AstroFrame/app/`) and adds an **AstroFrame** application-menu entry. It keeps the AppImage writable for updates. Alternatively, `chmod +x AstroFrame-linux-x64.AppImage` and run the file directly from a writable folder.
To uninstall a script-installed Linux copy, close AstroFrame and remove only `~/.local/share/AstroFrame/app`, `~/.local/share/applications/astroframe.desktop` and `~/.local/share/icons/hicolor/256x256/apps/astroframe.png` (adjust paths if using `XDG_DATA_HOME`). Keep the other AstroFrame directories to preserve projects and settings.
## Settings and updates
Open **Settings → Updates** for the installed version, update status, last successful check, automatic-check preference, and **Check for updates**. The sidebar and independent settings store leave room for future categories.
Installed packages check on launch and every six hours while running. A persistent **Settings · Update available** indicator appears when a newer stable version is found. **Install update and restart** downloads the update, validates its package checksum, saves the project and restarts. Analysis, export and saving block installation; if work starts during download, the package remains ready for a later restart. Projects and settings survive updates. Failed checks display an error rather than claiming the app is up to date. Source-tree builds explain that installing a package enables updates.
The source is the repository's public Gitea releases API:
<https://git.elijahkuntz.com/Elijah/AstroFrame/releases>
Only published stable release assets are consumed. Git commits by themselves do not trigger an update. End-user installations contain no repository write token. Packages use separate `win-x64` and `linux-x64` channels. Versions never downgrade automatically.
## Build release packages
Set the next stable version in `Directory.Build.props`. `-Version` can override it for a build. The application and package versions must match. A .NET 10 SDK/runtime is needed for the pinned Velopack CLI; the application itself targets .NET 8 and is published self-contained. Use PowerShell 7 for the release scripts.
```powershell
./Build.ps1 -Test
./packaging/Release.ps1
```
The Windows script cross-packages both platforms. Results appear in `artifacts/releases/win-x64` and `artifacts/releases/linux-x64`. It refuses to reuse an existing publish folder, avoiding stale application files. For an intentional local rebuild use a fresh `-PublishRoot artifacts/publish-candidate` and a fresh `-Output artifacts/releases-candidate`; published version numbers must remain immutable.
On Linux with a .NET 10 SDK:
```sh
bash packaging/release.sh 1.0.0
```
That script builds the Linux channel. The tool manifest pins Velopack CLI 1.2.161, matching the application's SDK dependency. Building on Windows is enough to create both packages, but compatibility should still be checked on target Linux desktops.
## Publish to the repository
Commit and push the versioned source first. The initial release has **not** been uploaded by this implementation. To make update discovery live, create a public stable release tagged `v1.0.0` and attach the files described below.
The helper script reads a Gitea repository-write token from `ASTROFRAME_RELEASE_TOKEN` in the process environment. It uploads both platforms into one draft, including the Linux installation helpers. It does not store the token or embed it in the application:
```powershell
./packaging/Publish.ps1
```
Review the draft in Gitea and publish it there. For a deliberately immediate publication use `./packaging/Publish.ps1 -Publish`. The script refuses to modify an already published version. If a partial upload fails, delete the incomplete draft and retry, or attach the remaining files manually. Do not put the token in a script, commit, or command history.
For manual publication attach, from **both** channel folders:
- `AstroFrame-<version>-<channel>-full.nupkg` and any generated delta package;
- `releases.<channel>.json`, `RELEASES-<channel>` and `assets.<channel>.json`;
- the Windows Setup executable and Linux AppImage;
- `install-linux.sh` and `astroframe.png`.
Keep older published releases available. The CLI can produce delta packages when previous packages are in the output folder. Full packages always support upgrading from older installs, even without a delta.
For later releases: change the version, validate, build, push the corresponding source, and publish a new stable tagged release with both channels. Existing installations then receive the notification and can update without reinstalling.
## Verification
`tests/AstroFrame.Updates.Validation` covers settings recovery, network failures, concurrent checks, restart safety, save failure, real package checksums, corruption rejection and downgrade prevention. An optional release-feed argument adds real-package checks:
```powershell
dotnet run --project tests/AstroFrame.Updates.Validation -c Release -- artifacts/update-verification/releases/win-x64 win-x64
```
That test feed must contain a **1.0.1** package for the requested channel; it is not a production release. An explicit packaged-app `--verify-update <local feed directory> <report.jsonl> --apply` probe verifies actual replacement and restart. A `--capture-settings <output.png> [width] [dpi]` diagnostic captures the real settings page.
Both Windows and Linux local 1.0.0 → 1.0.1 replacement/restart were exercised during implementation. Linux rendering and per-user installation were checked under Ubuntu WSL with the missing ICU/X11 libraries extracted into a workspace test directory. Debian and Arch desktop execution have not yet been tested directly; those compatibility targets are based on the cross-platform runtime and documented system dependencies, not separate distro acceptance runs. The public repository API was verified anonymously; it currently contains no published releases.
References: [Velopack C# integration](https://docs.velopack.io/getting-started/csharp), [cross-packaging](https://docs.velopack.io/packaging/cross-compiling), [Linux update behavior](https://docs.velopack.io/packaging/operating-systems/linux), [Gitea distribution](https://docs.velopack.io/distributing/self-hosting), [Avalonia Linux dependencies](https://v11.docs.avaloniaui.net/docs/overview/supported-platforms/).

47
packaging/Publish.ps1 Normal file
View file

@ -0,0 +1,47 @@
param([string]$Version = '', [string]$Directory = 'artifacts/releases', [switch]$Publish)
$ErrorActionPreference = 'Stop'
Set-Location (Split-Path $PSScriptRoot)
if (!$Version) { [xml]$props = Get-Content Directory.Build.props; $Version = $props.Project.PropertyGroup.Version }
if ($Version -notmatch '^\d+\.\d+\.\d+$') { throw 'Use a stable version such as 1.0.0.' }
if (!$env:ASTROFRAME_RELEASE_TOKEN) { throw 'Set ASTROFRAME_RELEASE_TOKEN to a Gitea token with repository write permission. Never put it in source control.' }
$headers = @{ Authorization = "token $env:ASTROFRAME_RELEASE_TOKEN" }
$api = 'https://git.elijahkuntz.com/api/v1/repos/Elijah/AstroFrame'
$files = @()
foreach ($channel in @('win-x64','linux-x64')) {
$folder = Join-Path $Directory $channel
$feedPath = Join-Path $folder "releases.$channel.json"
if (!(Test-Path $feedPath)) { throw "Missing release feed: $feedPath" }
$feed = Get-Content $feedPath -Raw | ConvertFrom-Json
$latest = @($feed.Assets | Where-Object { $_.Type -eq 'Full' -and $_.Version -eq $Version })
if ($latest.Count -ne 1) { throw "No full $Version release for $channel" }
$files += @(Get-ChildItem -LiteralPath $folder -File | Where-Object { $_.Extension -in @('.exe','.AppImage','.nupkg','.json','.sh','.png','.zip') -or $_.Name -like 'RELEASES-*' })
}
foreach ($file in $files) {
if ($file.Extension -eq '.nupkg' -and $file.Name -notlike "AstroFrame-$Version-*") { continue }
if ($file.Length -eq 0) { throw "Empty release asset: $($file.Name)" }
}
$commit = (& git rev-parse HEAD).Trim()
if ($LASTEXITCODE) { throw 'Cannot identify the release commit.' }
if (@(& git status --porcelain).Count -gt 0) { throw 'Commit the release source and push it before publishing.' }
Invoke-RestMethod "$api/commits/$commit" -Headers $headers | Out-Null
$tag = "v$Version"
$release = $null
try { $release = Invoke-RestMethod "$api/releases/tags/$tag" -Headers $headers }
catch { if ([int]$_.Exception.Response.StatusCode -ne 404) { throw } }
if ($release -and !$release.draft) { throw "$tag is already published. Release assets are immutable; build a new version." }
if (!$release) {
$body = @{ tag_name=$tag; target_commitish=$commit; name="AstroFrame $Version"; body="AstroFrame $Version for Windows and Linux. See the repository README for installation and update instructions."; draft=$true; prerelease=$false } | ConvertTo-Json
$release = Invoke-RestMethod "$api/releases" -Method Post -Headers $headers -ContentType 'application/json' -Body $body
}
$attached = @(Invoke-RestMethod "$api/releases/$($release.id)/assets" -Headers $headers)
foreach ($file in $files) {
if ($file.Extension -eq '.nupkg' -and $file.Name -notlike "AstroFrame-$Version-*") { continue }
if ($attached.name -contains $file.Name) { throw "Draft already contains $($file.Name). Remove the conflicting asset explicitly before retrying." }
$name = [Uri]::EscapeDataString($file.Name)
Invoke-RestMethod "$api/releases/$($release.id)/assets?name=$name" -Method Post -Headers $headers -Form @{ attachment=$file } | Out-Null
Write-Output "Attached $($file.Name)"
}
if ($Publish) {
Invoke-RestMethod "$api/releases/$($release.id)" -Method Patch -Headers $headers -ContentType 'application/json' -Body '{"draft":false}' | Out-Null
Write-Output "Published $($release.html_url)"
} else { Write-Output "Draft release ready: $($release.html_url). Review it, then publish in Gitea." }

46
packaging/Release.ps1 Normal file
View file

@ -0,0 +1,46 @@
param(
[string]$Version = '',
[ValidateSet('Both','Windows','Linux')][string]$Platform = 'Both',
[string]$Output = 'artifacts/releases',
[string]$PublishRoot = 'artifacts/publish'
)
$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot
Set-Location $root
if (!$Version) { [xml]$props = Get-Content Directory.Build.props; $Version = $props.Project.PropertyGroup.Version }
if ($Version -notmatch '^\d+\.\d+\.\d+$') { throw 'Use a stable version such as 1.0.0.' }
$env:DOTNET_CLI_HOME = Join-Path $root '.tools/home'
$env:NUGET_PACKAGES = Join-Path $root '.tools/packages'
$env:DOTNET_CLI_TELEMETRY_OPTOUT = '1'
New-Item -ItemType Directory -Force '.tools/feed' | Out-Null
$sdk = Join-Path $root '.tools/dotnet/dotnet.exe'
if (!(Test-Path $sdk)) { $sdk = 'dotnet' }
$localVpk = Join-Path $root '.tools/vpk/vpk.exe'
if (!(Test-Path $localVpk)) {
& dotnet tool restore
if ($LASTEXITCODE) { throw 'Velopack restore failed. Its CLI requires a .NET 10 SDK/runtime.' }
}
function Invoke-Vpk([string[]]$Arguments) {
if (Test-Path $localVpk) { & $localVpk @Arguments } else { & dotnet tool run vpk -- @Arguments }
if ($LASTEXITCODE) { throw 'Velopack packaging failed.' }
}
foreach ($rid in @('win-x64','linux-x64')) {
if ($Platform -eq 'Windows' -and $rid -ne 'win-x64') { continue }
if ($Platform -eq 'Linux' -and $rid -ne 'linux-x64') { continue }
$publish = Join-Path (Join-Path $root $PublishRoot) "$Version/$rid"
$releases = Join-Path $Output $rid
if (Test-Path $publish) { throw "Publish folder already exists: $publish. Use a fresh version or remove that build folder explicitly." }
& $sdk publish src/AstroFrame.Desktop -c Release -r $rid --self-contained true "-p:Version=$Version" -o $publish
if ($LASTEXITCODE) { throw "Publish failed for $rid" }
$argsList = @("[$(if($rid -eq 'win-x64'){'win'}else{'linux'})]", 'pack', '--packId', 'AstroFrame', '--packTitle', 'AstroFrame', '--packAuthors', 'Elijah Kuntz', '--packVersion', $Version, '--packDir', $publish, '--runtime', $rid, '--channel', $rid, '--outputDir', $releases)
if ($rid -eq 'win-x64') { $argsList += @('--mainExe','AstroFrame.Desktop.exe','--icon','src/AstroFrame.Desktop/Assets/astroframe.ico','--noPortable') }
else { $argsList += @('--mainExe','AstroFrame.Desktop','--icon','src/AstroFrame.Desktop/Assets/astroframe.png','--categories','Science;Astronomy;') }
Invoke-Vpk $argsList
if ($rid -eq 'linux-x64') {
Copy-Item -LiteralPath 'packaging/install-linux.sh' -Destination $releases
Copy-Item -LiteralPath 'src/AstroFrame.Desktop/Assets/astroframe.png' -Destination (Join-Path $releases 'astroframe.png')
$bundle = Join-Path $releases "AstroFrame-$Version-linux-x64.zip"
Compress-Archive -LiteralPath @((Join-Path $releases 'AstroFrame-linux-x64.AppImage'),(Join-Path $releases 'install-linux.sh'),(Join-Path $releases 'astroframe.png')) -DestinationPath $bundle -Force
}
}
Write-Output "Release $Version built in $Output. Upload all channel files to one Gitea release; see docs/releases.md."

View file

@ -0,0 +1,42 @@
#!/usr/bin/env bash
set -euo pipefail
# Install per-user, keeping the AppImage writable for in-app updates.
source_image="${1:?Usage: bash install-linux.sh /path/to/AstroFrame.AppImage}"
[[ -f "$source_image" ]] || { echo 'AppImage file does not exist.' >&2; exit 1; }
[[ "$(uname -m)" == x86_64 ]] || { echo 'This release requires an x64 PC.' >&2; exit 1; }
install_dir="${XDG_DATA_HOME:-$HOME/.local/share}/AstroFrame/app"
menu_dir="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
icon_dir="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
mkdir -p "$install_dir" "$menu_dir" "$icon_dir"
target="$install_dir/AstroFrame.AppImage"
if [[ -e "$target" && "$source_image" -ef "$target" ]]; then
chmod +x "$target"
else
install -m 755 "$source_image" "$target"
fi
script_dir="$(cd "$(dirname "$0")" && pwd)"
if [[ -f "$script_dir/astroframe.png" ]]; then
install -m 644 "$script_dir/astroframe.png" "$icon_dir/astroframe.png"
fi
# Use a wrapper so desktop files do not need to parse/escape user directory paths.
printf '#!/usr/bin/env bash\nexec %q "$@"\n' "$target" > "$install_dir/launch"
chmod +x "$install_dir/launch"
escaped_launcher="${install_dir//\\/\\\\}/launch"
escaped_launcher="${escaped_launcher//\"/\\\"}"
escaped_launcher="${escaped_launcher//\$/\\\$}"
escaped_launcher="${escaped_launcher//\`/\\\`}"
escaped_launcher="${escaped_launcher//%/%%}"
cat > "$menu_dir/astroframe.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=AstroFrame
Comment=Select astrophotography light frames
Exec="$escaped_launcher" %U
Icon=astroframe
Terminal=false
Categories=Science;Astronomy;
StartupWMClass=AstroFrame.Desktop
EOF
chmod 644 "$menu_dir/astroframe.desktop"
if command -v update-desktop-database >/dev/null 2>&1; then update-desktop-database "$menu_dir"; fi
echo "Installed to $target. Launch AstroFrame from your application menu."

17
packaging/release.sh Normal file
View file

@ -0,0 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
version="${1:-$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | tr -d '\r')}"
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Use a stable version such as 1.0.0.' >&2; exit 1; }
export DOTNET_CLI_HOME="$PWD/.tools/home-linux"
export NUGET_PACKAGES="$PWD/.tools/packages-linux"
export DOTNET_CLI_TELEMETRY_OPTOUT=1
mkdir -p .tools/feed
dotnet tool restore
publish="$PWD/artifacts/publish/$version/linux-x64"
output="$PWD/artifacts/releases/linux-x64"
[[ ! -e "$publish" ]] || { echo "Publish folder already exists: $publish" >&2; exit 1; }
dotnet publish src/AstroFrame.Desktop -c Release -r linux-x64 --self-contained true "-p:Version=$version" -o "$publish"
dotnet tool run vpk -- '[linux]' pack --packId AstroFrame --packTitle AstroFrame --packAuthors 'Elijah Kuntz' --packVersion "$version" --packDir "$publish" --mainExe AstroFrame.Desktop --runtime linux-x64 --channel linux-x64 --icon src/AstroFrame.Desktop/Assets/astroframe.png --categories 'Science;Astronomy;' --outputDir "$output"
cp packaging/install-linux.sh src/AstroFrame.Desktop/Assets/astroframe.png "$output/"
echo "Release $version built in $output. See docs/releases.md before publishing."

View file

@ -0,0 +1,31 @@
using System.Text.Json;
namespace AstroFrame.Desktop;
public sealed class AppSettings
{
public bool AutomaticallyCheckForUpdates { get; set; } = true;
public DateTimeOffset? LastUpdateCheck { get; set; }
public static string DataDirectory => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AstroFrame");
public static string SettingsPath => Path.Combine(DataDirectory, "settings.json");
public static AppSettings Load(string? path = null)
{
path ??= SettingsPath;
try
{
if (!File.Exists(path) || new FileInfo(path).Length > 64 * 1024) return new();
return JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(path)) ?? new();
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { return new(); }
}
public void Save(string? path = null)
{
path ??= SettingsPath;
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
string temporary = path + ".tmp";
File.WriteAllText(temporary, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, path, true);
}
}

View file

@ -0,0 +1,126 @@
using System.Reflection;
using Velopack;
using Velopack.Sources;
namespace AstroFrame.Desktop;
public interface IUpdateBackend
{
bool IsInstalled { get; }
string InstalledVersion { get; }
Task<string?> Check();
Task Download(Action<int> progress, CancellationToken cancellation);
void ApplyAndRestart(string[] arguments);
}
public sealed class ReleaseUpdateBackend : IUpdateBackend
{
public const string Repository = "https://git.elijahkuntz.com/Elijah/AstroFrame";
readonly UpdateManager manager;
UpdateInfo? available;
public ReleaseUpdateBackend()
{
manager = new UpdateManager(new GiteaSource(Repository, null, false), new UpdateOptions
{
ExplicitChannel = OperatingSystem.IsWindows() ? "win-x64" : "linux-x64",
AllowVersionDowngrade = false
});
}
public bool IsInstalled => manager.IsInstalled;
public string InstalledVersion => manager.CurrentVersion?.ToString()
?? typeof(ReleaseUpdateBackend).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0]
?? "1.0.0";
public async Task<string?> Check()
{
available = await manager.CheckForUpdatesAsync();
return available?.TargetFullRelease.Version.ToString();
}
public Task Download(Action<int> progress, CancellationToken cancellation) =>
manager.DownloadUpdatesAsync(available ?? throw new InvalidOperationException("Check for updates first."), progress, cancellation);
public void ApplyAndRestart(string[] arguments) =>
manager.WaitExitThenApplyUpdates(available!.TargetFullRelease, silent: false, restart: true, restartArgs: arguments);
}
// Independent of the settings view so notifications and future settings pages share one state.
// All state changes and callbacks run on the UI context when called by the desktop application.
public sealed class AppUpdates : IDisposable
{
readonly IUpdateBackend backend;
readonly Action<AppSettings> saveSettings;
readonly CancellationTokenSource lifetime = new();
public AppSettings Settings { get; }
public string InstalledVersion => backend.InstalledVersion;
public bool IsInstalled => backend.IsInstalled;
public bool Working { get; private set; }
public bool Applying { get; private set; }
public bool Ready { get; private set; }
public string? AvailableVersion { get; private set; }
public string Message { get; private set; }
public event Action? Changed;
public AppUpdates(IUpdateBackend? backend = null, AppSettings? settings = null, Action<AppSettings>? saveSettings = null)
{
this.backend = backend ?? new ReleaseUpdateBackend();
Settings = settings ?? AppSettings.Load();
this.saveSettings = saveSettings ?? (s => s.Save());
Message = IsInstalled ? "Updates have not been checked in this session." : "Install the Windows package or run the Linux AppImage to enable updates.";
}
void Notify() => Changed?.Invoke();
public bool SetAutomaticChecks(bool enabled)
{
bool previous = Settings.AutomaticallyCheckForUpdates;
Settings.AutomaticallyCheckForUpdates = enabled;
try { saveSettings(Settings); Notify(); return true; }
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
Settings.AutomaticallyCheckForUpdates = previous;
Message = "Could not save settings: " + e.Message; Notify(); return false;
}
}
public async Task Check(bool automatic = false)
{
if (Working || Applying || lifetime.IsCancellationRequested || !IsInstalled || (automatic && !Settings.AutomaticallyCheckForUpdates)) return;
Working = true; Message = "Checking for updates…"; Notify();
try
{
string? latest = await backend.Check();
if (latest != AvailableVersion) Ready = false;
AvailableVersion = latest;
if (lifetime.IsCancellationRequested) return;
Settings.LastUpdateCheck = DateTimeOffset.UtcNow;
Message = AvailableVersion == null ? "You are up to date." : Ready ? $"Version {AvailableVersion} is ready to install." : $"Version {AvailableVersion} is available.";
try { saveSettings(Settings); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { Message += " The check time could not be saved."; }
}
catch (Exception e) { Message = "Could not check for updates. " + e.Message; }
finally { Working = false; Notify(); }
}
public async Task<bool> Install(Func<bool> canRestart, Func<Task<bool>> saveBeforeRestart, string[] arguments)
{
if (Working || Applying || AvailableVersion == null || lifetime.IsCancellationRequested) return false;
if (!canRestart()) { Message = "Finish analysis, export, or saving before installing the update."; Notify(); return false; }
Working = true; Notify();
try
{
if (!Ready)
{
Message = "Downloading update…"; Notify();
var progress = new Progress<int>(value => { if (!lifetime.IsCancellationRequested && Working && !Ready && !Applying) { Message = $"Downloading update… {value}%"; Notify(); } });
await backend.Download(value => ((IProgress<int>)progress).Report(value), lifetime.Token);
Ready = true;
}
if (lifetime.IsCancellationRequested) return false;
// Work may have started during download. Never interrupt it to install.
if (!canRestart()) { Message = "Update downloaded. Finish analysis, export, or saving, then install."; return false; }
Applying = true; Notify(); // locks new work while the project is saved
if (!await saveBeforeRestart()) { Applying = false; Message = "Update downloaded. Save the project successfully before restarting."; return false; }
backend.ApplyAndRestart(arguments);
Message = "Restarting to install the update…";
return true;
}
catch (OperationCanceledException) { Applying = false; Message = "Update download cancelled."; return false; }
catch (Exception e) { Applying = false; Message = "Could not install the update. " + e.Message; return false; }
finally { Working = false; Notify(); }
}
public void Dispose() { lifetime.Cancel(); }
}

View file

@ -16,6 +16,9 @@
<PackageReference Include="Avalonia.Desktop" Version="11.3.9" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.9" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.9" />
<PackageReference Include="Velopack" Version="1.2.161" />
<!-- Compatible security backport for Avalonia's Linux D-Bus dependency (CVE-2026-39959). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,47 @@
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.Controls.ApplicationLifetimes;
namespace AstroFrame.Desktop;
public sealed partial class MainWindow
{
readonly AppUpdates updates = new();
readonly Button settingsButton = Button("Settings");
readonly DispatcherTimer updateTimer = new() { Interval = TimeSpan.FromHours(6) };
SettingsWindow? settingsWindow;
void InitializeUpdates()
{
settingsButton.Click += (_, _) => ShowSettings();
updates.Changed += () =>
{
settingsButton.Content = updates.AvailableVersion == null ? "Settings" : "Settings · Update available";
if (updates.Applying) { analyze.IsEnabled = false; export.IsEnabled = false; }
};
bool diagnostic = Program.Arguments.Any(a => a.StartsWith("--capture") || a == "--smoke");
if (!diagnostic)
{
Opened += async (_, _) => await updates.Check(automatic: true);
updateTimer.Tick += async (_, _) => await updates.Check(automatic: true);
updateTimer.Start();
}
Closed += (_, _) => { updateTimer.Stop(); updates.Dispose(); settingsWindow?.Close(); };
}
public SettingsWindow ShowSettings()
{
if (settingsWindow != null) { settingsWindow.Activate(); return settingsWindow; }
settingsWindow = new SettingsWindow(updates, InstallUpdate);
settingsWindow.Closed += (_, _) => settingsWindow = null;
settingsWindow.Show(this);
return settingsWindow;
}
async Task InstallUpdate()
{
bool analyzeEnabled = analyze.IsEnabled, exportEnabled = export.IsEnabled;
bool restarting = await updates.Install(() => !busy && !saving, async () => project == null || await Save(),
project == null ? [] : ["--project", projectDirectory]);
if (restarting && Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.Shutdown();
else { analyze.IsEnabled = analyzeEnabled; export.IsEnabled = exportEnabled; }
}
}

View file

@ -13,7 +13,7 @@ using System.Security.Cryptography;
using System.Text;
namespace AstroFrame.Desktop;
public sealed class MainWindow:Window
public sealed partial class MainWindow:Window
{
Project? project;string projectDirectory="";CancellationTokenSource? cancellation;bool busy,refreshing,saving;
readonly SemaphoreSlim saveGate=new(1);
@ -65,7 +65,7 @@ public sealed class MainWindow:Window
var header=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(22,0,22,2)};Grid.SetRow(header,1);
var heading=new StackPanel{Orientation=Orientation.Horizontal,Spacing=12,VerticalAlignment=VerticalAlignment.Center};title.MinWidth=140;title.MaxWidth=330;title.TextTrimming=TextTrimming.CharacterEllipsis;title.VerticalAlignment=subtitle.VerticalAlignment=VerticalAlignment.Center;heading.Children.Add(title);heading.Children.Add(subtitle);header.Children.Add(heading);
var toolbar=new WrapPanel{Orientation=Orientation.Horizontal,HorizontalAlignment=HorizontalAlignment.Right,VerticalAlignment=VerticalAlignment.Center};
foreach(var b in new[]{analyze,export}){b.Margin=new(8,1,0,1);toolbar.Children.Add(b);}Grid.SetColumn(toolbar,1);header.Children.Add(toolbar);headerSurface.Children.Add(header);
foreach(var b in new[]{analyze,export,settingsButton}){b.Margin=new(8,1,0,1);toolbar.Children.Add(b);}Grid.SetColumn(toolbar,1);header.Children.Add(toolbar);headerSurface.Children.Add(header);
var scope=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(20,7,20,7)};
sessions.ItemTemplate=new FuncDataTemplate<string>((text,_)=>SessionRow(text??""));sessions.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};scope.Children.Add(sessions);
var stats=new StackPanel{Orientation=Orientation.Horizontal,Spacing=28,VerticalAlignment=VerticalAlignment.Center};
@ -96,13 +96,13 @@ public sealed class MainWindow:Window
spatial.IsCheckedChanged+=(_,_)=>{preview.Spatial=spatial.IsChecked==true;preview.InvalidateVisual();};compare.IsCheckedChanged+=(_,_)=>UpdateComparison();
KeyDown+=async(_,e)=>
{
if(busy||e.Source is TextBox)return;
if(busy||updates.Applying||e.Source is TextBox)return;
if(e.Key==Key.J){Move(-1);e.Handled=true;}if(e.Key==Key.K){Move(1);e.Handled=true;}
if(e.Key is Key.D1 or Key.NumPad1){await Override(Verdict.Keep);e.Handled=true;}if(e.Key is Key.D2 or Key.NumPad2){await Override(Verdict.Review);e.Handled=true;}if(e.Key is Key.D3 or Key.NumPad3){await Override(Verdict.Reject);e.Handled=true;}
if(e.Key==Key.Z&&e.KeyModifiers.HasFlag(KeyModifiers.Control)&&undo.Count>0){var item=undo.Pop();item.Frame.Override=item.Verdict;item.Frame.Note=item.Note;item.Frame.ReviewedAt=item.At;await Save();RefreshFrames(item.Frame);e.Handled=true;}
};
Closing+=(_,e)=>{if(busy){e.Cancel=true;cancellation?.Cancel();status.Text="Stopping safely; close again when finished";}};
Closed+=(_,_)=>{preview.Dispose();comparison.Dispose();};ShowEmpty();
Closed+=(_,_)=>{preview.Dispose();comparison.Dispose();};ShowEmpty();InitializeUpdates();
}
static Button Button(string text,bool primary=false)=>new(){Content=text,Padding=new(12,7),CornerRadius=new(2),Background=primary?Palette.Accent:Palette.Raised,Foreground=primary?Palette.Background:Palette.Text};
static Border Panel(Control child)=>new(){Background=Palette.Panel,BorderBrush=Palette.Line,BorderThickness=new(.5),CornerRadius=new(2),ClipToBounds=true,Child=child};
@ -232,7 +232,7 @@ public sealed class MainWindow:Window
void Move(int step){if(visible.Count==0)return;int index=selected==null?0:visible.IndexOf(selected);var f=visible[Math.Clamp(index+step,0,visible.Count-1)];frames.SelectedItem=f;frames.ScrollIntoView(f);}
async Task Override(Verdict? verdict,bool advance=true)
{
if(selected==null||busy||saving)return;var f=selected;int index=visible.IndexOf(f);undo.Push((f,f.Override,f.Note,f.ReviewedAt));f.Override=verdict;f.ReviewedAt=DateTime.UtcNow;
if(selected==null||busy||saving||updates.Applying)return;var f=selected;int index=visible.IndexOf(f);undo.Push((f,f.Override,f.Note,f.ReviewedAt));f.Override=verdict;f.ReviewedAt=DateTime.UtcNow;
if(!await Save()){var previous=undo.Pop();f.Override=previous.Verdict;f.Note=previous.Note;f.ReviewedAt=previous.At;RefreshFrames(f);status.Text="Review could not be saved; decision restored";return;}
var next=advance?visible.ElementAtOrDefault(index+1)??visible.ElementAtOrDefault(index-1):f;RefreshFrames(next);status.Text="Manual decision saved · Ctrl+Z to undo";
}
@ -241,19 +241,20 @@ public sealed class MainWindow:Window
if(project==null)return false;await saveGate.WaitAsync();saving=true;analyze.IsEnabled=export.IsEnabled=false;
try{var p=project;var directory=projectDirectory;await Task.Run(()=>ProjectStore.Save(p,directory));return true;}
catch(Exception e){await Message("Could not save project",e.Message);return false;}
finally{saving=false;analyze.IsEnabled=!busy;export.IsEnabled=!busy&&project.Complete;saveGate.Release();}
finally{saving=false;analyze.IsEnabled=!busy&&!updates.Applying;export.IsEnabled=!busy&&!updates.Applying&&project.Complete;saveGate.Release();}
}
async Task<string?> Folder(string title)
{var result=await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions{Title=title,AllowMultiple=false});return result.FirstOrDefault()?.TryGetLocalPath();}
void Busy(bool value){busy=value;analyze.IsEnabled=!value;export.IsEnabled=!value&&project?.Complete==true;frames.IsEnabled=sessions.IsEnabled=chart.IsEnabled=filter.IsEnabled=sort.IsEnabled=metric.IsEnabled=!value;inspector.IsEnabled=!value;stop.IsVisible=progress.IsVisible=value;}
async Task Analyze()
{
if(busy||saving||updates.Applying)return;
string? source=project?.Source;
if(source!=null)
{
bool same=await Confirm("Analyze lights","Reanalyze the current source folder using cached measurements, or choose another folder?","Current source","Choose folder");if(!same)source=null;
}
source??=await Folder("Choose a folder containing raw FITS lights");if(source==null)return;
source??=await Folder("Choose a folder containing raw FITS lights");if(source==null||updates.Applying)return;
if(project?.Source!=source)
{
string hash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source)))[..16];
@ -261,10 +262,10 @@ public sealed class MainWindow:Window
project=File.Exists(System.IO.Path.Combine(projectDirectory,"project.json"))?ProjectStore.Load(projectDirectory):null;
}
Busy(true);cancellation=new();progress.Value=0;
var updates=new Progress<ProgressInfo>(p=>{progress.Value=p.Total==0?0:100.0*p.Done/p.Total;status.Text=$"{p.Stage} · {p.Done:N0} / {p.Total:N0} · {p.File}";});
var analysisProgress=new Progress<ProgressInfo>(p=>{progress.Value=p.Total==0?0:100.0*p.Done/p.Total;status.Text=$"{p.Stage} · {p.Done:N0} / {p.Total:N0} · {p.File}";});
try
{
var previous=project;await Task.Run(async()=>project=await new Analyzer().AnalyzeAsync(source,projectDirectory,previous,updates,cancellation.Token));LoadProject(projectDirectory);
var previous=project;await Task.Run(async()=>project=await new Analyzer().AnalyzeAsync(source,projectDirectory,previous,analysisProgress,cancellation.Token));LoadProject(projectDirectory);
}
catch(OperationCanceledException){if(File.Exists(System.IO.Path.Combine(projectDirectory,"project.json")))LoadProject(projectDirectory);status.Text="Cancelled · completed measurements saved; reanalyze to resume";}
catch(ResourcePressureException e){if(File.Exists(System.IO.Path.Combine(projectDirectory,"project.json")))LoadProject(projectDirectory);status.Text="Paused safely for RAM pressure · completed measurements saved";await Message("RAM headroom unavailable",e.Message);}
@ -273,7 +274,7 @@ public sealed class MainWindow:Window
}
async Task ExportAccepted()
{
if(project?.Complete!=true)return;
if(project?.Complete!=true||busy||saving||updates.Applying)return;
var options=new Window{Title="Export accepted lights",Width=470,SizeToContent=SizeToContent.Height,CanResize=false,WindowStartupLocation=WindowStartupLocation.CenterOwner,Background=Palette.Panel};
var layout=new StackPanel{Margin=new(24),Spacing=14};layout.Children.Add(Palette.Label("Prepare lights for Siril",21));layout.Children.Add(new TextBlock{Text="KEEP frames are included. Originals are opened read-only. Select an empty output folder outside your input tree.",TextWrapping=TextWrapping.Wrap,Foreground=Palette.Muted});
var scopes=new List<(string Name,List<Frame> Frames)>();
@ -282,7 +283,7 @@ public sealed class MainWindow:Window
scopes.Add(("Entire project · separate target folders",project.Frames));
var scope=new ComboBox{ItemsSource=scopes.Select(x=>x.Name).ToArray(),SelectedIndex=sessions.SelectedIndex>0?0:scopes.Count-1,HorizontalAlignment=HorizontalAlignment.Stretch};layout.Children.Add(Palette.Label("EXPORT SCOPE",10,Palette.Muted));layout.Children.Add(scope);
var include=new CheckBox{Content="Also include unresolved REVIEW frames",IsChecked=false};var links=new CheckBox{Content="Use hardlinks when available (copy fallback)",IsChecked=true};layout.Children.Add(include);layout.Children.Add(links);layout.Children.Add(new TextBlock{Text="Hardlinks share source bytes. Use Siril to read and process these inputs into separate outputs. Choose copies if another tool may overwrite input files.",FontSize=11,TextWrapping=TextWrapping.Wrap,Foreground=Palette.Muted});var buttons=new WrapPanel();var go=Button("Choose output folder",true);var cancel=Button("Cancel");cancel.Margin=new(8,0,0,0);buttons.Children.Add(go);buttons.Children.Add(cancel);layout.Children.Add(buttons);options.Content=layout;go.Click+=(_,_)=>options.Close(true);cancel.Click+=(_,_)=>options.Close(false);
if(!await options.ShowDialog<bool>(this))return;string? output=await Folder("Choose an empty output folder for accepted lights");if(output==null)return;
if(!await options.ShowDialog<bool>(this))return;string? output=await Folder("Choose an empty output folder for accepted lights");if(output==null||updates.Applying)return;
var exportProject=new Project{Name=project.Name,Source=project.Source,Complete=project.Complete,Frames=scopes[scope.SelectedIndex].Frames};
Busy(true);cancellation=new();try{var result=await Export.AcceptedAsync(exportProject,output,include.IsChecked==true,links.IsChecked==true,new Progress<ProgressInfo>(p=>{progress.Value=100.0*p.Done/Math.Max(1,p.Total);status.Text=$"{p.Stage} · {p.Done}/{p.Total}";}),cancellation.Token);status.Text=$"Export complete · {result.Linked} hardlinks, {result.Copied} copies · {output}";}
catch(OperationCanceledException){status.Text="Export cancelled · completed output files retained; choose a new empty folder to retry";}catch(Exception e){await Message("Export could not finish",e.Message);}finally{Busy(false);cancellation.Dispose();cancellation=null;}

View file

@ -14,13 +14,15 @@ internal static class Program
static Mutex? instance;
[STAThread] public static void Main(string[] args)
{
Velopack.VelopackApp.Build().SetAutoApplyOnStartup(false).Run();
if(args.Length>=3&&args[0]=="--verify-update"){Environment.ExitCode=UpdateDiagnostics.Run(args).GetAwaiter().GetResult();return;}
instance=new Mutex(true,"AstroFrame.Desktop.OneInstance",out bool created);if(!created)return;
try
{
ResourcePolicy.InstallWindowsLimit();Arguments=args;
AppBuilder.Configure<App>().UsePlatformDetect().With(new Win32PlatformOptions{RenderingMode=[Win32RenderingMode.Software]}).WithInterFont().LogToTrace().StartWithClassicDesktopLifetime(args);
}
catch(Exception e){File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory,"startup-error.log"),e.ToString());Environment.ExitCode=1;}
catch(Exception e){try{Directory.CreateDirectory(AppSettings.DataDirectory);File.WriteAllText(System.IO.Path.Combine(AppSettings.DataDirectory,"startup-error.log"),e.ToString());}catch{}Environment.ExitCode=1;}
finally{instance.ReleaseMutex();instance.Dispose();}
}
}
@ -40,7 +42,23 @@ public sealed class App:Application
string directory=System.IO.Path.GetFullPath(Program.Arguments[1]);var project=ProjectStore.Load(directory);var frame=project.Frames.First(f=>f.Name.Contains(Program.Arguments[3],StringComparison.OrdinalIgnoreCase));desktop.MainWindow=new StarInspector(project,directory,frame,Program.Arguments[2]);base.OnFrameworkInitializationCompleted();return;
}
var window=new MainWindow();desktop.MainWindow=window;
if(Program.Arguments.Length>=3&&Program.Arguments[0] is "--capture" or "--smoke")
if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--capture-settings")
{
window.Opened+=async(_,_)=>
{
try
{
var settings=window.ShowSettings();
if(Program.Arguments.Length>2)settings.Width=double.Parse(Program.Arguments[2],System.Globalization.CultureInfo.InvariantCulture);
await Task.Delay(400);
double dpi=Program.Arguments.Length>3?double.Parse(Program.Arguments[3],System.Globalization.CultureInfo.InvariantCulture):96;
using var bitmap=new RenderTargetBitmap(new PixelSize((int)Math.Ceiling(settings.Bounds.Width*dpi/96),(int)Math.Ceiling(settings.Bounds.Height*dpi/96)),new Vector(dpi,dpi));bitmap.Render(settings);bitmap.Save(Program.Arguments[1]);
desktop.Shutdown(0);
}
catch(Exception e){File.WriteAllText(Program.Arguments[1]+".error",e.ToString());desktop.Shutdown(1);}
};
}
else if(Program.Arguments.Length>=3&&Program.Arguments[0] is "--capture" or "--smoke")
{
window.Opened+=async(_,_)=>
{

View file

@ -0,0 +1,57 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace AstroFrame.Desktop;
public sealed class SettingsWindow : Window
{
readonly AppUpdates updates;
readonly TextBlock message = Text(""), lastCheck = Text("");
readonly Button check = new() { Content = "Check for updates", Padding = new(12, 8) };
readonly Button install = new() { Content = "Install update and restart", Padding = new(12, 8) };
readonly CheckBox automatic = new() { Content = "Automatically check for updates", FontSize = 13 };
public SettingsWindow(AppUpdates updates, Func<Task> installUpdate)
{
this.updates = updates;
Title = "AstroFrame settings"; Width = 760; Height = 530; MinWidth = 620; MinHeight = 390;
Background = Palette.Background; FontFamily = "Inter"; WindowStartupLocation = WindowStartupLocation.CenterOwner;
var root = new Grid { ColumnDefinitions = new("160,*") };
// Add categories and their views here as the application gains more settings.
var categories = new ListBox { ItemsSource = new[] { "Updates" }, SelectedIndex = 0, Background = Palette.Panel, Padding = new(10, 18) };
root.Children.Add(categories);
var page = new StackPanel { Spacing = 18, Margin = new(26), MaxWidth = 650 };
page.Children.Add(Text("Updates", 23));
page.Children.Add(Text($"Installed version {updates.InstalledVersion}", 15));
page.Children.Add(Text("Receive stable AstroFrame releases and install them when you are ready to restart."));
page.Children.Add(automatic); page.Children.Add(message); page.Children.Add(lastCheck);
var buttons = new WrapPanel { Orientation = Orientation.Horizontal };
check.Margin = new(0, 0, 10, 10); install.Margin = new(0, 0, 0, 10);
buttons.Children.Add(check); buttons.Children.Add(install); page.Children.Add(buttons);
var scroll = new ScrollViewer { Content = page, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled };
Grid.SetColumn(scroll, 1); root.Children.Add(scroll); Content = root;
check.Click += async (_, _) => await updates.Check();
install.Click += async (_, _) => await installUpdate();
automatic.IsChecked = updates.Settings.AutomaticallyCheckForUpdates;
automatic.IsCheckedChanged += (_, _) =>
{
bool requested = automatic.IsChecked == true;
if (requested != updates.Settings.AutomaticallyCheckForUpdates && !updates.SetAutomaticChecks(requested)) automatic.IsChecked = updates.Settings.AutomaticallyCheckForUpdates;
};
updates.Changed += Refresh;
Closed += (_, _) => updates.Changed -= Refresh;
Refresh();
}
static TextBlock Text(string value, double size = 13) => new() { Text = value, FontSize = size, Foreground = Palette.Text, TextWrapping = TextWrapping.Wrap };
void Refresh()
{
message.Text = updates.Message;
lastCheck.Text = updates.Settings.LastUpdateCheck is { } time ? $"Last successful check {time.ToLocalTime():g}" : "Last successful check Never";
lastCheck.Foreground = Palette.Muted;
check.IsEnabled = updates.IsInstalled && !updates.Working && !updates.Applying;
install.IsVisible = updates.AvailableVersion != null;
install.IsEnabled = !updates.Working && !updates.Applying;
}
}

View file

@ -0,0 +1,29 @@
using System.Text.Json;
using Velopack;
namespace AstroFrame.Desktop;
// Explicit local-feed probe used to verify installed package lifecycle without publishing test releases.
internal static class UpdateDiagnostics
{
public static async Task<int> Run(string[] args)
{
string report = Path.GetFullPath(args[2]);
try
{
string feed = args[1] == ReleaseUpdateBackend.Repository ? args[1] : Path.GetFullPath(args[1]);
var options = new UpdateOptions { ExplicitChannel = OperatingSystem.IsWindows() ? "win-x64" : "linux-x64" };
var manager = feed == ReleaseUpdateBackend.Repository
? new UpdateManager(new Velopack.Sources.GiteaSource(feed, null, false), options)
: new UpdateManager(feed, options);
if (!manager.IsInstalled) throw new InvalidOperationException("Probe requires an installed Windows package or Linux AppImage.");
var update = await manager.CheckForUpdatesAsync();
if (update != null) await manager.DownloadUpdatesAsync(update);
var record = new { version = manager.CurrentVersion?.ToString(), available = update?.TargetFullRelease.Version.ToString(), downloaded = manager.UpdatePendingRestart?.Version.ToString() };
File.AppendAllText(report, JsonSerializer.Serialize(record) + Environment.NewLine);
if (update != null && args.Contains("--apply")) manager.WaitExitThenApplyUpdates(update.TargetFullRelease, silent: true, restart: true, restartArgs: ["--verify-update", feed, report]);
return 0;
}
catch (Exception e) { File.AppendAllText(report, e + Environment.NewLine); return 1; }
}
}

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/AstroFrame.Desktop/AstroFrame.Desktop.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,95 @@
using AstroFrame.Desktop;
using Velopack;
using Velopack.Locators;
using Velopack.Sources;
int passed = 0;
void Check(bool value, string label) { if (!value) throw new Exception(label); Console.WriteLine("PASS " + label); passed++; }
var temp = Path.Combine(Path.GetTempPath(), "AstroFrame-update-tests-" + Guid.NewGuid());
Directory.CreateDirectory(temp);
try
{
var path = Path.Combine(temp, "settings.json");
var settings = AppSettings.Load(path);
Check(settings.AutomaticallyCheckForUpdates && settings.LastUpdateCheck == null, "new installs enable automatic checks");
settings.AutomaticallyCheckForUpdates = false; settings.LastUpdateCheck = DateTimeOffset.UtcNow; settings.Save(path);
var restored = AppSettings.Load(path);
Check(!restored.AutomaticallyCheckForUpdates && restored.LastUpdateCheck == settings.LastUpdateCheck, "settings and check time persist independently of project state");
File.WriteAllText(path, "broken json"); Check(AppSettings.Load(path).AutomaticallyCheckForUpdates, "corrupt settings recover safely");
var backend = new FakeBackend();
using var updates = new AppUpdates(backend, new AppSettings(), _ => { });
updates.SetAutomaticChecks(false); await updates.Check(automatic: true);
Check(backend.Checks == 0, "disabled automatic checks do not contact release source");
await updates.Check(); Check(updates.AvailableVersion == "1.0.1" && backend.Checks == 1, "manual check works with automatic checks disabled");
bool saved = false;
Check(!await updates.Install(() => false, () => { saved = true; return Task.FromResult(true); }, []), "active processing blocks update install");
Check(backend.Downloads == 0 && !saved, "blocked install never downloads or saves");
backend.AfterDownload = () => backend.Busy = true;
Check(!await updates.Install(() => !backend.Busy, () => Task.FromResult(true), []), "work starting during download prevents restart");
Check(updates.Ready && backend.Applies == 0, "download remains staged for a later safe restart");
backend.Busy = false;
Check(!await updates.Install(() => true, () => Task.FromResult(false), []), "save failure prevents restart");
Check(!updates.Applying && backend.Applies == 0, "failed save releases restart lock");
Check(await updates.Install(() => true, () => { saved = true; return Task.FromResult(true); }, ["--project", "example"]), "staged update installs after successful save");
Check(saved && backend.Downloads == 1 && backend.Applies == 1 && backend.Arguments.SequenceEqual(new[] { "--project", "example" }), "install saves before apply, reuses download and restores project arguments");
backend = new FakeBackend { Failure = new IOException("offline") };
using var offline = new AppUpdates(backend, new AppSettings(), _ => { });
await offline.Check(); Check(offline.Settings.LastUpdateCheck == null && offline.Message.Contains("Could not check"), "offline check never reports up to date or a successful check time");
backend.Failure = null; await offline.Check(); Check(offline.AvailableVersion == "1.0.1", "manual check recovers after network failure");
backend.CheckGate = new TaskCompletionSource(); var checking = offline.Check(); await offline.Check();
Check(backend.Checks == 3, "overlapping manual and automatic checks share one operation");
backend.CheckGate.SetResult(); await checking;
using var readOnly = new AppUpdates(new FakeBackend(), new AppSettings(), _ => throw new UnauthorizedAccessException());
Check(!readOnly.SetAutomaticChecks(false) && readOnly.Settings.AutomaticallyCheckForUpdates, "failed settings write restores checkbox preference");
using var unpackaged = new AppUpdates(new FakeBackend { IsInstalled = false }, new AppSettings(), _ => { });
await unpackaged.Check(); Check(unpackaged.AvailableVersion == null && !unpackaged.IsInstalled, "unpackaged builds do not attempt self replacement");
if (args.Length > 0 && args[0] == "--live")
{
var live = new UpdateManager(new GiteaSource(ReleaseUpdateBackend.Repository, null, false), new UpdateOptions { ExplicitChannel = "win-x64" },
new TestVelopackLocator("AstroFrame", "1.0.0", Path.Combine(temp, "live")));
var result = await live.CheckForUpdatesAsync();
Check(result == null, "public Gitea source is reachable and handles the repository with no published releases");
}
else if (args.Length > 0)
{
string feed = Path.GetFullPath(args[0]);
string channel = args.Length > 1 ? args[1] : "win-x64";
var locator = new TestVelopackLocator("AstroFrame", "1.0.0", Path.Combine(temp, "packages"));
var manager = new UpdateManager(new SimpleFileSource(new DirectoryInfo(feed)), new UpdateOptions { ExplicitChannel = channel }, locator);
var update = await manager.CheckForUpdatesAsync();
Check(update?.TargetFullRelease.Version.ToString() == "1.0.1", "real release feed selects newer platform package");
await manager.DownloadUpdatesAsync(update!);
Check(manager.UpdatePendingRestart?.Version.ToString() == "1.0.1", "real package downloads and passes Velopack checksum verification");
var current = new UpdateManager(new SimpleFileSource(new DirectoryInfo(feed)), new UpdateOptions { ExplicitChannel = channel }, new TestVelopackLocator("AstroFrame", "1.0.1", Path.Combine(temp, "latest")));
Check(await current.CheckForUpdatesAsync() == null, "installed latest version does not offer itself again");
var future = new UpdateManager(new SimpleFileSource(new DirectoryInfo(feed)), new UpdateOptions { ExplicitChannel = channel }, new TestVelopackLocator("AstroFrame", "2.0.0", Path.Combine(temp, "future")));
Check(await future.CheckForUpdatesAsync() == null, "older published releases never downgrade installed application");
string badFeed = Path.Combine(temp, "bad-feed"); Directory.CreateDirectory(badFeed);
File.Copy(Path.Combine(feed, $"releases.{channel}.json"), Path.Combine(badFeed, $"releases.{channel}.json"));
foreach (string package in Directory.GetFiles(feed, "*.nupkg")) File.WriteAllText(Path.Combine(badFeed, Path.GetFileName(package)), "corrupted package");
var bad = new UpdateManager(new SimpleFileSource(new DirectoryInfo(badFeed)), new UpdateOptions { ExplicitChannel = channel }, new TestVelopackLocator("AstroFrame", "1.0.0", Path.Combine(temp, "bad-packages")));
bool rejected = false; try { await bad.DownloadUpdatesAsync((await bad.CheckForUpdatesAsync())!); } catch { rejected = true; }
Check(rejected && bad.UpdatePendingRestart == null, "corrupt release download cannot be staged for installation");
}
Console.WriteLine($"{passed} update checks passed.");
}
finally { Directory.Delete(temp, true); }
sealed class FakeBackend : IUpdateBackend
{
public bool IsInstalled { get; set; } = true;
public string InstalledVersion => "1.0.0";
public int Checks, Downloads, Applies;
public bool Busy;
public Exception? Failure;
public TaskCompletionSource? CheckGate;
public Action? AfterDownload;
public string[] Arguments = [];
public async Task<string?> Check() { Checks++; if (CheckGate != null) await CheckGate.Task; if (Failure != null) throw Failure; return "1.0.1"; }
public Task Download(Action<int> progress, CancellationToken cancellation) { Downloads++; progress(100); AfterDownload?.Invoke(); return Task.CompletedTask; }
public void ApplyAndRestart(string[] arguments) { Applies++; Arguments = arguments; }
}