mirror of
https://github.com/wwiinnddyy/LanMountainDesktop.git
synced 2026-06-21 16:14:28 +08:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2ac302ee7 | ||
|
|
c351a8e7f3 | ||
|
|
21e970c5b6 | ||
|
|
17873f0f43 | ||
|
|
4051b5cd74 | ||
|
|
5be4537b2c | ||
|
|
c5e75244af | ||
|
|
6a650873bc | ||
|
|
d004088601 |
298
.github/workflows/plonds-comparator.yml
vendored
298
.github/workflows/plonds-comparator.yml
vendored
@@ -1,4 +1,4 @@
|
||||
name: PLONDS Comparator
|
||||
name: PLONDS Comparator
|
||||
|
||||
concurrency:
|
||||
group: plonds-${{ github.event_name }}-${{ github.event.release.tag_name || github.event.inputs.tag || github.run_id }}
|
||||
@@ -9,7 +9,6 @@ on:
|
||||
types:
|
||||
- published
|
||||
- prereleased
|
||||
- edited
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
@@ -17,7 +16,7 @@ on:
|
||||
required: true
|
||||
type: string
|
||||
baseline_tag:
|
||||
description: 'Optional baseline tag'
|
||||
description: 'Optional baseline tag (auto-detected if omitted)'
|
||||
required: false
|
||||
type: string
|
||||
channel:
|
||||
@@ -28,12 +27,28 @@ on:
|
||||
options:
|
||||
- stable
|
||||
- preview
|
||||
compare_method:
|
||||
description: 'Compare method'
|
||||
required: false
|
||||
type: choice
|
||||
default: file-compare
|
||||
options:
|
||||
- file-compare
|
||||
- commit-analyze
|
||||
hash_algorithm:
|
||||
description: 'Hash algorithm (file-compare only)'
|
||||
required: false
|
||||
type: choice
|
||||
default: sha256
|
||||
options:
|
||||
- sha256
|
||||
- md5
|
||||
|
||||
env:
|
||||
DOTNET_VERSION: '10.0.x'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
compare:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -48,6 +63,7 @@ jobs:
|
||||
- name: Resolve release context
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ "${{ github.event_name }}" == "release" ]]; then
|
||||
TAG="${{ github.event.release.tag_name }}"
|
||||
if [[ "${{ github.event.release.prerelease }}" == "true" ]]; then
|
||||
@@ -55,7 +71,9 @@ jobs:
|
||||
else
|
||||
CHANNEL="stable"
|
||||
fi
|
||||
BASELINE_TAG=""
|
||||
BASELINE_TAG_INPUT=""
|
||||
COMPARE_METHOD="file-compare"
|
||||
HASH_ALGORITHM="sha256"
|
||||
else
|
||||
RAW_TAG="${{ github.event.inputs.tag }}"
|
||||
if [[ "${RAW_TAG}" == v* ]]; then
|
||||
@@ -64,18 +82,17 @@ jobs:
|
||||
TAG="v${RAW_TAG}"
|
||||
fi
|
||||
CHANNEL="${{ github.event.inputs.channel }}"
|
||||
BASELINE_TAG="${{ github.event.inputs.baseline_tag }}"
|
||||
BASELINE_TAG_INPUT="${{ github.event.inputs.baseline_tag }}"
|
||||
COMPARE_METHOD="${{ github.event.inputs.compare_method }}"
|
||||
HASH_ALGORITHM="${{ github.event.inputs.hash_algorithm }}"
|
||||
fi
|
||||
|
||||
echo "RELEASE_TAG=${TAG}" >> "$GITHUB_ENV"
|
||||
echo "RELEASE_VERSION=${TAG#v}" >> "$GITHUB_ENV"
|
||||
echo "RELEASE_CHANNEL=${CHANNEL}" >> "$GITHUB_ENV"
|
||||
echo "BASELINE_TAG_INPUT=${BASELINE_TAG}" >> "$GITHUB_ENV"
|
||||
PUBLIC_BASE="${{ vars.S3_PUBLIC_BASE_URL }}"
|
||||
if [[ -z "$PUBLIC_BASE" ]]; then
|
||||
PUBLIC_BASE="https://cn-nb1.rains3.com/lmdesktop/lanmountain/update"
|
||||
fi
|
||||
echo "S3_PUBLIC_BASE_URL=${PUBLIC_BASE%/}" >> "$GITHUB_ENV"
|
||||
echo "BASELINE_TAG_INPUT=${BASELINE_TAG_INPUT}" >> "$GITHUB_ENV"
|
||||
echo "COMPARE_METHOD=${COMPARE_METHOD}" >> "$GITHUB_ENV"
|
||||
echo "HASH_ALGORITHM=${HASH_ALGORITHM}" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
@@ -83,194 +100,159 @@ jobs:
|
||||
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||
dotnet-quality: preview
|
||||
|
||||
- name: Prepare signing key
|
||||
env:
|
||||
UPDATE_PRIVATE_KEY_PEM: ${{ secrets.UPDATE_PRIVATE_KEY_PEM }}
|
||||
PLONDS_SIGNING_KEY: ${{ secrets.PLONDS_SIGNING_KEY }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
KEY="${PLONDS_SIGNING_KEY:-}"
|
||||
if [[ -z "$KEY" ]]; then KEY="${UPDATE_PRIVATE_KEY_PEM:-}"; fi
|
||||
if [[ -z "$KEY" ]]; then
|
||||
echo "No signing key is configured."
|
||||
exit 1
|
||||
fi
|
||||
printf '%s' "$KEY" > update-private-key.pem
|
||||
echo "UPDATE_PRIVATE_KEY_PATH=$PWD/update-private-key.pem" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build PLONDS tool
|
||||
run: dotnet build PenguinLogisticsOnlineNetworkDistributionSystem/src/Plonds.Tool/Plonds.Tool.csproj -c Release
|
||||
|
||||
- name: Resolve baseline plan
|
||||
- name: Resolve baseline
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
shell: bash
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = '${{ github.repository }}'
|
||||
$tag = $env:RELEASE_TAG
|
||||
$baselineInput = $env:BASELINE_TAG_INPUT
|
||||
$currentRelease = gh release view $tag --repo $repo --json tagName,isPrerelease,assets,publishedAt | ConvertFrom-Json
|
||||
$allReleases = gh api "repos/$repo/releases?per_page=100" | ConvertFrom-Json
|
||||
$platforms = @('windows-x64', 'windows-x86', 'linux-x64')
|
||||
set -euo pipefail
|
||||
BASELINE_TAG=""
|
||||
BASELINE_VERSION=""
|
||||
|
||||
$entries = foreach ($platform in $platforms) {
|
||||
$assetName = "files-$platform.zip"
|
||||
$currentAsset = $currentRelease.assets | Where-Object { $_.name -eq $assetName } | Select-Object -First 1
|
||||
if (-not $currentAsset) {
|
||||
throw "Current release $tag does not contain required asset $assetName"
|
||||
}
|
||||
if [[ -n "$BASELINE_TAG_INPUT" ]]; then
|
||||
NORMALIZED="$BASELINE_TAG_INPUT"
|
||||
if [[ "$NORMALIZED" != v* ]]; then NORMALIZED="v$NORMALIZED"; fi
|
||||
if gh release view "$NORMALIZED" --repo "${{ github.repository }}" --json tagName >/dev/null 2>&1; then
|
||||
BASELINE_TAG="$NORMALIZED"
|
||||
BASELINE_VERSION="${NORMALIZED#v}"
|
||||
else
|
||||
echo "Specified baseline tag not found: $NORMALIZED"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
IS_PRERELEASE="$(gh release view "$RELEASE_TAG" --repo "${{ github.repository }}" --json isPrerelease --jq '.isPrerelease')"
|
||||
CANDIDATES="$(gh api "repos/${{ github.repository }}/releases?per_page=50" \
|
||||
--jq ".[] | select(.draft == false and .prerelease == ${IS_PRERELEASE} and .tag_name != \"${RELEASE_TAG}\") | .tag_name")"
|
||||
|
||||
$baselineRelease = $null
|
||||
if (-not [string]::IsNullOrWhiteSpace($baselineInput)) {
|
||||
$normalizedBaseline = if ($baselineInput.StartsWith('v')) { $baselineInput } else { "v$baselineInput" }
|
||||
$baselineRelease = $allReleases | Where-Object { $_.tag_name -eq $normalizedBaseline } | Select-Object -First 1
|
||||
if (-not $baselineRelease) {
|
||||
throw "Specified baseline tag not found: $normalizedBaseline"
|
||||
}
|
||||
}
|
||||
else {
|
||||
$baselineRelease = $allReleases |
|
||||
Where-Object {
|
||||
$_.tag_name -ne $tag -and
|
||||
-not $_.draft -and
|
||||
[bool]$_.prerelease -eq [bool]$currentRelease.isPrerelease -and
|
||||
($_.assets | Where-Object { $_.name -eq $assetName } | Measure-Object).Count -gt 0
|
||||
} |
|
||||
Select-Object -First 1
|
||||
}
|
||||
for CANDIDATE in $CANDIDATES; do
|
||||
if gh release download "$CANDIDATE" -p "files-windows-x64.zip" -D /tmp/baseline-check --clobber 2>/dev/null; then
|
||||
BASELINE_TAG="$CANDIDATE"
|
||||
BASELINE_VERSION="${CANDIDATE#v}"
|
||||
rm -rf /tmp/baseline-check
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
[pscustomobject]@{
|
||||
platform = $platform
|
||||
assetName = $assetName
|
||||
baselineTag = if ($baselineRelease) { $baselineRelease.tag_name } else { $null }
|
||||
baselineVersion = if ($baselineRelease) { ($baselineRelease.tag_name -replace '^v', '') } else { $null }
|
||||
isFullPayload = -not $baselineRelease
|
||||
}
|
||||
}
|
||||
|
||||
$plan = [pscustomobject]@{
|
||||
tag = $tag
|
||||
version = $env:RELEASE_VERSION
|
||||
channel = $env:RELEASE_CHANNEL
|
||||
platforms = $entries
|
||||
}
|
||||
|
||||
$plan | ConvertTo-Json -Depth 8 | Set-Content plonds-plan.json -Encoding utf8
|
||||
Get-Content plonds-plan.json
|
||||
if [[ -n "$BASELINE_TAG" ]]; then
|
||||
echo "BASELINE_TAG=${BASELINE_TAG}" >> "$GITHUB_ENV"
|
||||
echo "BASELINE_VERSION=${BASELINE_VERSION}" >> "$GITHUB_ENV"
|
||||
echo "Resolved baseline: ${BASELINE_TAG}"
|
||||
else
|
||||
echo "No baseline found. This will be a full update."
|
||||
fi
|
||||
|
||||
- name: Download payload zips
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: pwsh
|
||||
shell: bash
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = '${{ github.repository }}'
|
||||
$plan = Get-Content plonds-plan.json | ConvertFrom-Json
|
||||
set -euo pipefail
|
||||
mkdir -p plonds-input
|
||||
|
||||
foreach ($entry in $plan.platforms) {
|
||||
$currentDir = Join-Path $PWD "plonds-input/current/$($entry.platform)"
|
||||
New-Item -ItemType Directory -Path $currentDir -Force | Out-Null
|
||||
gh release download $plan.tag --repo $repo -p $entry.assetName -D $currentDir
|
||||
gh release download "$RELEASE_TAG" -p "files-windows-x64.zip" -D plonds-input
|
||||
mv plonds-input/files-windows-x64.zip plonds-input/current-files-windows-x64.zip
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($entry.baselineTag)) {
|
||||
$baselineDir = Join-Path $PWD "plonds-input/baseline/$($entry.platform)"
|
||||
New-Item -ItemType Directory -Path $baselineDir -Force | Out-Null
|
||||
gh release download $entry.baselineTag --repo $repo -p $entry.assetName -D $baselineDir
|
||||
}
|
||||
}
|
||||
if [[ -n "$BASELINE_TAG" ]]; then
|
||||
gh release download "$BASELINE_TAG" -p "files-windows-x64.zip" -D plonds-input
|
||||
mv plonds-input/files-windows-x64.zip plonds-input/baseline-files-windows-x64.zip
|
||||
fi
|
||||
|
||||
- name: Build delta assets
|
||||
shell: pwsh
|
||||
- name: Run build-delta (file-compare)
|
||||
if: env.COMPARE_METHOD == 'file-compare'
|
||||
shell: bash
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$plan = Get-Content plonds-plan.json | ConvertFrom-Json
|
||||
foreach ($entry in $plan.platforms) {
|
||||
$currentZip = Join-Path $PWD "plonds-input/current/$($entry.platform)/$($entry.assetName)"
|
||||
$args = @(
|
||||
'run', '--project', 'PenguinLogisticsOnlineNetworkDistributionSystem/src/Plonds.Tool/Plonds.Tool.csproj', '--configuration', 'Release', '--',
|
||||
'build-delta',
|
||||
'--platform', $entry.platform,
|
||||
'--current-version', $plan.version,
|
||||
'--current-tag', $plan.tag,
|
||||
'--current-zip', $currentZip,
|
||||
'--output-dir', 'plonds-output',
|
||||
'--private-key', $env:UPDATE_PRIVATE_KEY_PATH,
|
||||
'--channel', $plan.channel,
|
||||
'--static-output-dir', 'plonds-output/static',
|
||||
'--update-base-url', $env:S3_PUBLIC_BASE_URL
|
||||
set -euo pipefail
|
||||
mkdir -p plonds-output
|
||||
|
||||
ARGS=(
|
||||
'run' '--project' 'PenguinLogisticsOnlineNetworkDistributionSystem/src/Plonds.Tool/Plonds.Tool.csproj'
|
||||
'--configuration' 'Release' '--'
|
||||
'build-delta'
|
||||
'--platform' 'windows-x64'
|
||||
'--current-version' "$RELEASE_VERSION"
|
||||
'--current-zip' "$PWD/plonds-input/current-files-windows-x64.zip"
|
||||
'--output-dir' "$PWD/plonds-output"
|
||||
'--channel' "$RELEASE_CHANNEL"
|
||||
'--hash-algorithm' "$HASH_ALGORITHM"
|
||||
)
|
||||
|
||||
if [[ -n "$BASELINE_TAG" ]]; then
|
||||
ARGS+=(
|
||||
'--baseline-version' "$BASELINE_VERSION"
|
||||
'--baseline-zip' "$PWD/plonds-input/baseline-files-windows-x64.zip"
|
||||
)
|
||||
fi
|
||||
|
||||
if ([bool]$entry.isFullPayload) {
|
||||
$args += @('--is-full-payload', 'true')
|
||||
}
|
||||
else {
|
||||
$baselineZip = Join-Path $PWD "plonds-input/baseline/$($entry.platform)/$($entry.assetName)"
|
||||
$args += @('--baseline-tag', $entry.baselineTag, '--baseline-version', $entry.baselineVersion, '--baseline-zip', $baselineZip)
|
||||
}
|
||||
dotnet "${ARGS[@]}"
|
||||
|
||||
dotnet @args
|
||||
}
|
||||
- name: Run build-delta-from-commits (commit-analyze)
|
||||
if: env.COMPARE_METHOD == 'commit-analyze'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p plonds-output
|
||||
|
||||
dotnet run --project PenguinLogisticsOnlineNetworkDistributionSystem/src/Plonds.Tool/Plonds.Tool.csproj --configuration Release -- `
|
||||
build-index `
|
||||
--release-tag $plan.tag `
|
||||
--version $plan.version `
|
||||
--channel $plan.channel `
|
||||
--platform-summaries-dir plonds-output/platform-summaries `
|
||||
--output-dir plonds-output `
|
||||
--private-key $env:UPDATE_PRIVATE_KEY_PATH
|
||||
ARGS=(
|
||||
'run' '--project' 'PenguinLogisticsOnlineNetworkDistributionSystem/src/Plonds.Tool/Plonds.Tool.csproj'
|
||||
'--configuration' 'Release' '--'
|
||||
'build-delta-from-commits'
|
||||
'--platform' 'windows-x64'
|
||||
'--current-version' "$RELEASE_VERSION"
|
||||
'--current-zip' "$PWD/plonds-input/current-files-windows-x64.zip"
|
||||
'--output-dir' "$PWD/plonds-output"
|
||||
'--channel' "$RELEASE_CHANNEL"
|
||||
'--baseline-tag' "${BASELINE_TAG:-$RELEASE_TAG}"
|
||||
'--current-tag' "$RELEASE_TAG"
|
||||
'--hash-algorithm' "$HASH_ALGORITHM"
|
||||
)
|
||||
|
||||
foreach ($entry in $plan.platforms) {
|
||||
$summary = Get-Content "plonds-output/platform-summaries/platform-summary-$($entry.platform).json" | ConvertFrom-Json
|
||||
$required = @(
|
||||
"plonds-output/static/meta/channels/$($plan.channel)/$($entry.platform)/latest.json",
|
||||
"plonds-output/static/meta/distributions/$($summary.distributionId).json",
|
||||
"plonds-output/static/manifests/$($summary.distributionId)/plonds-filemap.json",
|
||||
"plonds-output/static/manifests/$($summary.distributionId)/plonds-filemap.json.sig"
|
||||
if [[ -n "$BASELINE_TAG" ]]; then
|
||||
ARGS+=(
|
||||
'--fallback-zip' "$PWD/plonds-input/baseline-files-windows-x64.zip"
|
||||
)
|
||||
fi
|
||||
|
||||
foreach ($path in $required) {
|
||||
if (-not (Test-Path $path)) {
|
||||
throw "Missing PLONDS static output: $path"
|
||||
}
|
||||
}
|
||||
}
|
||||
dotnet "${ARGS[@]}"
|
||||
|
||||
$objects = Get-ChildItem -Path "plonds-output/static/repo/sha256" -File -Recurse -ErrorAction SilentlyContinue
|
||||
if (-not $objects -or $objects.Count -eq 0) {
|
||||
throw "PLONDS static object repository is empty."
|
||||
}
|
||||
- name: Validate output
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! -f plonds-output/changed.zip ]]; then
|
||||
echo "Missing output: changed.zip"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -f plonds-output/PLONDS.json ]]; then
|
||||
echo "Missing output: PLONDS.json"
|
||||
exit 1
|
||||
fi
|
||||
jq -e . plonds-output/PLONDS.json >/dev/null
|
||||
|
||||
Compress-Archive -Path "plonds-output/static/*" -DestinationPath "plonds-output/release-assets/plonds-static.zip" -Force
|
||||
|
||||
- name: Upload PLONDS assets to release
|
||||
- name: Upload to GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release upload "$RELEASE_TAG" plonds-output/release-assets/* --clobber
|
||||
gh release upload "$RELEASE_TAG" plonds-output/changed.zip plonds-output/PLONDS.json --clobber
|
||||
|
||||
- name: Persist run metadata
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p plonds-run-metadata
|
||||
printf '%s' "$RELEASE_TAG" > plonds-run-metadata/tag.txt
|
||||
printf '%s' "$COMPARE_METHOD" > plonds-run-metadata/compare-method.txt
|
||||
|
||||
- name: Upload run metadata artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: plonds-run-metadata
|
||||
path: plonds-run-metadata/tag.txt
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload PLONDS static artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: plonds-static
|
||||
path: plonds-output/static/**
|
||||
path: |
|
||||
plonds-run-metadata/tag.txt
|
||||
plonds-run-metadata/compare-method.txt
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
97
.github/workflows/release.yml
vendored
97
.github/workflows/release.yml
vendored
@@ -185,6 +185,29 @@ jobs:
|
||||
-p:InformationalVersion=${{ needs.prepare.outputs.informational_version }}
|
||||
shell: pwsh
|
||||
|
||||
- name: Publish AirAppRuntime
|
||||
run: |
|
||||
$arch = "${{ matrix.arch }}"
|
||||
$publishDir = "publish/airapp-runtime-win-$arch"
|
||||
|
||||
dotnet publish LanMountainDesktop.AirAppRuntime/LanMountainDesktop.AirAppRuntime.csproj `
|
||||
-c Release `
|
||||
-o ./$publishDir `
|
||||
--self-contained:false `
|
||||
-r win-$arch `
|
||||
-p:SelfContained=false `
|
||||
-p:PublishAot=false `
|
||||
-p:PublishSingleFile=false `
|
||||
-p:PublishTrimmed=false `
|
||||
-p:PublishReadyToRun=false `
|
||||
-p:DebugType=none `
|
||||
-p:DebugSymbols=false `
|
||||
-p:Version=${{ needs.prepare.outputs.version }} `
|
||||
-p:AssemblyVersion=${{ needs.prepare.outputs.assembly_version }} `
|
||||
-p:FileVersion=${{ needs.prepare.outputs.assembly_version }} `
|
||||
-p:InformationalVersion=${{ needs.prepare.outputs.informational_version }}
|
||||
shell: pwsh
|
||||
|
||||
- name: Publish AirAppHost
|
||||
run: |
|
||||
$arch = "${{ matrix.arch }}"
|
||||
@@ -215,6 +238,7 @@ jobs:
|
||||
$arch = "${{ matrix.arch }}"
|
||||
$publishDir = "publish/windows-$arch"
|
||||
$launcherPublishDir = "publish/launcher-win-$arch"
|
||||
$runtimePublishDir = "publish/airapp-runtime-win-$arch"
|
||||
$appDir = "app-$version"
|
||||
$newStructure = "publish-launcher/windows-$arch"
|
||||
|
||||
@@ -226,10 +250,15 @@ jobs:
|
||||
Copy-Item -Path "$launcherPublishDir\*" -Destination $newStructure -Recurse -Force
|
||||
}
|
||||
|
||||
if (Test-Path $runtimePublishDir) {
|
||||
Copy-Item -Path "$runtimePublishDir\*" -Destination $newStructure -Recurse -Force
|
||||
}
|
||||
|
||||
New-Item -ItemType File -Path (Join-Path $appPath ".current") -Force | Out-Null
|
||||
|
||||
Remove-Item -Path $publishDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -Path $launcherPublishDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -Path $runtimePublishDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Move-Item -Path $newStructure -Destination $publishDir -Force
|
||||
shell: pwsh
|
||||
|
||||
@@ -253,6 +282,7 @@ jobs:
|
||||
|
||||
$requiredFiles = @(
|
||||
(Join-Path $publishDir "LanMountainDesktop.Launcher.exe"),
|
||||
(Join-Path $publishDir "LanMountainDesktop.AirAppRuntime.exe"),
|
||||
(Join-Path $appDir "LanMountainDesktop.exe"),
|
||||
(Join-Path $appDir "LanMountainDesktop.AirAppHost.exe")
|
||||
)
|
||||
@@ -462,12 +492,32 @@ jobs:
|
||||
-p:FileVersion=${{ needs.prepare.outputs.assembly_version }} \
|
||||
-p:InformationalVersion=${{ needs.prepare.outputs.informational_version }}
|
||||
|
||||
- name: Publish AirAppRuntime
|
||||
run: |
|
||||
dotnet publish LanMountainDesktop.AirAppRuntime/LanMountainDesktop.AirAppRuntime.csproj \
|
||||
-c Release \
|
||||
-o ./publish/airapp-runtime-linux-x64 \
|
||||
--self-contained false \
|
||||
-r linux-x64 \
|
||||
-p:SelfContained=false \
|
||||
-p:PublishAot=false \
|
||||
-p:PublishSingleFile=false \
|
||||
-p:PublishTrimmed=false \
|
||||
-p:PublishReadyToRun=false \
|
||||
-p:DebugType=none \
|
||||
-p:DebugSymbols=false \
|
||||
-p:Version=${{ needs.prepare.outputs.version }} \
|
||||
-p:AssemblyVersion=${{ needs.prepare.outputs.assembly_version }} \
|
||||
-p:FileVersion=${{ needs.prepare.outputs.assembly_version }} \
|
||||
-p:InformationalVersion=${{ needs.prepare.outputs.informational_version }}
|
||||
|
||||
- name: Restructure for Launcher
|
||||
run: |
|
||||
version="${{ needs.prepare.outputs.version }}"
|
||||
publishDir="publish/linux-x64"
|
||||
appDir="app-$version"
|
||||
launcherDir="publish/launcher-linux-x64"
|
||||
runtimeDir="publish/airapp-runtime-linux-x64"
|
||||
|
||||
mkdir -p "$publishDir"
|
||||
mv "publish/linux-x64-app" "$publishDir/$appDir"
|
||||
@@ -477,8 +527,13 @@ jobs:
|
||||
chmod +x "$publishDir/LanMountainDesktop.Launcher" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ -d "$runtimeDir" ]; then
|
||||
cp -r "$runtimeDir"/* "$publishDir/"
|
||||
chmod +x "$publishDir/LanMountainDesktop.AirAppRuntime" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
touch "$publishDir/$appDir/.current"
|
||||
rm -rf "$launcherDir"
|
||||
rm -rf "$launcherDir" "$runtimeDir"
|
||||
|
||||
- name: Package as DEB
|
||||
run: |
|
||||
@@ -637,10 +692,10 @@ jobs:
|
||||
dotnet publish LanMountainDesktop/LanMountainDesktop.csproj \
|
||||
-c Release \
|
||||
-o ./publish/macos-${{ matrix.arch }}-app \
|
||||
--self-contained \
|
||||
--self-contained:false \
|
||||
-r osx-${{ matrix.arch }} \
|
||||
-p:SelfContained=false \
|
||||
-p:PublishSingleFile=false \
|
||||
-p:SelfContained=true \
|
||||
-p:DebugType=none \
|
||||
-p:DebugSymbols=false \
|
||||
-p:SkipAirAppHostBuild=true \
|
||||
@@ -651,6 +706,36 @@ jobs:
|
||||
-p:FileVersion=${{ needs.prepare.outputs.assembly_version }} \
|
||||
-p:InformationalVersion=${{ needs.prepare.outputs.informational_version }}
|
||||
|
||||
- name: Publish AirAppRuntime
|
||||
run: |
|
||||
dotnet publish LanMountainDesktop.AirAppRuntime/LanMountainDesktop.AirAppRuntime.csproj \
|
||||
-c Release \
|
||||
-o ./publish/airapp-runtime-macos-${{ matrix.arch }} \
|
||||
--self-contained false \
|
||||
-r osx-${{ matrix.arch }} \
|
||||
-p:SelfContained=false \
|
||||
-p:PublishAot=false \
|
||||
-p:PublishSingleFile=false \
|
||||
-p:PublishTrimmed=false \
|
||||
-p:PublishReadyToRun=false \
|
||||
-p:DebugType=none \
|
||||
-p:DebugSymbols=false \
|
||||
-p:Version=${{ needs.prepare.outputs.version }} \
|
||||
-p:AssemblyVersion=${{ needs.prepare.outputs.assembly_version }} \
|
||||
-p:FileVersion=${{ needs.prepare.outputs.assembly_version }} \
|
||||
-p:InformationalVersion=${{ needs.prepare.outputs.informational_version }}
|
||||
|
||||
- name: Optimize and Guard macOS Payload
|
||||
run: |
|
||||
arch="${{ matrix.arch }}"
|
||||
publishDir="publish/macos-${arch}-app"
|
||||
|
||||
pwsh ./LanMountainDesktop/scripts/Optimize-PublishPayload.ps1 \
|
||||
-PublishDir "$publishDir" \
|
||||
-RuntimeIdentifier "osx-${arch}" \
|
||||
-AssertClean
|
||||
shell: bash
|
||||
|
||||
- name: Package Payload Zip
|
||||
run: |
|
||||
release_dir="$PWD/release-assets"
|
||||
@@ -673,6 +758,7 @@ jobs:
|
||||
app_name="LanMountainDesktop"
|
||||
package_name="${app_name}-${version}-macos-${arch}"
|
||||
launcherDir="publish/launcher-macos-$arch"
|
||||
runtimeDir="publish/airapp-runtime-macos-$arch"
|
||||
appSourceDir="publish/macos-$arch-app"
|
||||
|
||||
mkdir -p "${app_name}.app/Contents/MacOS"
|
||||
@@ -685,6 +771,11 @@ jobs:
|
||||
chmod +x "${app_name}.app/Contents/MacOS/LanMountainDesktop.Launcher" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ -d "$runtimeDir" ]; then
|
||||
cp -r "$runtimeDir"/* "${app_name}.app/Contents/MacOS/"
|
||||
chmod +x "${app_name}.app/Contents/MacOS/LanMountainDesktop.AirAppRuntime" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
touch "${app_name}.app/Contents/MacOS/$appDir/.current"
|
||||
mkdir -p "${app_name}.app/Contents/Resources"
|
||||
|
||||
|
||||
9
.trae/specs/air-app-runtime-container/checklist.md
Normal file
9
.trae/specs/air-app-runtime-container/checklist.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Checklist
|
||||
|
||||
- [x] `LanMountainDesktop.AirAppRuntime` is included in `LanMountainDesktop.slnx`.
|
||||
- [x] Launcher no longer hosts `IAirAppLifecycleService`.
|
||||
- [x] Host fallback starts `LanMountainDesktop.AirAppRuntime`, not `LanMountainDesktop.Launcher air-app-broker`.
|
||||
- [x] AirApp Runtime is explicitly non-AOT and framework-dependent.
|
||||
- [x] `dotnet build LanMountainDesktop.slnx -c Debug` passes.
|
||||
- [x] Related AirApp Runtime tests pass.
|
||||
- [x] `dotnet test LanMountainDesktop.slnx -c Debug` passes.
|
||||
21
.trae/specs/air-app-runtime-container/spec.md
Normal file
21
.trae/specs/air-app-runtime-container/spec.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# AirApp Runtime Container
|
||||
|
||||
## Goal
|
||||
|
||||
Move built-in Air APP lifecycle management out of Launcher into a dedicated framework-dependent JIT process named `LanMountainDesktop.AirAppRuntime`.
|
||||
|
||||
## Behavior
|
||||
|
||||
- Launcher remains the user-facing entry point and pre-starts AirApp Runtime during normal `launch`.
|
||||
- AirApp Runtime exposes `IAirAppLifecycleService` and `IAirAppRuntimeControlService` on `LanMountainDesktop.AirAppRuntime.v1`.
|
||||
- Desktop host requests Air APP operations through AirApp Runtime IPC.
|
||||
- If the runtime pipe is unavailable, the desktop host starts `LanMountainDesktop.AirAppRuntime` directly and retries.
|
||||
- AirApp Runtime keeps one AirAppHost process per `{appId}:{sourceComponentId}:{sourcePlacementId}` key, with `world-clock` sharing `world-clock:clock-suite:global`.
|
||||
- AirApp Runtime remains alive while Launcher, Host, requester, or any AirAppHost process is alive.
|
||||
- AirApp Runtime exits after Launcher/Host/requester are gone and no Air APP windows remain.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Moving Air APP windows into the runtime process.
|
||||
- Third-party plugin-declared Air APP metadata.
|
||||
- Persisting the Air APP instance table across OS reboot.
|
||||
11
.trae/specs/air-app-runtime-container/tasks.md
Normal file
11
.trae/specs/air-app-runtime-container/tasks.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Tasks
|
||||
|
||||
- [x] Add shared AirApp Runtime IPC/control contracts.
|
||||
- [x] Add shared AirApp Runtime path resolver and process starter.
|
||||
- [x] Add `LanMountainDesktop.AirAppRuntime` as a framework-dependent JIT process.
|
||||
- [x] Move Air APP lifecycle service out of Launcher.
|
||||
- [x] Make Launcher pre-start AirApp Runtime and attach Host PID after launch.
|
||||
- [x] Make Host fallback start AirApp Runtime instead of Launcher broker.
|
||||
- [x] Remove Launcher `air-app-broker` command handling.
|
||||
- [x] Update packaging scripts and release workflow to include AirApp Runtime.
|
||||
- [x] Update unit tests and architecture/package assertions.
|
||||
@@ -1,5 +1,7 @@
|
||||
# Checklist
|
||||
|
||||
> Superseded by `.trae/specs/air-app-runtime-container/`; the checked items below describe the former Launcher-managed implementation.
|
||||
|
||||
- [x] `LanMountainDesktop.Shared.IPC` builds in Debug.
|
||||
- [x] `LanMountainDesktop.Launcher` builds in Debug.
|
||||
- [x] `LanMountainDesktop` builds in Debug.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Launcher Managed Air APP Lifecycle
|
||||
|
||||
> Superseded by `.trae/specs/air-app-runtime-container/`. Launcher no longer hosts the Air APP lifecycle broker; it pre-starts `LanMountainDesktop.AirAppRuntime`, which owns the lifecycle IPC and AirAppHost process table.
|
||||
|
||||
## Goal
|
||||
|
||||
Make Launcher the authoritative lifecycle manager for built-in Air APP processes. The desktop host requests Air APP operations through IPC, while Launcher creates, activates, tracks, and cleans up Air APP host processes.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Tasks
|
||||
|
||||
> Superseded by `.trae/specs/air-app-runtime-container/`; the checked items below describe the former Launcher-managed implementation.
|
||||
|
||||
- [x] Add shared Air APP lifecycle IPC contracts.
|
||||
- [x] Add Launcher Air APP lifecycle service and dedicated IPC host.
|
||||
- [x] Make Launcher remain alive while desktop or Air APP processes exist.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
- [ ] New install shows OOBE once.
|
||||
- [ ] Same-user reinstall does not show OOBE again.
|
||||
- [ ] `postinstall` launch path is handled without misclassifying the user state.
|
||||
- [ ] `apply-update` and `plugin-install` do not auto-enter OOBE.
|
||||
- [ ] `plugin-install` does not auto-enter OOBE.
|
||||
- [ ] Default plugin install does not request UAC.
|
||||
- [ ] Logs include OOBE status, suppression reason, and launch source.
|
||||
- [ ] Startup presentation step inside `OobeWindow` (after data location) writes host `settings.json` and syncs Windows Run when autostart is chosen (Launcher executable).
|
||||
|
||||
@@ -23,12 +23,11 @@ Stabilize the launcher startup path so that:
|
||||
- `launchSource` values are treated as:
|
||||
- `normal`
|
||||
- `postinstall`
|
||||
- `apply-update`
|
||||
- `plugin-install`
|
||||
- `debug-preview`
|
||||
- Automatic OOBE is allowed only for normal user-mode startup.
|
||||
- `postinstall` may show OOBE only when the launcher is not elevated and user state is available.
|
||||
- `apply-update`, `plugin-install`, and `debug-preview` must not auto-enter OOBE.
|
||||
- `plugin-install` and `debug-preview` must not auto-enter OOBE.
|
||||
- Allowed elevation paths are limited to:
|
||||
- the installer itself
|
||||
- full installer update application
|
||||
|
||||
512
.trae/specs/plonds-comparator-redesign/spec.md
Normal file
512
.trae/specs/plonds-comparator-redesign/spec.md
Normal file
@@ -0,0 +1,512 @@
|
||||
# PLONDS Comparator 改造设计
|
||||
|
||||
> 日期:2026-05-30
|
||||
> 状态:待审批
|
||||
|
||||
## 1. 背景与动机
|
||||
|
||||
PLONDS(Penguin Logistics Online Network Distribution System)是 LanMountainDesktop 的文件驱动式分布式更新系统。当前 Comparator 工作流存在以下问题:
|
||||
|
||||
1. **产出物过于复杂**:生成 `update-{platform}.zip`、`plonds-filemap-{platform}.json`、`plonds-filemap-{platform}.json.sig`、`platform-summary-{platform}.json`、`plonds-static.zip` 等多个文件,客户端消费困难
|
||||
2. **模型定义重复**:`Plonds.Shared`、`Plonds.Core`、宿主侧、Launcher 侧各自定义独立的 DTO,字段名不一致
|
||||
3. **签名机制过重**:RSA 签名增加了 CI 复杂度(需要管理密钥),且对文件驱动式更新系统而言 SHA256 哈希校验已足够
|
||||
4. **平台覆盖不当**:Linux 平台不需要 PLONDS 支持,macOS 尚未接入,但代码中硬编码了三个平台
|
||||
5. **工作流间 artifact 传递脆弱**:Comparator → Publisher 通过 artifact 传递 `plonds-static.zip`,容易断裂
|
||||
|
||||
## 2. 设计目标
|
||||
|
||||
- 产出物精简为两个文件:`changed.zip` + `PLONDS.json`
|
||||
- 去掉 RSA 签名,只用 SHA256/MD5 校验
|
||||
- 只关注 Windows 平台
|
||||
- 统一模型定义,消除 DTO 重复
|
||||
- 保持 Comparator 和 Publisher 两个工作流的职责分离
|
||||
|
||||
## 3. 新产出物定义
|
||||
|
||||
### 3.1 changed.zip
|
||||
|
||||
只包含与上一版本有差异的文件(action 为 `add` 或 `replace` 的文件),目录结构与部署目录一致。
|
||||
|
||||
### 3.2 PLONDS.json
|
||||
|
||||
```json
|
||||
{
|
||||
"formatVersion": "2.0",
|
||||
"currentVersion": "1.2.0",
|
||||
"previousVersion": "1.1.0",
|
||||
"isFullUpdate": false,
|
||||
"requiresCleanInstall": false,
|
||||
"channel": "stable",
|
||||
"platform": "windows-x64",
|
||||
"updatedAt": "2026-05-30T12:00:00Z",
|
||||
|
||||
"filesMap": {
|
||||
"LanMountainDesktop.exe": {
|
||||
"action": "replace",
|
||||
"sha256": "abc123...",
|
||||
"size": 1024000
|
||||
},
|
||||
"LanMountainDesktop.dll": {
|
||||
"action": "reuse",
|
||||
"sha256": "def456...",
|
||||
"size": 512000
|
||||
},
|
||||
"OldModule.dll": {
|
||||
"action": "delete",
|
||||
"sha256": "",
|
||||
"size": 0
|
||||
}
|
||||
},
|
||||
|
||||
"changedFilesMap": {
|
||||
"LanMountainDesktop.exe": {
|
||||
"archivePath": "LanMountainDesktop.exe",
|
||||
"sha256": "abc123...",
|
||||
"size": 1024000
|
||||
}
|
||||
},
|
||||
|
||||
"checksums": {
|
||||
"changed.zip": "md5:9a8b7c6d..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 字段语义
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `formatVersion` | string | 协议版本,固定 `"2.0"` |
|
||||
| `currentVersion` | string | 当前发布版本 |
|
||||
| `previousVersion` | string | 基线版本(全量更新时为 `"0.0.0"`) |
|
||||
| `isFullUpdate` | bool | 是否为全量更新(找不到基线版本时为 true) |
|
||||
| `requiresCleanInstall` | bool | 启动器是否也更新了——如果是,客户端不走增量流程,让用户重新运行安装器 |
|
||||
| `channel` | string | 更新通道:`stable` 或 `preview` |
|
||||
| `platform` | string | 平台标识:`windows-x64` |
|
||||
| `updatedAt` | string | ISO 8601 时间戳 |
|
||||
| `filesMap` | object | 全量文件图:每个文件的 action + sha256 + size |
|
||||
| `changedFilesMap` | object | 变更文件图:只包含需要从 changed.zip 解压的文件 |
|
||||
| `checksums` | object | 产出物的 MD5 值 |
|
||||
|
||||
### 3.4 filesMap 中 action 的值
|
||||
|
||||
| Action | 含义 | changed.zip 中是否包含 |
|
||||
|--------|------|----------------------|
|
||||
| `add` | 新增文件 | ✅ |
|
||||
| `replace` | 替换文件 | ✅ |
|
||||
| `reuse` | 复用上一版本文件 | ❌ |
|
||||
| `delete` | 删除文件 | ❌ |
|
||||
|
||||
### 3.5 requiresCleanInstall 判断逻辑
|
||||
|
||||
比较 `LanMountainDesktop.Launcher.exe` 在当前版本和基线版本中的 SHA256:
|
||||
- 如果 SHA256 不同 → `requiresCleanInstall = true`
|
||||
- 如果 SHA256 相同或没有基线版本 → `requiresCleanInstall = false`
|
||||
|
||||
## 4. Plonds.Tool build-delta 命令改造
|
||||
|
||||
### 4.1 新命令签名
|
||||
|
||||
```
|
||||
build-delta --platform <platform>
|
||||
--current-version <version>
|
||||
--current-zip <file>
|
||||
--output-dir <dir>
|
||||
--channel <channel>
|
||||
[--baseline-version <version>]
|
||||
[--baseline-zip <file>]
|
||||
[--launcher-path <relative-path>]
|
||||
```
|
||||
|
||||
### 4.2 参数说明
|
||||
|
||||
| 参数 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `--platform` | 是 | 平台标识,如 `windows-x64` |
|
||||
| `--current-version` | 是 | 当前发布版本号 |
|
||||
| `--current-zip` | 是 | 当前版本的 payload zip 路径 |
|
||||
| `--output-dir` | 是 | 输出目录 |
|
||||
| `--channel` | 是 | 更新通道 |
|
||||
| `--baseline-version` | 否 | 基线版本号(省略则视为全量更新) |
|
||||
| `--baseline-zip` | 否 | 基线版本的 payload zip 路径(省略则视为全量更新) |
|
||||
| `--launcher-path` | 否 | Launcher 可执行文件的相对路径,默认 `LanMountainDesktop.Launcher.exe` |
|
||||
|
||||
### 4.3 删除的参数
|
||||
|
||||
| 参数 | 原因 |
|
||||
|------|------|
|
||||
| `--current-tag` | 不再需要,version 就够了 |
|
||||
| `--private-key` | 去掉签名 |
|
||||
| `--is-full-payload` | 自动判断:没有 baseline-zip 就是全量 |
|
||||
| `--static-output-dir` | 不再生成 S3 静态布局 |
|
||||
| `--update-base-url` | 不再生成 S3 URL |
|
||||
| `--baseline-tag` | 不再需要 |
|
||||
|
||||
### 4.4 内部逻辑
|
||||
|
||||
```
|
||||
1. 解压 current-zip → currentDir
|
||||
2. 如果有 baseline-zip → 解压 → baselineDir
|
||||
否则 → baselineDir = 空(全量更新)
|
||||
|
||||
3. 扫描 currentDir → 计算 SHA256
|
||||
4. 扫描 baselineDir → 计算 SHA256(如果有)
|
||||
|
||||
5. 对比生成 filesMap:
|
||||
- 两个版本都有且 SHA256 相同 → reuse
|
||||
- 两个版本都有但 SHA256 不同 → replace
|
||||
- 只在新版本中存在 → add
|
||||
- 只在旧版本中存在 → delete
|
||||
|
||||
6. 从 filesMap 提取 changedFilesMap:
|
||||
- 只包含 action=add/replace 的条目
|
||||
- 添加 archivePath(在 changed.zip 中的路径)
|
||||
|
||||
7. 打包 changed.zip:
|
||||
- 只包含 add/replace 的文件
|
||||
- 保持原始目录结构
|
||||
|
||||
8. 判断 requiresCleanInstall:
|
||||
- 比较 Launcher 可执行文件在两个版本中的 SHA256
|
||||
- 如果不同 → requiresCleanInstall=true
|
||||
|
||||
9. 计算 changed.zip 的 MD5
|
||||
|
||||
10. 生成 PLONDS.json
|
||||
|
||||
11. 输出到 output-dir:
|
||||
- changed.zip
|
||||
- PLONDS.json
|
||||
```
|
||||
|
||||
### 4.5 不再生成的产物
|
||||
|
||||
| 旧产物 | 处置 |
|
||||
|--------|------|
|
||||
| `update-{platform}.zip` | 被 `changed.zip` 替代 |
|
||||
| `plonds-filemap-{platform}.json` | 被 `PLONDS.json` 替代 |
|
||||
| `plonds-filemap-{platform}.json.sig` | 去掉签名 |
|
||||
| `platform-summary-{platform}.json` | 不再需要 |
|
||||
| `plonds-static.zip` | 不再生成 S3 静态布局 |
|
||||
| `meta/channels/...` | 不再由 Tool 生成,由 Publisher 负责 |
|
||||
|
||||
## 5. Plonds.Shared 模型改造
|
||||
|
||||
### 5.1 删除的模型
|
||||
|
||||
| 模型 | 原因 |
|
||||
|------|------|
|
||||
| `PlondsFileMap` | 被新的 `PlondsManifest` 替代 |
|
||||
| `PlondsFileEntry` | 被新的 `PlondsFileEntry` 替代 |
|
||||
| `PlondsComponent` | 不再有组件概念 |
|
||||
| `PlondsDistributionInfo` | 不再生成分发文档 |
|
||||
| `PlondsChannelPointer` | 由 Publisher 用脚本生成 |
|
||||
| `PlondsReleaseManifest` | 不再需要 |
|
||||
| `PlondsReleasePlatformEntry` | 不再需要 |
|
||||
| `PlondsSignatureDescriptor` | 去掉签名 |
|
||||
| `PlondsMirrorAsset` | 由 Publisher 处理 |
|
||||
| `PlondsMirrorEntry` | 由 Publisher 处理 |
|
||||
| `PlondsMetadataCatalog` | 不再需要 |
|
||||
| `PlondsAssetEntry` | 不再需要 |
|
||||
|
||||
### 5.2 新模型定义
|
||||
|
||||
```csharp
|
||||
// PlondsManifest — 对应 PLONDS.json
|
||||
public sealed record PlondsManifest(
|
||||
string FormatVersion,
|
||||
string CurrentVersion,
|
||||
string PreviousVersion,
|
||||
bool IsFullUpdate,
|
||||
bool RequiresCleanInstall,
|
||||
string Channel,
|
||||
string Platform,
|
||||
DateTimeOffset UpdatedAt,
|
||||
IReadOnlyDictionary<string, PlondsFileEntry> FilesMap,
|
||||
IReadOnlyDictionary<string, PlondsChangedFileEntry> ChangedFilesMap,
|
||||
IReadOnlyDictionary<string, string> Checksums);
|
||||
|
||||
// PlondsFileEntry — filesMap 中的条目
|
||||
public sealed record PlondsFileEntry(
|
||||
string Action, // add | replace | reuse | delete
|
||||
string Sha256,
|
||||
long Size);
|
||||
|
||||
// PlondsChangedFileEntry — changedFilesMap 中的条目
|
||||
public sealed record PlondsChangedFileEntry(
|
||||
string ArchivePath, // 在 changed.zip 中的路径
|
||||
string Sha256,
|
||||
long Size);
|
||||
```
|
||||
|
||||
### 5.3 设计决策
|
||||
|
||||
- `FilesMap` 和 `ChangedFilesMap` 用 `IReadOnlyDictionary<string, T>` 而非 `IReadOnlyList<T>`,key 就是文件相对路径,查找 O(1)
|
||||
- 去掉 `Component` 概念——当前只有一个 `app` 组件,分层没有实际意义
|
||||
- `FormatVersion` 固定为 `"2.0"`,与旧格式区分
|
||||
|
||||
## 6. Comparator 工作流改造
|
||||
|
||||
### 6.1 保留两个工作流
|
||||
|
||||
- **Comparator**(`plonds-comparator.yml`):比较文件生成器,只负责生成 `changed.zip` + `PLONDS.json`
|
||||
- **Publisher**(`plonds-publisher.yml`,原 `plonds-uploader.yml`):发布器,负责上传到 S3 和生成 channel pointer
|
||||
|
||||
### 6.2 Comparator 改造后步骤
|
||||
|
||||
```yaml
|
||||
# plonds-comparator.yml
|
||||
触发: release.published / release.prereleased / workflow_dispatch
|
||||
|
||||
jobs:
|
||||
compare:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- Checkout
|
||||
|
||||
- 解析发布上下文
|
||||
→ RELEASE_TAG, RELEASE_VERSION, RELEASE_CHANNEL
|
||||
|
||||
- Setup .NET
|
||||
|
||||
- 构建 PLONDS Tool
|
||||
|
||||
- 解析基线版本
|
||||
→ 查找上一个同频道 Release
|
||||
→ 如果有 → 记录 baseline_tag, baseline_version
|
||||
→ 如果没有 → is_full_update=true
|
||||
|
||||
- 下载 payload zips
|
||||
→ 下载当前版本 files-windows-x64.zip
|
||||
→ 下载基线版本 files-windows-x64.zip (如果有)
|
||||
|
||||
- 运行 build-delta
|
||||
→ dotnet run Plonds.Tool -- build-delta \
|
||||
--platform windows-x64 \
|
||||
--current-version $VERSION \
|
||||
--current-zip files-windows-x64.zip \
|
||||
--output-dir plonds-output \
|
||||
--channel $CHANNEL \
|
||||
[--baseline-version $BASELINE_VERSION] \
|
||||
[--baseline-zip baseline-files-windows-x64.zip]
|
||||
|
||||
- 上传到 GitHub Release
|
||||
→ gh release upload changed.zip PLONDS.json
|
||||
|
||||
- 传递元数据给 Publisher
|
||||
→ 上传 artifact: plonds-run-metadata (tag.txt)
|
||||
```
|
||||
|
||||
### 6.3 与当前步骤的差异
|
||||
|
||||
| 当前步骤 | 改造后 |
|
||||
|---------|--------|
|
||||
| 准备签名密钥 | ❌ 删除 |
|
||||
| 解析基线计划 (pwsh,三平台) | ✅ 简化:只找 Windows,逻辑简化 |
|
||||
| 下载 payload zips (pwsh,三平台) | ✅ 简化:只下载 Windows |
|
||||
| 构建增量资产 (pwsh,含 build-index + 静态布局验证 + plonds-static.zip 打包) | ✅ 简化:只调用 build-delta |
|
||||
| 上传 PLONDS assets 到 release | ✅ 简化:只上传 changed.zip + PLONDS.json |
|
||||
| 传递元数据 | ✅ 保留,但 artifact 内容简化 |
|
||||
|
||||
## 7. 双模式差分生成
|
||||
|
||||
### 7.1 概述
|
||||
|
||||
Comparator 支持两种差分生成方法,通过 `workflow_dispatch` 的 `compare_method` 输入项选择:
|
||||
|
||||
| 方法 | 标识 | 核心思路 |
|
||||
|------|------|---------|
|
||||
| 方法一 | `file-compare` | 下载两个版本的 files zip,全量文件哈希对比 |
|
||||
| 方法二 | `commit-analyze` | 分析两个版本之间的 git commit,映射源码变更到产物文件 |
|
||||
|
||||
### 7.2 GitHub Actions 触发器新增输入项
|
||||
|
||||
```yaml
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag: ...
|
||||
baseline_tag: ...
|
||||
channel: ...
|
||||
compare_method: # 新增
|
||||
description: '比较方法'
|
||||
type: choice
|
||||
default: file-compare
|
||||
options:
|
||||
- file-compare
|
||||
- commit-analyze
|
||||
hash_algorithm: # 新增(仅方法一)
|
||||
description: '哈希算法'
|
||||
type: choice
|
||||
default: sha256
|
||||
options:
|
||||
- sha256
|
||||
- md5
|
||||
```
|
||||
|
||||
当由 `release` 事件触发时,默认使用 `file-compare` + `sha256`。
|
||||
|
||||
### 7.3 方法一:文件对比模式(file-compare)
|
||||
|
||||
**流程:**
|
||||
|
||||
```
|
||||
1. 下载当前版本 files-windows-x64.zip
|
||||
2. 下载基线版本 files-windows-x64.zip(如果有)
|
||||
3. 解压两个 zip 到临时目录
|
||||
4. 用指定哈希算法(sha256/md5)扫描两个目录的所有文件
|
||||
5. 对比哈希值,生成 filesMap(add/replace/reuse/delete)
|
||||
6. 从当前版本目录中提取 add/replace 的文件 → changed.zip
|
||||
7. 生成 PLONDS.json
|
||||
```
|
||||
|
||||
**PlondsDeltaBuildOptions 新增参数:**
|
||||
|
||||
```csharp
|
||||
string HashAlgorithm = "sha256" // "sha256" | "md5"
|
||||
```
|
||||
|
||||
**哈希算法对 PLONDS.json 的影响:**
|
||||
|
||||
- `sha256`:`filesMap` 和 `changedFilesMap` 中使用 `sha256` 字段
|
||||
- `md5`:`filesMap` 和 `changedFilesMap` 中使用 `md5` 字段
|
||||
|
||||
### 7.4 方法二:Commit 分析模式(commit-analyze)
|
||||
|
||||
**流程:**
|
||||
|
||||
```
|
||||
1. 下载当前版本 files-windows-x64.zip
|
||||
2. 解压到临时目录
|
||||
3. git log --name-only baseline_tag..current_tag
|
||||
→ 得到两个版本之间的 commit 列表和涉及的源码文件
|
||||
4. 过滤:只保留源码目录下的文件
|
||||
5. 用简单规则映射源码文件到产物文件
|
||||
6. 从当前版本的解压目录中提取映射到的产物文件 → changed.zip
|
||||
7. 生成 PLONDS.json
|
||||
8. 如果没有源码变更 → 自动回退到方法一
|
||||
```
|
||||
|
||||
**源码目录过滤规则:**
|
||||
|
||||
只分析以下目录下的文件变更:
|
||||
|
||||
| 目录 | 说明 |
|
||||
|------|------|
|
||||
| `LanMountainDesktop/` | 主宿主应用 |
|
||||
| `LanMountainDesktop.Launcher/` | 启动器 |
|
||||
| `LanMountainDesktop.Shared.Contracts/` | 共享契约 |
|
||||
| `LanMountainDesktop.PluginSdk/` | 插件 SDK |
|
||||
| `LanMountainDesktop.Appearance/` | 外观系统 |
|
||||
| `LanMountainDesktop.Settings.Core/` | 设置核心 |
|
||||
| `LanMountainDesktop.ComponentSystem/` | 组件系统 |
|
||||
|
||||
忽略的目录:`docs/`、`scripts/`、`.github/`、`.trae/`、`PenguinLogisticsOnlineNetworkDistributionSystem/`
|
||||
|
||||
**源码到产物的映射规则:**
|
||||
|
||||
| 源码路径模式 | 映射到产物文件 |
|
||||
|-------------|--------------|
|
||||
| `LanMountainDesktop/**/*.{cs,axaml,xaml}` | `LanMountainDesktop.dll`, `LanMountainDesktop.exe` |
|
||||
| `LanMountainDesktop.Launcher/**/*.{cs,axaml,xaml}` | `LanMountainDesktop.Launcher.exe` |
|
||||
| `LanMountainDesktop.Shared.Contracts/**/*.cs` | `LanMountainDesktop.Shared.Contracts.dll` |
|
||||
| `LanMountainDesktop.PluginSdk/**/*.cs` | `LanMountainDesktop.PluginSdk.dll` |
|
||||
| `LanMountainDesktop.Appearance/**/*.cs` | `LanMountainDesktop.Appearance.dll` |
|
||||
| `LanMountainDesktop.Settings.Core/**/*.cs` | `LanMountainDesktop.Settings.Core.dll` |
|
||||
| `LanMountainDesktop.ComponentSystem/**/*.cs` | `LanMountainDesktop.ComponentSystem.dll` |
|
||||
| `**/*.json`(配置文件) | 同路径的 .json |
|
||||
| 其他无法映射的变更 | 保守标记 → 所有核心 .dll/.exe |
|
||||
|
||||
**方法二在 Plonds.Tool 中的新命令:**
|
||||
|
||||
```
|
||||
build-delta-from-commits --platform <platform>
|
||||
--current-version <version>
|
||||
--current-zip <file>
|
||||
--output-dir <dir>
|
||||
--channel <channel>
|
||||
--baseline-tag <tag>
|
||||
--current-tag <tag>
|
||||
[--source-dirs <dir1,dir2,...>]
|
||||
[--fallback-zip <file>]
|
||||
```
|
||||
|
||||
| 参数 | 必需 | 说明 |
|
||||
|------|------|------|
|
||||
| `--platform` | 是 | 平台标识 |
|
||||
| `--current-version` | 是 | 当前发布版本号 |
|
||||
| `--current-zip` | 是 | 当前版本的 payload zip |
|
||||
| `--output-dir` | 是 | 输出目录 |
|
||||
| `--channel` | 是 | 更新通道 |
|
||||
| `--baseline-tag` | 是 | 基线版本的 git tag |
|
||||
| `--current-tag` | 是 | 当前版本的 git tag |
|
||||
| `--source-dirs` | 否 | 要分析的源码目录列表(逗号分隔) |
|
||||
| `--fallback-zip` | 否 | 回退到方法一时使用的基线 zip |
|
||||
|
||||
**回退逻辑:**
|
||||
|
||||
如果 `git log` 分析后发现没有源码目录下的文件变更(比如只有 docs/ 变更),则自动回退到方法一:
|
||||
1. 如果提供了 `--fallback-zip` → 用方法一对比两个 zip
|
||||
2. 如果没有提供 → 生成全量更新(`isFullUpdate=true`)
|
||||
|
||||
### 7.5 方法二的 PLONDS.json 特殊处理
|
||||
|
||||
方法二无法像方法一那样生成完整的 `filesMap`(因为不知道哪些文件是 reuse 的),因此:
|
||||
|
||||
- `filesMap` 只包含映射到的变更文件(标记为 `add` 或 `replace`)
|
||||
- 不包含 `reuse` 和 `delete` 条目
|
||||
- `isFullUpdate` 始终为 `false`(除非回退到方法一且无基线)
|
||||
- `requiresCleanInstall` 根据 Launcher.exe 是否在映射到的变更文件列表中判断
|
||||
|
||||
### 7.6 工作流中的条件分支
|
||||
|
||||
```yaml
|
||||
- name: Run build-delta
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$COMPARE_METHOD" == "commit-analyze" ]]; then
|
||||
# 方法二
|
||||
dotnet run --project ... -- build-delta-from-commits \
|
||||
--platform windows-x64 \
|
||||
--current-version $RELEASE_VERSION \
|
||||
--current-zip $PWD/plonds-input/current-files-windows-x64.zip \
|
||||
--output-dir $PWD/plonds-output \
|
||||
--channel $RELEASE_CHANNEL \
|
||||
--baseline-tag $BASELINE_TAG \
|
||||
--current-tag $RELEASE_TAG \
|
||||
--fallback-zip $PWD/plonds-input/baseline-files-windows-x64.zip
|
||||
else
|
||||
# 方法一
|
||||
dotnet run --project ... -- build-delta \
|
||||
--platform windows-x64 \
|
||||
--current-version $RELEASE_VERSION \
|
||||
--current-zip $PWD/plonds-input/current-files-windows-x64.zip \
|
||||
--output-dir $PWD/plonds-output \
|
||||
--channel $RELEASE_CHANNEL \
|
||||
--hash-algorithm $HASH_ALGORITHM \
|
||||
--baseline-version $BASELINE_VERSION \
|
||||
--baseline-zip $PWD/plonds-input/baseline-files-windows-x64.zip
|
||||
fi
|
||||
```
|
||||
|
||||
方法二时,基线 zip 仍然需要下载(用于回退),但不需要解压(除非回退)。
|
||||
|
||||
### 7.7 两种方法的步骤差异
|
||||
|
||||
| 步骤 | 方法一 (file-compare) | 方法二 (commit-analyze) |
|
||||
|------|----------------------|------------------------|
|
||||
| 下载基线 zip | ✅ 需要 | ✅ 需要(用于回退) |
|
||||
| 下载当前 zip | ✅ | ✅ |
|
||||
| 解压两个 zip | ✅ | ✅ 只解压当前(回退时解压基线) |
|
||||
| git diff/log | ❌ | ✅ 需要 fetch-depth:0 |
|
||||
| 哈希对比 | ✅ 两个目录全量扫描 | ❌ 不做(除非回退) |
|
||||
| 源码→产物映射 | ❌ | ✅ |
|
||||
| 回退逻辑 | ❌ | ✅ 无源码变更时回退方法一 |
|
||||
|
||||
## 8. 不在本次改造范围内的事项
|
||||
|
||||
- Publisher 工作流改造(后续单独设计)
|
||||
- Rollback 工作流改造(后续单独设计)
|
||||
- 宿主侧客户端代码改造(PlondsUpdateApplier 等,后续单独设计)
|
||||
- Launcher 侧客户端代码改造(后续单独设计)
|
||||
- Plonds.Api 项目处置(后续决定是否保留)
|
||||
- `build-index`、`build-plonds`、`generate`、`publish`、`sign`、`pack-payload` 等 Tool 命令的清理(后续处理)
|
||||
@@ -8,7 +8,10 @@ Rebuild the settings window as an independent Fluent shell with a custom titleba
|
||||
|
||||
- Keep the existing independent settings-window lifecycle: open-or-focus, no owner anchor, own taskbar entry.
|
||||
- Use a 48 DIP titlebar with Back, pane toggle, icon/title, search, restart action, more menu, and caption-button spacer.
|
||||
- Keep the titlebar and content area on one shared full-window background layer; the custom titlebar must remain transparent and must not paint a contrasting strip.
|
||||
- Avoid a visible titlebar bottom divider that makes the titlebar read as a separate color band.
|
||||
- Keep `FANavigationView` as the primary navigation surface with `OpenPaneLength` around 283 DIP.
|
||||
- Keep `FANavigationView` pane and content template backgrounds transparent in the settings shell so the navigation control does not reintroduce a second surface color.
|
||||
- Move the compact/minimal pane toggle from the navigation footer into the titlebar.
|
||||
- Add search over built-in settings pages and settings expanders; selecting a result navigates, expands, focuses, and highlights.
|
||||
- Add `auto` system material mode and make it the default.
|
||||
|
||||
@@ -15,7 +15,7 @@ Make the Settings > Update page the single user-facing control surface for the h
|
||||
- Users can opt into forced reinstall. When enabled, the update check targets the current version manifest where available and the UI labels the next payload as reinstall.
|
||||
- The page displays whether the current payload is an incremental update or reinstall/full installer.
|
||||
- The page exposes pause, resume, and cancel actions for resumable downloads and install recovery.
|
||||
- Existing PloNDS/FileMap incremental update and Launcher rollback ownership remain unchanged.
|
||||
- Existing PloNDS/FileMap incremental update behavior remains, but update apply and rollback ownership belongs to the Host. Launcher only selects and starts the current app version.
|
||||
|
||||
## Acceptance
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ This spec is deprecated and superseded by `.trae/specs/pdc-incremental-migration
|
||||
|
||||
- VeloPack native package generation introduced unstable release blocking (version format coupling and platform divergence).
|
||||
- The project has switched back to signed FileMap incremental assets as the primary update path.
|
||||
- Launcher remains the update installer/rollback authority; packaging and distribution are being migrated to PDC/S3-compatible flows.
|
||||
- Host owns update install and rollback authority; packaging and distribution are being migrated to PDC/S3-compatible flows. Launcher only selects and starts the current app version.
|
||||
|
||||
## Migration Note
|
||||
|
||||
|
||||
14
CheckIpcAot/CheckIpcAot.csproj
Normal file
14
CheckIpcAot/CheckIpcAot.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="dotnetCampus.Ipc" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
10
CheckIpcAot/Program.cs
Normal file
10
CheckIpcAot/Program.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using dotnetCampus.Ipc.CompilerServices.Attributes;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
[IpcPublic]
|
||||
public interface IMyService {
|
||||
Task<MyResult> DoWork(MyRequest req);
|
||||
}
|
||||
|
||||
public class MyResult { public string Msg {get;set;} }
|
||||
public class MyRequest { public string Data {get;set;} }
|
||||
@@ -1,10 +1,15 @@
|
||||
namespace LanMountainDesktop.Launcher.AirApp;
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal sealed class AirAppHostLocator
|
||||
{
|
||||
private const string WindowsExecutableName = "LanMountainDesktop.AirAppHost.exe";
|
||||
private const string UnixExecutableName = "LanMountainDesktop.AirAppHost";
|
||||
private const string DllName = "LanMountainDesktop.AirAppHost.dll";
|
||||
|
||||
private static string ExecutableName => OperatingSystem.IsWindows()
|
||||
? WindowsExecutableName
|
||||
: UnixExecutableName;
|
||||
|
||||
public string Resolve(string? packageRoot, string? hostPath = null)
|
||||
{
|
||||
foreach (var candidate in EnumerateCandidates(packageRoot, hostPath))
|
||||
@@ -22,18 +27,18 @@ internal sealed class AirAppHostLocator
|
||||
{
|
||||
foreach (var root in EnumerateRoots(packageRoot, hostPath))
|
||||
{
|
||||
yield return Path.Combine(root, "AirAppHost", WindowsExecutableName);
|
||||
yield return Path.Combine(root, "AirAppHost", ExecutableName);
|
||||
yield return Path.Combine(root, "AirAppHost", DllName);
|
||||
yield return Path.Combine(root, WindowsExecutableName);
|
||||
yield return Path.Combine(root, ExecutableName);
|
||||
yield return Path.Combine(root, DllName);
|
||||
|
||||
if (Directory.Exists(root))
|
||||
{
|
||||
foreach (var deploymentDirectory in Directory.GetDirectories(root, "app-*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
yield return Path.Combine(deploymentDirectory, "AirAppHost", WindowsExecutableName);
|
||||
yield return Path.Combine(deploymentDirectory, "AirAppHost", ExecutableName);
|
||||
yield return Path.Combine(deploymentDirectory, "AirAppHost", DllName);
|
||||
yield return Path.Combine(deploymentDirectory, WindowsExecutableName);
|
||||
yield return Path.Combine(deploymentDirectory, ExecutableName);
|
||||
yield return Path.Combine(deploymentDirectory, DllName);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +57,7 @@ internal sealed class AirAppHostLocator
|
||||
"Release",
|
||||
#endif
|
||||
"net10.0",
|
||||
WindowsExecutableName);
|
||||
ExecutableName);
|
||||
|
||||
yield return Path.Combine(
|
||||
current.FullName,
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace LanMountainDesktop.Launcher.AirApp;
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal static class AirAppInstanceKey
|
||||
{
|
||||
@@ -17,8 +17,6 @@ internal static class AirAppInstanceKey
|
||||
|
||||
private static string Normalize(string? value, string fallback)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value)
|
||||
? fallback
|
||||
: value.Trim();
|
||||
return string.IsNullOrWhiteSpace(value) ? fallback : value.Trim();
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,15 @@ using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.AirApp;
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
internal sealed class AirAppLifecycleService : IAirAppLifecycleService
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly IAirAppProcessStarter _processStarter;
|
||||
private readonly Dictionary<string, ManagedAirAppInstance> _instances = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public LauncherAirAppLifecycleService(IAirAppProcessStarter processStarter)
|
||||
public AirAppLifecycleService(IAirAppProcessStarter processStarter)
|
||||
{
|
||||
_processStarter = processStarter;
|
||||
}
|
||||
@@ -20,7 +20,7 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var appId = Normalize(request.AppId, "unknown");
|
||||
var instanceKey = AirAppInstanceKey.Build(appId, request.SourceComponentId, request.SourcePlacementId);
|
||||
Logger.Info(
|
||||
AirAppRuntimeLogger.Info(
|
||||
$"Air APP open requested. AppId='{appId}'; InstanceKey='{instanceKey}'; RequesterProcessId={request.RequesterProcessId}.");
|
||||
|
||||
lock (_gate)
|
||||
@@ -57,12 +57,12 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
request.SourceComponentId,
|
||||
request.SourcePlacementId);
|
||||
_instances[instanceKey] = instance;
|
||||
Logger.Info($"Started Air APP. AppId='{appId}'; InstanceKey='{instanceKey}'; ProcessId={process.Id}.");
|
||||
AirAppRuntimeLogger.Info($"Started Air APP. AppId='{appId}'; InstanceKey='{instanceKey}'; ProcessId={process.Id}.");
|
||||
return Task.FromResult(BuildResult(true, "started", "Started Air APP instance.", instance));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Failed to start Air APP '{appId}': {ex.Message}");
|
||||
AirAppRuntimeLogger.Warn($"Failed to start Air APP '{appId}': {ex.Message}");
|
||||
return Task.FromResult(BuildResult(false, "start_failed", ex.Message, null));
|
||||
}
|
||||
}
|
||||
@@ -134,7 +134,7 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
request.SourceComponentId,
|
||||
request.SourcePlacementId);
|
||||
_instances[instanceKey] = instance;
|
||||
Logger.Info($"Registered Air APP. AppId='{instance.AppId}'; InstanceKey='{instanceKey}'; ProcessId={instance.ProcessId}.");
|
||||
AirAppRuntimeLogger.Info($"Registered Air APP. AppId='{instance.AppId}'; InstanceKey='{instanceKey}'; ProcessId={instance.ProcessId}.");
|
||||
return Task.FromResult(BuildResult(true, "registered", "Air APP instance registered.", instance));
|
||||
}
|
||||
}
|
||||
@@ -147,7 +147,7 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
(processId <= 0 || instance.ProcessId == processId))
|
||||
{
|
||||
_instances.Remove(instanceKey);
|
||||
Logger.Info($"Unregistered Air APP. InstanceKey='{instanceKey}'; ProcessId={processId}.");
|
||||
AirAppRuntimeLogger.Info($"Unregistered Air APP. InstanceKey='{instanceKey}'; ProcessId={processId}.");
|
||||
return Task.FromResult(BuildResult(true, "unregistered", "Air APP instance unregistered.", instance));
|
||||
}
|
||||
|
||||
@@ -174,7 +174,7 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
foreach (var key in exitedKeys)
|
||||
{
|
||||
_instances.Remove(key);
|
||||
Logger.Info($"Pruned exited Air APP instance. InstanceKey='{key}'.");
|
||||
AirAppRuntimeLogger.Info($"Pruned exited Air APP instance. InstanceKey='{key}'.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,7 +237,7 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsProcessAlive(int processId)
|
||||
internal static bool IsProcessAlive(int processId)
|
||||
{
|
||||
if (processId <= 0)
|
||||
{
|
||||
@@ -257,9 +257,7 @@ internal sealed class LauncherAirAppLifecycleService : IAirAppLifecycleService
|
||||
|
||||
private static string Normalize(string? value, string fallback)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value)
|
||||
? fallback
|
||||
: value.Trim();
|
||||
return string.IsNullOrWhiteSpace(value) ? fallback : value.Trim();
|
||||
}
|
||||
|
||||
private const int SW_SHOWNORMAL = 1;
|
||||
@@ -0,0 +1,29 @@
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal sealed class AirAppRuntimeControlService : IAirAppRuntimeControlService
|
||||
{
|
||||
private readonly AirAppRuntimeLifetime _lifetime;
|
||||
|
||||
public AirAppRuntimeControlService(AirAppRuntimeLifetime lifetime)
|
||||
{
|
||||
_lifetime = lifetime;
|
||||
}
|
||||
|
||||
public Task<AirAppRuntimeControlResult> AttachHostAsync(int hostProcessId)
|
||||
{
|
||||
_lifetime.AttachHost(hostProcessId);
|
||||
var status = _lifetime.GetStatus();
|
||||
return Task.FromResult(new AirAppRuntimeControlResult(
|
||||
hostProcessId > 0,
|
||||
hostProcessId > 0 ? "host_attached" : "invalid_host_pid",
|
||||
hostProcessId > 0 ? "AirApp runtime host process attached." : "Host process id must be positive.",
|
||||
status));
|
||||
}
|
||||
|
||||
public Task<AirAppRuntimeStatus> GetStatusAsync()
|
||||
{
|
||||
return Task.FromResult(_lifetime.GetStatus());
|
||||
}
|
||||
}
|
||||
29
LanMountainDesktop.AirAppRuntime/AirAppRuntimeIpcHost.cs
Normal file
29
LanMountainDesktop.AirAppRuntime/AirAppRuntimeIpcHost.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using LanMountainDesktop.Shared.IPC;
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal sealed class AirAppRuntimeIpcHost : IDisposable
|
||||
{
|
||||
private readonly PublicIpcHostService _host;
|
||||
|
||||
public AirAppRuntimeIpcHost(
|
||||
AirAppLifecycleService lifecycleService,
|
||||
AirAppRuntimeControlService controlService)
|
||||
{
|
||||
_host = new PublicIpcHostService(IpcConstants.AirAppRuntimePipeName);
|
||||
_host.RegisterPublicService<IAirAppLifecycleService>(lifecycleService);
|
||||
_host.RegisterPublicService<IAirAppRuntimeControlService>(controlService);
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_host.Start();
|
||||
AirAppRuntimeLogger.Info($"Air APP runtime IPC started. Pipe='{IpcConstants.AirAppRuntimePipeName}'.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_host.Dispose();
|
||||
}
|
||||
}
|
||||
77
LanMountainDesktop.AirAppRuntime/AirAppRuntimeLifetime.cs
Normal file
77
LanMountainDesktop.AirAppRuntime/AirAppRuntimeLifetime.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal sealed class AirAppRuntimeLifetime
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly DateTimeOffset _startedAtUtc = DateTimeOffset.UtcNow;
|
||||
private readonly AirAppLifecycleService _lifecycleService;
|
||||
private readonly int _launcherProcessId;
|
||||
private readonly int _requesterProcessId;
|
||||
private int _hostProcessId;
|
||||
private DateTimeOffset _updatedAtUtc;
|
||||
|
||||
public AirAppRuntimeLifetime(AirAppRuntimeOptions options, AirAppLifecycleService lifecycleService)
|
||||
{
|
||||
_lifecycleService = lifecycleService;
|
||||
_launcherProcessId = options.LauncherProcessId;
|
||||
_requesterProcessId = options.RequesterProcessId;
|
||||
_hostProcessId = options.RequesterProcessId;
|
||||
_updatedAtUtc = _startedAtUtc;
|
||||
}
|
||||
|
||||
public void AttachHost(int hostProcessId)
|
||||
{
|
||||
if (hostProcessId <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_hostProcessId = hostProcessId;
|
||||
_updatedAtUtc = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
AirAppRuntimeLogger.Info($"Attached host process. HostPid={hostProcessId}.");
|
||||
}
|
||||
|
||||
public bool ShouldKeepAlive()
|
||||
{
|
||||
var status = GetStatus();
|
||||
return status.LauncherProcessAlive ||
|
||||
status.HostProcessAlive ||
|
||||
IsProcessAlive(_requesterProcessId) ||
|
||||
status.HasLiveAirApps;
|
||||
}
|
||||
|
||||
public AirAppRuntimeStatus GetStatus()
|
||||
{
|
||||
int hostPid;
|
||||
DateTimeOffset updatedAt;
|
||||
lock (_gate)
|
||||
{
|
||||
hostPid = _hostProcessId;
|
||||
updatedAt = _updatedAtUtc;
|
||||
}
|
||||
|
||||
var launcherAlive = IsProcessAlive(_launcherProcessId);
|
||||
var hostAlive = IsProcessAlive(hostPid);
|
||||
var hasLiveAirApps = _lifecycleService.HasLiveAirApps();
|
||||
return new AirAppRuntimeStatus(
|
||||
Environment.ProcessId,
|
||||
_launcherProcessId,
|
||||
hostPid,
|
||||
launcherAlive,
|
||||
hostAlive,
|
||||
hasLiveAirApps,
|
||||
_startedAtUtc,
|
||||
updatedAt);
|
||||
}
|
||||
|
||||
internal static bool IsProcessAlive(int processId)
|
||||
{
|
||||
return AirAppLifecycleService.IsProcessAlive(processId);
|
||||
}
|
||||
}
|
||||
16
LanMountainDesktop.AirAppRuntime/AirAppRuntimeLogger.cs
Normal file
16
LanMountainDesktop.AirAppRuntime/AirAppRuntimeLogger.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal static class AirAppRuntimeLogger
|
||||
{
|
||||
public static void Info(string message) => Trace.WriteLine($"[AirAppRuntime] INFO {message}");
|
||||
|
||||
public static void Warn(string message) => Trace.WriteLine($"[AirAppRuntime] WARN {message}");
|
||||
|
||||
public static void Warn(string message, Exception ex) =>
|
||||
Trace.WriteLine($"[AirAppRuntime] WARN {message} {ex}");
|
||||
|
||||
public static void Error(string message, Exception ex) =>
|
||||
Trace.WriteLine($"[AirAppRuntime] ERROR {message} {ex}");
|
||||
}
|
||||
66
LanMountainDesktop.AirAppRuntime/AirAppRuntimeOptions.cs
Normal file
66
LanMountainDesktop.AirAppRuntime/AirAppRuntimeOptions.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal sealed record AirAppRuntimeOptions(
|
||||
string? AppRoot,
|
||||
string? DataRoot,
|
||||
int LauncherProcessId,
|
||||
int RequesterProcessId)
|
||||
{
|
||||
public static AirAppRuntimeOptions Parse(IReadOnlyList<string> args)
|
||||
{
|
||||
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var index = 0; index < args.Count; index++)
|
||||
{
|
||||
var current = args[index];
|
||||
if (!current.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = current[2..];
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var equalsIndex = key.IndexOf('=');
|
||||
if (equalsIndex >= 0)
|
||||
{
|
||||
values[key[..equalsIndex]] = key[(equalsIndex + 1)..];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index + 1 < args.Count && !args[index + 1].StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
values[key] = args[++index];
|
||||
}
|
||||
else
|
||||
{
|
||||
values[key] = "true";
|
||||
}
|
||||
}
|
||||
|
||||
return new AirAppRuntimeOptions(
|
||||
GetOptionalPath(values, "app-root"),
|
||||
GetOptionalPath(values, "data-root"),
|
||||
GetInt(values, "launcher-pid"),
|
||||
GetInt(values, "requester-pid"));
|
||||
}
|
||||
|
||||
private static string? GetOptionalPath(IReadOnlyDictionary<string, string> values, string key)
|
||||
{
|
||||
return values.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value)
|
||||
? Path.GetFullPath(value)
|
||||
: null;
|
||||
}
|
||||
|
||||
private static int GetInt(IReadOnlyDictionary<string, string> values, string key)
|
||||
{
|
||||
return values.TryGetValue(key, out var value) &&
|
||||
int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed)
|
||||
? parsed
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Diagnostics;
|
||||
namespace LanMountainDesktop.Launcher.AirApp;
|
||||
using LanMountainDesktop.Shared.IPC;
|
||||
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal interface IAirAppProcessStarter
|
||||
{
|
||||
@@ -12,20 +14,17 @@ internal sealed class AirAppProcessStarter : IAirAppProcessStarter
|
||||
private readonly Func<string?> _packageRootProvider;
|
||||
private readonly Func<string?> _hostPathProvider;
|
||||
private readonly Func<string?> _dataRootProvider;
|
||||
private readonly DotNetRuntimeProbeOptions? _runtimeProbeOptions;
|
||||
|
||||
public AirAppProcessStarter(
|
||||
AirAppHostLocator locator,
|
||||
Func<string?> packageRootProvider,
|
||||
Func<string?> hostPathProvider,
|
||||
Func<string?> dataRootProvider,
|
||||
DotNetRuntimeProbeOptions? runtimeProbeOptions = null)
|
||||
Func<string?> dataRootProvider)
|
||||
{
|
||||
_locator = locator;
|
||||
_packageRootProvider = packageRootProvider;
|
||||
_hostPathProvider = hostPathProvider;
|
||||
_dataRootProvider = dataRootProvider;
|
||||
_runtimeProbeOptions = runtimeProbeOptions;
|
||||
}
|
||||
|
||||
public Process? Start(
|
||||
@@ -36,12 +35,12 @@ internal sealed class AirAppProcessStarter : IAirAppProcessStarter
|
||||
string? sourcePlacementId)
|
||||
{
|
||||
var hostPath = _locator.Resolve(_packageRootProvider(), _hostPathProvider());
|
||||
var startInfo = CreateStartInfo(hostPath, _runtimeProbeOptions);
|
||||
var startInfo = CreateStartInfo(hostPath);
|
||||
|
||||
AddArgument(startInfo, "--app-id", appId);
|
||||
AddArgument(startInfo, "--session-id", sessionId);
|
||||
AddArgument(startInfo, "--instance-key", instanceKey);
|
||||
AddArgument(startInfo, "--launcher-pipe", LanMountainDesktop.Shared.IPC.IpcConstants.AirAppLifecyclePipeName);
|
||||
AddArgument(startInfo, "--launcher-pipe", IpcConstants.AirAppRuntimePipeName);
|
||||
var dataRoot = _dataRootProvider();
|
||||
if (!string.IsNullOrWhiteSpace(dataRoot))
|
||||
{
|
||||
@@ -58,7 +57,7 @@ internal sealed class AirAppProcessStarter : IAirAppProcessStarter
|
||||
AddArgument(startInfo, "--source-placement-id", sourcePlacementId.Trim());
|
||||
}
|
||||
|
||||
Logger.Info(
|
||||
AirAppRuntimeLogger.Info(
|
||||
$"Starting AirAppHost. AppId='{appId}'; InstanceKey='{instanceKey}'; HostPath='{hostPath}'; DataRoot='{dataRoot ?? string.Empty}'.");
|
||||
var process = Process.Start(startInfo);
|
||||
if (process is not null)
|
||||
@@ -68,12 +67,12 @@ internal sealed class AirAppProcessStarter : IAirAppProcessStarter
|
||||
{
|
||||
try
|
||||
{
|
||||
Logger.Info(
|
||||
AirAppRuntimeLogger.Info(
|
||||
$"AirAppHost exited. AppId='{appId}'; InstanceKey='{instanceKey}'; ProcessId={process.Id}; ExitCode={process.ExitCode}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Failed to log AirAppHost exit: {ex.Message}");
|
||||
AirAppRuntimeLogger.Warn($"Failed to log AirAppHost exit: {ex.Message}");
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -81,54 +80,11 @@ internal sealed class AirAppProcessStarter : IAirAppProcessStarter
|
||||
return process;
|
||||
}
|
||||
|
||||
internal static ProcessStartInfo CreateStartInfo(
|
||||
string hostPath,
|
||||
DotNetRuntimeProbeOptions? runtimeProbeOptions = null)
|
||||
internal static ProcessStartInfo CreateStartInfo(string hostPath)
|
||||
{
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = Path.GetDirectoryName(hostPath) ?? AppContext.BaseDirectory
|
||||
};
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
if (string.Equals(Path.GetExtension(hostPath), ".exe", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (DotNetRuntimeProbe.IsFrameworkDependentWindowsApp(hostPath))
|
||||
{
|
||||
var executableRuntime = DotNetRuntimeProbe.Probe(runtimeProbeOptions);
|
||||
if (!executableRuntime.IsAvailable)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Unable to start AirAppHost because the architecture-matched .NET 10 runtime was not found. " +
|
||||
executableRuntime.Message);
|
||||
}
|
||||
}
|
||||
|
||||
startInfo.FileName = hostPath;
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
var runtime = DotNetRuntimeProbe.Probe(runtimeProbeOptions);
|
||||
if (!runtime.IsAvailable || string.IsNullOrWhiteSpace(runtime.DotNetHostPath))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Unable to start AirAppHost because the architecture-matched .NET 10 runtime was not found. " +
|
||||
runtime.Message);
|
||||
}
|
||||
|
||||
startInfo.FileName = runtime.DotNetHostPath;
|
||||
startInfo.ArgumentList.Add(hostPath);
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
startInfo.FileName = "dotnet";
|
||||
startInfo.ArgumentList.Add(hostPath);
|
||||
return startInfo;
|
||||
return AirAppRuntimeProcessStarter.CreateStartInfo(hostPath);
|
||||
}
|
||||
|
||||
|
||||
private static void AddArgument(ProcessStartInfo startInfo, string name, string value)
|
||||
{
|
||||
startInfo.ArgumentList.Add(name);
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RollForward>LatestMajor</RollForward>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<PublishAot>false</PublishAot>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
<PublishTrimmed>false</PublishTrimmed>
|
||||
<PublishReadyToRun>false</PublishReadyToRun>
|
||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||
<ApplicationIcon>..\LanMountainDesktop\Assets\logo_nightly.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LanMountainDesktop.Shared.IPC\LanMountainDesktop.Shared.IPC.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
40
LanMountainDesktop.AirAppRuntime/Program.cs
Normal file
40
LanMountainDesktop.AirAppRuntime/Program.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
namespace LanMountainDesktop.AirAppRuntime;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
var options = AirAppRuntimeOptions.Parse(args);
|
||||
AirAppRuntimeLogger.Info(
|
||||
$"Starting. AppRoot='{options.AppRoot ?? string.Empty}'; DataRoot='{options.DataRoot ?? string.Empty}'; " +
|
||||
$"LauncherPid={options.LauncherProcessId}; RequesterPid={options.RequesterProcessId}.");
|
||||
|
||||
try
|
||||
{
|
||||
var lifecycleService = new AirAppLifecycleService(
|
||||
new AirAppProcessStarter(
|
||||
new AirAppHostLocator(),
|
||||
() => options.AppRoot,
|
||||
() => null,
|
||||
() => options.DataRoot));
|
||||
var lifetime = new AirAppRuntimeLifetime(options, lifecycleService);
|
||||
var controlService = new AirAppRuntimeControlService(lifetime);
|
||||
|
||||
using var ipcHost = new AirAppRuntimeIpcHost(lifecycleService, controlService);
|
||||
ipcHost.Start();
|
||||
|
||||
while (lifetime.ShouldKeepAlive())
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
AirAppRuntimeLogger.Info("Exiting because launcher, host, requester, and AirApp windows are gone.");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AirAppRuntimeLogger.Error("Unhandled runtime failure.", ex);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("LanMountainDesktop.Tests")]
|
||||
@@ -1,29 +0,0 @@
|
||||
using LanMountainDesktop.Shared.IPC;
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.AirApp;
|
||||
|
||||
internal sealed class LauncherAirAppLifecycleIpcHost : IDisposable
|
||||
{
|
||||
private readonly PublicIpcHostService _host;
|
||||
|
||||
public LauncherAirAppLifecycleIpcHost(LauncherAirAppLifecycleService lifecycleService)
|
||||
{
|
||||
LifecycleService = lifecycleService;
|
||||
_host = new PublicIpcHostService(IpcConstants.AirAppLifecyclePipeName);
|
||||
_host.RegisterPublicService<IAirAppLifecycleService>(lifecycleService);
|
||||
}
|
||||
|
||||
public LauncherAirAppLifecycleService LifecycleService { get; }
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_host.Start();
|
||||
Logger.Info($"Air APP lifecycle IPC started. Pipe='{IpcConstants.AirAppLifecyclePipeName}'.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_host.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -60,15 +60,7 @@ public partial class App : Application
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.IsAirAppBrokerCommand)
|
||||
{
|
||||
_ = AirAppBrokerEntryHandler.RunAsync(desktop, context);
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.IsDebugMode && !context.IsPreviewCommand &&
|
||||
!string.Equals(context.Command, "apply-update", StringComparison.OrdinalIgnoreCase))
|
||||
if (context.IsDebugMode && !context.IsPreviewCommand)
|
||||
{
|
||||
Logger.Info("Debug mode active; showing DevDebugWindow instead of normal launch flow.");
|
||||
new DevDebugWindow().Show();
|
||||
@@ -76,18 +68,9 @@ public partial class App : Application
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.Equals(context.Command, "apply-update", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var updateWindow = new UpdateWindow();
|
||||
updateWindow.Show();
|
||||
_ = ApplyUpdateEntryHandler.RunAsync(desktop, context, updateWindow);
|
||||
}
|
||||
else
|
||||
{
|
||||
var splashWindow = LaunchEntryHandler.CreateSplashWindow();
|
||||
splashWindow.Show();
|
||||
_ = LauncherCompositionRoot.RunOrchestratorWithSplashAsync(desktop, context, splashWindow);
|
||||
}
|
||||
var splashWindow = LaunchEntryHandler.CreateSplashWindow();
|
||||
splashWindow.Show();
|
||||
_ = LauncherCompositionRoot.RunOrchestratorWithSplashAsync(desktop, context, splashWindow);
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
@@ -11,15 +11,7 @@ namespace LanMountainDesktop.Launcher;
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(SignedFileMap))]
|
||||
[JsonSerializable(typeof(UpdateFileEntry))]
|
||||
[JsonSerializable(typeof(PlondsUpdateMetadata))]
|
||||
[JsonSerializable(typeof(PlondsFileMap))]
|
||||
[JsonSerializable(typeof(PlondsComponentEntry))]
|
||||
[JsonSerializable(typeof(PlondsFileEntry))]
|
||||
[JsonSerializable(typeof(PlondsHashDescriptor))]
|
||||
[JsonSerializable(typeof(SnapshotMetadata))]
|
||||
[JsonSerializable(typeof(InstallCheckpoint))]
|
||||
[JsonSerializable(typeof(AppVersionInfo))]
|
||||
[JsonSerializable(typeof(StartupProgressMessage))]
|
||||
[JsonSerializable(typeof(LauncherCoordinatorRequest))]
|
||||
@@ -37,6 +29,11 @@ namespace LanMountainDesktop.Launcher;
|
||||
[JsonSerializable(typeof(StartupAttemptRecord))]
|
||||
[JsonSerializable(typeof(PrivacyConfig))]
|
||||
[JsonSerializable(typeof(PrivacyAgreementState))]
|
||||
[JsonSerializable(typeof(LanMountainDesktop.Shared.Contracts.Update.InstallProgressReport))]
|
||||
[JsonSerializable(typeof(LanMountainDesktop.Shared.Contracts.Update.InstallCompleteReport))]
|
||||
[JsonSerializable(typeof(AirAppOpenRequest))]
|
||||
[JsonSerializable(typeof(AirAppRegistrationRequest))]
|
||||
[JsonSerializable(typeof(AirAppInstanceInfo))]
|
||||
[JsonSerializable(typeof(AirAppOperationResult))]
|
||||
[JsonSerializable(typeof(AirAppInstanceInfo[]))]
|
||||
[JsonSerializable(typeof(AirAppRuntimeControlResult))]
|
||||
[JsonSerializable(typeof(AirAppRuntimeStatus))]
|
||||
internal sealed partial class AppJsonContext : JsonSerializerContext;
|
||||
|
||||
@@ -4,15 +4,11 @@ namespace LanMountainDesktop.Launcher;
|
||||
|
||||
internal sealed class CommandContext
|
||||
{
|
||||
public const string AirAppBrokerCommand = "air-app-broker";
|
||||
|
||||
private const string LaunchSourceOptionName = "launch-source";
|
||||
|
||||
private static readonly string[] GuiCommands =
|
||||
[
|
||||
"launch",
|
||||
AirAppBrokerCommand,
|
||||
"apply-update",
|
||||
"preview-splash",
|
||||
"preview-error",
|
||||
"preview-update",
|
||||
@@ -63,16 +59,11 @@ internal sealed class CommandContext
|
||||
public bool IsPreviewCommand =>
|
||||
Command.StartsWith("preview-", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public bool IsAirAppBrokerCommand =>
|
||||
string.Equals(Command, AirAppBrokerCommand, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public bool IsGuiCommand =>
|
||||
GuiCommands.Contains(Command, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public bool IsMaintenanceCommand =>
|
||||
string.Equals(LaunchSource, "apply-update", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(LaunchSource, "plugin-install", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(Command, "update", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(Command, "plugin", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public string? ExplicitAppRoot => GetOption("app-root");
|
||||
@@ -118,11 +109,6 @@ internal sealed class CommandContext
|
||||
return "debug-preview";
|
||||
}
|
||||
|
||||
if (string.Equals(Command, "apply-update", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "apply-update";
|
||||
}
|
||||
|
||||
if (IsLegacyPluginInstall || string.Equals(Command, "plugin", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "plugin-install";
|
||||
@@ -143,7 +129,6 @@ internal sealed class CommandContext
|
||||
"normal" => "normal",
|
||||
"restart" => "restart",
|
||||
"postinstall" => "postinstall",
|
||||
"apply-update" => "apply-update",
|
||||
"plugin-install" => "plugin-install",
|
||||
"debug-preview" => "debug-preview",
|
||||
_ => null
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
global using LanMountainDesktop.Launcher.AirApp;
|
||||
global using LanMountainDesktop.Launcher.Deployment;
|
||||
global using LanMountainDesktop.Launcher.Infrastructure;
|
||||
global using LanMountainDesktop.Launcher.Ipc;
|
||||
global using LanMountainDesktop.Launcher.Oobe;
|
||||
global using LanMountainDesktop.Launcher.Plugins;
|
||||
global using LanMountainDesktop.Launcher.Startup;
|
||||
global using LanMountainDesktop.Launcher.Update;
|
||||
|
||||
@@ -14,7 +14,7 @@ internal static class Commands
|
||||
{
|
||||
var source = context.GetOption("source") ?? string.Empty;
|
||||
var pluginsDir = context.GetOption("plugins-dir") ?? string.Empty;
|
||||
result = installer.InstallPackage(source, pluginsDir);
|
||||
result = installer.InstallPackage(source, pluginsDir, context.ExplicitAppRoot);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -35,15 +35,14 @@ internal static class Commands
|
||||
public static async Task<int> RunCliCommandAsync(CommandContext context)
|
||||
{
|
||||
var appRoot = ResolveAppRoot(context);
|
||||
var deploymentLocator = new DeploymentLocator(appRoot);
|
||||
var updateEngine = UpdateEngineFactory.Create(deploymentLocator);
|
||||
_ = new DeploymentLocator(appRoot);
|
||||
var pluginInstaller = new PluginInstallerService();
|
||||
var pluginUpgrades = new PluginUpgradeQueueService(pluginInstaller);
|
||||
|
||||
LauncherResult result;
|
||||
try
|
||||
{
|
||||
result = await ExecuteCoreAsync(context, updateEngine, pluginInstaller, pluginUpgrades).ConfigureAwait(false);
|
||||
result = ExecuteCore(context, pluginInstaller, pluginUpgrades);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -61,16 +60,13 @@ internal static class Commands
|
||||
return result.Success ? 0 : 1;
|
||||
}
|
||||
|
||||
private static async Task<LauncherResult> ExecuteCoreAsync(
|
||||
private static LauncherResult ExecuteCore(
|
||||
CommandContext context,
|
||||
IUpdateEngine updateEngine,
|
||||
PluginInstallerService pluginInstaller,
|
||||
PluginUpgradeQueueService pluginUpgrades)
|
||||
{
|
||||
switch (context.Command.ToLowerInvariant())
|
||||
{
|
||||
case "update":
|
||||
return await ExecuteUpdateAsync(context, updateEngine).ConfigureAwait(false);
|
||||
case "plugin":
|
||||
return ExecutePluginCommand(context, pluginInstaller, pluginUpgrades);
|
||||
default:
|
||||
@@ -84,33 +80,6 @@ internal static class Commands
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<LauncherResult> ExecuteUpdateAsync(CommandContext context, IUpdateEngine updateEngine)
|
||||
{
|
||||
return context.SubCommand.ToLowerInvariant() switch
|
||||
{
|
||||
"check" => updateEngine.CheckPendingUpdate(),
|
||||
"apply" => await updateEngine.ApplyPendingUpdateAsync().ConfigureAwait(false),
|
||||
"rollback" => updateEngine.RollbackLatest(),
|
||||
"download" => await DownloadUpdatePayloadAsync(context, updateEngine).ConfigureAwait(false),
|
||||
_ => new LauncherResult
|
||||
{
|
||||
Success = false,
|
||||
Stage = "update",
|
||||
Code = "unsupported_subcommand",
|
||||
Message = $"Unsupported update sub-command '{context.SubCommand}'."
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<LauncherResult> DownloadUpdatePayloadAsync(CommandContext context, IUpdateEngine updateEngine)
|
||||
{
|
||||
return await updateEngine.DownloadAsync(
|
||||
context.GetOption("manifest-url") ?? throw new InvalidOperationException("Missing --manifest-url."),
|
||||
context.GetOption("signature-url") ?? throw new InvalidOperationException("Missing --signature-url."),
|
||||
context.GetOption("archive-url") ?? throw new InvalidOperationException("Missing --archive-url."),
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static LauncherResult ExecutePluginCommand(
|
||||
CommandContext context,
|
||||
PluginInstallerService pluginInstaller,
|
||||
@@ -122,12 +91,12 @@ internal static class Commands
|
||||
{
|
||||
var source = context.GetOption("source") ?? throw new InvalidOperationException("Missing --source.");
|
||||
var pluginsDir = context.GetOption("plugins-dir") ?? throw new InvalidOperationException("Missing --plugins-dir.");
|
||||
return pluginInstaller.InstallPackage(source, pluginsDir);
|
||||
return pluginInstaller.InstallPackage(source, pluginsDir, context.ExplicitAppRoot);
|
||||
}
|
||||
case "update":
|
||||
{
|
||||
var pluginsDir = context.GetOption("plugins-dir") ?? throw new InvalidOperationException("Missing --plugins-dir.");
|
||||
return pluginUpgrades.ApplyPendingUpgrades(pluginsDir);
|
||||
return pluginUpgrades.ApplyPendingUpgrades(pluginsDir, context.ExplicitAppRoot);
|
||||
}
|
||||
default:
|
||||
return new LauncherResult
|
||||
|
||||
@@ -193,8 +193,10 @@ internal sealed class DataLocationResolver
|
||||
|
||||
public bool ApplyLocationChoice(DataLocationMode mode, string? customPath = null, bool migrateExistingData = false)
|
||||
{
|
||||
var targetDataRoot = mode == DataLocationMode.Portable && !string.IsNullOrWhiteSpace(customPath)
|
||||
? Path.GetFullPath(customPath)
|
||||
var targetDataRoot = mode == DataLocationMode.Portable
|
||||
? Path.GetFullPath(!string.IsNullOrWhiteSpace(customPath)
|
||||
? customPath
|
||||
: DefaultPortableDataPath)
|
||||
: _defaultSystemDataPath;
|
||||
|
||||
var config = new DataLocationConfig
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
using System.Buffers;
|
||||
using System.IO.Pipes;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop.Shared.Contracts.Update;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Ipc;
|
||||
|
||||
internal sealed class LauncherUpdateProgressIpcServer : IUpdateProgressReporter, IDisposable
|
||||
{
|
||||
private const int LengthPrefixSize = 4;
|
||||
|
||||
private readonly string _pipeName;
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private NamedPipeServerStream? _pipe;
|
||||
private Task? _listenTask;
|
||||
private volatile bool _clientConnected;
|
||||
|
||||
public LauncherUpdateProgressIpcServer(int launcherPid)
|
||||
{
|
||||
_pipeName = $"LanMountainDesktop_Update_{launcherPid}";
|
||||
}
|
||||
|
||||
public string PipeName => _pipeName;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_listenTask = Task.Run(AcceptConnectionAsync, _cts.Token);
|
||||
}
|
||||
|
||||
private async Task AcceptConnectionAsync()
|
||||
{
|
||||
while (!_cts.Token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
_pipe = new NamedPipeServerStream(
|
||||
_pipeName,
|
||||
PipeDirection.Out,
|
||||
1,
|
||||
PipeTransmissionMode.Byte,
|
||||
PipeOptions.Asynchronous);
|
||||
|
||||
await _pipe.WaitForConnectionAsync(_cts.Token).ConfigureAwait(false);
|
||||
_clientConnected = true;
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Update progress IPC listen error: {ex.Message}");
|
||||
try
|
||||
{
|
||||
await Task.Delay(200, _cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void ReportProgress(InstallProgressReport report)
|
||||
{
|
||||
if (!_clientConnected || _pipe is null || !_pipe.IsConnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
WriteMessage(_pipe, JsonSerializer.Serialize(report, AppJsonContext.Default.InstallProgressReport));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Failed to report progress via IPC: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void ReportComplete(InstallCompleteReport report)
|
||||
{
|
||||
if (!_clientConnected || _pipe is null || !_pipe.IsConnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
WriteMessage(_pipe, JsonSerializer.Serialize(report, AppJsonContext.Default.InstallCompleteReport));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Failed to report completion via IPC: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteMessage(Stream stream, string json)
|
||||
{
|
||||
var payload = Encoding.UTF8.GetBytes(json);
|
||||
var lengthPrefix = BitConverter.GetBytes(payload.Length);
|
||||
stream.Write(lengthPrefix, 0, LengthPrefixSize);
|
||||
stream.Write(payload, 0, payload.Length);
|
||||
stream.Flush();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
try
|
||||
{
|
||||
_pipe?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_listenTask?.Wait(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<!-- AOT 兼容性:某些包可能需要特殊处理 -->
|
||||
|
||||
<PropertyGroup Condition="'$(PublishAot)' == 'true'">
|
||||
<!-- 忽略某些警告 -->
|
||||
<SuppressTrimAnalysisWarnings>false</SuppressTrimAnalysisWarnings>
|
||||
@@ -60,7 +61,8 @@
|
||||
|
||||
<!-- AOT 模式下禁用反射式 JSON 序列化,强制使用 Source Generator -->
|
||||
<!-- 之前设置为 true 与 AOT 矛盾,导致 IL2026/IL3050 警告和运行时失败 -->
|
||||
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||
<!-- [Fix]: 必须设置为 true 以支持 dotnetCampus.Ipc 内部的反射序列化。相关类型的剪裁保护通过 AppJsonContext 保证 -->
|
||||
<JsonSerializerIsReflectionEnabledByDefault>true</JsonSerializerIsReflectionEnabledByDefault>
|
||||
|
||||
<!-- 启用 ISerializable 支持(部分库需要) -->
|
||||
<IsAotCompatible>true</IsAotCompatible>
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
<Target Name="CopyPublicKeyToLauncherDir" AfterTargets="Build">
|
||||
<PropertyGroup>
|
||||
<PublicKeySource>$(MSBuildProjectDirectory)\Assets\public-key.pem</PublicKeySource>
|
||||
<PublicKeyDestDir>$(OutDir).launcher\update</PublicKeyDestDir>
|
||||
<PublicKeyDestDir>$(OutDir).Launcher\update</PublicKeyDestDir>
|
||||
</PropertyGroup>
|
||||
<MakeDir Directories="$(PublicKeyDestDir)" />
|
||||
<Copy SourceFiles="$(PublicKeySource)" DestinationFolder="$(PublicKeyDestDir)" SkipUnchangedFiles="true" />
|
||||
@@ -55,7 +55,7 @@
|
||||
<Target Name="CopyPublicKeyToPublishDir" AfterTargets="Publish">
|
||||
<PropertyGroup>
|
||||
<PublishedKeySource>$(MSBuildProjectDirectory)\Assets\public-key.pem</PublishedKeySource>
|
||||
<PublishedKeyDestDir>$(PublishDir).launcher\update</PublishedKeyDestDir>
|
||||
<PublishedKeyDestDir>$(PublishDir).Launcher\update</PublishedKeyDestDir>
|
||||
</PropertyGroup>
|
||||
<MakeDir Directories="$(PublishedKeyDestDir)" />
|
||||
<Copy SourceFiles="$(PublishedKeySource)" DestinationFolder="$(PublishedKeyDestDir)" SkipUnchangedFiles="true" />
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace LanMountainDesktop.Launcher.Models;
|
||||
|
||||
/// <summary>
|
||||
/// 更新频道
|
||||
/// </summary>
|
||||
public enum UpdateChannel
|
||||
{
|
||||
/// <summary>
|
||||
/// 正式版 - 只检查 prerelease=false 的版本
|
||||
/// </summary>
|
||||
Stable,
|
||||
|
||||
/// <summary>
|
||||
/// 预览版 - 检查所有版本(包括 prerelease=true)
|
||||
/// </summary>
|
||||
Preview
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
namespace LanMountainDesktop.Launcher.Models;
|
||||
|
||||
/// <summary>
|
||||
/// 更新检查结果
|
||||
/// </summary>
|
||||
public sealed class UpdateCheckResult
|
||||
{
|
||||
public bool HasUpdate { get; init; }
|
||||
public string? LatestVersion { get; init; }
|
||||
public string? CurrentVersion { get; init; }
|
||||
public ReleaseInfo? Release { get; init; }
|
||||
public string? ErrorMessage { get; init; }
|
||||
}
|
||||
@@ -1,29 +1,5 @@
|
||||
namespace LanMountainDesktop.Launcher.Models;
|
||||
|
||||
internal sealed class SignedFileMap
|
||||
{
|
||||
public string? FromVersion { get; set; }
|
||||
|
||||
public string? ToVersion { get; set; }
|
||||
|
||||
public string? Platform { get; set; }
|
||||
|
||||
public string? Arch { get; set; }
|
||||
|
||||
public List<UpdateFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class UpdateFileEntry
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
|
||||
public string? ArchivePath { get; set; }
|
||||
|
||||
public string Action { get; set; } = "replace";
|
||||
|
||||
public string? Sha256 { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class SnapshotMetadata
|
||||
{
|
||||
public string SnapshotId { get; set; } = string.Empty;
|
||||
@@ -40,124 +16,3 @@ internal sealed class SnapshotMetadata
|
||||
|
||||
public string Status { get; set; } = "pending";
|
||||
}
|
||||
|
||||
internal sealed class InstallCheckpoint
|
||||
{
|
||||
public string SnapshotId { get; set; } = string.Empty;
|
||||
|
||||
public string SourceVersion { get; set; } = string.Empty;
|
||||
|
||||
public string? TargetVersion { get; set; }
|
||||
|
||||
public string? SourceDirectory { get; set; }
|
||||
|
||||
public string TargetDirectory { get; set; } = string.Empty;
|
||||
|
||||
public bool IsInitialDeployment { get; set; }
|
||||
|
||||
public int AppliedCount { get; set; }
|
||||
|
||||
public int VerifiedCount { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class UpdateApplyResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string Message { get; init; } = string.Empty;
|
||||
|
||||
public string? FromVersion { get; init; }
|
||||
|
||||
public string? ToVersion { get; init; }
|
||||
|
||||
public string? RolledBackTo { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class PlondsUpdateMetadata
|
||||
{
|
||||
public string? DistributionId { get; set; }
|
||||
|
||||
public string? Channel { get; set; }
|
||||
|
||||
public string? SubChannel { get; set; }
|
||||
|
||||
public string? FromVersion { get; set; }
|
||||
|
||||
public string? ToVersion { get; set; }
|
||||
|
||||
public string? FileMapPath { get; set; }
|
||||
|
||||
public string? FileMapSignaturePath { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsFileMap
|
||||
{
|
||||
public string? DistributionId { get; set; }
|
||||
|
||||
public string? FromVersion { get; set; }
|
||||
|
||||
public string? ToVersion { get; set; }
|
||||
|
||||
public string? Version { get; set; }
|
||||
|
||||
public string? Platform { get; set; }
|
||||
|
||||
public string? Arch { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
|
||||
public List<PlondsComponentEntry> Components { get; set; } = [];
|
||||
|
||||
public List<PlondsFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsComponentEntry
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string? Version { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
|
||||
public List<PlondsFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsFileEntry
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
|
||||
public string? Action { get; set; } = "replace";
|
||||
|
||||
public string? Url { get; set; }
|
||||
|
||||
public string? ObjectUrl { get; set; }
|
||||
|
||||
public string? ObjectPath { get; set; }
|
||||
|
||||
public string? ObjectKey { get; set; }
|
||||
|
||||
public string? ArchivePath { get; set; }
|
||||
|
||||
public string? Sha256 { get; set; }
|
||||
|
||||
public string? Sha512 { get; set; }
|
||||
|
||||
public string? Sha512Base64 { get; set; }
|
||||
|
||||
public byte[]? Sha512Bytes { get; set; }
|
||||
|
||||
public PlondsHashDescriptor? Hash { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsHashDescriptor
|
||||
{
|
||||
public string? Algorithm { get; set; }
|
||||
|
||||
public string? Value { get; set; }
|
||||
|
||||
public byte[]? Bytes { get; set; }
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ internal sealed class PluginInstallerService
|
||||
TimeSpan.FromMilliseconds(500)
|
||||
];
|
||||
|
||||
public LauncherResult InstallPackage(string sourcePath, string pluginsDirectory)
|
||||
public LauncherResult InstallPackage(string sourcePath, string pluginsDirectory, string? appRoot = null)
|
||||
{
|
||||
var fullSourcePath = Path.GetFullPath(sourcePath);
|
||||
var fullPluginsDirectory = Path.GetFullPath(pluginsDirectory);
|
||||
@@ -32,7 +32,7 @@ internal sealed class PluginInstallerService
|
||||
throw new FileNotFoundException($"Plugin package '{fullSourcePath}' was not found.", fullSourcePath);
|
||||
}
|
||||
|
||||
if (TryBuildElevationRequiredResult(fullPluginsDirectory) is { } elevationRequiredResult)
|
||||
if (TryBuildElevationRequiredResult(fullPluginsDirectory, appRoot) is { } elevationRequiredResult)
|
||||
{
|
||||
return elevationRequiredResult;
|
||||
}
|
||||
@@ -58,7 +58,7 @@ internal sealed class PluginInstallerService
|
||||
};
|
||||
}
|
||||
|
||||
private static LauncherResult? TryBuildElevationRequiredResult(string pluginsDirectory)
|
||||
private static LauncherResult? TryBuildElevationRequiredResult(string pluginsDirectory, string? appRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
@@ -68,8 +68,10 @@ internal sealed class PluginInstallerService
|
||||
string? allowedRoot = null;
|
||||
try
|
||||
{
|
||||
var appRoot = Commands.ResolveAppRoot(CommandContext.FromArgs([]));
|
||||
var resolver = new DataLocationResolver(appRoot);
|
||||
var resolvedAppRoot = !string.IsNullOrWhiteSpace(appRoot)
|
||||
? Path.GetFullPath(appRoot)
|
||||
: Commands.ResolveAppRoot(CommandContext.FromArgs([]));
|
||||
var resolver = new DataLocationResolver(resolvedAppRoot);
|
||||
allowedRoot = EnsureTrailingSeparator(resolver.ResolveDataRoot());
|
||||
}
|
||||
catch
|
||||
|
||||
@@ -14,7 +14,7 @@ internal sealed class PluginUpgradeQueueService
|
||||
_installerService = installerService;
|
||||
}
|
||||
|
||||
public LauncherResult ApplyPendingUpgrades(string pluginsDirectory)
|
||||
public LauncherResult ApplyPendingUpgrades(string pluginsDirectory, string? appRoot = null)
|
||||
{
|
||||
var pendingPath = Path.Combine(pluginsDirectory, PendingUpgradesFileName);
|
||||
if (!File.Exists(pendingPath))
|
||||
@@ -43,7 +43,7 @@ internal sealed class PluginUpgradeQueueService
|
||||
|
||||
try
|
||||
{
|
||||
_installerService.InstallPackage(item.SourcePackagePath, pluginsDirectory);
|
||||
_installerService.InstallPackage(item.SourcePackagePath, pluginsDirectory, appRoot);
|
||||
succeeded.Add(item);
|
||||
}
|
||||
catch
|
||||
|
||||
@@ -57,14 +57,6 @@
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Launcher (Update Check)": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "update check",
|
||||
"workingDirectory": "$(SolutionDir)",
|
||||
"environmentVariables": {
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Launcher (Plugin Install)": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "plugin install <path-to-plugin.laapp>",
|
||||
|
||||
83
LanMountainDesktop.Launcher/Shell/AirAppRuntimeBridge.cs
Normal file
83
LanMountainDesktop.Launcher/Shell/AirAppRuntimeBridge.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using LanMountainDesktop.Shared.IPC;
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Shell;
|
||||
|
||||
internal sealed class AirAppRuntimeBridge
|
||||
{
|
||||
private const int ConnectAttempts = 8;
|
||||
|
||||
private readonly string _appRoot;
|
||||
private readonly string? _dataRoot;
|
||||
|
||||
public AirAppRuntimeBridge(string appRoot, string? dataRoot)
|
||||
{
|
||||
_appRoot = appRoot;
|
||||
_dataRoot = dataRoot;
|
||||
}
|
||||
|
||||
public async Task EnsureStartedAsync()
|
||||
{
|
||||
if (await TryGetStatusAsync().ConfigureAwait(false) is not null)
|
||||
{
|
||||
Logger.Info("AirApp Runtime is already available.");
|
||||
return;
|
||||
}
|
||||
|
||||
var process = AirAppRuntimeProcessStarter.Start(new AirAppRuntimeStartRequest(
|
||||
_appRoot,
|
||||
Environment.ProcessId,
|
||||
0,
|
||||
_dataRoot));
|
||||
Logger.Info($"AirApp Runtime start requested. Pid={(process is null ? -1 : process.Id)}; AppRoot='{_appRoot}'.");
|
||||
|
||||
for (var attempt = 1; attempt <= ConnectAttempts; attempt++)
|
||||
{
|
||||
if (await TryGetStatusAsync().ConfigureAwait(false) is not null)
|
||||
{
|
||||
Logger.Info("AirApp Runtime IPC is ready.");
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Logger.Warn("AirApp Runtime did not become ready after pre-start; Host fallback remains available.");
|
||||
}
|
||||
|
||||
public async Task AttachHostAsync(int hostProcessId)
|
||||
{
|
||||
if (hostProcessId <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var client = new LanMountainDesktopIpcClient();
|
||||
await client.ConnectAsync(IpcConstants.AirAppRuntimePipeName).ConfigureAwait(false);
|
||||
var proxy = client.CreateProxy<IAirAppRuntimeControlService>();
|
||||
var result = await proxy.AttachHostAsync(hostProcessId).ConfigureAwait(false);
|
||||
Logger.Info($"AirApp Runtime host attach completed. Accepted={result.Accepted}; Code='{result.Code}'; HostPid={hostProcessId}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Failed to attach Host to AirApp Runtime: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<AirAppRuntimeStatus?> TryGetStatusAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new LanMountainDesktopIpcClient();
|
||||
await client.ConnectAsync(IpcConstants.AirAppRuntimePipeName).ConfigureAwait(false);
|
||||
var proxy = client.CreateProxy<IAirAppRuntimeControlService>();
|
||||
return await proxy.GetStatusAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using LanMountainDesktop.Launcher.Resources;
|
||||
using LanMountainDesktop.Launcher.Views;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Shell;
|
||||
|
||||
internal static class ApplyUpdateGuiFlow
|
||||
{
|
||||
public static async Task RunAsync(
|
||||
IClassicDesktopStyleApplicationLifetime desktop,
|
||||
CommandContext context,
|
||||
UpdateWindow window)
|
||||
{
|
||||
var appRoot = Commands.ResolveAppRoot(context);
|
||||
var deploymentLocator = new DeploymentLocator(appRoot);
|
||||
var updateEngine = UpdateEngineFactory.Create(deploymentLocator);
|
||||
var pluginInstaller = new PluginInstallerService();
|
||||
var pluginUpgrades = new PluginUpgradeQueueService(pluginInstaller);
|
||||
|
||||
var success = true;
|
||||
string? errorMessage = null;
|
||||
|
||||
try
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() => window.Report("verify", Strings.Update_Verifying, 10));
|
||||
var updateResult = await updateEngine.ApplyPendingUpdateAsync().ConfigureAwait(false);
|
||||
if (!updateResult.Success)
|
||||
{
|
||||
success = false;
|
||||
errorMessage = updateResult.Message;
|
||||
}
|
||||
|
||||
if (success)
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() => window.Report("plugins", Strings.Update_ApplyingPlugins, 60));
|
||||
var pluginsDir = context.GetOption("plugins-dir") ?? Path.Combine(appRoot, "plugins");
|
||||
var queueResult = pluginUpgrades.ApplyPendingUpgrades(pluginsDir);
|
||||
if (!queueResult.Success && queueResult.Code != "noop")
|
||||
{
|
||||
Logger.Error($"Plugin upgrade failed during apply-update: {queueResult.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (success)
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() => window.Report("cleanup", Strings.Update_CleaningUp, 90));
|
||||
deploymentLocator.CleanupOldDeployments(minVersionsToKeep: 3);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
success = false;
|
||||
errorMessage = ex.Message;
|
||||
Logger.Error("Apply-update flow failed.", ex);
|
||||
}
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() => window.ReportComplete(success, errorMessage));
|
||||
await Task.Delay(success ? 1500 : 5000).ConfigureAwait(false);
|
||||
|
||||
await Commands.WriteResultIfNeededAsync(context.GetOption("result"), new LauncherResult
|
||||
{
|
||||
Success = success,
|
||||
Stage = "apply-update",
|
||||
Code = success ? "ok" : "failed",
|
||||
Message = success ? "Update applied successfully." : (errorMessage ?? "Unknown error"),
|
||||
Details = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["command"] = context.Command,
|
||||
["launchSource"] = context.LaunchSource
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
Environment.ExitCode = success ? 0 : 1;
|
||||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(Environment.ExitCode), DispatcherPriority.Background);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using LanMountainDesktop.Launcher.Views;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Shell.EntryHandlers;
|
||||
@@ -30,61 +28,3 @@ internal static class LaunchEntryHandler
|
||||
SplashWindow splashWindow) =>
|
||||
LauncherCompositionRoot.RunOrchestratorWithSplashAsync(desktop, context, splashWindow);
|
||||
}
|
||||
|
||||
internal static class ApplyUpdateEntryHandler
|
||||
{
|
||||
public static Task RunAsync(
|
||||
IClassicDesktopStyleApplicationLifetime desktop,
|
||||
CommandContext context,
|
||||
UpdateWindow window) =>
|
||||
ApplyUpdateGuiFlow.RunAsync(desktop, context, window);
|
||||
}
|
||||
|
||||
internal static class AirAppBrokerEntryHandler
|
||||
{
|
||||
public static async Task RunAsync(IClassicDesktopStyleApplicationLifetime desktop, CommandContext context)
|
||||
{
|
||||
var appRoot = Commands.ResolveAppRoot(context);
|
||||
var requesterPid = context.GetIntOption("requester-pid", 0);
|
||||
var dataLocationResolver = new DataLocationResolver(appRoot);
|
||||
Logger.Info($"Air APP broker starting. AppRoot='{appRoot}'; RequesterPid={requesterPid}.");
|
||||
|
||||
using var airAppIpcHost = new LauncherAirAppLifecycleIpcHost(
|
||||
new LauncherAirAppLifecycleService(
|
||||
new AirAppProcessStarter(
|
||||
new AirAppHostLocator(),
|
||||
() => appRoot,
|
||||
() => null,
|
||||
() => dataLocationResolver.ResolveDataRoot())));
|
||||
airAppIpcHost.Start();
|
||||
|
||||
while (ShouldKeepAlive(requesterPid, airAppIpcHost.LifecycleService))
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Logger.Info("Air APP broker exiting.");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(0), DispatcherPriority.Background);
|
||||
}
|
||||
|
||||
internal static bool ShouldKeepAirAppBrokerAlive(int requesterPid, LauncherAirAppLifecycleService lifecycleService)
|
||||
{
|
||||
if (requesterPid <= 0)
|
||||
{
|
||||
return lifecycleService.HasLiveAirApps();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var process = System.Diagnostics.Process.GetProcessById(requesterPid);
|
||||
return !process.HasExited || lifecycleService.HasLiveAirApps();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return lifecycleService.HasLiveAirApps();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ShouldKeepAlive(int requesterPid, LauncherAirAppLifecycleService lifecycleService) =>
|
||||
ShouldKeepAirAppBrokerAlive(requesterPid, lifecycleService);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ internal static class LauncherGuiCoordinator
|
||||
var startupAttemptRegistry = new StartupAttemptRegistry();
|
||||
var coordinatorPipeName = LauncherCoordinatorIpcServer.CreatePipeName();
|
||||
var successPolicy = LauncherOrchestrator.ResolveSuccessPolicyKey(context);
|
||||
var airAppRuntimeBridge = new AirAppRuntimeBridge(appRoot, dataLocationResolver.ResolveDataRoot());
|
||||
await airAppRuntimeBridge.EnsureStartedAsync().ConfigureAwait(false);
|
||||
|
||||
if (!startupAttemptRegistry.TryReserveCoordinator(
|
||||
context.LaunchSource,
|
||||
successPolicy,
|
||||
@@ -44,15 +47,6 @@ internal static class LauncherGuiCoordinator
|
||||
return;
|
||||
}
|
||||
|
||||
using var airAppIpcHost = new LauncherAirAppLifecycleIpcHost(
|
||||
new LauncherAirAppLifecycleService(
|
||||
new AirAppProcessStarter(
|
||||
new AirAppHostLocator(),
|
||||
() => appRoot,
|
||||
() => null,
|
||||
() => dataLocationResolver.ResolveDataRoot())));
|
||||
airAppIpcHost.Start();
|
||||
|
||||
using var coordinatorServer = new LauncherCoordinatorIpcServer(
|
||||
coordinatorPipeName,
|
||||
BuildCoordinatorStatusFromAttempt(reservedAttempt),
|
||||
@@ -129,7 +123,8 @@ internal static class LauncherGuiCoordinator
|
||||
if (result.Success)
|
||||
{
|
||||
var hostPid = ResolveManagedHostPid(result, startupAttemptRegistry.GetOwnedAttempt()?.HostPid ?? 0);
|
||||
await WaitForManagedProcessesToExitAsync(hostPid, airAppIpcHost.LifecycleService).ConfigureAwait(false);
|
||||
await airAppRuntimeBridge.AttachHostAsync(hostPid).ConfigureAwait(false);
|
||||
await WaitForHostProcessToExitAsync(hostPid).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(Environment.ExitCode), DispatcherPriority.Background);
|
||||
@@ -173,17 +168,15 @@ internal static class LauncherGuiCoordinator
|
||||
return fallbackHostPid;
|
||||
}
|
||||
|
||||
private static async Task WaitForManagedProcessesToExitAsync(
|
||||
int hostPid,
|
||||
LauncherAirAppLifecycleService airAppLifecycleService)
|
||||
private static async Task WaitForHostProcessToExitAsync(int hostPid)
|
||||
{
|
||||
Logger.Info($"Launcher entering managed background lifetime. HostPid={hostPid}.");
|
||||
while (TryGetLiveProcess(hostPid) || airAppLifecycleService.HasLiveAirApps())
|
||||
Logger.Info($"Launcher entering host background lifetime. HostPid={hostPid}.");
|
||||
while (TryGetLiveProcess(hostPid))
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Logger.Info("Launcher managed background lifetime completed; no host or Air APP process remains.");
|
||||
Logger.Info("Launcher host background lifetime completed; host process is gone.");
|
||||
}
|
||||
|
||||
private static async Task<LauncherResult> AttachToExistingCoordinatorAsync(
|
||||
|
||||
@@ -13,7 +13,6 @@ internal sealed class LauncherOrchestrator
|
||||
private readonly CommandContext _context;
|
||||
private readonly DeploymentLocator _deploymentLocator;
|
||||
private readonly OobeStateService _oobeStateService;
|
||||
private readonly IUpdateEngine _updateEngine;
|
||||
private readonly StartupAttemptRegistry _startupAttemptRegistry;
|
||||
private readonly LauncherCoordinatorIpcServer? _coordinatorIpcServer;
|
||||
private readonly DataLocationResolver _dataLocationResolver;
|
||||
@@ -24,7 +23,6 @@ internal sealed class LauncherOrchestrator
|
||||
CommandContext context,
|
||||
DeploymentLocator deploymentLocator,
|
||||
OobeStateService oobeStateService,
|
||||
IUpdateEngine updateEngine,
|
||||
StartupAttemptRegistry startupAttemptRegistry,
|
||||
LauncherCoordinatorIpcServer? coordinatorIpcServer = null,
|
||||
LaunchPipeline? pipeline = null)
|
||||
@@ -32,7 +30,6 @@ internal sealed class LauncherOrchestrator
|
||||
_context = context;
|
||||
_deploymentLocator = deploymentLocator;
|
||||
_oobeStateService = oobeStateService;
|
||||
_updateEngine = updateEngine;
|
||||
_startupAttemptRegistry = startupAttemptRegistry;
|
||||
_coordinatorIpcServer = coordinatorIpcServer;
|
||||
_dataLocationResolver = new DataLocationResolver(deploymentLocator.GetAppRoot());
|
||||
@@ -45,7 +42,6 @@ internal sealed class LauncherOrchestrator
|
||||
[
|
||||
new CleanupDeploymentsPhase(),
|
||||
new ExistingHostProbePhase(),
|
||||
new ApplyPendingUpdatePhase(),
|
||||
new OobeGatePhase(),
|
||||
new LaunchHostPhase(),
|
||||
new MonitorStartupPhase()
|
||||
@@ -217,7 +213,6 @@ internal sealed class LauncherOrchestrator
|
||||
CommandContext = _context,
|
||||
DeploymentLocator = _deploymentLocator,
|
||||
OobeStateService = _oobeStateService,
|
||||
UpdateEngine = _updateEngine,
|
||||
StartupAttemptRegistry = _startupAttemptRegistry,
|
||||
CoordinatorIpcServer = _coordinatorIpcServer,
|
||||
DataLocationResolver = _dataLocationResolver,
|
||||
|
||||
@@ -22,12 +22,10 @@ internal static class LauncherServiceRegistration
|
||||
services.AddSingleton(new DeploymentLocator(appRoot));
|
||||
services.AddSingleton(sp => new OobeStateService(appRoot));
|
||||
services.AddSingleton(sp => new DataLocationResolver(appRoot));
|
||||
services.AddSingleton(sp => UpdateEngineFactory.Create(sp.GetRequiredService<DeploymentLocator>()));
|
||||
services.AddSingleton<HostLaunchService>();
|
||||
services.AddSingleton<StartupAttemptRegistry>();
|
||||
services.AddSingleton<ILaunchPhase, CleanupDeploymentsPhase>();
|
||||
services.AddSingleton<ILaunchPhase, ExistingHostProbePhase>();
|
||||
services.AddSingleton<ILaunchPhase, ApplyPendingUpdatePhase>();
|
||||
services.AddSingleton<ILaunchPhase, OobeGatePhase>();
|
||||
services.AddSingleton<ILaunchPhase, LaunchHostPhase>();
|
||||
services.AddSingleton<ILaunchPhase, MonitorStartupPhase>();
|
||||
@@ -47,7 +45,6 @@ internal static class LauncherServiceRegistration
|
||||
context,
|
||||
services.GetRequiredService<DeploymentLocator>(),
|
||||
services.GetRequiredService<OobeStateService>(),
|
||||
services.GetRequiredService<IUpdateEngine>(),
|
||||
startupAttemptRegistry,
|
||||
coordinatorServer,
|
||||
services.GetRequiredService<LaunchPipeline>());
|
||||
|
||||
@@ -27,7 +27,6 @@ internal sealed class LaunchContext
|
||||
public required CommandContext CommandContext { get; init; }
|
||||
public required DeploymentLocator DeploymentLocator { get; init; }
|
||||
public required OobeStateService OobeStateService { get; init; }
|
||||
public required IUpdateEngine UpdateEngine { get; init; }
|
||||
public required StartupAttemptRegistry StartupAttemptRegistry { get; init; }
|
||||
public LauncherCoordinatorIpcServer? CoordinatorIpcServer { get; init; }
|
||||
public required DataLocationResolver DataLocationResolver { get; init; }
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
namespace LanMountainDesktop.Launcher.Startup;
|
||||
|
||||
internal sealed class ApplyPendingUpdatePhase : ILaunchPhase
|
||||
{
|
||||
public string Name => nameof(ApplyPendingUpdatePhase);
|
||||
|
||||
public async Task<LaunchPhaseResult> ExecuteAsync(LaunchContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
context.Reporter.Report("update", "Checking updates...");
|
||||
var updateResult = await context.UpdateEngine.ApplyPendingUpdateAsync().ConfigureAwait(false);
|
||||
if (!updateResult.Success)
|
||||
{
|
||||
Logger.Warn($"Update apply failed, will try to launch existing version. Error='{updateResult.Message}'.");
|
||||
context.Reporter.Report("update", "Update failed, launching existing version...");
|
||||
try
|
||||
{
|
||||
context.UpdateEngine.CleanupIncomingArtifacts();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warn($"Failed to cleanup update artifacts after failed update: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
return new LaunchPhaseResult(LaunchPhaseStatus.Continue);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal interface IUpdateEngine
|
||||
{
|
||||
LauncherResult CheckPendingUpdate();
|
||||
|
||||
Task<LauncherResult> DownloadAsync(string manifestUrl, string signatureUrl, string archiveUrl, CancellationToken cancellationToken);
|
||||
|
||||
Task<LauncherResult> ApplyPendingUpdateAsync();
|
||||
|
||||
LauncherResult RollbackLatest();
|
||||
|
||||
void CleanupDestroyedDeployments();
|
||||
|
||||
void CleanupIncomingArtifacts();
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
using LanMountainDesktop.Shared.Contracts.Update;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
public interface IUpdateProgressReporter
|
||||
{
|
||||
void ReportProgress(InstallProgressReport report);
|
||||
void ReportComplete(InstallCompleteReport report);
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using ContractsUpdate = LanMountainDesktop.Shared.Contracts.Update;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal sealed class LegacyUpdateApplier(
|
||||
DeploymentLocator deploymentLocator,
|
||||
UpdateEnginePaths paths,
|
||||
UpdateSignatureVerifier signatureVerifier,
|
||||
IUpdateProgressReporter progressReporter,
|
||||
UpdateSnapshotStore snapshotStore,
|
||||
InstallCheckpointStore checkpointStore,
|
||||
DeploymentActivator deploymentActivator,
|
||||
IncomingArtifactsCleaner incomingCleaner)
|
||||
{
|
||||
public async Task<LauncherResult> ApplyAsync()
|
||||
{
|
||||
if (!File.Exists(paths.FileMapPath) || !File.Exists(paths.ArchivePath))
|
||||
{
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.apply",
|
||||
Code = "noop",
|
||||
Message = "No update payload found."
|
||||
};
|
||||
}
|
||||
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.VerifySignature, "Verifying signature...", 0, null, 0, 0));
|
||||
var verifyResult = signatureVerifier.Verify(paths.FileMapPath, paths.SignaturePath, UpdateEnginePaths.SignatureFileName);
|
||||
if (!verifyResult.Success)
|
||||
{
|
||||
progressReporter.ReportComplete(new ContractsUpdate.InstallCompleteReport(false, null, null, verifyResult.Message, false));
|
||||
return UpdateEngineResults.Failed("update.apply", "signature_failed", verifyResult.Message);
|
||||
}
|
||||
|
||||
var fileMapText = await File.ReadAllTextAsync(paths.FileMapPath).ConfigureAwait(false);
|
||||
var fileMap = JsonSerializer.Deserialize(fileMapText, AppJsonContext.Default.SignedFileMap);
|
||||
if (fileMap is null || fileMap.Files.Count == 0)
|
||||
{
|
||||
progressReporter.ReportComplete(new ContractsUpdate.InstallCompleteReport(false, null, null, "No update file entries were found.", false));
|
||||
return UpdateEngineResults.Failed("update.apply", "invalid_manifest", "No update file entries were found.");
|
||||
}
|
||||
|
||||
var currentDeployment = deploymentLocator.FindCurrentDeploymentDirectory();
|
||||
var currentVersion = deploymentLocator.GetCurrentVersion();
|
||||
if (!string.IsNullOrWhiteSpace(fileMap.FromVersion) &&
|
||||
!string.Equals(fileMap.FromVersion, currentVersion, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return UpdateEngineResults.Failed(
|
||||
"update.apply",
|
||||
"version_mismatch",
|
||||
$"Update requires source version {fileMap.FromVersion} but current is {currentVersion}.");
|
||||
}
|
||||
|
||||
var targetVersion = string.IsNullOrWhiteSpace(fileMap.ToVersion) ? currentVersion : fileMap.ToVersion!;
|
||||
var existingCheckpoint = checkpointStore.Load();
|
||||
var canResume = existingCheckpoint is not null
|
||||
&& string.Equals(existingCheckpoint.SourceVersion, currentVersion, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(existingCheckpoint.TargetVersion, targetVersion, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(existingCheckpoint.SourceDirectory ?? string.Empty, currentDeployment ?? string.Empty, StringComparison.OrdinalIgnoreCase)
|
||||
&& Directory.Exists(existingCheckpoint.TargetDirectory)
|
||||
&& File.Exists(Path.Combine(existingCheckpoint.TargetDirectory, ".partial"));
|
||||
|
||||
if (existingCheckpoint is not null && !canResume)
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.apply", "resume_state_invalid", "Install checkpoint is stale or invalid. Please cancel and redownload update payload.");
|
||||
}
|
||||
|
||||
var targetDeployment = canResume
|
||||
? existingCheckpoint!.TargetDirectory
|
||||
: deploymentLocator.BuildNextDeploymentDirectory(targetVersion);
|
||||
var snapshot = BuildSnapshot(canResume, existingCheckpoint, currentVersion, targetVersion, currentDeployment, targetDeployment);
|
||||
var snapshotPath = snapshotStore.CreateSnapshotPath(snapshot.SnapshotId);
|
||||
var checkpoint = canResume
|
||||
? existingCheckpoint!
|
||||
: BuildCheckpoint(snapshot, currentVersion, targetVersion, currentDeployment, targetDeployment);
|
||||
|
||||
try
|
||||
{
|
||||
snapshotStore.Save(snapshotPath, snapshot);
|
||||
PrepareExtractRoot();
|
||||
ZipFile.ExtractToDirectory(paths.ArchivePath, paths.ExtractRoot, overwriteFiles: true);
|
||||
|
||||
if (!canResume)
|
||||
{
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.CreateTarget, "Creating target deployment...", 20, null, 0, fileMap.Files.Count));
|
||||
Directory.CreateDirectory(targetDeployment);
|
||||
File.WriteAllText(Path.Combine(targetDeployment, ".partial"), string.Empty);
|
||||
}
|
||||
|
||||
checkpointStore.Save(checkpoint);
|
||||
ApplyFiles(fileMap, currentDeployment!, targetDeployment, checkpoint);
|
||||
VerifyFiles(fileMap, targetDeployment, checkpoint);
|
||||
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.ActivateDeployment, "Activating deployment...", 85, null, fileMap.Files.Count, fileMap.Files.Count));
|
||||
deploymentActivator.Activate(currentDeployment!, targetDeployment);
|
||||
|
||||
snapshot.Status = "applied";
|
||||
snapshotStore.Save(snapshotPath, snapshot);
|
||||
incomingCleaner.Cleanup();
|
||||
deploymentActivator.RetainDeploymentsForRollback();
|
||||
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.Completed, $"Updated to {targetVersion}.", 100, null, fileMap.Files.Count, fileMap.Files.Count));
|
||||
progressReporter.ReportComplete(new ContractsUpdate.InstallCompleteReport(true, currentVersion, targetVersion, null, false));
|
||||
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.apply",
|
||||
Code = "ok",
|
||||
Message = $"Updated to {targetVersion}.",
|
||||
CurrentVersion = currentVersion,
|
||||
TargetVersion = targetVersion
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.RollingBack, "Rolling back...", 0, null, 0, 0));
|
||||
var rollbackResult = deploymentActivator.TryRollbackOnFailure(snapshot);
|
||||
snapshot.Status = rollbackResult.Success ? "rolled_back" : "rollback_failed";
|
||||
snapshotStore.Save(snapshotPath, snapshot);
|
||||
var errorMessage = rollbackResult.Success
|
||||
? ex.Message
|
||||
: $"{ex.Message}; rollback failed: {rollbackResult.ErrorMessage}";
|
||||
progressReporter.ReportComplete(new ContractsUpdate.InstallCompleteReport(false, currentVersion, targetVersion, errorMessage, rollbackResult.Success));
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = false,
|
||||
Stage = "update.apply",
|
||||
Code = rollbackResult.Success ? "apply_failed" : "rollback_failed",
|
||||
Message = rollbackResult.Success
|
||||
? "Failed to apply update. Rolled back to previous version."
|
||||
: "Failed to apply update and rollback failed.",
|
||||
ErrorMessage = errorMessage,
|
||||
CurrentVersion = currentVersion,
|
||||
RolledBackTo = rollbackResult.Success ? currentVersion : null
|
||||
};
|
||||
}
|
||||
finally
|
||||
{
|
||||
checkpointStore.Delete();
|
||||
TryDeleteExtractRoot();
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyFiles(SignedFileMap fileMap, string currentDeployment, string targetDeployment, InstallCheckpoint checkpoint)
|
||||
{
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.ApplyFiles, "Applying files...", 30, null, checkpoint.AppliedCount, fileMap.Files.Count));
|
||||
for (var fileIndex = checkpoint.AppliedCount; fileIndex < fileMap.Files.Count; fileIndex++)
|
||||
{
|
||||
var file = fileMap.Files[fileIndex];
|
||||
ApplyFileEntry(file, currentDeployment, targetDeployment);
|
||||
checkpoint.AppliedCount = fileIndex + 1;
|
||||
checkpointStore.Save(checkpoint);
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.ApplyFiles, "Applying files...", 30 + (checkpoint.AppliedCount * 30 / fileMap.Files.Count), file.Path, checkpoint.AppliedCount, fileMap.Files.Count));
|
||||
}
|
||||
}
|
||||
|
||||
private void VerifyFiles(SignedFileMap fileMap, string targetDeployment, InstallCheckpoint checkpoint)
|
||||
{
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.VerifyHashes, "Verifying hashes...", 65, null, checkpoint.VerifiedCount, fileMap.Files.Count));
|
||||
for (var verifyIndex = checkpoint.VerifiedCount; verifyIndex < fileMap.Files.Count; verifyIndex++)
|
||||
{
|
||||
var file = fileMap.Files[verifyIndex];
|
||||
if (NeedsVerification(file))
|
||||
{
|
||||
var fullPath = Path.Combine(targetDeployment, file.Path);
|
||||
var actualHash = UpdateHash.ComputeSha256Hex(fullPath);
|
||||
if (!string.Equals(actualHash, file.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new InvalidOperationException($"File hash mismatch for '{file.Path}'.");
|
||||
}
|
||||
}
|
||||
|
||||
checkpoint.VerifiedCount = verifyIndex + 1;
|
||||
checkpointStore.Save(checkpoint);
|
||||
progressReporter.ReportProgress(new ContractsUpdate.InstallProgressReport(ContractsUpdate.InstallStage.VerifyHashes, "Verifying hashes...", 65 + (checkpoint.VerifiedCount * 15 / fileMap.Files.Count), file.Path, checkpoint.VerifiedCount, fileMap.Files.Count));
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyFileEntry(UpdateFileEntry file, string currentDeployment, string targetDeployment)
|
||||
{
|
||||
var normalizedPath = UpdatePathGuard.NormalizeRelativePath(file.Path);
|
||||
if (string.Equals(file.Action, "delete", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var targetPath = Path.Combine(targetDeployment, normalizedPath);
|
||||
UpdatePathGuard.EnsurePathWithinRoot(targetPath, targetDeployment);
|
||||
var targetDir = Path.GetDirectoryName(targetPath);
|
||||
if (!string.IsNullOrWhiteSpace(targetDir))
|
||||
{
|
||||
Directory.CreateDirectory(targetDir);
|
||||
}
|
||||
|
||||
if (string.Equals(file.Action, "reuse", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var sourcePath = Path.Combine(currentDeployment, normalizedPath);
|
||||
UpdatePathGuard.EnsurePathWithinRoot(sourcePath, currentDeployment);
|
||||
if (!File.Exists(sourcePath))
|
||||
{
|
||||
throw new FileNotFoundException($"Cannot reuse file '{file.Path}' because it was not found in current deployment.");
|
||||
}
|
||||
|
||||
File.Copy(sourcePath, targetPath, overwrite: true);
|
||||
return;
|
||||
}
|
||||
|
||||
var archiveRelative = string.IsNullOrWhiteSpace(file.ArchivePath) ? normalizedPath : UpdatePathGuard.NormalizeRelativePath(file.ArchivePath);
|
||||
var extractedPath = Path.Combine(paths.ExtractRoot, archiveRelative);
|
||||
UpdatePathGuard.EnsurePathWithinRoot(extractedPath, paths.ExtractRoot);
|
||||
if (!File.Exists(extractedPath))
|
||||
{
|
||||
throw new FileNotFoundException($"Archive file '{archiveRelative}' not found for '{file.Path}'.");
|
||||
}
|
||||
|
||||
File.Copy(extractedPath, targetPath, overwrite: true);
|
||||
}
|
||||
|
||||
private void PrepareExtractRoot()
|
||||
{
|
||||
if (Directory.Exists(paths.ExtractRoot))
|
||||
{
|
||||
Directory.Delete(paths.ExtractRoot, true);
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(paths.ExtractRoot);
|
||||
}
|
||||
|
||||
private void TryDeleteExtractRoot()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(paths.ExtractRoot))
|
||||
{
|
||||
Directory.Delete(paths.ExtractRoot, true);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static SnapshotMetadata BuildSnapshot(
|
||||
bool canResume,
|
||||
InstallCheckpoint? existingCheckpoint,
|
||||
string currentVersion,
|
||||
string targetVersion,
|
||||
string? currentDeployment,
|
||||
string targetDeployment) =>
|
||||
new()
|
||||
{
|
||||
SnapshotId = canResume ? existingCheckpoint!.SnapshotId : Guid.NewGuid().ToString("N"),
|
||||
SourceVersion = currentVersion,
|
||||
TargetVersion = targetVersion,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
SourceDirectory = currentDeployment ?? string.Empty,
|
||||
TargetDirectory = targetDeployment,
|
||||
Status = "pending"
|
||||
};
|
||||
|
||||
private static InstallCheckpoint BuildCheckpoint(
|
||||
SnapshotMetadata snapshot,
|
||||
string currentVersion,
|
||||
string targetVersion,
|
||||
string? currentDeployment,
|
||||
string targetDeployment) =>
|
||||
new()
|
||||
{
|
||||
SnapshotId = snapshot.SnapshotId,
|
||||
SourceVersion = currentVersion,
|
||||
TargetVersion = targetVersion,
|
||||
SourceDirectory = currentDeployment,
|
||||
TargetDirectory = targetDeployment,
|
||||
IsInitialDeployment = false
|
||||
};
|
||||
|
||||
private static bool NeedsVerification(UpdateFileEntry file)
|
||||
{
|
||||
return !string.Equals(file.Action, "delete", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.IsNullOrWhiteSpace(file.Sha256);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
using LanMountainDesktop.Shared.Contracts.Update;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal sealed class NullUpdateProgressReporter : IUpdateProgressReporter
|
||||
{
|
||||
public void ReportProgress(InstallProgressReport report) { }
|
||||
public void ReportComplete(InstallCompleteReport report) { }
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal sealed class PendingUpdateDetector(
|
||||
DeploymentLocator deploymentLocator,
|
||||
UpdateEnginePaths paths,
|
||||
UpdateSignatureVerifier signatureVerifier)
|
||||
{
|
||||
public LauncherResult CheckPendingUpdate()
|
||||
{
|
||||
if (File.Exists(paths.PlondsFileMapPath) && File.Exists(paths.PlondsSignaturePath))
|
||||
{
|
||||
var plondsFileMapText = File.ReadAllText(paths.PlondsFileMapPath);
|
||||
var plondsFileMap = JsonSerializer.Deserialize(plondsFileMapText, AppJsonContext.Default.PlondsFileMap);
|
||||
if (plondsFileMap is null)
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.check", "invalid_manifest", "plonds-filemap.json is invalid.");
|
||||
}
|
||||
|
||||
var plondsVerified = signatureVerifier.Verify(
|
||||
paths.PlondsFileMapPath,
|
||||
paths.PlondsSignaturePath,
|
||||
UpdateEnginePaths.PlondsSignatureFileName);
|
||||
if (!plondsVerified.Success)
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.check", "signature_failed", plondsVerified.Message);
|
||||
}
|
||||
|
||||
var plondsMetadata = PlondsManifestParser.LoadMetadata(paths.PlondsUpdateMetadataPath);
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.check",
|
||||
Code = "available",
|
||||
Message = "Pending PLONDS update is available.",
|
||||
CurrentVersion = deploymentLocator.GetCurrentVersion(),
|
||||
TargetVersion = PlondsManifestParser.ResolveTargetVersion(plondsFileMap, plondsMetadata)
|
||||
};
|
||||
}
|
||||
|
||||
if (!File.Exists(paths.FileMapPath) || !File.Exists(paths.ArchivePath))
|
||||
{
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.check",
|
||||
Code = "noop",
|
||||
Message = "No pending update."
|
||||
};
|
||||
}
|
||||
|
||||
var fileMapText = File.ReadAllText(paths.FileMapPath);
|
||||
var fileMap = JsonSerializer.Deserialize(fileMapText, AppJsonContext.Default.SignedFileMap);
|
||||
if (fileMap is null)
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.check", "invalid_manifest", "files.json is invalid.");
|
||||
}
|
||||
|
||||
var verified = signatureVerifier.Verify(paths.FileMapPath, paths.SignaturePath, UpdateEnginePaths.SignatureFileName);
|
||||
if (!verified.Success)
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.check", "signature_failed", verified.Message);
|
||||
}
|
||||
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.check",
|
||||
Code = "available",
|
||||
Message = "Pending update is available.",
|
||||
CurrentVersion = deploymentLocator.GetCurrentVersion(),
|
||||
TargetVersion = fileMap.ToVersion
|
||||
};
|
||||
}
|
||||
|
||||
public LauncherResult ValidateIncomingState()
|
||||
{
|
||||
if (File.Exists(paths.ApplyLockPath))
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.apply", "lock_conflict", "Another update apply operation is already in progress.");
|
||||
}
|
||||
|
||||
if (!File.Exists(paths.DeploymentLockPath))
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.apply", "staging_incomplete", "Deployment lock is missing. Please redownload the update.");
|
||||
}
|
||||
|
||||
var hasPlondsMap = File.Exists(paths.PlondsFileMapPath);
|
||||
var hasLegacyMap = File.Exists(paths.FileMapPath);
|
||||
if (hasPlondsMap && !File.Exists(paths.DownloadMarkerPath))
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.apply", "staging_incomplete", "Download marker is missing for pending PLONDS update.");
|
||||
}
|
||||
|
||||
if (!hasPlondsMap && !hasLegacyMap)
|
||||
{
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.apply",
|
||||
Code = "noop",
|
||||
Message = "No update payload found."
|
||||
};
|
||||
}
|
||||
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = true,
|
||||
Stage = "update.apply",
|
||||
Code = "ok",
|
||||
Message = "Incoming update state validated."
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal sealed class UpdateEngineFacade : IUpdateEngine
|
||||
{
|
||||
private readonly UpdateEnginePaths _paths;
|
||||
private readonly PendingUpdateDetector _pendingUpdateDetector;
|
||||
private readonly LegacyUpdateApplier _legacyUpdateApplier;
|
||||
private readonly PlondsUpdateApplier _plondsUpdateApplier;
|
||||
private readonly RollbackStrategy _rollbackStrategy;
|
||||
private readonly DeploymentActivator _deploymentActivator;
|
||||
private readonly IncomingArtifactsCleaner _incomingArtifactsCleaner;
|
||||
|
||||
public UpdateEngineFacade(DeploymentLocator deploymentLocator, IUpdateProgressReporter? progressReporter = null)
|
||||
{
|
||||
var reporter = progressReporter ?? new NullUpdateProgressReporter();
|
||||
_paths = new UpdateEnginePaths(deploymentLocator.GetAppRoot());
|
||||
var signatureVerifier = new UpdateSignatureVerifier(_paths);
|
||||
var snapshotStore = new UpdateSnapshotStore(_paths);
|
||||
var checkpointStore = new InstallCheckpointStore(_paths);
|
||||
_deploymentActivator = new DeploymentActivator(deploymentLocator);
|
||||
_incomingArtifactsCleaner = new IncomingArtifactsCleaner(_paths);
|
||||
_pendingUpdateDetector = new PendingUpdateDetector(deploymentLocator, _paths, signatureVerifier);
|
||||
_legacyUpdateApplier = new LegacyUpdateApplier(
|
||||
deploymentLocator,
|
||||
_paths,
|
||||
signatureVerifier,
|
||||
reporter,
|
||||
snapshotStore,
|
||||
checkpointStore,
|
||||
_deploymentActivator,
|
||||
_incomingArtifactsCleaner);
|
||||
_plondsUpdateApplier = new PlondsUpdateApplier(
|
||||
deploymentLocator,
|
||||
_paths,
|
||||
signatureVerifier,
|
||||
reporter,
|
||||
snapshotStore,
|
||||
checkpointStore,
|
||||
_deploymentActivator,
|
||||
_incomingArtifactsCleaner,
|
||||
new PlondsPayloadResolver(_paths));
|
||||
_rollbackStrategy = new RollbackStrategy(deploymentLocator, snapshotStore, _deploymentActivator);
|
||||
}
|
||||
|
||||
public LauncherResult CheckPendingUpdate() => _pendingUpdateDetector.CheckPendingUpdate();
|
||||
|
||||
public Task<LauncherResult> DownloadAsync(string manifestUrl, string signatureUrl, string archiveUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
_ = manifestUrl;
|
||||
_ = signatureUrl;
|
||||
_ = archiveUrl;
|
||||
_ = cancellationToken;
|
||||
|
||||
return Task.FromResult(new LauncherResult
|
||||
{
|
||||
Success = false,
|
||||
Stage = "update.download",
|
||||
Code = "host_managed_only",
|
||||
Message = "Launcher no longer performs network downloads. Host must download update payload into incoming directory first."
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<LauncherResult> ApplyPendingUpdateAsync()
|
||||
{
|
||||
Directory.CreateDirectory(_paths.IncomingRoot);
|
||||
Directory.CreateDirectory(_paths.SnapshotsRoot);
|
||||
|
||||
var stateValidation = _pendingUpdateDetector.ValidateIncomingState();
|
||||
if (!stateValidation.Success || stateValidation.Code == "noop")
|
||||
{
|
||||
return stateValidation;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
File.WriteAllText(_paths.ApplyLockPath, DateTimeOffset.UtcNow.ToString("O"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return UpdateEngineResults.Failed("update.apply", "lock_conflict", $"Failed to acquire apply lock: {ex.Message}");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_paths.HasPlondsPayload)
|
||||
{
|
||||
return await _plondsUpdateApplier.ApplyAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await _legacyUpdateApplier.ApplyAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteApplyLock();
|
||||
}
|
||||
}
|
||||
|
||||
public LauncherResult RollbackLatest() => _rollbackStrategy.RollbackLatest();
|
||||
|
||||
public void CleanupDestroyedDeployments() => _deploymentActivator.RetainDeploymentsForRollback();
|
||||
|
||||
public void CleanupIncomingArtifacts() => _incomingArtifactsCleaner.Cleanup();
|
||||
|
||||
private void TryDeleteApplyLock()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(_paths.ApplyLockPath))
|
||||
{
|
||||
File.Delete(_paths.ApplyLockPath);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal static class UpdateEngineFactory
|
||||
{
|
||||
public static IUpdateEngine Create(DeploymentLocator deploymentLocator, IUpdateProgressReporter? progressReporter = null) =>
|
||||
new UpdateEngineFacade(deploymentLocator, progressReporter);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
|
||||
namespace LanMountainDesktop.Launcher.Update;
|
||||
|
||||
internal static class UpdateEngineResults
|
||||
{
|
||||
public static LauncherResult Failed(string stage, string code, string message)
|
||||
{
|
||||
return new LauncherResult
|
||||
{
|
||||
Success = false,
|
||||
Stage = stage,
|
||||
Code = code,
|
||||
Message = message,
|
||||
ErrorMessage = message
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ using LanMountainDesktop.Launcher.Resources;
|
||||
namespace LanMountainDesktop.Launcher.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 更新进度窗口 - 用于 apply-update 命令模式下显示更新/插件升级进度
|
||||
/// 更新进度窗口 - 用于预览模式显示更新/插件升级进度
|
||||
/// </summary>
|
||||
public partial class UpdateWindow : Window
|
||||
{
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using dotnetCampus.Ipc.CompilerServices.Attributes;
|
||||
|
||||
namespace LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
|
||||
[IpcPublic(IgnoresIpcException = true)]
|
||||
public interface IAirAppRuntimeControlService
|
||||
{
|
||||
Task<AirAppRuntimeControlResult> AttachHostAsync(int hostProcessId);
|
||||
|
||||
Task<AirAppRuntimeStatus> GetStatusAsync();
|
||||
}
|
||||
|
||||
public sealed record AirAppRuntimeControlResult(
|
||||
bool Accepted,
|
||||
string Code,
|
||||
string Message,
|
||||
AirAppRuntimeStatus Status);
|
||||
|
||||
public sealed record AirAppRuntimeStatus(
|
||||
int ProcessId,
|
||||
int LauncherProcessId,
|
||||
int HostProcessId,
|
||||
bool LauncherProcessAlive,
|
||||
bool HostProcessAlive,
|
||||
bool HasLiveAirApps,
|
||||
DateTimeOffset StartedAtUtc,
|
||||
DateTimeOffset UpdatedAtUtc);
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LanMountainDesktop.Shared.IPC;
|
||||
|
||||
public static class AirAppRuntimeDataRootResolver
|
||||
{
|
||||
private const string LauncherDataFolderName = ".Launcher";
|
||||
private const string ConfigFileName = "data-location.config.json";
|
||||
private const string DesktopFolderName = "Desktop";
|
||||
|
||||
public static string ResolveDataRoot(string? appRoot)
|
||||
{
|
||||
var defaultSystemDataPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LanMountainDesktop");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(appRoot))
|
||||
{
|
||||
return defaultSystemDataPath;
|
||||
}
|
||||
|
||||
var normalizedAppRoot = Path.GetFullPath(appRoot);
|
||||
var configPath = Path.Combine(normalizedAppRoot, LauncherDataFolderName, ConfigFileName);
|
||||
if (!File.Exists(configPath))
|
||||
{
|
||||
return defaultSystemDataPath;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(configPath));
|
||||
var root = document.RootElement;
|
||||
var mode = GetString(root, "dataLocationMode");
|
||||
|
||||
if (string.Equals(mode, "Portable", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Path.GetFullPath(
|
||||
GetString(root, "portableDataPath")
|
||||
?? Path.Combine(normalizedAppRoot, DesktopFolderName));
|
||||
}
|
||||
|
||||
return Path.GetFullPath(GetString(root, "systemDataPath") ?? defaultSystemDataPath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultSystemDataPath;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? GetString(JsonElement element, string propertyName)
|
||||
{
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (string.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) &&
|
||||
property.Value.ValueKind is JsonValueKind.String)
|
||||
{
|
||||
var value = property.Value.GetString();
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
77
LanMountainDesktop.Shared.IPC/AirAppRuntimePathResolver.cs
Normal file
77
LanMountainDesktop.Shared.IPC/AirAppRuntimePathResolver.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
namespace LanMountainDesktop.Shared.IPC;
|
||||
|
||||
public static class AirAppRuntimePathResolver
|
||||
{
|
||||
private const string WindowsExecutableName = "LanMountainDesktop.AirAppRuntime.exe";
|
||||
private const string UnixExecutableName = "LanMountainDesktop.AirAppRuntime";
|
||||
private const string DllName = "LanMountainDesktop.AirAppRuntime.dll";
|
||||
|
||||
private static string ExecutableName => OperatingSystem.IsWindows()
|
||||
? WindowsExecutableName
|
||||
: UnixExecutableName;
|
||||
|
||||
public static string? ResolveExecutablePath(string? appRoot = null, string? hostBaseDirectory = null)
|
||||
{
|
||||
return EnumerateCandidates(appRoot, hostBaseDirectory)
|
||||
.Select(Path.GetFullPath)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.FirstOrDefault(File.Exists);
|
||||
}
|
||||
|
||||
public static IEnumerable<string> EnumerateCandidates(string? appRoot = null, string? hostBaseDirectory = null)
|
||||
{
|
||||
foreach (var root in EnumerateRoots(appRoot, hostBaseDirectory))
|
||||
{
|
||||
yield return Path.Combine(root, ExecutableName);
|
||||
yield return Path.Combine(root, DllName);
|
||||
yield return Path.Combine(root, "AirAppRuntime", ExecutableName);
|
||||
yield return Path.Combine(root, "AirAppRuntime", DllName);
|
||||
}
|
||||
|
||||
var current = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
for (var depth = 0; depth < 8 && current is not null; depth++, current = current.Parent)
|
||||
{
|
||||
yield return Path.Combine(
|
||||
current.FullName,
|
||||
"LanMountainDesktop.AirAppRuntime",
|
||||
"bin",
|
||||
#if DEBUG
|
||||
"Debug",
|
||||
#else
|
||||
"Release",
|
||||
#endif
|
||||
"net10.0",
|
||||
ExecutableName);
|
||||
|
||||
yield return Path.Combine(
|
||||
current.FullName,
|
||||
"LanMountainDesktop.AirAppRuntime",
|
||||
"bin",
|
||||
#if DEBUG
|
||||
"Debug",
|
||||
#else
|
||||
"Release",
|
||||
#endif
|
||||
"net10.0",
|
||||
DllName);
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> EnumerateRoots(string? appRoot, string? hostBaseDirectory)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(appRoot))
|
||||
{
|
||||
yield return Path.GetFullPath(appRoot);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(hostBaseDirectory))
|
||||
{
|
||||
var hostDirectory = Path.GetFullPath(hostBaseDirectory);
|
||||
yield return hostDirectory;
|
||||
yield return Path.GetFullPath(Path.Combine(hostDirectory, ".."));
|
||||
}
|
||||
|
||||
yield return AppContext.BaseDirectory;
|
||||
yield return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, ".."));
|
||||
}
|
||||
}
|
||||
101
LanMountainDesktop.Shared.IPC/AirAppRuntimeProcessStarter.cs
Normal file
101
LanMountainDesktop.Shared.IPC/AirAppRuntimeProcessStarter.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace LanMountainDesktop.Shared.IPC;
|
||||
|
||||
public sealed record AirAppRuntimeStartRequest(
|
||||
string? AppRoot,
|
||||
int LauncherProcessId,
|
||||
int RequesterProcessId,
|
||||
string? DataRoot);
|
||||
|
||||
public static class AirAppRuntimeProcessStarter
|
||||
{
|
||||
public static Process? Start(AirAppRuntimeStartRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
var runtimePath = AirAppRuntimePathResolver.ResolveExecutablePath(
|
||||
request.AppRoot,
|
||||
AppContext.BaseDirectory);
|
||||
if (string.IsNullOrWhiteSpace(runtimePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var startInfo = CreateStartInfo(runtimePath);
|
||||
AddOptionalArgument(startInfo, "--app-root", request.AppRoot);
|
||||
AddOptionalArgument(startInfo, "--data-root", request.DataRoot);
|
||||
AddIntArgument(startInfo, "--launcher-pid", request.LauncherProcessId);
|
||||
AddIntArgument(startInfo, "--requester-pid", request.RequesterProcessId);
|
||||
return Process.Start(startInfo);
|
||||
}
|
||||
|
||||
public static ProcessStartInfo CreateStartInfo(string runtimePath)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(runtimePath);
|
||||
var fullPath = Path.GetFullPath(runtimePath);
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = Path.GetDirectoryName(fullPath) ?? AppContext.BaseDirectory
|
||||
};
|
||||
|
||||
var extension = Path.GetExtension(fullPath);
|
||||
if (OperatingSystem.IsWindows() &&
|
||||
string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
startInfo.FileName = ResolveDotNetHostPath();
|
||||
startInfo.ArgumentList.Add(fullPath);
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
if (!OperatingSystem.IsWindows() &&
|
||||
string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
startInfo.FileName = "dotnet";
|
||||
startInfo.ArgumentList.Add(fullPath);
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
startInfo.FileName = fullPath;
|
||||
return startInfo;
|
||||
}
|
||||
|
||||
private static string ResolveDotNetHostPath()
|
||||
{
|
||||
var programFiles = Environment.GetEnvironmentVariable("ProgramW6432") ??
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
var programFilesCandidate = Path.Combine(programFiles, "dotnet", "dotnet.exe");
|
||||
if (File.Exists(programFilesCandidate))
|
||||
{
|
||||
return programFilesCandidate;
|
||||
}
|
||||
|
||||
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
var perUserCandidate = Path.Combine(localAppData, "dotnet", "dotnet.exe");
|
||||
return File.Exists(perUserCandidate) ? perUserCandidate : "dotnet";
|
||||
}
|
||||
|
||||
private static void AddOptionalArgument(ProcessStartInfo startInfo, string name, string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
startInfo.ArgumentList.Add(name);
|
||||
startInfo.ArgumentList.Add(Path.GetFullPath(value));
|
||||
}
|
||||
|
||||
private static void AddIntArgument(ProcessStartInfo startInfo, string name, int value)
|
||||
{
|
||||
if (value <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
startInfo.ArgumentList.Add(name);
|
||||
startInfo.ArgumentList.Add(value.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,10 @@ public static class IpcConstants
|
||||
|
||||
public const string ProtocolVersion = "external-ipc-public-api.v1";
|
||||
|
||||
public const string AirAppLifecyclePipeName = "LanMountainDesktop.Launcher.AirApp.v1";
|
||||
public const string AirAppRuntimePipeName = "LanMountainDesktop.AirAppRuntime.v1";
|
||||
|
||||
[Obsolete("Use AirAppRuntimePipeName. The lifecycle service is now hosted by LanMountainDesktop.AirAppRuntime.")]
|
||||
public const string AirAppLifecyclePipeName = AirAppRuntimePipeName;
|
||||
|
||||
public const string AirAppLifecycleProtocolVersion = "air-app-lifecycle.v1";
|
||||
|
||||
|
||||
@@ -96,17 +96,17 @@ public sealed class AirAppLauncherServiceTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateBrokerStartInfo_UsesAirAppBrokerCommandAndRequesterPid()
|
||||
public void CreateRuntimeStartInfo_UsesAirAppRuntimeAndRequesterPid()
|
||||
{
|
||||
var startInfo = AirAppLauncherService.CreateBrokerStartInfo(
|
||||
@"C:\Apps\LanMountainDesktop.Launcher.exe",
|
||||
var startInfo = AirAppLauncherService.CreateRuntimeStartInfo(
|
||||
@"C:\Apps\LanMountainDesktop.AirAppRuntime.exe",
|
||||
12345);
|
||||
|
||||
Assert.Equal(@"C:\Apps\LanMountainDesktop.Launcher.exe", startInfo.FileName);
|
||||
Assert.Equal(@"C:\Apps\LanMountainDesktop.AirAppRuntime.exe", startInfo.FileName);
|
||||
Assert.Equal(@"C:\Apps", startInfo.WorkingDirectory);
|
||||
Assert.False(startInfo.UseShellExecute);
|
||||
Assert.Equal(
|
||||
["air-app-broker", "--requester-pid", "12345"],
|
||||
["--requester-pid", "12345"],
|
||||
startInfo.ArgumentList);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using LanMountainDesktop.Launcher.AirApp;
|
||||
using LanMountainDesktop.Launcher.Infrastructure;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
@@ -29,38 +27,14 @@ public sealed class AirAppProcessStarterRuntimeTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateStartInfo_UsesArchitectureMatchedDotnetHost_ForDllFallbackOnWindows()
|
||||
public void CreateStartInfo_UsesDotnetHost_ForDllFallback()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var programFiles = Path.Combine(_root, "ProgramFiles");
|
||||
var dotnetRoot = Path.Combine(programFiles, "dotnet");
|
||||
Directory.CreateDirectory(dotnetRoot);
|
||||
var dotnetHost = Path.Combine(dotnetRoot, "dotnet.exe");
|
||||
File.WriteAllText(dotnetHost, string.Empty);
|
||||
Directory.CreateDirectory(Path.Combine(
|
||||
dotnetRoot,
|
||||
"shared",
|
||||
DotNetRuntimeProbe.RequiredSharedFrameworkName,
|
||||
"10.0.5"));
|
||||
|
||||
var hostDll = Path.Combine(_root, "LanMountainDesktop.AirAppHost.dll");
|
||||
File.WriteAllText(hostDll, string.Empty);
|
||||
var options = new DotNetRuntimeProbeOptions
|
||||
{
|
||||
Architecture = DotNetRuntimeArchitecture.X64,
|
||||
ProgramFilesPath = programFiles,
|
||||
ProgramFilesX86Path = Path.Combine(_root, "ProgramFilesX86"),
|
||||
IncludeRegistry = false,
|
||||
IncludeDotNetCli = false
|
||||
};
|
||||
|
||||
var startInfo = AirAppProcessStarter.CreateStartInfo(hostDll, options);
|
||||
var startInfo = AirAppProcessStarter.CreateStartInfo(hostDll);
|
||||
|
||||
Assert.Equal(dotnetHost, startInfo.FileName);
|
||||
Assert.Contains("dotnet", Path.GetFileName(startInfo.FileName), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Equal(hostDll, startInfo.ArgumentList.Single());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop.Shared.IPC;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class AirAppRuntimeDataRootResolverTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
"LanMountainDesktop.AirAppRuntimeDataRootResolverTests",
|
||||
Guid.NewGuid().ToString("N"));
|
||||
|
||||
[Fact]
|
||||
public void ResolveDataRoot_UsesPortableDataLocationConfig()
|
||||
{
|
||||
var portableRoot = Path.Combine(_root, "PortableData");
|
||||
WriteConfig(new
|
||||
{
|
||||
dataLocationMode = "Portable",
|
||||
portableDataPath = portableRoot
|
||||
});
|
||||
|
||||
var resolved = AirAppRuntimeDataRootResolver.ResolveDataRoot(_root);
|
||||
|
||||
Assert.Equal(Path.GetFullPath(portableRoot), resolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveDataRoot_UsesSystemDataLocationConfig()
|
||||
{
|
||||
var systemRoot = Path.Combine(_root, "SystemData");
|
||||
WriteConfig(new
|
||||
{
|
||||
dataLocationMode = "System",
|
||||
systemDataPath = systemRoot
|
||||
});
|
||||
|
||||
var resolved = AirAppRuntimeDataRootResolver.ResolveDataRoot(_root);
|
||||
|
||||
Assert.Equal(Path.GetFullPath(systemRoot), resolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveDataRoot_FallsBackToDefaultWhenConfigMissing()
|
||||
{
|
||||
var resolved = AirAppRuntimeDataRootResolver.ResolveDataRoot(_root);
|
||||
|
||||
Assert.Equal(
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LanMountainDesktop"),
|
||||
resolved);
|
||||
}
|
||||
|
||||
private void WriteConfig<T>(T config)
|
||||
{
|
||||
var configDirectory = Path.Combine(_root, ".Launcher");
|
||||
Directory.CreateDirectory(configDirectory);
|
||||
File.WriteAllText(
|
||||
Path.Combine(configDirectory, "data-location.config.json"),
|
||||
JsonSerializer.Serialize(config));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_root))
|
||||
{
|
||||
Directory.Delete(_root, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,17 @@
|
||||
using System.Diagnostics;
|
||||
using LanMountainDesktop.ComponentSystem;
|
||||
using LanMountainDesktop.Launcher;
|
||||
using LanMountainDesktop.Launcher.AirApp;
|
||||
using LanMountainDesktop.Launcher.Shell.EntryHandlers;
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class LauncherAirAppLifecycleServiceTests
|
||||
public sealed class AirAppRuntimeLifecycleServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task OpenAsync_ReusesExistingInstanceForSameKey()
|
||||
{
|
||||
var starter = new TestAirAppProcessStarter(Process.GetCurrentProcess());
|
||||
var service = new LauncherAirAppLifecycleService(starter);
|
||||
var service = new AirAppLifecycleService(starter);
|
||||
var request = new AirAppOpenRequest(
|
||||
"whiteboard",
|
||||
BuiltInComponentIds.DesktopWhiteboard,
|
||||
@@ -36,7 +33,7 @@ public sealed class LauncherAirAppLifecycleServiceTests
|
||||
public async Task OpenAsync_ReusesGlobalClockSuiteAcrossClockComponents()
|
||||
{
|
||||
var starter = new TestAirAppProcessStarter(Process.GetCurrentProcess());
|
||||
var service = new LauncherAirAppLifecycleService(starter);
|
||||
var service = new AirAppLifecycleService(starter);
|
||||
|
||||
var first = await service.OpenAsync(new AirAppOpenRequest(
|
||||
"world-clock",
|
||||
@@ -62,7 +59,7 @@ public sealed class LauncherAirAppLifecycleServiceTests
|
||||
public async Task OpenAsync_PrunesExitedRegisteredInstanceBeforeRestart()
|
||||
{
|
||||
var starter = new TestAirAppProcessStarter(Process.GetCurrentProcess());
|
||||
var service = new LauncherAirAppLifecycleService(starter);
|
||||
var service = new AirAppLifecycleService(starter);
|
||||
var instanceKey = AirAppInstanceKey.Build(
|
||||
"whiteboard",
|
||||
BuiltInComponentIds.DesktopWhiteboard,
|
||||
@@ -92,7 +89,7 @@ public sealed class LauncherAirAppLifecycleServiceTests
|
||||
[Fact]
|
||||
public async Task HasLiveAirApps_ReturnsFalseAfterUnregisteringLastInstance()
|
||||
{
|
||||
var service = new LauncherAirAppLifecycleService(new TestAirAppProcessStarter(Process.GetCurrentProcess()));
|
||||
var service = new AirAppLifecycleService(new TestAirAppProcessStarter(Process.GetCurrentProcess()));
|
||||
var instanceKey = AirAppInstanceKey.Build("world-clock", BuiltInComponentIds.DesktopWorldClock, "clock-1");
|
||||
|
||||
_ = await service.RegisterAsync(new AirAppRegistrationRequest(
|
||||
@@ -112,26 +109,35 @@ public sealed class LauncherAirAppLifecycleServiceTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AirAppBrokerLifetime_KeepsAliveWhileRequesterIsAlive()
|
||||
public void RuntimeLifetime_KeepsAliveWhileRequesterIsAlive()
|
||||
{
|
||||
var service = new LauncherAirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var service = new AirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var lifetime = new AirAppRuntimeLifetime(
|
||||
new AirAppRuntimeOptions(null, null, 0, Environment.ProcessId),
|
||||
service);
|
||||
|
||||
Assert.True(AirAppBrokerEntryHandler.ShouldKeepAirAppBrokerAlive(Environment.ProcessId, service));
|
||||
Assert.True(lifetime.ShouldKeepAlive());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AirAppBrokerLifetime_StopsWhenRequesterExitedAndNoAirAppsRemain()
|
||||
public void RuntimeLifetime_StopsWhenNoProcessOrAirAppsRemain()
|
||||
{
|
||||
var service = new LauncherAirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var service = new AirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var lifetime = new AirAppRuntimeLifetime(
|
||||
new AirAppRuntimeOptions(null, null, int.MaxValue, int.MaxValue),
|
||||
service);
|
||||
|
||||
Assert.False(AirAppBrokerEntryHandler.ShouldKeepAirAppBrokerAlive(int.MaxValue, service));
|
||||
Assert.False(lifetime.ShouldKeepAlive());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AirAppBrokerLifetime_KeepsAliveWhileAirAppIsAlive()
|
||||
public async Task RuntimeLifetime_KeepsAliveWhileAirAppIsAlive()
|
||||
{
|
||||
var service = new LauncherAirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var service = new AirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var instanceKey = AirAppInstanceKey.Build("world-clock", BuiltInComponentIds.DesktopWorldClock, "clock-2");
|
||||
var lifetime = new AirAppRuntimeLifetime(
|
||||
new AirAppRuntimeOptions(null, null, int.MaxValue, int.MaxValue),
|
||||
service);
|
||||
|
||||
_ = await service.RegisterAsync(new AirAppRegistrationRequest(
|
||||
instanceKey,
|
||||
@@ -142,28 +148,23 @@ public sealed class LauncherAirAppLifecycleServiceTests
|
||||
BuiltInComponentIds.DesktopWorldClock,
|
||||
"clock-2"));
|
||||
|
||||
Assert.True(AirAppBrokerEntryHandler.ShouldKeepAirAppBrokerAlive(int.MaxValue, service));
|
||||
Assert.True(lifetime.ShouldKeepAlive());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CommandContext_RecognizesAirAppBrokerAsGuiCommandInDebugEnvironment()
|
||||
public async Task RuntimeControl_AttachesHostProcess()
|
||||
{
|
||||
var oldEnvironment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
|
||||
try
|
||||
{
|
||||
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", "Development");
|
||||
var service = new AirAppLifecycleService(new TestAirAppProcessStarter(null));
|
||||
var lifetime = new AirAppRuntimeLifetime(
|
||||
new AirAppRuntimeOptions(null, null, int.MaxValue, int.MaxValue),
|
||||
service);
|
||||
var control = new AirAppRuntimeControlService(lifetime);
|
||||
|
||||
var context = CommandContext.FromArgs(["air-app-broker", "--requester-pid", "42"]);
|
||||
var result = await control.AttachHostAsync(Environment.ProcessId);
|
||||
|
||||
Assert.True(context.IsGuiCommand);
|
||||
Assert.True(context.IsAirAppBrokerCommand);
|
||||
Assert.True(context.IsDebugMode);
|
||||
Assert.Equal(42, context.GetIntOption("requester-pid", 0));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", oldEnvironment);
|
||||
}
|
||||
Assert.True(result.Accepted);
|
||||
Assert.Equal(Environment.ProcessId, result.Status.HostProcessId);
|
||||
Assert.True(result.Status.HostProcessAlive);
|
||||
}
|
||||
|
||||
private sealed class TestAirAppProcessStarter : IAirAppProcessStarter
|
||||
@@ -9,7 +9,6 @@ public sealed class CommandContextTests
|
||||
{
|
||||
{ [], "normal" },
|
||||
{ ["preview-oobe"], "debug-preview" },
|
||||
{ ["apply-update"], "apply-update" },
|
||||
{ ["--source", "plugin.lmdp", "--plugins-dir", "plugins", "--result", "result.json"], "plugin-install" },
|
||||
{ ["launch", "--launch-source", "postinstall"], "postinstall" }
|
||||
};
|
||||
@@ -22,4 +21,12 @@ public sealed class CommandContextTests
|
||||
|
||||
Assert.Equal(expectedLaunchSource, context.LaunchSource);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromArgs_DoesNotTreatAirAppBrokerAsLauncherGuiCommand()
|
||||
{
|
||||
var context = CommandContext.FromArgs(["air-app-broker", "--requester-pid", "42"]);
|
||||
|
||||
Assert.False(context.IsGuiCommand);
|
||||
}
|
||||
}
|
||||
|
||||
35
LanMountainDesktop.Tests/DataLocationResolverTests.cs
Normal file
35
LanMountainDesktop.Tests/DataLocationResolverTests.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class DataLocationResolverTests : IDisposable
|
||||
{
|
||||
private readonly string _appRoot = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
"LanMountainDesktop.Tests",
|
||||
nameof(DataLocationResolverTests),
|
||||
Guid.NewGuid().ToString("N"));
|
||||
|
||||
[Fact]
|
||||
public void ApplyLocationChoice_PortableWithoutCustomPath_UsesAppRootDesktopDirectory()
|
||||
{
|
||||
Directory.CreateDirectory(_appRoot);
|
||||
var resolver = new DataLocationResolver(_appRoot);
|
||||
|
||||
var applied = resolver.ApplyLocationChoice(DataLocationMode.Portable);
|
||||
|
||||
Assert.True(applied);
|
||||
Assert.Equal(
|
||||
Path.Combine(Path.GetFullPath(_appRoot), "Desktop"),
|
||||
resolver.ResolveDataRoot());
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_appRoot))
|
||||
{
|
||||
Directory.Delete(_appRoot, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
7
LanMountainDesktop.Tests/GlobalUsings.cs
Normal file
7
LanMountainDesktop.Tests/GlobalUsings.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
global using LanMountainDesktop.AirAppRuntime;
|
||||
global using LanMountainDesktop.Launcher.Deployment;
|
||||
global using LanMountainDesktop.Launcher.Infrastructure;
|
||||
global using LanMountainDesktop.Launcher.Ipc;
|
||||
global using LanMountainDesktop.Launcher.Oobe;
|
||||
global using LanMountainDesktop.Launcher.Plugins;
|
||||
global using LanMountainDesktop.Launcher.Startup;
|
||||
@@ -11,7 +11,6 @@ public sealed class HostActivationPolicyTests
|
||||
[Theory]
|
||||
[InlineData("launch", "normal", true)]
|
||||
[InlineData("launch", "restart", false)]
|
||||
[InlineData("apply-update", "normal", false)]
|
||||
public void ShouldProbeExistingHostBeforeLaunch_RespectsLaunchSource(
|
||||
string command,
|
||||
string launchSource,
|
||||
|
||||
69
LanMountainDesktop.Tests/HostStartupMonitorTests.cs
Normal file
69
LanMountainDesktop.Tests/HostStartupMonitorTests.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using LanMountainDesktop.Launcher.Startup;
|
||||
using LanMountainDesktop.Shared.Contracts.Launcher;
|
||||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class HostStartupMonitorTests
|
||||
{
|
||||
[Fact]
|
||||
public void InitialIpcConnectUsesStagedBackoff()
|
||||
{
|
||||
var source = ReadRepositoryFile("LanMountainDesktop.Launcher", "Startup", "HostStartupMonitor.cs");
|
||||
|
||||
Assert.Contains("StartupTimeoutPolicy.InitialIpcConnectTimeout", source);
|
||||
Assert.Contains("TimeSpan.FromMilliseconds(3000)", source);
|
||||
Assert.Contains("TimeSpan.FromMilliseconds(5000)", source);
|
||||
Assert.Contains("TryConnectWithBackoffAsync", source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefreshShellStatus_UsesStartupSuccessTrackerForSuccess()
|
||||
{
|
||||
var source = ReadRepositoryFile("LanMountainDesktop.Launcher", "Startup", "HostStartupMonitor.cs");
|
||||
|
||||
Assert.Contains("SuccessTracker.TryResolve(shellStatus, out var successState)", source);
|
||||
var refreshBlock = source[
|
||||
source.IndexOf("RefreshShellStatusAsync", StringComparison.Ordinal) ..
|
||||
source.IndexOf("var connected = await PublicIpcConnection.TryConnectWithBackoffAsync", StringComparison.Ordinal)];
|
||||
Assert.DoesNotContain("return new StartupSuccessState", refreshBlock);
|
||||
Assert.DoesNotContain("successState = new StartupSuccessState", refreshBlock);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildDelayedLoadingState_AddsSoftTimeoutItem()
|
||||
{
|
||||
var loadingState = new LoadingStateMessage
|
||||
{
|
||||
ActiveItems = [],
|
||||
OverallProgressPercent = 0,
|
||||
TotalCount = 0
|
||||
};
|
||||
|
||||
var delayed = HostStartupMonitor.BuildDelayedLoadingState(
|
||||
loadingState,
|
||||
"Still starting",
|
||||
"Host is still warming up.",
|
||||
DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Equal("Still starting", delayed.Message);
|
||||
Assert.Contains(delayed.ActiveItems, item => item.Id == "launcher-soft-timeout");
|
||||
}
|
||||
|
||||
private static string ReadRepositoryFile(params string[] pathParts)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "LanMountainDesktop.slnx")))
|
||||
{
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
if (directory is null)
|
||||
{
|
||||
throw new DirectoryNotFoundException("Unable to locate repository root.");
|
||||
}
|
||||
|
||||
return File.ReadAllText(Path.Combine([directory.FullName, .. pathParts]));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LanMountainDesktop\LanMountainDesktop.csproj" />
|
||||
<ProjectReference Include="..\LanMountainDesktop.AirAppRuntime\LanMountainDesktop.AirAppRuntime.csproj" />
|
||||
<ProjectReference Include="..\LanMountainDesktop.Launcher\LanMountainDesktop.Launcher.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -33,8 +33,7 @@ public sealed class LauncherArchitectureTests
|
||||
{
|
||||
var guardedFiles = new[]
|
||||
{
|
||||
Path.Combine(LauncherProjectRoot, "Infrastructure", "Commands.cs"),
|
||||
Path.Combine(LauncherProjectRoot, "Shell", "ApplyUpdateGuiFlow.cs")
|
||||
Path.Combine(LauncherProjectRoot, "Infrastructure", "Commands.cs")
|
||||
}.Concat(Directory.EnumerateFiles(
|
||||
Path.Combine(LauncherProjectRoot, "Shell", "EntryHandlers"),
|
||||
"*.cs",
|
||||
@@ -49,9 +48,97 @@ public sealed class LauncherArchitectureTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LauncherFacadeAndCompositionRootStayThin()
|
||||
public void LauncherProject_DoesNotOwnUpdateApplyOrRollback()
|
||||
{
|
||||
var launcherFiles = Directory
|
||||
.EnumerateFiles(LauncherProjectRoot, "*.cs", SearchOption.AllDirectories)
|
||||
.Where(file => !file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.OrdinalIgnoreCase))
|
||||
.Where(file => !file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.OrdinalIgnoreCase))
|
||||
.ToArray();
|
||||
|
||||
var forbiddenTokens = new[]
|
||||
{
|
||||
"LauncherUpdateCommandExecutor",
|
||||
"PlondsUpdateApplier",
|
||||
"UpdateRollbackGateway",
|
||||
"UpdateInstallGateway",
|
||||
"LanMountainDesktop.Services.Update",
|
||||
"apply-update",
|
||||
"rollback --app-root"
|
||||
};
|
||||
|
||||
var offenders = launcherFiles
|
||||
.SelectMany(file => forbiddenTokens
|
||||
.Where(token => File.ReadAllText(file).Contains(token, StringComparison.Ordinal))
|
||||
.Select(token => $"{RelativeToRepo(file)} contains {token}"))
|
||||
.ToArray();
|
||||
|
||||
Assert.Empty(offenders);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LauncherProjectFile_DoesNotSourceLinkHostUpdateImplementation()
|
||||
{
|
||||
var project = File.ReadAllText(Path.Combine(LauncherProjectRoot, "LanMountainDesktop.Launcher.csproj"));
|
||||
|
||||
Assert.DoesNotContain(@"..\LanMountainDesktop\Services\Update", project, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("PlondsUpdateApplier", project, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("UpdateRollbackGateway", project, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("UpdateInstallGateway", project, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HostUpdateFlow_DoesNotDelegateApplyOrRollbackToLauncher()
|
||||
{
|
||||
var guardedFiles = new[]
|
||||
{
|
||||
Path.Combine(RepoRoot, "LanMountainDesktop", "Services", "Update", "UpdateInstallGateway.cs"),
|
||||
Path.Combine(RepoRoot, "LanMountainDesktop", "Services", "Update", "UpdateOrchestrator.cs")
|
||||
};
|
||||
|
||||
var forbiddenTokens = new[]
|
||||
{
|
||||
"LauncherPathResolver",
|
||||
"ResolveLauncherExecutablePath",
|
||||
"apply-update",
|
||||
"rollback --app-root",
|
||||
"Launched Launcher"
|
||||
};
|
||||
|
||||
var offenders = guardedFiles
|
||||
.SelectMany(file => forbiddenTokens
|
||||
.Where(token => File.ReadAllText(file).Contains(token, StringComparison.Ordinal))
|
||||
.Select(token => $"{RelativeToRepo(file)} contains {token}"))
|
||||
.ToArray();
|
||||
|
||||
Assert.Empty(offenders);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HostUpdateFlow_OwnsDeltaApplyAndRollbackExecution()
|
||||
{
|
||||
var installGateway = File.ReadAllText(Path.Combine(
|
||||
RepoRoot,
|
||||
"LanMountainDesktop",
|
||||
"Services",
|
||||
"Update",
|
||||
"UpdateInstallGateway.cs"));
|
||||
var orchestrator = File.ReadAllText(Path.Combine(
|
||||
RepoRoot,
|
||||
"LanMountainDesktop",
|
||||
"Services",
|
||||
"Update",
|
||||
"UpdateOrchestrator.cs"));
|
||||
|
||||
Assert.Contains("new PlondsUpdateApplier", installGateway, StringComparison.Ordinal);
|
||||
Assert.Contains("DeploymentLockService.ClearLock", installGateway, StringComparison.Ordinal);
|
||||
Assert.Contains("new UpdateRollbackGateway().RollbackLatest", orchestrator, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("LanMountainDesktop.Launcher", orchestrator, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LauncherCompositionRootStaysThin()
|
||||
{
|
||||
AssertFileLineCountAtMost(Path.Combine(LauncherProjectRoot, "Update", "UpdateEngineFacade.cs"), 140);
|
||||
AssertFileLineCountAtMost(Path.Combine(LauncherProjectRoot, "Shell", "LauncherCompositionRoot.cs"), 80);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
global using LanMountainDesktop.Launcher.AirApp;
|
||||
global using LanMountainDesktop.AirAppRuntime;
|
||||
global using LanMountainDesktop.Launcher.Deployment;
|
||||
global using LanMountainDesktop.Launcher.Infrastructure;
|
||||
global using LanMountainDesktop.Launcher.Ipc;
|
||||
global using LanMountainDesktop.Launcher.Oobe;
|
||||
global using LanMountainDesktop.Launcher.Startup;
|
||||
global using LanMountainDesktop.Launcher.Update;
|
||||
59
LanMountainDesktop.Tests/LauncherUpdateCommandTests.cs
Normal file
59
LanMountainDesktop.Tests/LauncherUpdateCommandTests.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop.Launcher;
|
||||
using LanMountainDesktop.Launcher.Infrastructure;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class LauncherUpdateCommandTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
"LanMountainDesktop.LauncherUpdateCommandTests",
|
||||
Guid.NewGuid().ToString("N"));
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyUpdateCommand_IsNotHandledByLauncherCli()
|
||||
{
|
||||
Directory.CreateDirectory(_root);
|
||||
var resultPath = Path.Combine(_root, "result.json");
|
||||
var context = CommandContext.FromArgs(["apply-update", "--app-root", _root, "--result", resultPath]);
|
||||
|
||||
var exitCode = await Commands.RunCliCommandAsync(context);
|
||||
var result = ReadResult(resultPath);
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Equal("command", result.Stage);
|
||||
Assert.Equal("unsupported_command", result.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RollbackCommand_IsNotHandledByLauncherCli()
|
||||
{
|
||||
Directory.CreateDirectory(_root);
|
||||
var resultPath = Path.Combine(_root, "result.json");
|
||||
var context = CommandContext.FromArgs(["rollback", "--app-root", _root, "--result", resultPath]);
|
||||
|
||||
var exitCode = await Commands.RunCliCommandAsync(context);
|
||||
var result = ReadResult(resultPath);
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Equal("command", result.Stage);
|
||||
Assert.Equal("unsupported_command", result.Code);
|
||||
}
|
||||
|
||||
private static LauncherResult ReadResult(string path)
|
||||
{
|
||||
var result = JsonSerializer.Deserialize<LauncherResult>(File.ReadAllText(path));
|
||||
return result ?? throw new InvalidOperationException("Launcher result was not written.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_root))
|
||||
{
|
||||
Directory.Delete(_root, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Media;
|
||||
using LanMountainDesktop.Appearance;
|
||||
using LanMountainDesktop.Models;
|
||||
using LanMountainDesktop.PluginSdk;
|
||||
using LanMountainDesktop.Services;
|
||||
using LanMountainDesktop.Services.Settings;
|
||||
using LanMountainDesktop.Settings.Core;
|
||||
using LanMountainDesktop.Shared.Contracts;
|
||||
using LanMountainDesktop.ViewModels;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class MaterialColorSettingsPageViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public void Load_SelectsSavedNoneMaterialMode()
|
||||
{
|
||||
var facade = new FakeSettingsFacade(CreateThemeState(ThemeAppearanceValues.MaterialNone));
|
||||
var materialService = new FakeMaterialColorService(CreateSnapshot(ThemeAppearanceValues.MaterialNone));
|
||||
|
||||
var viewModel = new MaterialColorSettingsPageViewModel(facade, materialService);
|
||||
|
||||
Assert.Equal(ThemeAppearanceValues.MaterialNone, viewModel.SelectedSystemMaterialMode.Value);
|
||||
Assert.Contains(viewModel.SystemMaterialModes, option => option.Value == ThemeAppearanceValues.MaterialAuto);
|
||||
Assert.Contains(viewModel.SystemMaterialModes, option => option.Value == ThemeAppearanceValues.MaterialNone);
|
||||
Assert.Contains(viewModel.SystemMaterialModes, option => option.Value == ThemeAppearanceValues.MaterialMica);
|
||||
Assert.Contains(viewModel.SystemMaterialModes, option => option.Value == ThemeAppearanceValues.MaterialAcrylic);
|
||||
Assert.Equal(0, facade.ThemeSaveCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MaterialSnapshotRefresh_KeepsExplicitNoneSelection()
|
||||
{
|
||||
var facade = new FakeSettingsFacade(CreateThemeState(ThemeAppearanceValues.MaterialNone));
|
||||
var materialService = new FakeMaterialColorService(CreateSnapshot(ThemeAppearanceValues.MaterialNone));
|
||||
var viewModel = new MaterialColorSettingsPageViewModel(facade, materialService);
|
||||
|
||||
materialService.RaiseChanged(CreateSnapshot(ThemeAppearanceValues.MaterialAuto));
|
||||
|
||||
Assert.Equal(ThemeAppearanceValues.MaterialNone, viewModel.SelectedSystemMaterialMode.Value);
|
||||
Assert.Equal(0, facade.ThemeSaveCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ThemeAppearanceValues.MaterialNone)]
|
||||
[InlineData(ThemeAppearanceValues.MaterialAuto)]
|
||||
[InlineData(ThemeAppearanceValues.MaterialMica)]
|
||||
[InlineData(ThemeAppearanceValues.MaterialAcrylic)]
|
||||
public void UserSelection_SavesRequestedMaterialMode(string targetMode)
|
||||
{
|
||||
var initialMode = targetMode == ThemeAppearanceValues.MaterialNone
|
||||
? ThemeAppearanceValues.MaterialAuto
|
||||
: ThemeAppearanceValues.MaterialNone;
|
||||
var facade = new FakeSettingsFacade(CreateThemeState(initialMode));
|
||||
var materialService = new FakeMaterialColorService(CreateSnapshot(initialMode));
|
||||
var viewModel = new MaterialColorSettingsPageViewModel(facade, materialService);
|
||||
|
||||
viewModel.SelectedSystemMaterialMode = viewModel.SystemMaterialModes.Single(option =>
|
||||
option.Value == targetMode);
|
||||
|
||||
Assert.Equal(targetMode, facade.ThemeState.SystemMaterialMode);
|
||||
Assert.Equal(1, facade.ThemeSaveCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserSelection_SystemMaterialModeRequestsRestart()
|
||||
{
|
||||
var facade = new FakeSettingsFacade(CreateThemeState(ThemeAppearanceValues.MaterialNone));
|
||||
var materialService = new FakeMaterialColorService(CreateSnapshot(ThemeAppearanceValues.MaterialNone));
|
||||
var viewModel = new MaterialColorSettingsPageViewModel(facade, materialService);
|
||||
string? restartReason = null;
|
||||
viewModel.RestartRequested += reason => restartReason = reason;
|
||||
|
||||
viewModel.SelectedSystemMaterialMode = viewModel.SystemMaterialModes.Single(option =>
|
||||
option.Value == ThemeAppearanceValues.MaterialMica);
|
||||
|
||||
Assert.Equal(viewModel.SystemMaterialRestartMessage, restartReason);
|
||||
Assert.False(string.IsNullOrWhiteSpace(restartReason));
|
||||
}
|
||||
|
||||
private static ThemeAppearanceSettingsState CreateThemeState(string materialMode)
|
||||
{
|
||||
return new ThemeAppearanceSettingsState(
|
||||
IsNightMode: false,
|
||||
ThemeColor: "#FF445566",
|
||||
UseSystemChrome: false,
|
||||
CornerRadiusStyle: GlobalAppearanceSettings.CornerRadiusStyleRounded,
|
||||
ThemeColorMode: ThemeAppearanceValues.ColorModeDefaultNeutral,
|
||||
SystemMaterialMode: materialMode,
|
||||
SelectedWallpaperSeed: null,
|
||||
ThemeMode: ThemeAppearanceValues.ThemeModeLight,
|
||||
ThemeWallpaperColorSource: ThemeAppearanceValues.WallpaperColorSourceAuto,
|
||||
UseNativeWallpaperChangeEvents: true);
|
||||
}
|
||||
|
||||
private static MaterialColorSnapshot CreateSnapshot(string materialMode)
|
||||
{
|
||||
var seed = Color.Parse("#FF3B82F6");
|
||||
var palette = new LanMountainDesktop.Models.MaterialColorPalette(
|
||||
seed,
|
||||
Color.Parse("#FF64748B"),
|
||||
seed,
|
||||
Colors.White,
|
||||
Color.Parse("#FF60A5FA"),
|
||||
Color.Parse("#FF93C5FD"),
|
||||
Color.Parse("#FFBFDBFE"),
|
||||
Color.Parse("#FF2563EB"),
|
||||
Color.Parse("#FF1D4ED8"),
|
||||
Color.Parse("#FF1E40AF"),
|
||||
Color.Parse("#FFF8FAFC"),
|
||||
Color.Parse("#FFFFFFFF"),
|
||||
Color.Parse("#FFF1F5F9"),
|
||||
Color.Parse("#FF0F172A"),
|
||||
Color.Parse("#FF334155"),
|
||||
Color.Parse("#FF64748B"),
|
||||
seed,
|
||||
Color.Parse("#FF0F172A"),
|
||||
Colors.White,
|
||||
seed,
|
||||
Color.Parse("#22000000"),
|
||||
Color.Parse("#33000000"),
|
||||
Color.Parse("#443B82F6"),
|
||||
seed,
|
||||
Color.Parse("#4464748B"),
|
||||
Color.Parse("#663B82F6"));
|
||||
var surface = new MaterialSurfaceSnapshot(
|
||||
MaterialSurfaceRole.SettingsWindowBackground,
|
||||
Color.Parse("#FFF8FAFC"),
|
||||
Color.Parse("#22000000"),
|
||||
0,
|
||||
1);
|
||||
var surfaces = new Dictionary<MaterialSurfaceRole, MaterialSurfaceSnapshot>
|
||||
{
|
||||
[MaterialSurfaceRole.SettingsWindowBackground] = surface,
|
||||
[MaterialSurfaceRole.DockBackground] = surface with { Role = MaterialSurfaceRole.DockBackground },
|
||||
[MaterialSurfaceRole.DesktopComponentHost] = surface with { Role = MaterialSurfaceRole.DesktopComponentHost },
|
||||
[MaterialSurfaceRole.OverlayPanel] = surface with { Role = MaterialSurfaceRole.OverlayPanel }
|
||||
};
|
||||
|
||||
return new MaterialColorSnapshot(
|
||||
IsNightMode: false,
|
||||
ThemeColorMode: ThemeAppearanceValues.ColorModeDefaultNeutral,
|
||||
ThemeWallpaperColorSource: ThemeAppearanceValues.WallpaperColorSourceAuto,
|
||||
ColorSourceKind: MaterialColorSourceKind.Neutral,
|
||||
ResolvedSeedSource: "neutral",
|
||||
CornerRadiusTokens: new AppearanceCornerRadiusTokens(
|
||||
new CornerRadius(2),
|
||||
new CornerRadius(4),
|
||||
new CornerRadius(6),
|
||||
new CornerRadius(8),
|
||||
new CornerRadius(10),
|
||||
new CornerRadius(12),
|
||||
new CornerRadius(14),
|
||||
new CornerRadius(8)),
|
||||
UserThemeColor: seed.ToString(),
|
||||
SelectedWallpaperSeed: null,
|
||||
EffectiveSeedColor: seed,
|
||||
AccentColor: seed,
|
||||
MonetPalette: new MonetPalette([seed], seed, seed, seed, seed, seed, seed),
|
||||
Palette: palette,
|
||||
WallpaperSeedCandidates: [seed],
|
||||
SystemMaterialMode: materialMode,
|
||||
AvailableSystemMaterialModes:
|
||||
[
|
||||
ThemeAppearanceValues.MaterialAuto,
|
||||
ThemeAppearanceValues.MaterialNone,
|
||||
ThemeAppearanceValues.MaterialMica,
|
||||
ThemeAppearanceValues.MaterialAcrylic
|
||||
],
|
||||
CanChangeSystemMaterial: true,
|
||||
UseSystemChrome: false,
|
||||
ResolvedWallpaperPath: null,
|
||||
UseNativeWallpaperChangeEvents: true,
|
||||
NativeWallpaperChangeEventsActive: false,
|
||||
WallpaperPollingActive: false,
|
||||
Surfaces: surfaces);
|
||||
}
|
||||
|
||||
private sealed class FakeSettingsFacade(ThemeAppearanceSettingsState themeState) : ISettingsFacadeService
|
||||
{
|
||||
private readonly FakeThemeAppearanceService _theme = new(themeState);
|
||||
private readonly FakeRegionSettingsService _region = new();
|
||||
private readonly FakeWallpaperSettingsService _wallpaper = new();
|
||||
|
||||
public ThemeAppearanceSettingsState ThemeState => _theme.State;
|
||||
public int ThemeSaveCount => _theme.SaveCount;
|
||||
|
||||
public ISettingsService Settings => throw new NotSupportedException();
|
||||
public ISettingsCatalog Catalog => throw new NotSupportedException();
|
||||
public IGridSettingsService Grid => throw new NotSupportedException();
|
||||
public IWallpaperSettingsService Wallpaper => _wallpaper;
|
||||
public IWallpaperMediaService WallpaperMedia => throw new NotSupportedException();
|
||||
public IThemeAppearanceService Theme => _theme;
|
||||
public IStatusBarSettingsService StatusBar => throw new NotSupportedException();
|
||||
public ITextCapsuleSettingsService TextCapsule => throw new NotSupportedException();
|
||||
public IWeatherSettingsService Weather => throw new NotSupportedException();
|
||||
public IRegionSettingsService Region => _region;
|
||||
public IPrivacySettingsService Privacy => throw new NotSupportedException();
|
||||
public IUpdateSettingsService Update => throw new NotSupportedException();
|
||||
public ILauncherCatalogService LauncherCatalog => throw new NotSupportedException();
|
||||
public ILauncherPolicyService LauncherPolicy => throw new NotSupportedException();
|
||||
public IPluginManagementSettingsService PluginManagement => throw new NotSupportedException();
|
||||
public IPluginCatalogSettingsService PluginCatalog => throw new NotSupportedException();
|
||||
public IApplicationInfoService ApplicationInfo => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
private sealed class FakeThemeAppearanceService(ThemeAppearanceSettingsState state) : IThemeAppearanceService
|
||||
{
|
||||
public ThemeAppearanceSettingsState State { get; private set; } = state;
|
||||
public int SaveCount { get; private set; }
|
||||
|
||||
public ThemeAppearanceSettingsState Get() => State;
|
||||
|
||||
public void Save(ThemeAppearanceSettingsState state)
|
||||
{
|
||||
SaveCount++;
|
||||
State = state;
|
||||
}
|
||||
|
||||
public MonetPalette BuildPalette(bool nightMode, string? wallpaperPath, string? preferredSeedColor = null)
|
||||
{
|
||||
var seed = Color.Parse(preferredSeedColor ?? "#FF3B82F6");
|
||||
return new MonetPalette([seed], seed, seed, seed, seed, seed, seed);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeRegionSettingsService : IRegionSettingsService
|
||||
{
|
||||
public RegionSettingsState Get() => new("en-US", null);
|
||||
|
||||
public void Save(RegionSettingsState state)
|
||||
{
|
||||
_ = state;
|
||||
}
|
||||
|
||||
public TimeZoneService GetTimeZoneService() => new();
|
||||
}
|
||||
|
||||
private sealed class FakeWallpaperSettingsService : IWallpaperSettingsService
|
||||
{
|
||||
public WallpaperSettingsState Get() => new(null, "SolidColor", "#FFFFFFFF", "Fill", 300);
|
||||
|
||||
public void Save(WallpaperSettingsState state)
|
||||
{
|
||||
_ = state;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeMaterialColorService(MaterialColorSnapshot snapshot) : IMaterialColorService
|
||||
{
|
||||
private MaterialColorSnapshot _snapshot = snapshot;
|
||||
|
||||
public event EventHandler<MaterialColorSnapshot>? MaterialColorChanged;
|
||||
|
||||
public MaterialColorSnapshot GetMaterialColorSnapshot() => _snapshot;
|
||||
|
||||
public MaterialColorSnapshot BuildMaterialColorPreview(ThemeAppearanceSettingsState pendingState)
|
||||
{
|
||||
_ = pendingState;
|
||||
return _snapshot;
|
||||
}
|
||||
|
||||
public void ApplyThemeResources(IResourceDictionary resources)
|
||||
{
|
||||
_ = resources;
|
||||
}
|
||||
|
||||
public MaterialSurfaceSnapshot GetSurface(MaterialSurfaceRole role)
|
||||
{
|
||||
return _snapshot.Surfaces[role];
|
||||
}
|
||||
|
||||
public void ApplyWindowMaterial(Window window, MaterialSurfaceRole role)
|
||||
{
|
||||
_ = window;
|
||||
_ = role;
|
||||
}
|
||||
|
||||
public void RefreshWallpaperColors()
|
||||
{
|
||||
}
|
||||
|
||||
public void RaiseChanged(MaterialColorSnapshot snapshot)
|
||||
{
|
||||
_snapshot = snapshot;
|
||||
MaterialColorChanged?.Invoke(this, snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,12 @@ public sealed class PackagingRuntimePolicyTests
|
||||
var script = ReadRepositoryFile("LanMountainDesktop", "scripts", "package.ps1");
|
||||
|
||||
Assert.Contains("Publish-LauncherPayload", script);
|
||||
Assert.Contains("Publish-AirAppRuntimePayload", script);
|
||||
Assert.Contains("\"app-$Version\"", script);
|
||||
Assert.Contains("Publish-MainAppFrameworkDependentPayload", script);
|
||||
Assert.Contains("\"--self-contained\", \"false\"", script);
|
||||
Assert.Contains("\"-p:SelfContained=false\"", script);
|
||||
Assert.Contains("\"-p:PublishAot=false\"", script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -28,12 +30,13 @@ public sealed class PackagingRuntimePolicyTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WindowsPayloadGuard_RequiresLauncherMainAndAirAppHost()
|
||||
public void WindowsPayloadGuard_RequiresLauncherRuntimeMainAndAirAppHost()
|
||||
{
|
||||
var script = ReadRepositoryFile("LanMountainDesktop", "scripts", "Optimize-PublishPayload.ps1");
|
||||
|
||||
Assert.Contains("Assert-WindowsPayloadContainsRequiredHosts", script);
|
||||
Assert.Contains("LanMountainDesktop.Launcher.exe", script);
|
||||
Assert.Contains("LanMountainDesktop.AirAppRuntime.exe", script);
|
||||
Assert.Contains("LanMountainDesktop.exe", script);
|
||||
Assert.Contains("LanMountainDesktop.AirAppHost.exe", script);
|
||||
}
|
||||
@@ -44,9 +47,21 @@ public sealed class PackagingRuntimePolicyTests
|
||||
var workflow = ReadRepositoryFile(".github", "workflows", "release.yml");
|
||||
|
||||
Assert.Contains("Verify Windows app host payload", workflow);
|
||||
Assert.Contains("LanMountainDesktop.AirAppRuntime.exe", workflow);
|
||||
Assert.Contains("LanMountainDesktop.AirAppHost.exe", workflow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AirAppRuntimeProject_IsFrameworkDependentJit()
|
||||
{
|
||||
var project = ReadRepositoryFile("LanMountainDesktop.AirAppRuntime", "LanMountainDesktop.AirAppRuntime.csproj");
|
||||
|
||||
Assert.Contains("<PublishAot>false</PublishAot>", project);
|
||||
Assert.Contains("<SelfContained>false</SelfContained>", project);
|
||||
Assert.Contains("<PublishTrimmed>false</PublishTrimmed>", project);
|
||||
Assert.Contains("<PublishReadyToRun>false</PublishReadyToRun>", project);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Installer_DownloadsArchitectureSpecificDesktopRuntime()
|
||||
{
|
||||
|
||||
@@ -134,13 +134,13 @@ public sealed class PendingPluginUpgradeServiceTests : IDisposable
|
||||
return packagePath;
|
||||
}
|
||||
|
||||
private static PluginManifest ReadManifestFromPackage(string packagePath)
|
||||
private static LanMountainDesktop.PluginSdk.PluginManifest ReadManifestFromPackage(string packagePath)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(packagePath);
|
||||
var entry = archive.GetEntry(PluginSdkInfo.ManifestFileName)
|
||||
?? throw new InvalidOperationException("Missing plugin manifest.");
|
||||
using var stream = entry.Open();
|
||||
return PluginManifest.Load(stream, $"{packagePath}!/{entry.FullName}");
|
||||
return LanMountainDesktop.PluginSdk.PluginManifest.Load(stream, $"{packagePath}!/{entry.FullName}");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using LanMountainDesktop.Launcher.Plugins;
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
@@ -34,10 +35,10 @@ public sealed class PluginInstallerServiceTests : IDisposable
|
||||
Directory.CreateDirectory(_tempRoot);
|
||||
CreatePluginPackage(packagePath, "plugin.json", "plugin.install.sample", "Sample Plugin");
|
||||
|
||||
var pluginsDirectory = CreateUserScopedPluginsDirectory();
|
||||
var pluginsDirectory = CreateConfiguredPortablePluginsDirectory(out var appRoot);
|
||||
var service = new PluginInstallerService();
|
||||
|
||||
var result = service.InstallPackage(packagePath, pluginsDirectory);
|
||||
var result = service.InstallPackage(packagePath, pluginsDirectory, appRoot);
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal("ok", result.Code);
|
||||
@@ -49,6 +50,42 @@ public sealed class PluginInstallerServiceTests : IDisposable
|
||||
Assert.Empty(Directory.EnumerateFiles(pluginsDirectory, "*.incoming", SearchOption.AllDirectories));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InstallPackage_AllowsConfiguredPortableDataRootOutsideUserScope()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_tempRoot);
|
||||
var appRoot = Path.Combine(_tempRoot, "PackageRoot");
|
||||
var portableDataRoot = Path.Combine(appRoot, "Desktop");
|
||||
var launcherDataRoot = Path.Combine(appRoot, ".Launcher");
|
||||
Directory.CreateDirectory(launcherDataRoot);
|
||||
File.WriteAllText(
|
||||
Path.Combine(launcherDataRoot, "data-location.config.json"),
|
||||
JsonSerializer.Serialize(new
|
||||
{
|
||||
DataLocationMode = "Portable",
|
||||
SystemDataPath = Path.Combine(_tempRoot, "System"),
|
||||
PortableDataPath = portableDataRoot
|
||||
}));
|
||||
|
||||
var packagePath = Path.Combine(_tempRoot, "portable.laapp");
|
||||
CreatePluginPackage(packagePath, "plugin.json", "plugin.portable.sample", "Portable Plugin");
|
||||
|
||||
var pluginsDirectory = Path.Combine(portableDataRoot, "Extensions", "Plugins");
|
||||
var service = new PluginInstallerService();
|
||||
|
||||
var result = service.InstallPackage(packagePath, pluginsDirectory, appRoot);
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal("ok", result.Code);
|
||||
Assert.True(File.Exists(result.InstalledPackagePath));
|
||||
Assert.StartsWith(Path.GetFullPath(portableDataRoot), Path.GetFullPath(result.InstalledPackagePath!), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InstallPackage_ReplacesExistingPackageWithSamePluginId()
|
||||
{
|
||||
@@ -58,11 +95,11 @@ public sealed class PluginInstallerServiceTests : IDisposable
|
||||
CreatePluginPackage(firstPackagePath, "plugin.json", "plugin.replace.sample", "Sample Plugin v1");
|
||||
CreatePluginPackage(secondPackagePath, "plugin.json", "plugin.replace.sample", "Sample Plugin v2");
|
||||
|
||||
var pluginsDirectory = CreateUserScopedPluginsDirectory();
|
||||
var pluginsDirectory = CreateConfiguredPortablePluginsDirectory(out var appRoot);
|
||||
var service = new PluginInstallerService();
|
||||
|
||||
var first = service.InstallPackage(firstPackagePath, pluginsDirectory);
|
||||
var second = service.InstallPackage(secondPackagePath, pluginsDirectory);
|
||||
var first = service.InstallPackage(firstPackagePath, pluginsDirectory, appRoot);
|
||||
var second = service.InstallPackage(secondPackagePath, pluginsDirectory, appRoot);
|
||||
|
||||
Assert.True(first.Success);
|
||||
Assert.True(second.Success);
|
||||
@@ -77,10 +114,10 @@ public sealed class PluginInstallerServiceTests : IDisposable
|
||||
Directory.CreateDirectory(_tempRoot);
|
||||
CreatePluginPackage(packagePath, "manifest.json", "plugin.legacy.sample", "Legacy Plugin");
|
||||
|
||||
var pluginsDirectory = CreateUserScopedPluginsDirectory();
|
||||
var pluginsDirectory = CreateConfiguredPortablePluginsDirectory(out var appRoot);
|
||||
var service = new PluginInstallerService();
|
||||
|
||||
var result = service.InstallPackage(packagePath, pluginsDirectory);
|
||||
var result = service.InstallPackage(packagePath, pluginsDirectory, appRoot);
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal("plugin.legacy.sample", result.ManifestId);
|
||||
@@ -103,18 +140,24 @@ public sealed class PluginInstallerServiceTests : IDisposable
|
||||
""");
|
||||
}
|
||||
|
||||
private static string CreateUserScopedPluginsDirectory()
|
||||
private string CreateConfiguredPortablePluginsDirectory(out string appRoot)
|
||||
{
|
||||
var root = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LanMountainDesktop",
|
||||
"Tests",
|
||||
nameof(PluginInstallerServiceTests),
|
||||
Guid.NewGuid().ToString("N"),
|
||||
"Extensions",
|
||||
"Plugins");
|
||||
Directory.CreateDirectory(root);
|
||||
return root;
|
||||
appRoot = Path.Combine(_tempRoot, "ConfiguredPackageRoot", Guid.NewGuid().ToString("N"));
|
||||
var portableDataRoot = Path.Combine(appRoot, "Desktop");
|
||||
var launcherDataRoot = Path.Combine(appRoot, ".Launcher");
|
||||
Directory.CreateDirectory(launcherDataRoot);
|
||||
File.WriteAllText(
|
||||
Path.Combine(launcherDataRoot, "data-location.config.json"),
|
||||
JsonSerializer.Serialize(new
|
||||
{
|
||||
DataLocationMode = "Portable",
|
||||
SystemDataPath = Path.Combine(_tempRoot, "System"),
|
||||
PortableDataPath = portableDataRoot
|
||||
}));
|
||||
|
||||
var pluginsDirectory = Path.Combine(portableDataRoot, "Extensions", "Plugins");
|
||||
Directory.CreateDirectory(pluginsDirectory);
|
||||
return pluginsDirectory;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
||||
40
LanMountainDesktop.Tests/PluginRuntimeDataPathTests.cs
Normal file
40
LanMountainDesktop.Tests/PluginRuntimeDataPathTests.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using LanMountainDesktop.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class PluginRuntimeDataPathTests : IDisposable
|
||||
{
|
||||
private readonly string _dataRoot = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
"LanMountainDesktop.Tests",
|
||||
nameof(PluginRuntimeDataPathTests),
|
||||
Guid.NewGuid().ToString("N"));
|
||||
|
||||
[Fact]
|
||||
public void PluginRuntime_UsesHostDataRootForPluginsAndMarketData()
|
||||
{
|
||||
AppDataPathProvider.Initialize(["--data-root", _dataRoot]);
|
||||
|
||||
using var runtime = new PluginRuntimeService();
|
||||
|
||||
Assert.Equal(
|
||||
Path.Combine(Path.GetFullPath(_dataRoot), "Extensions", "Plugins"),
|
||||
runtime.PluginsDirectory);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
AppDataPathProvider.ResetForTests();
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_dataRoot))
|
||||
{
|
||||
Directory.Delete(_dataRoot, recursive: true);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
93
LanMountainDesktop.Tests/SettingsWindowShellVisualTests.cs
Normal file
93
LanMountainDesktop.Tests/SettingsWindowShellVisualTests.cs
Normal file
@@ -0,0 +1,93 @@
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class SettingsWindowShellVisualTests
|
||||
{
|
||||
[Fact]
|
||||
public void SettingsWindow_UsesOneFullWindowBackgroundBehindTitlebarAndContent()
|
||||
{
|
||||
var xaml = ReadRepositoryFile("LanMountainDesktop", "Views", "SettingsWindow.axaml");
|
||||
|
||||
Assert.Contains("x:Name=\"RootGrid\"", xaml);
|
||||
Assert.Contains("Background=\"Transparent\"", ExtractElementStart(xaml, "<Grid x:Name=\"RootGrid\""));
|
||||
Assert.Contains("Grid.RowSpan=\"2\"", xaml);
|
||||
Assert.Contains("Background=\"{DynamicResource AdaptiveSettingsWindowBackgroundBrush}\"", xaml);
|
||||
Assert.Contains("Background=\"{DynamicResource AdaptiveSettingsWindowTintBrush}\"", xaml);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SettingsWindow_TitlebarDoesNotPaintASeparateSurfaceBand()
|
||||
{
|
||||
var xaml = ReadRepositoryFile("LanMountainDesktop", "Views", "SettingsWindow.axaml");
|
||||
var titlebar = ExtractElementStart(xaml, "<Border x:Name=\"WindowTitleBarHost\"");
|
||||
|
||||
Assert.Contains("Background=\"Transparent\"", titlebar);
|
||||
Assert.Contains("BorderBrush=\"Transparent\"", titlebar);
|
||||
Assert.Contains("BorderThickness=\"0\"", titlebar);
|
||||
Assert.DoesNotContain("BorderThickness=\"0,0,0,1\"", titlebar);
|
||||
Assert.DoesNotContain("AdaptiveSettingsWindowBackgroundBrush", titlebar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SettingsWindow_NavigationShellBackgroundsAreTransparent()
|
||||
{
|
||||
var xaml = ReadRepositoryFile("LanMountainDesktop", "Views", "SettingsWindow.axaml");
|
||||
|
||||
Assert.Contains("Classes=\"settings-navigation-view\"", xaml);
|
||||
Assert.Contains("<SolidColorBrush x:Key=\"NavigationViewContentBackground\" Color=\"Transparent\" />", xaml);
|
||||
Assert.Contains("<SolidColorBrush x:Key=\"NavigationViewContentGridBorderBrush\" Color=\"Transparent\" />", xaml);
|
||||
Assert.Contains("<SolidColorBrush x:Key=\"NavigationViewDefaultPaneBackground\" Color=\"Transparent\" />", xaml);
|
||||
Assert.Contains("<SolidColorBrush x:Key=\"NavigationViewExpandedPaneBackground\" Color=\"Transparent\" />", xaml);
|
||||
Assert.Contains("<SolidColorBrush x:Key=\"NavigationViewTopPaneBackground\" Color=\"Transparent\" />", xaml);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NavigationStyles_KeepSettingsNavigationTemplateTransparent()
|
||||
{
|
||||
var styles = ReadRepositoryFile("LanMountainDesktop", "Styles", "NavigationStyles.axaml");
|
||||
|
||||
Assert.Contains("ui|FANavigationView.settings-navigation-view", styles);
|
||||
Assert.Contains("Grid#RootGrid", styles);
|
||||
Assert.Contains("Grid#ContentGrid", styles);
|
||||
Assert.Contains("Grid#PaneRoot", styles);
|
||||
Assert.Contains("Border#NavigationViewBorder", styles);
|
||||
Assert.Contains("Border#ContentGridBorder", styles);
|
||||
Assert.Contains("Border#PaneBorder", styles);
|
||||
Assert.Contains("<Setter Property=\"Background\" Value=\"Transparent\" />", styles);
|
||||
Assert.Contains("<Setter Property=\"BorderBrush\" Value=\"Transparent\" />", styles);
|
||||
}
|
||||
|
||||
private static string ExtractElementStart(string source, string startToken)
|
||||
{
|
||||
var start = source.IndexOf(startToken, StringComparison.Ordinal);
|
||||
Assert.True(start >= 0, $"Could not find '{startToken}'.");
|
||||
|
||||
var end = source.IndexOf('>', start);
|
||||
Assert.True(end > start, $"Could not find end of '{startToken}'.");
|
||||
|
||||
return source.Substring(start, end - start + 1);
|
||||
}
|
||||
|
||||
private static string ReadRepositoryFile(params string[] segments)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(new[] { directory.FullName }.Concat(segments).ToArray());
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return File.ReadAllText(candidate);
|
||||
}
|
||||
|
||||
if (File.Exists(Path.Combine(directory.FullName, "LanMountainDesktop.slnx")))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{Path.Combine(segments)}'.");
|
||||
}
|
||||
}
|
||||
103
LanMountainDesktop.Tests/SystemChromeModeTests.cs
Normal file
103
LanMountainDesktop.Tests/SystemChromeModeTests.cs
Normal file
@@ -0,0 +1,103 @@
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class SystemChromeModeTests
|
||||
{
|
||||
[Fact]
|
||||
public void SettingsWindow_SystemChromeUsesNativeDecorations()
|
||||
{
|
||||
var source = ReadRepositoryFile("LanMountainDesktop", "Views", "SettingsWindow.axaml.cs");
|
||||
var applyChromeMode = ExtractMethodSource(source, "ApplyChromeMode");
|
||||
var onLoaded = ExtractMethodSource(source, "OnLoaded");
|
||||
|
||||
Assert.Contains("_useSystemChrome = useSystemChrome || OperatingSystem.IsMacOS();", applyChromeMode);
|
||||
Assert.Contains("WindowDecorations = WindowDecorations.Full;", applyChromeMode);
|
||||
Assert.Contains("ExtendClientAreaToDecorationsHint = !_useSystemChrome;", applyChromeMode);
|
||||
Assert.Contains("ExtendClientAreaTitleBarHeightHint = _useSystemChrome ? 0d : CustomTitleBarHeight;", applyChromeMode);
|
||||
Assert.Contains("TitleBar.ExtendsContentIntoTitleBar = !_useSystemChrome;", applyChromeMode);
|
||||
Assert.Contains("WindowTitleBarHost.IsVisible = false;", applyChromeMode);
|
||||
Assert.Contains("WindowTitleBarHost.IsVisible = true;", applyChromeMode);
|
||||
Assert.DoesNotContain("TitleBar.ExtendsContentIntoTitleBar = true;", onLoaded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComponentEditorWindow_SystemChromeUsesNativeDecorations()
|
||||
{
|
||||
var source = ReadRepositoryFile("LanMountainDesktop", "Views", "ComponentEditorWindow.axaml.cs");
|
||||
var applyChromeMode = ExtractMethodSource(source, "ApplyChromeMode");
|
||||
|
||||
Assert.Contains("var preferSystemChrome = useSystemChrome || OperatingSystem.IsMacOS();", applyChromeMode);
|
||||
Assert.Contains("WindowDecorations = WindowDecorations.Full;", applyChromeMode);
|
||||
Assert.Contains("ExtendClientAreaToDecorationsHint = false;", applyChromeMode);
|
||||
Assert.Contains("ExtendClientAreaTitleBarHeightHint = 0d;", applyChromeMode);
|
||||
Assert.Contains("CustomTitleBarHost.IsVisible = false;", applyChromeMode);
|
||||
Assert.Contains("WindowDecorations = WindowDecorations.BorderOnly;", applyChromeMode);
|
||||
Assert.Contains("ExtendClientAreaToDecorationsHint = true;", applyChromeMode);
|
||||
Assert.Contains("CustomTitleBarHost.IsVisible = true;", applyChromeMode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SavingSystemChromeSynchronizesWindowsPatcherState()
|
||||
{
|
||||
var source = ReadRepositoryFile("LanMountainDesktop", "Services", "Settings", "SettingsDomainServices.cs");
|
||||
|
||||
Assert.Contains("if (OperatingSystem.IsWindows())", source);
|
||||
Assert.Contains("LanMountainDesktop.Platform.Windows.ChromePatchState.UseSystemChrome = state.UseSystemChrome;", source);
|
||||
}
|
||||
|
||||
private static string ReadRepositoryFile(params string[] segments)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(new[] { directory.FullName }.Concat(segments).ToArray());
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return File.ReadAllText(candidate);
|
||||
}
|
||||
|
||||
if (File.Exists(Path.Combine(directory.FullName, "LanMountainDesktop.slnx")))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{Path.Combine(segments)}'.");
|
||||
}
|
||||
|
||||
private static string ExtractMethodSource(string source, string methodName)
|
||||
{
|
||||
var methodIndex = source.IndexOf($"private void {methodName}(", StringComparison.Ordinal);
|
||||
if (methodIndex < 0)
|
||||
{
|
||||
methodIndex = source.IndexOf($"public void {methodName}(", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
Assert.True(methodIndex >= 0, $"Could not locate method '{methodName}'.");
|
||||
|
||||
var braceIndex = source.IndexOf('{', methodIndex);
|
||||
Assert.True(braceIndex >= 0, $"Could not locate method body for '{methodName}'.");
|
||||
|
||||
var depth = 0;
|
||||
for (var i = braceIndex; i < source.Length; i++)
|
||||
{
|
||||
if (source[i] == '{')
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (source[i] == '}')
|
||||
{
|
||||
depth--;
|
||||
if (depth == 0)
|
||||
{
|
||||
return source.Substring(methodIndex, i - methodIndex + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"Could not extract method '{methodName}'.");
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop.Launcher;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class PendingUpdateDetectorTests : IDisposable
|
||||
{
|
||||
private readonly TempLauncherRoot _root = new();
|
||||
|
||||
[Fact]
|
||||
public void ValidateIncomingState_WhenNoPayloadButDeploymentLockExists_ReturnsNoop()
|
||||
{
|
||||
_root.WriteDeploymentLock();
|
||||
var detector = new PendingUpdateDetector(
|
||||
new DeploymentLocator(_root.AppRoot),
|
||||
_root.Paths,
|
||||
new UpdateSignatureVerifier(_root.Paths));
|
||||
|
||||
var result = detector.ValidateIncomingState();
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal("noop", result.Code);
|
||||
}
|
||||
|
||||
public void Dispose() => _root.Dispose();
|
||||
}
|
||||
|
||||
public sealed class UpdateSignatureVerifierTests : IDisposable
|
||||
{
|
||||
private readonly TempLauncherRoot _root = new();
|
||||
|
||||
[Fact]
|
||||
public void Verify_WhenSignatureIsMissing_ReturnsStructuredFailure()
|
||||
{
|
||||
var payload = Path.Combine(_root.Paths.IncomingRoot, "files.json");
|
||||
Directory.CreateDirectory(_root.Paths.IncomingRoot);
|
||||
File.WriteAllText(payload, "{}");
|
||||
|
||||
var result = new UpdateSignatureVerifier(_root.Paths)
|
||||
.Verify(payload, Path.Combine(_root.Paths.IncomingRoot, "files.json.sig"), "files.json.sig");
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("Missing files.json.sig.", result.Message);
|
||||
}
|
||||
|
||||
public void Dispose() => _root.Dispose();
|
||||
}
|
||||
|
||||
public sealed class IncomingArtifactsCleanerTests : IDisposable
|
||||
{
|
||||
private readonly TempLauncherRoot _root = new();
|
||||
|
||||
[Fact]
|
||||
public void Cleanup_RemovesLegacyPlondsAndCheckpointArtifacts()
|
||||
{
|
||||
Directory.CreateDirectory(_root.Paths.PlondsObjectsRoot);
|
||||
foreach (var path in new[]
|
||||
{
|
||||
_root.Paths.FileMapPath,
|
||||
_root.Paths.SignaturePath,
|
||||
_root.Paths.ArchivePath,
|
||||
_root.Paths.PlondsFileMapPath,
|
||||
_root.Paths.PlondsSignaturePath,
|
||||
_root.Paths.PlondsUpdateMetadataPath,
|
||||
_root.Paths.InstallCheckpointPath,
|
||||
Path.Combine(_root.Paths.PlondsObjectsRoot, "payload")
|
||||
})
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, "x");
|
||||
}
|
||||
|
||||
new IncomingArtifactsCleaner(_root.Paths).Cleanup();
|
||||
|
||||
Assert.False(File.Exists(_root.Paths.FileMapPath));
|
||||
Assert.False(File.Exists(_root.Paths.InstallCheckpointPath));
|
||||
Assert.False(Directory.Exists(_root.Paths.PlondsObjectsRoot));
|
||||
}
|
||||
|
||||
public void Dispose() => _root.Dispose();
|
||||
}
|
||||
|
||||
public sealed class DeploymentActivatorTests : IDisposable
|
||||
{
|
||||
private readonly TempLauncherRoot _root = new();
|
||||
|
||||
[Fact]
|
||||
public void Activate_MovesCurrentMarkerAndMarksPreviousDestroy()
|
||||
{
|
||||
var from = Path.Combine(_root.AppRoot, "app-1");
|
||||
var to = Path.Combine(_root.AppRoot, "app-2");
|
||||
Directory.CreateDirectory(from);
|
||||
Directory.CreateDirectory(to);
|
||||
File.WriteAllText(Path.Combine(from, ".current"), string.Empty);
|
||||
File.WriteAllText(Path.Combine(to, ".partial"), string.Empty);
|
||||
|
||||
new DeploymentActivator(new DeploymentLocator(_root.AppRoot)).Activate(from, to);
|
||||
|
||||
Assert.False(File.Exists(Path.Combine(from, ".current")));
|
||||
Assert.True(File.Exists(Path.Combine(from, ".destroy")));
|
||||
Assert.True(File.Exists(Path.Combine(to, ".current")));
|
||||
Assert.False(File.Exists(Path.Combine(to, ".partial")));
|
||||
}
|
||||
|
||||
public void Dispose() => _root.Dispose();
|
||||
}
|
||||
|
||||
public sealed class RollbackStrategyTests : IDisposable
|
||||
{
|
||||
private readonly TempLauncherRoot _root = new();
|
||||
|
||||
[Fact]
|
||||
public void RollbackLatest_WhenNoSnapshotsExist_ReturnsNoSnapshot()
|
||||
{
|
||||
var snapshotStore = new UpdateSnapshotStore(_root.Paths);
|
||||
var activator = new DeploymentActivator(new DeploymentLocator(_root.AppRoot));
|
||||
|
||||
var result = new RollbackStrategy(new DeploymentLocator(_root.AppRoot), snapshotStore, activator)
|
||||
.RollbackLatest();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("no_snapshot", result.Code);
|
||||
}
|
||||
|
||||
public void Dispose() => _root.Dispose();
|
||||
}
|
||||
|
||||
public sealed class PlondsUpdateApplierTests
|
||||
{
|
||||
[Fact]
|
||||
public void ManifestParser_ReadsObjectComponentFiles()
|
||||
{
|
||||
var map = new PlondsFileMap();
|
||||
var entries = PlondsManifestParser.CollectFileEntries(map);
|
||||
|
||||
PlondsManifestParser.PopulateFromRawJson(
|
||||
"""
|
||||
{
|
||||
"toVersion": "2.0.0",
|
||||
"components": {
|
||||
"desktop": {
|
||||
"files": {
|
||||
"LanMountainDesktop.exe": {
|
||||
"archiveSha512": "abcd",
|
||||
"archivePath": "objects/ab/cd"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""",
|
||||
map,
|
||||
entries);
|
||||
|
||||
Assert.Equal("2.0.0", PlondsManifestParser.ResolveTargetVersion(map, null));
|
||||
var entry = Assert.Single(entries);
|
||||
Assert.Equal("LanMountainDesktop.exe", entry.Path);
|
||||
Assert.Equal("desktop", entry.Metadata["component"]);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class LegacyUpdateApplierTests : IDisposable
|
||||
{
|
||||
private readonly TempLauncherRoot _root = new();
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyAsync_WhenSignatureIsMissing_ReturnsSignatureFailure()
|
||||
{
|
||||
_root.WriteDeploymentLock();
|
||||
Directory.CreateDirectory(_root.Paths.IncomingRoot);
|
||||
File.WriteAllText(_root.Paths.FileMapPath, JsonSerializer.Serialize(new SignedFileMap
|
||||
{
|
||||
FromVersion = "1.0.0",
|
||||
ToVersion = "2.0.0",
|
||||
Files = [new UpdateFileEntry { Path = "state.txt" }]
|
||||
}, AppJsonContext.Default.SignedFileMap));
|
||||
using (var archive = ZipFile.Open(_root.Paths.ArchivePath, ZipArchiveMode.Create))
|
||||
{
|
||||
var entry = archive.CreateEntry("state.txt");
|
||||
await using var stream = entry.Open();
|
||||
await stream.WriteAsync(Encoding.UTF8.GetBytes("state"));
|
||||
}
|
||||
|
||||
var applier = CreateLegacyApplier();
|
||||
var result = await applier.ApplyAsync();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("signature_failed", result.Code);
|
||||
}
|
||||
|
||||
public void Dispose() => _root.Dispose();
|
||||
|
||||
private LegacyUpdateApplier CreateLegacyApplier()
|
||||
{
|
||||
var locator = new DeploymentLocator(_root.AppRoot);
|
||||
var snapshotStore = new UpdateSnapshotStore(_root.Paths);
|
||||
var checkpointStore = new InstallCheckpointStore(_root.Paths);
|
||||
var activator = new DeploymentActivator(locator);
|
||||
var cleaner = new IncomingArtifactsCleaner(_root.Paths);
|
||||
return new LegacyUpdateApplier(
|
||||
locator,
|
||||
_root.Paths,
|
||||
new UpdateSignatureVerifier(_root.Paths),
|
||||
new NullUpdateProgressReporter(),
|
||||
snapshotStore,
|
||||
checkpointStore,
|
||||
activator,
|
||||
cleaner);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TempLauncherRoot : IDisposable
|
||||
{
|
||||
public TempLauncherRoot()
|
||||
{
|
||||
AppRoot = Path.Combine(Path.GetTempPath(), "lmd-launcher-tests", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(AppRoot);
|
||||
Paths = new UpdateEnginePaths(AppRoot);
|
||||
Directory.CreateDirectory(Paths.IncomingRoot);
|
||||
}
|
||||
|
||||
public string AppRoot { get; }
|
||||
|
||||
public UpdateEnginePaths Paths { get; }
|
||||
|
||||
public void WriteDeploymentLock()
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Paths.DeploymentLockPath)!);
|
||||
File.WriteAllText(Paths.DeploymentLockPath, string.Empty);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(AppRoot))
|
||||
{
|
||||
Directory.Delete(AppRoot, true);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,612 +0,0 @@
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using LanMountainDesktop;
|
||||
using LanMountainDesktop.Launcher;
|
||||
using LanMountainDesktop.Launcher.Models;
|
||||
using LanMountainDesktop.Services;
|
||||
using LanMountainDesktop.Services.Update;
|
||||
using LanMountainDesktop.Shared.Contracts.Update;
|
||||
using Xunit;
|
||||
|
||||
namespace LanMountainDesktop.Tests;
|
||||
|
||||
public sealed class UpdateEngineRollbackRegressionTests : IDisposable
|
||||
{
|
||||
private readonly UpdateTestDirectory _directory = new();
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyPlondsUpdate_KeepsPreviousDeploymentForManualRollback()
|
||||
{
|
||||
var current = _directory.CreateDeployment("1.0.0", "old-state", isCurrent: true);
|
||||
var newState = Encoding.UTF8.GetBytes("new-state");
|
||||
|
||||
_directory.StagePlondsUpdate("1.0.0", "1.1.0", newState, Sha256Hex(newState));
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = await service.ApplyPendingUpdateAsync();
|
||||
|
||||
Assert.True(result.Success, result.ErrorMessage);
|
||||
Assert.True(Directory.Exists(current));
|
||||
Assert.False(File.Exists(Path.Combine(current, ".current")));
|
||||
|
||||
var rollback = service.RollbackLatest();
|
||||
|
||||
Assert.True(rollback.Success, rollback.ErrorMessage);
|
||||
Assert.Equal("1.0.0", rollback.RolledBackTo);
|
||||
Assert.True(File.Exists(Path.Combine(current, ".current")));
|
||||
Assert.False(File.Exists(Path.Combine(current, ".destroy")));
|
||||
Assert.Equal("old-state", File.ReadAllText(Path.Combine(current, "state.txt")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyPlondsUpdate_WhenObjectHashMismatches_RollsBackToPreviousDeployment()
|
||||
{
|
||||
var current = _directory.CreateDeployment("1.0.0", "old-state", isCurrent: true);
|
||||
var newState = Encoding.UTF8.GetBytes("new-state");
|
||||
|
||||
_directory.StagePlondsUpdate("1.0.0", "1.1.0", newState, new string('0', 64));
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = await service.ApplyPendingUpdateAsync();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("apply_failed", result.Code);
|
||||
Assert.Equal("1.0.0", result.RolledBackTo);
|
||||
Assert.True(File.Exists(Path.Combine(current, ".current")));
|
||||
Assert.False(File.Exists(Path.Combine(current, ".destroy")));
|
||||
Assert.Equal("old-state", File.ReadAllText(Path.Combine(current, "state.txt")));
|
||||
Assert.Empty(Directory.GetDirectories(_directory.AppRoot, "app-1.1.0-*"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RollbackLatest_WhenSnapshotSourceDirectoryIsMissing_ReturnsStructuredFailure()
|
||||
{
|
||||
_directory.CreateDeployment("1.1.0", "new-state", isCurrent: true);
|
||||
_directory.WriteSnapshot(
|
||||
sourceVersion: "1.0.0",
|
||||
sourceDirectory: Path.Combine(_directory.AppRoot, "app-1.0.0-0"),
|
||||
targetVersion: "1.1.0",
|
||||
targetDirectory: Path.Combine(_directory.AppRoot, "app-1.1.0-0"));
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = service.RollbackLatest();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("source_missing", result.Code);
|
||||
Assert.Contains("app-1.0.0-0", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyPlondsUpdate_WhenInstallCheckpointIsStale_ReturnsStructuredFailure()
|
||||
{
|
||||
_directory.CreateDeployment("1.0.0", "old-state", isCurrent: true);
|
||||
var newState = Encoding.UTF8.GetBytes("new-state");
|
||||
_directory.StagePlondsUpdate("1.0.0", "1.1.0", newState, Sha256Hex(newState));
|
||||
_directory.WriteStaleInstallCheckpoint("9.9.9", "1.1.0");
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = await service.ApplyPendingUpdateAsync();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("resume_state_invalid", result.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyLegacyUpdate_WhenInstallCheckpointIsStale_ReturnsStructuredFailure()
|
||||
{
|
||||
_directory.CreateDeployment("1.0.0", "old-state", isCurrent: true);
|
||||
_directory.StageLegacyUpdate("1.0.0", "1.1.0", "new-state");
|
||||
_directory.WriteStaleInstallCheckpoint("9.9.9", "1.1.0");
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = await service.ApplyPendingUpdateAsync();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("resume_state_invalid", result.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyPlondsUpdate_WhenCheckpointIsValid_ResumesAndSucceeds()
|
||||
{
|
||||
var current = _directory.CreateDeployment("1.0.0", "old-state", isCurrent: true);
|
||||
var newState = Encoding.UTF8.GetBytes("new-state");
|
||||
_directory.StagePlondsUpdate("1.0.0", "1.1.0", newState, Sha256Hex(newState));
|
||||
_directory.WriteValidPlondsResumeCheckpoint("1.0.0", "1.1.0");
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = await service.ApplyPendingUpdateAsync();
|
||||
|
||||
Assert.True(result.Success, result.ErrorMessage);
|
||||
Assert.Equal("1.1.0", result.TargetVersion);
|
||||
Assert.False(File.Exists(Path.Combine(current, ".current")));
|
||||
var resumedTarget = Path.Combine(_directory.AppRoot, "app-1.1.0-0");
|
||||
Assert.True(File.Exists(Path.Combine(resumedTarget, ".current")));
|
||||
Assert.Equal("new-state", File.ReadAllText(Path.Combine(resumedTarget, "state.txt")));
|
||||
Assert.False(File.Exists(UpdatePaths.GetInstallCheckpointPath(_directory.AppRoot)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyLegacyUpdate_WhenCheckpointIsValid_ResumesAndSucceeds()
|
||||
{
|
||||
var current = _directory.CreateDeployment("1.0.0", "old-state", isCurrent: true);
|
||||
_directory.StageLegacyUpdate("1.0.0", "1.1.0", "new-state");
|
||||
_directory.WriteValidLegacyResumeCheckpoint("1.0.0", "1.1.0");
|
||||
|
||||
var service = new UpdateEngineFacade(new DeploymentLocator(_directory.AppRoot));
|
||||
var result = await service.ApplyPendingUpdateAsync();
|
||||
|
||||
Assert.True(result.Success, result.ErrorMessage);
|
||||
Assert.Equal("1.1.0", result.TargetVersion);
|
||||
Assert.False(File.Exists(Path.Combine(current, ".current")));
|
||||
var resumedTarget = Path.Combine(_directory.AppRoot, "app-1.1.0-0");
|
||||
Assert.True(File.Exists(Path.Combine(resumedTarget, ".current")));
|
||||
Assert.Equal("new-state", File.ReadAllText(Path.Combine(resumedTarget, "state.txt")));
|
||||
Assert.False(File.Exists(UpdatePaths.GetInstallCheckpointPath(_directory.AppRoot)));
|
||||
}
|
||||
|
||||
public void Dispose() => _directory.Dispose();
|
||||
|
||||
private static string Sha256Hex(byte[] bytes)
|
||||
{
|
||||
return Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private sealed class UpdateTestDirectory : IDisposable
|
||||
{
|
||||
private readonly string _root;
|
||||
private readonly RSA _rsa = RSA.Create(2048);
|
||||
|
||||
public UpdateTestDirectory()
|
||||
{
|
||||
_root = Path.Combine(Path.GetTempPath(), "LanMountainDesktop.UpdateRegression", Guid.NewGuid().ToString("N"));
|
||||
AppRoot = Path.Combine(_root, "app-root");
|
||||
Directory.CreateDirectory(AppRoot);
|
||||
|
||||
var resolver = new DataLocationResolver(AppRoot);
|
||||
LauncherRoot = resolver.ResolveLauncherDataPath();
|
||||
IncomingRoot = Path.Combine(LauncherRoot, "update", "incoming");
|
||||
SnapshotsRoot = Path.Combine(LauncherRoot, "snapshots");
|
||||
|
||||
Directory.CreateDirectory(Path.Combine(LauncherRoot, "update"));
|
||||
File.WriteAllText(Path.Combine(LauncherRoot, "update", "public-key.pem"), _rsa.ExportSubjectPublicKeyInfoPem());
|
||||
}
|
||||
|
||||
public string AppRoot { get; }
|
||||
|
||||
private string LauncherRoot { get; }
|
||||
|
||||
private string IncomingRoot { get; }
|
||||
|
||||
private string SnapshotsRoot { get; }
|
||||
|
||||
public string CreateDeployment(string version, string state, bool isCurrent)
|
||||
{
|
||||
var deployment = Path.Combine(AppRoot, $"app-{version}-0");
|
||||
Directory.CreateDirectory(deployment);
|
||||
File.WriteAllText(Path.Combine(deployment, ExecutableName), $"exe-{version}");
|
||||
File.WriteAllText(Path.Combine(deployment, "state.txt"), state);
|
||||
|
||||
if (isCurrent)
|
||||
{
|
||||
File.WriteAllText(Path.Combine(deployment, ".current"), string.Empty);
|
||||
}
|
||||
|
||||
return deployment;
|
||||
}
|
||||
|
||||
public void StagePlondsUpdate(string fromVersion, string toVersion, byte[] statePayload, string expectedStateSha256)
|
||||
{
|
||||
Directory.CreateDirectory(IncomingRoot);
|
||||
var objectsRoot = Path.Combine(IncomingRoot, "objects");
|
||||
Directory.CreateDirectory(objectsRoot);
|
||||
|
||||
var objectHash = Convert.ToHexString(SHA256.HashData(statePayload)).ToLowerInvariant();
|
||||
File.WriteAllBytes(Path.Combine(objectsRoot, objectHash), statePayload);
|
||||
|
||||
var currentExecutable = Path.Combine(AppRoot, $"app-{fromVersion}-0", ExecutableName);
|
||||
var fileMap = new PlondsFileMap
|
||||
{
|
||||
DistributionId = $"stable-{PlondsStaticUpdateService.ResolveCurrentPlatform()}-{toVersion}",
|
||||
FromVersion = fromVersion,
|
||||
ToVersion = toVersion,
|
||||
Platform = PlondsStaticUpdateService.ResolveCurrentPlatform(),
|
||||
Files =
|
||||
[
|
||||
new PlondsFileEntry
|
||||
{
|
||||
Path = ExecutableName,
|
||||
Action = "reuse",
|
||||
Sha256 = Sha256File(currentExecutable)
|
||||
},
|
||||
new PlondsFileEntry
|
||||
{
|
||||
Path = "state.txt",
|
||||
Action = "replace",
|
||||
Sha256 = expectedStateSha256,
|
||||
ObjectUrl = $"https://static.example/lanmountain/update/repo/sha256/{objectHash[..2]}/{objectHash}"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var fileMapPath = Path.Combine(IncomingRoot, "plonds-filemap.json");
|
||||
File.WriteAllText(fileMapPath, JsonSerializer.Serialize(fileMap, AppJsonContext.Default.PlondsFileMap));
|
||||
Sign(fileMapPath, Path.Combine(IncomingRoot, "plonds-filemap.sig"));
|
||||
|
||||
var deploymentLock = new DeploymentLock(
|
||||
SchemaVersion: 1,
|
||||
Kind: "delta",
|
||||
TargetVersion: toVersion,
|
||||
PayloadPath: fileMapPath,
|
||||
PayloadSha256: Sha256File(fileMapPath),
|
||||
CreatedAtUtc: DateTimeOffset.UtcNow);
|
||||
var deploymentLockPath = UpdatePaths.GetDeploymentLockPath(AppRoot);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(deploymentLockPath)!);
|
||||
File.WriteAllText(deploymentLockPath, JsonSerializer.Serialize(deploymentLock));
|
||||
|
||||
var markerPath = UpdatePaths.GetDownloadMarkerPath(AppRoot);
|
||||
File.WriteAllText(markerPath, UpdatePaths.GetDownloadMarkerContent(
|
||||
manifestSha256: Sha256File(fileMapPath),
|
||||
targetVersion: toVersion,
|
||||
objectCount: 1));
|
||||
}
|
||||
|
||||
public void StageLegacyUpdate(string fromVersion, string toVersion, string newState)
|
||||
{
|
||||
Directory.CreateDirectory(IncomingRoot);
|
||||
var extractRoot = Path.Combine(IncomingRoot, "legacy-src");
|
||||
Directory.CreateDirectory(extractRoot);
|
||||
|
||||
File.WriteAllText(Path.Combine(extractRoot, ExecutableName), $"exe-{toVersion}");
|
||||
File.WriteAllText(Path.Combine(extractRoot, "state.txt"), newState);
|
||||
|
||||
var archivePath = Path.Combine(IncomingRoot, "update.zip");
|
||||
if (File.Exists(archivePath))
|
||||
{
|
||||
File.Delete(archivePath);
|
||||
}
|
||||
|
||||
System.IO.Compression.ZipFile.CreateFromDirectory(extractRoot, archivePath);
|
||||
|
||||
var fileMap = new SignedFileMap
|
||||
{
|
||||
FromVersion = fromVersion,
|
||||
ToVersion = toVersion,
|
||||
Files =
|
||||
[
|
||||
new LanMountainDesktop.Launcher.Models.UpdateFileEntry
|
||||
{
|
||||
Path = ExecutableName,
|
||||
ArchivePath = ExecutableName,
|
||||
Action = "replace",
|
||||
Sha256 = Sha256File(Path.Combine(extractRoot, ExecutableName))
|
||||
},
|
||||
new LanMountainDesktop.Launcher.Models.UpdateFileEntry
|
||||
{
|
||||
Path = "state.txt",
|
||||
ArchivePath = "state.txt",
|
||||
Action = "replace",
|
||||
Sha256 = Sha256File(Path.Combine(extractRoot, "state.txt"))
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var fileMapPath = Path.Combine(IncomingRoot, "files.json");
|
||||
File.WriteAllText(fileMapPath, JsonSerializer.Serialize(fileMap, AppJsonContext.Default.SignedFileMap));
|
||||
Sign(fileMapPath, Path.Combine(IncomingRoot, "files.json.sig"));
|
||||
|
||||
var deploymentLock = new DeploymentLock(
|
||||
SchemaVersion: 1,
|
||||
Kind: "delta",
|
||||
TargetVersion: toVersion,
|
||||
PayloadPath: fileMapPath,
|
||||
PayloadSha256: Sha256File(fileMapPath),
|
||||
CreatedAtUtc: DateTimeOffset.UtcNow);
|
||||
var deploymentLockPath = UpdatePaths.GetDeploymentLockPath(AppRoot);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(deploymentLockPath)!);
|
||||
File.WriteAllText(deploymentLockPath, JsonSerializer.Serialize(deploymentLock));
|
||||
|
||||
Directory.Delete(extractRoot, true);
|
||||
}
|
||||
|
||||
public void WriteSnapshot(string sourceVersion, string sourceDirectory, string targetVersion, string targetDirectory)
|
||||
{
|
||||
Directory.CreateDirectory(SnapshotsRoot);
|
||||
var snapshot = new SnapshotMetadata
|
||||
{
|
||||
SnapshotId = Guid.NewGuid().ToString("N"),
|
||||
SourceVersion = sourceVersion,
|
||||
TargetVersion = targetVersion,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
SourceDirectory = sourceDirectory,
|
||||
TargetDirectory = targetDirectory,
|
||||
Status = "applied"
|
||||
};
|
||||
|
||||
File.WriteAllText(
|
||||
Path.Combine(SnapshotsRoot, $"{snapshot.SnapshotId}.json"),
|
||||
JsonSerializer.Serialize(snapshot, AppJsonContext.Default.SnapshotMetadata));
|
||||
}
|
||||
|
||||
public void WriteStaleInstallCheckpoint(string sourceVersion, string targetVersion)
|
||||
{
|
||||
var checkpoint = new InstallCheckpoint
|
||||
{
|
||||
SnapshotId = Guid.NewGuid().ToString("N"),
|
||||
SourceVersion = sourceVersion,
|
||||
TargetVersion = targetVersion,
|
||||
SourceDirectory = Path.Combine(AppRoot, $"app-{sourceVersion}-0"),
|
||||
TargetDirectory = Path.Combine(AppRoot, $"app-{targetVersion}-999"),
|
||||
IsInitialDeployment = false,
|
||||
AppliedCount = 1,
|
||||
VerifiedCount = 1
|
||||
};
|
||||
|
||||
var checkpointPath = UpdatePaths.GetInstallCheckpointPath(AppRoot);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(checkpointPath)!);
|
||||
File.WriteAllText(checkpointPath, JsonSerializer.Serialize(checkpoint, AppJsonContext.Default.InstallCheckpoint));
|
||||
}
|
||||
|
||||
public void WriteValidPlondsResumeCheckpoint(string sourceVersion, string targetVersion)
|
||||
{
|
||||
var targetDeployment = Path.Combine(AppRoot, $"app-{targetVersion}-0");
|
||||
Directory.CreateDirectory(targetDeployment);
|
||||
File.WriteAllText(Path.Combine(targetDeployment, ".partial"), string.Empty);
|
||||
File.WriteAllText(Path.Combine(targetDeployment, ExecutableName), $"exe-{sourceVersion}");
|
||||
|
||||
var checkpoint = new InstallCheckpoint
|
||||
{
|
||||
SnapshotId = Guid.NewGuid().ToString("N"),
|
||||
SourceVersion = sourceVersion,
|
||||
TargetVersion = targetVersion,
|
||||
SourceDirectory = Path.Combine(AppRoot, $"app-{sourceVersion}-0"),
|
||||
TargetDirectory = targetDeployment,
|
||||
IsInitialDeployment = false,
|
||||
AppliedCount = 1,
|
||||
VerifiedCount = 0
|
||||
};
|
||||
|
||||
var checkpointPath = UpdatePaths.GetInstallCheckpointPath(AppRoot);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(checkpointPath)!);
|
||||
File.WriteAllText(checkpointPath, JsonSerializer.Serialize(checkpoint, AppJsonContext.Default.InstallCheckpoint));
|
||||
}
|
||||
|
||||
public void WriteValidLegacyResumeCheckpoint(string sourceVersion, string targetVersion)
|
||||
{
|
||||
var targetDeployment = Path.Combine(AppRoot, $"app-{targetVersion}-0");
|
||||
Directory.CreateDirectory(targetDeployment);
|
||||
File.WriteAllText(Path.Combine(targetDeployment, ".partial"), string.Empty);
|
||||
|
||||
var checkpoint = new InstallCheckpoint
|
||||
{
|
||||
SnapshotId = Guid.NewGuid().ToString("N"),
|
||||
SourceVersion = sourceVersion,
|
||||
TargetVersion = targetVersion,
|
||||
SourceDirectory = Path.Combine(AppRoot, $"app-{sourceVersion}-0"),
|
||||
TargetDirectory = targetDeployment,
|
||||
IsInitialDeployment = false,
|
||||
AppliedCount = 0,
|
||||
VerifiedCount = 0
|
||||
};
|
||||
|
||||
var checkpointPath = UpdatePaths.GetInstallCheckpointPath(AppRoot);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(checkpointPath)!);
|
||||
File.WriteAllText(checkpointPath, JsonSerializer.Serialize(checkpoint, AppJsonContext.Default.InstallCheckpoint));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_rsa.Dispose();
|
||||
if (Directory.Exists(_root))
|
||||
{
|
||||
Directory.Delete(_root, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private void Sign(string payloadPath, string signaturePath)
|
||||
{
|
||||
var signature = _rsa.SignData(File.ReadAllBytes(payloadPath), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
File.WriteAllText(signaturePath, Convert.ToBase64String(signature));
|
||||
}
|
||||
|
||||
private static string Sha256File(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static string ExecutableName => OperatingSystem.IsWindows()
|
||||
? "LanMountainDesktop.exe"
|
||||
: "LanMountainDesktop";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PlondsStaticUpdateServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task CheckForUpdatesAsync_ReadsStaticLatestDistributionAndBuildsPayloadUrls()
|
||||
{
|
||||
var platform = PlondsStaticUpdateService.ResolveCurrentPlatform();
|
||||
var handler = new StaticManifestHandler(request =>
|
||||
{
|
||||
var path = request.RequestUri?.AbsolutePath ?? string.Empty;
|
||||
if (path.EndsWith($"/meta/channels/stable/{platform}/latest.json", StringComparison.Ordinal))
|
||||
{
|
||||
return Json("""{"distributionId":"dist-1","version":"1.2.0","channel":"stable","platform":"PLATFORM","publishedAt":"2026-05-06T00:00:00Z"}"""
|
||||
.Replace("PLATFORM", platform));
|
||||
}
|
||||
|
||||
if (path.EndsWith("/meta/distributions/dist-1.json", StringComparison.Ordinal))
|
||||
{
|
||||
return Json("""{"distributionId":"dist-1","version":"1.2.0","sourceVersion":"1.0.0","channel":"stable","platform":"PLATFORM","publishedAt":"2026-05-06T00:00:00Z","fileMapUrl":"https://static.example/lanmountain/update/manifests/dist-1/plonds-filemap.json","fileMapSignatureUrl":"https://static.example/lanmountain/update/manifests/dist-1/plonds-filemap.json.sig"}"""
|
||||
.Replace("PLATFORM", platform));
|
||||
}
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||
});
|
||||
|
||||
using var client = new HttpClient(handler);
|
||||
using var service = new PlondsStaticUpdateService("https://static.example/lanmountain/update", client);
|
||||
|
||||
var result = await service.CheckForUpdatesAsync(new Version(1, 0, 0), includePrerelease: false);
|
||||
|
||||
Assert.True(result.Success, result.ErrorMessage);
|
||||
Assert.True(result.IsUpdateAvailable);
|
||||
Assert.Equal("1.2.0", result.LatestVersionText);
|
||||
Assert.NotNull(result.PlondsPayload);
|
||||
Assert.Equal("dist-1", result.PlondsPayload.DistributionId);
|
||||
Assert.Equal(platform, result.PlondsPayload.SubChannel);
|
||||
Assert.Equal("https://static.example/lanmountain/update/manifests/dist-1/plonds-filemap.json", result.PlondsPayload.FileMapJsonUrl);
|
||||
Assert.Equal("https://static.example/lanmountain/update/manifests/dist-1/plonds-filemap.json.sig", result.PlondsPayload.FileMapSignatureUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckForUpdatesAsync_WhenLatestIsMissing_ReturnsFailureForFallback()
|
||||
{
|
||||
using var client = new HttpClient(new StaticManifestHandler(_ => new HttpResponseMessage(HttpStatusCode.NotFound)));
|
||||
using var service = new PlondsStaticUpdateService("https://static.example/lanmountain/update", client);
|
||||
|
||||
var result = await service.CheckForUpdatesAsync(new Version(1, 0, 0), includePrerelease: false);
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.False(result.IsUpdateAvailable);
|
||||
Assert.Contains("latest manifest", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveCurrentPlatform_UsesCanonicalNames()
|
||||
{
|
||||
var platform = PlondsStaticUpdateService.ResolveCurrentPlatform();
|
||||
|
||||
Assert.DoesNotContain("win-", platform, StringComparison.OrdinalIgnoreCase);
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
Assert.StartsWith("windows-", platform, StringComparison.Ordinal);
|
||||
}
|
||||
else if (OperatingSystem.IsLinux())
|
||||
{
|
||||
Assert.StartsWith("linux-", platform, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Json(string json)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
|
||||
private sealed class StaticManifestHandler(Func<HttpRequestMessage, HttpResponseMessage> responder) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(responder(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class UpdatePathConsistencyTests
|
||||
{
|
||||
[Fact]
|
||||
public void HostAndSharedUpdatePathsUseLauncherDirectoryCasing()
|
||||
{
|
||||
var incoming = UpdatePaths.GetIncomingDirectory("root");
|
||||
var sharedIncoming = UpdatePaths.GetIncomingDirectory("root");
|
||||
|
||||
Assert.Contains($"{Path.DirectorySeparatorChar}.Launcher{Path.DirectorySeparatorChar}", incoming);
|
||||
Assert.Equal(
|
||||
Path.Combine("root", ".Launcher", "update", "incoming"),
|
||||
sharedIncoming);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PlondsApiManifestProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task GetLatestAsync_MapsCanonicalAndLegacyFileFields()
|
||||
{
|
||||
using var client = new HttpClient(new StaticManifestHandler(request =>
|
||||
{
|
||||
var path = request.RequestUri?.AbsolutePath ?? string.Empty;
|
||||
if (path.EndsWith("/api/plonds/v1/channels/stable/windows-x64/latest", StringComparison.Ordinal))
|
||||
{
|
||||
return Json("""{"distributionId":"dist-2","version":"1.2.0","publishedAt":"2026-05-06T00:00:00Z"}""");
|
||||
}
|
||||
|
||||
if (path.EndsWith("/api/plonds/v1/distributions/dist-2", StringComparison.Ordinal))
|
||||
{
|
||||
return Json("""
|
||||
{
|
||||
"distributionId": "dist-2",
|
||||
"version": "1.2.0",
|
||||
"sourceVersion": "1.1.0",
|
||||
"publishedAt": "2026-05-06T00:00:00Z",
|
||||
"fileMapUrl": "https://static.example/filemap.json",
|
||||
"signatures": [{ "signature": "https://static.example/filemap.json.sig" }],
|
||||
"components": [
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop.exe",
|
||||
"action": "replace",
|
||||
"sha256": "abc123",
|
||||
"size": 42,
|
||||
"objectUrl": "https://static.example/repo/sha256/ab/abc123",
|
||||
"archiveSha256": "archive123"
|
||||
},
|
||||
{
|
||||
"path": "legacy.dll",
|
||||
"op": "add",
|
||||
"contentHash": "def456",
|
||||
"size": 7
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||
}));
|
||||
var provider = new PlondsApiManifestProvider("https://static.example", client);
|
||||
|
||||
var manifest = await provider.GetLatestAsync("stable", "windows-x64", new Version(1, 1, 0), CancellationToken.None);
|
||||
|
||||
Assert.NotNull(manifest);
|
||||
Assert.Equal(UpdatePayloadKind.DeltaPlonds, manifest.Kind);
|
||||
Assert.Equal("https://static.example/filemap.json.sig", manifest.FileMapSignatureUrl);
|
||||
Assert.Collection(
|
||||
manifest.Files,
|
||||
first =>
|
||||
{
|
||||
Assert.Equal("replace", first.Action);
|
||||
Assert.Equal("abc123", first.Sha256);
|
||||
Assert.Equal("https://static.example/repo/sha256/ab/abc123", first.ObjectUrl);
|
||||
Assert.Equal("archive123", first.ArchiveSha256);
|
||||
},
|
||||
second =>
|
||||
{
|
||||
Assert.Equal("add", second.Action);
|
||||
Assert.Equal("def456", second.Sha256);
|
||||
});
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Json(string json)
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
|
||||
private sealed class StaticManifestHandler(Func<HttpRequestMessage, HttpResponseMessage> responder) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(responder(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,7 +130,7 @@ public sealed class WindowLayerIsolationTests
|
||||
{
|
||||
var optionsSource = ReadRepositoryFile("LanMountainDesktop.AirAppHost", "AirAppLaunchOptions.cs");
|
||||
var programSource = ReadRepositoryFile("LanMountainDesktop.AirAppHost", "Program.cs");
|
||||
var starterSource = ReadRepositoryFile("LanMountainDesktop.Launcher", "AirApp", "IAirAppProcessStarter.cs");
|
||||
var starterSource = ReadRepositoryFile("LanMountainDesktop.AirAppRuntime", "IAirAppProcessStarter.cs");
|
||||
var dataPathSource = ReadRepositoryFile("LanMountainDesktop", "Services", "AppDataPathProvider.cs");
|
||||
|
||||
Assert.Contains("DataRoot", optionsSource);
|
||||
@@ -146,15 +146,10 @@ public sealed class WindowLayerIsolationTests
|
||||
public void FusedDesktopWindows_KeepDesktopBottomMostBoundary()
|
||||
{
|
||||
var desktopWidgetWindow = ReadRepositoryFile("LanMountainDesktop", "Views", "DesktopWidgetWindow.axaml.cs");
|
||||
var transparentOverlayWindow = ReadRepositoryFile("LanMountainDesktop", "Views", "TransparentOverlayWindow.axaml.cs");
|
||||
|
||||
Assert.Contains("WindowBottomMostServiceFactory.GetOrCreate()", desktopWidgetWindow);
|
||||
Assert.Contains("RefreshDesktopLayer", desktopWidgetWindow);
|
||||
Assert.Contains("SendToBottom", desktopWidgetWindow);
|
||||
|
||||
Assert.Contains("WindowBottomMostServiceFactory.GetOrCreate()", transparentOverlayWindow);
|
||||
Assert.Contains("RefreshDesktopLayer", transparentOverlayWindow);
|
||||
Assert.Contains("SendToBottom", transparentOverlayWindow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<Project Path="LanMountainDesktop.PluginIsolation.Ipc/LanMountainDesktop.PluginIsolation.Ipc.csproj" />
|
||||
<Project Path="LanMountainDesktop.PluginPackaging/LanMountainDesktop.PluginPackaging.csproj" />
|
||||
<Project Path="LanMountainDesktop.PluginSdk/LanMountainDesktop.PluginSdk.csproj" />
|
||||
<Project Path="LanMountainDesktop.AirAppRuntime/LanMountainDesktop.AirAppRuntime.csproj" />
|
||||
<Project Path="LanMountainDesktop.AirAppHost/LanMountainDesktop.AirAppHost.csproj" />
|
||||
<Project Path="LanMountainDesktop.PluginTemplate/LanMountainDesktop.PluginTemplate.csproj" />
|
||||
<Project Path="LanMountainDesktop.Launcher/LanMountainDesktop.Launcher.csproj" />
|
||||
|
||||
@@ -75,9 +75,7 @@ public partial class App : Application
|
||||
private DispatcherTimer? _shellRecoveryTimer;
|
||||
private PluginRuntimeService? _pluginRuntimeService;
|
||||
private MainWindow? _mainWindow;
|
||||
private TransparentOverlayWindow? _transparentOverlayWindow;
|
||||
private FusedDesktopComponentLibraryWindow? _fusedComponentLibraryWindow;
|
||||
private bool _isExitingFusedDesktopEditMode;
|
||||
private bool _mainWindowClosed;
|
||||
private DesktopShellHost? _desktopShellHost;
|
||||
private PublicIpcHostService? _publicIpcHostService;
|
||||
@@ -454,22 +452,10 @@ public partial class App : Application
|
||||
|
||||
try
|
||||
{
|
||||
var fusedDesktopManager = FusedDesktopManagerServiceFactory.GetOrCreate();
|
||||
fusedDesktopManager.EnterEditMode();
|
||||
|
||||
EnsureTransparentOverlayWindow();
|
||||
if (_transparentOverlayWindow is not null && !_transparentOverlayWindow.IsVisible)
|
||||
{
|
||||
_transparentOverlayWindow.Show();
|
||||
}
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().EnterEditMode();
|
||||
|
||||
if (_fusedComponentLibraryWindow is { } existingWindow)
|
||||
{
|
||||
if (_transparentOverlayWindow is not null)
|
||||
{
|
||||
existingWindow.SetOverlayWindow(_transparentOverlayWindow);
|
||||
}
|
||||
|
||||
if (!existingWindow.IsVisible)
|
||||
{
|
||||
existingWindow.Show();
|
||||
@@ -477,7 +463,7 @@ public partial class App : Application
|
||||
|
||||
if (centerInWorkArea)
|
||||
{
|
||||
existingWindow.CenterInWorkArea(_transparentOverlayWindow);
|
||||
existingWindow.CenterInWorkArea();
|
||||
}
|
||||
|
||||
existingWindow.Activate();
|
||||
@@ -486,16 +472,12 @@ public partial class App : Application
|
||||
|
||||
var window = new FusedDesktopComponentLibraryWindow();
|
||||
_fusedComponentLibraryWindow = window;
|
||||
if (_transparentOverlayWindow is not null)
|
||||
{
|
||||
window.SetOverlayWindow(_transparentOverlayWindow);
|
||||
}
|
||||
|
||||
window.Closed += OnFusedComponentLibraryWindowClosed;
|
||||
window.Show();
|
||||
if (centerInWorkArea)
|
||||
{
|
||||
window.CenterInWorkArea(_transparentOverlayWindow);
|
||||
window.CenterInWorkArea();
|
||||
}
|
||||
|
||||
window.Activate();
|
||||
@@ -503,7 +485,13 @@ public partial class App : Application
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLogger.Warn("FusedDesktop", "Failed to open fused desktop component library.", ex);
|
||||
ExitFusedDesktopEditModeFromUi(closeLibrary: true);
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().ExitEditMode();
|
||||
if (_fusedComponentLibraryWindow is { } libWindow)
|
||||
{
|
||||
_fusedComponentLibraryWindow = null;
|
||||
libWindow.Closed -= OnFusedComponentLibraryWindowClosed;
|
||||
libWindow.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,50 +508,13 @@ public partial class App : Application
|
||||
_fusedComponentLibraryWindow = null;
|
||||
}
|
||||
|
||||
if (!window.PreserveEditModeOnClose && !_isExitingFusedDesktopEditMode)
|
||||
{
|
||||
ExitFusedDesktopEditModeFromUi(closeLibrary: false);
|
||||
}
|
||||
}
|
||||
|
||||
private void ExitFusedDesktopEditModeFromUi(bool closeLibrary)
|
||||
{
|
||||
if (_isExitingFusedDesktopEditMode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isExitingFusedDesktopEditMode = true;
|
||||
try
|
||||
{
|
||||
if (closeLibrary && _fusedComponentLibraryWindow is { } libraryWindow)
|
||||
{
|
||||
_fusedComponentLibraryWindow = null;
|
||||
libraryWindow.Closed -= OnFusedComponentLibraryWindowClosed;
|
||||
libraryWindow.Close();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_transparentOverlayWindow?.SaveLayoutAndHide();
|
||||
}
|
||||
catch (Exception overlayEx)
|
||||
{
|
||||
AppLogger.Warn("FusedDesktop", "Failed to hide fused desktop overlay.", overlayEx);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().ExitEditMode();
|
||||
}
|
||||
catch (Exception exitEx)
|
||||
{
|
||||
AppLogger.Warn("FusedDesktop", "Failed to exit fused desktop edit mode.", exitEx);
|
||||
}
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().ExitEditMode();
|
||||
}
|
||||
finally
|
||||
catch (Exception ex)
|
||||
{
|
||||
_isExitingFusedDesktopEditMode = false;
|
||||
AppLogger.Warn("FusedDesktop", "Failed to exit fused desktop edit mode after library closed.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -890,11 +841,6 @@ public partial class App : Application
|
||||
{
|
||||
AppLogger.Info("DesktopShell", $"Restoring desktop shell started. Source='{source}'.");
|
||||
|
||||
if (_transparentOverlayWindow is not null && _transparentOverlayWindow.IsVisible)
|
||||
{
|
||||
_transparentOverlayWindow.Hide();
|
||||
}
|
||||
|
||||
var mainWindow = GetOrCreateMainWindow(desktop, source);
|
||||
mainWindow.PrepareEnterAnimation();
|
||||
|
||||
@@ -938,26 +884,6 @@ public partial class App : Application
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureTransparentOverlayWindow()
|
||||
{
|
||||
if (_transparentOverlayWindow is null)
|
||||
{
|
||||
_transparentOverlayWindow = new TransparentOverlayWindow();
|
||||
_transparentOverlayWindow.RestoreMainWindowRequested += (s, e) =>
|
||||
{
|
||||
RestoreOrCreateMainWindow("TransparentOverlay");
|
||||
};
|
||||
_transparentOverlayWindow.ExitEditRequested += (s, e) =>
|
||||
{
|
||||
ExitFusedDesktopEditModeFromUi(closeLibrary: true);
|
||||
};
|
||||
_transparentOverlayWindow.RestoreComponentLibraryRequested += (s, e) =>
|
||||
{
|
||||
OpenFusedDesktopComponentLibraryFromUi(centerInWorkArea: true);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal bool TrySubmitShutdown(HostShutdownMode mode, HostApplicationLifecycleRequest? request)
|
||||
{
|
||||
@@ -1263,31 +1189,16 @@ public partial class App : Application
|
||||
finally
|
||||
{
|
||||
_fusedComponentLibraryWindow = null;
|
||||
try
|
||||
{
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().ExitEditMode();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLogger.Warn("FusedDesktop", "Failed to exit fused desktop edit mode during shutdown.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_transparentOverlayWindow is not null)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
_transparentOverlayWindow.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLogger.Warn("DesktopShell", "Failed to close transparent overlay during exit cleanup.", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_transparentOverlayWindow = null;
|
||||
}
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().Shutdown();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLogger.Warn("FusedDesktop", "Failed to shut down fused desktop manager during exit cleanup.", ex);
|
||||
}
|
||||
|
||||
AudioRecorderServiceFactory.DisposeSharedServices();
|
||||
@@ -1572,13 +1483,6 @@ public partial class App : Application
|
||||
AppLogger.Info(
|
||||
"DesktopShell",
|
||||
$"Main window hidden to tray. Source='{source}'; WindowState='{mainWindow.WindowState}'.");
|
||||
|
||||
var appSnapshot = _settingsFacade.Settings.LoadSnapshot<AppSettingsSnapshot>(SettingsScope.App);
|
||||
if (appSnapshot.EnableThreeFingerSwipe && appSnapshot.EnableFusedDesktop)
|
||||
{
|
||||
EnsureTransparentOverlayWindow();
|
||||
_transparentOverlayWindow?.Show();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -1668,7 +1572,6 @@ public partial class App : Application
|
||||
|
||||
if (IsMainWindowDesktopLayerEnabled())
|
||||
{
|
||||
ExitFusedDesktopEditModeFromUi(closeLibrary: true);
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().Shutdown();
|
||||
_mainWindow.ShowInTaskbar = false;
|
||||
_mainWindowDesktopLayerService.EnableOrRefresh(_mainWindow);
|
||||
@@ -1697,7 +1600,6 @@ public partial class App : Application
|
||||
return;
|
||||
}
|
||||
|
||||
ExitFusedDesktopEditModeFromUi(closeLibrary: true);
|
||||
FusedDesktopManagerServiceFactory.GetOrCreate().Shutdown();
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,35 +0,0 @@
|
||||
# MiSans 字体说明
|
||||
|
||||
## 中文
|
||||
|
||||
本项目内置 MiSans 字体,用于在不同设备上保持相对一致的文字渲染效果。
|
||||
|
||||
### 包含文件
|
||||
|
||||
- `MiSans-Regular.ttf`
|
||||
- `MiSans-Semibold.ttf`
|
||||
- `MiSans-Bold.ttf`
|
||||
|
||||
### 来源
|
||||
|
||||
- 上游仓库:https://github.com/dsrkafuu/misans
|
||||
- 上游所引用的小米字体页面:https://hyperos.mi.com/font/zh/
|
||||
|
||||
### 许可与使用说明
|
||||
|
||||
- 上游脚本或打包仓库使用 Apache-2.0 许可。
|
||||
- MiSans 字体本身的版权和补充使用条款以小米官方说明为准:
|
||||
- https://hyperos.mi.com/font-download/MiSans%E5%AD%97%E4%BD%93%E7%9F%A5%E8%AF%86%E4%BA%A7%E6%9D%83%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf
|
||||
|
||||
在重新分发本项目时,请自行确认并遵守 MiSans 字体的相关条款。
|
||||
|
||||
## English
|
||||
|
||||
This project bundles MiSans fonts for more consistent cross-device rendering.
|
||||
|
||||
### Sources
|
||||
|
||||
- Upstream package repository: https://github.com/dsrkafuu/misans
|
||||
- Xiaomi font source page: https://hyperos.mi.com/font/zh/
|
||||
|
||||
Please review and comply with the MiSans font terms before redistributing this application.
|
||||
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user