"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(desktop): stabilize Windows packaging inputs
Haozhe Wubc846ebaefdc
diff --git a/.github/workflows/desktop-windows.yml b/.github/workflows/desktop-windows.ymlindex c13656242..ad2664690 100644--- a/.github/workflows/desktop-windows.yml+++ b/.github/workflows/desktop-windows.yml@@ -2,6 +2,14 @@ name: Desktop Windowson:workflow_dispatch:+ push:+ branches: [main]+ paths:+ - ".github/workflows/desktop-windows.yml"+ - "agent/**"+ - "desktop/electron/**"+ - "frontend/**"+ - "pyproject.toml"pull_request:paths:- ".github/workflows/desktop-windows.yml"@@ -15,12 +23,10 @@ permissions:jobs:package:- # The checksum-pinned legacy GTK runtime extractor crashes on the Server- # 2025 image even though the resulting runtime works on current Windows.- # Keep packaging reproducible on the clean Server 2022 image until the- # native PDF dependency is replaced with a newer archive format.- runs-on: windows-2022- timeout-minutes: 90+ # GTK is extracted as a checksum-pinned archive rather than executed as a+ # legacy NSIS installer, so packaging can run on the current Windows image.+ runs-on: windows-2025+ timeout-minutes: 60steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1@@ -52,6 +58,10 @@ jobs:working-directory: desktop/electronrun: npm run test:update-safety+ - name: Prepare verified Electron runtime+ working-directory: desktop/electron+ run: npm run prepare:electron+- name: Verify encrypted credential storageworking-directory: desktop/electronrun: npm run smoke:credentialsdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 67bf60f4f..b99a2119e 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -184,6 +184,10 @@ jobs:working-directory: desktop/electronrun: npm ci+ - name: Prepare verified Electron runtime+ working-directory: desktop/electron+ run: npm run prepare:electron+- name: Build desktop shellworking-directory: desktop/electronrun: npm run builddiff --git a/desktop/electron/README.md b/desktop/electron/README.mdindex fe4cb71fa..f0aace5fd 100644--- a/desktop/electron/README.md+++ b/desktop/electron/README.md@@ -58,9 +58,16 @@ npm run buildcd ..\desktop\electronnpm ci+npm run prepare:electronnpm start```+`prepare:electron` uses bounded retries and the official checksum bundled with+the pinned Electron package, then installs the verified Windows x64 runtime for+the source lifecycle tests. The packaging command additionally requires a+current `7z.exe`; it treats the pinned GTK NSIS asset as an archive and never+executes its legacy self-extractor.+The Windows lifecycle suite used by CI can be run from the same directory:```powershelldiff --git a/desktop/electron/WINDOWS_PACKAGING.md b/desktop/electron/WINDOWS_PACKAGING.mdindex eb8e812d5..77f79048c 100644--- a/desktop/electron/WINDOWS_PACKAGING.md+++ b/desktop/electron/WINDOWS_PACKAGING.md@@ -36,6 +36,7 @@ npm run buildcd ..\desktop\electronnpm ci+npm run prepare:electronnpm run smoke:credentialsnpm run runtime:win -- -Cleannpm run smoke:lifecycle@@ -54,6 +55,11 @@ Python dependencies are installed fromchecked-out Vibe-Trading package is then installed with `--no-deps` sopackaging cannot silently resolve versions outside that lock.+`prepare:electron` downloads the official Windows x64 Electron archive with+bounded retries, verifies the checksum shipped by the pinned `electron` npm+package, and extracts that same archive for source-mode smoke tests. Packaging+therefore never falls through to Electron's unbounded lazy-download path.+The repository-root lock is generated for the upstream Linux environment andcontains platform-specific dependencies such as `uvloop`. It cannot be reusedfor the Windows runtime. Regenerate the Windows lock only on Windows with@@ -111,15 +117,15 @@ tooling. Those packages are not copied into the packaged application, but thereview workflow still treats the lockfile as trusted build input. This shouldbe re-audited whenever Electron Builder publishes a repaired dependency tree.-## CI build-host note+## Native archive extraction and CI visibility-The packaging job is pinned to GitHub's clean `windows-2022` image. The-checksum-pinned GTK runtime installer used solely to extract WeasyPrint's-native DLL subset exits with an access violation on the Server 2025 runner,-although the extracted runtime and packaged application work on current-Windows 10/11 hosts. Moving that native dependency to a newer, directly-extractable upstream archive is a follow-up; silently dropping PDF support or-accepting an unverified binary is not.+The GTK asset remains checksum-pinned, but the build never executes its legacy+NSIS self-extractor. A current `7z.exe` (available on `PATH` or under the+standard Program Files location) reads the verified asset as an archive under+a two-minute process timeout, after which the build copies only the explicit+WeasyPrint DLL/font closure. GitHub's `windows-2025` image supplies 7-Zip and+runs the complete packaging path for relevant pull requests and pushes to+`main`, so default-branch packaging regressions are visible.## Local validation recorddiff --git a/desktop/electron/package-lock.json b/desktop/electron/package-lock.jsonindex d84352e60..eeea11025 100644--- a/desktop/electron/package-lock.json+++ b/desktop/electron/package-lock.json@@ -9,6 +9,7 @@"version": "0.3.0","license": "MIT","devDependencies": {+ "@electron-internal/extract-zip": "1.0.4","@types/node": "^24.10.0","electron": "43.1.1","electron-builder": "26.15.3",diff --git a/desktop/electron/package.json b/desktop/electron/package.jsonindex de96519f9..c41b64167 100644--- a/desktop/electron/package.json+++ b/desktop/electron/package.json@@ -8,21 +8,23 @@"main": "dist/main.js","scripts": {"build": "tsc && node scripts/copy-static.mjs",- "start": "npm run build && electron .",+ "start": "npm run build && npm run prepare:electron && electron .","test:locales": "npm run build && node scripts/test-locales.mjs","test:backend-resolution": "npm run build && node scripts/test-backend-resolution.mjs","test:update-safety": "npm run build && node scripts/test-update-safety.mjs",- "smoke:parent-death": "npm run build && node scripts/smoke-parent-death.mjs",+ "test:packaging-preparation": "node scripts/test-packaging-preparation.mjs",+ "smoke:parent-death": "npm run build && npm run prepare:electron && node scripts/smoke-parent-death.mjs","prepare:electron": "node scripts/prepare-electron.mjs","runtime:win": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/build-backend.ps1",- "smoke:credentials": "npm run build && electron scripts/smoke-credentials.cjs",- "smoke:lifecycle": "npm run build && node scripts/test-locales.mjs && node scripts/test-backend-resolution.mjs && node scripts/smoke-lifecycle.mjs && node scripts/smoke-parent-death.mjs",+ "smoke:credentials": "npm run build && npm run prepare:electron && electron scripts/smoke-credentials.cjs",+ "smoke:lifecycle": "npm run build && npm run prepare:electron && node scripts/test-packaging-preparation.mjs && node scripts/test-locales.mjs && node scripts/test-backend-resolution.mjs && node scripts/smoke-lifecycle.mjs && node scripts/smoke-parent-death.mjs","pack:win": "npm run build && npm run prepare:electron && electron-builder --publish never --win dir","installer:win:review": "npm run build && npm run prepare:electron && node scripts/build-review-installer.mjs","installer:win:signed": "node scripts/build-signed-installer.mjs","sbom": "npm sbom --sbom-format cyclonedx"},"devDependencies": {+ "@electron-internal/extract-zip": "1.0.4","@types/node": "^24.10.0","electron": "43.1.1","electron-builder": "26.15.3",diff --git a/desktop/electron/scripts/build-backend.ps1 b/desktop/electron/scripts/build-backend.ps1index 28db00ee7..0000a16c4 100644--- a/desktop/electron/scripts/build-backend.ps1+++ b/desktop/electron/scripts/build-backend.ps1@@ -23,7 +23,106 @@ $gtkInstallerName = 'gtk3-runtime-3.24.31-2022-01-04-ts-win64.exe'$gtkInstallerPath = Join-Path $gtkCacheRoot $gtkInstallerName$gtkInstallerUrl = "https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/releases/download/2022-01-04/$gtkInstallerName"$gtkInstallerSha256 = 'd05e1488ca0e6ffaabb579bbeb82113c099152ca4260ebc63084b0dd174d4558'-$gtkInstallRoot = Join-Path $gtkCacheRoot 'runtime'+$gtkExtractRoot = Join-Path $gtkCacheRoot 'archive-runtime-v1'++function Get-VerifiedDownload {+ param(+ [Parameter(Mandatory)][string]$Uri,+ [Parameter(Mandatory)][string]$DestinationPath,+ [Parameter(Mandatory)][string]$ExpectedSha256,+ [Parameter(Mandatory)][string]$Label,+ [Parameter(Mandatory)][string]$CurlPath+ )++ if (Test-Path -LiteralPath $DestinationPath) {+ $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $DestinationPath).Hash.ToLowerInvariant()+ if ($actual -ne $ExpectedSha256) {+ throw "$Label checksum mismatch. Expected $ExpectedSha256, got $actual"+ }+ return+ }++ New-Item -ItemType Directory -Path (Split-Path -Parent $DestinationPath) -Force | Out-Null+ $temporaryPath = "$DestinationPath.download-$PID-$([Guid]::NewGuid().ToString('N'))"+ try {+ & $CurlPath `+ --fail `+ --location `+ --silent `+ --show-error `+ --connect-timeout 30 `+ --max-time 180 `+ --retry 2 `+ --retry-max-time 420 `+ --retry-delay 2 `+ --retry-all-errors `+ --output $temporaryPath `+ $Uri+ if ($LASTEXITCODE -ne 0) {+ throw "$Label download failed."+ }+ $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $temporaryPath).Hash.ToLowerInvariant()+ if ($actual -ne $ExpectedSha256) {+ throw "$Label checksum mismatch. Expected $ExpectedSha256, got $actual"+ }+ Move-Item -LiteralPath $temporaryPath -Destination $DestinationPath+ }+ finally {+ Remove-Item -LiteralPath $temporaryPath -Force -ErrorAction SilentlyContinue+ }+}++function Resolve-SevenZip {+ $candidates = [System.Collections.Generic.List[string]]::new()+ $command = Get-Command 7z.exe -ErrorAction SilentlyContinue+ if ($command) {+ $candidates.Add($command.Source)+ }+ if ($env:ProgramFiles) {+ $candidates.Add((Join-Path $env:ProgramFiles '7-Zip\7z.exe'))+ }+ if (${env:ProgramFiles(x86)}) {+ $candidates.Add((Join-Path ${env:ProgramFiles(x86)} '7-Zip\7z.exe'))+ }+ foreach ($candidate in ($candidates | Select-Object -Unique)) {+ if (Test-Path -LiteralPath $candidate) {+ return (Resolve-Path -LiteralPath $candidate).Path+ }+ }+ throw '7z.exe is required to extract the checksum-pinned GTK archive without executing its legacy installer.'+}++function Invoke-BoundedProcess {+ param(+ [Parameter(Mandatory)][string]$FilePath,+ [Parameter(Mandatory)][string]$Arguments,+ [Parameter(Mandatory)][int]$TimeoutSeconds,+ [Parameter(Mandatory)][string]$Label+ )++ $process = $null+ try {+ $process = Start-Process `+ -FilePath $FilePath `+ -ArgumentList $Arguments `+ -NoNewWindow `+ -PassThru+ if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {+ $taskkill = Join-Path $env:SystemRoot 'System32\taskkill.exe'+ & $taskkill /PID $process.Id /T /F | Out-Null+ $process.WaitForExit(10000) | Out-Null+ throw "$Label timed out after $TimeoutSeconds seconds."+ }+ if ($process.ExitCode -ne 0) {+ throw "$Label failed (exit code $($process.ExitCode))."+ }+ }+ finally {+ if ($process) {+ $process.Dispose()+ }+ }+}if (-not $BuildPython) {$repoVenvPython = Join-Path $repoRoot '.venv\Scripts\python.exe'@@ -47,22 +146,16 @@ if (-not (Test-Path -LiteralPath $requirementsLock)) {throw 'desktop/electron/requirements-windows-lock.txt is missing. Windows packaging requires its platform-specific hash-locked dependencies.'}-New-Item -ItemType Directory -Path $cacheRoot -Force | Out-Null-if (-not (Test-Path -LiteralPath $archivePath)) {- $curl = Join-Path $env:SystemRoot 'System32\curl.exe'- if (-not (Test-Path -LiteralPath $curl)) {- throw 'Windows curl.exe is unavailable.'- }- & $curl --fail --location --retry 3 --output $archivePath $archiveUrl- if ($LASTEXITCODE -ne 0) {- throw 'Python embeddable package download failed.'- }-}--$actualSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $archivePath).Hash.ToLowerInvariant()-if ($actualSha256 -ne $expectedSha256) {- throw "Python archive checksum mismatch. Expected $expectedSha256, got $actualSha256"+$curl = Join-Path $env:SystemRoot 'System32\curl.exe'+if (-not (Test-Path -LiteralPath $curl)) {+ throw 'Windows curl.exe is unavailable.'}+Get-VerifiedDownload `+ -Uri $archiveUrl `+ -DestinationPath $archivePath `+ -ExpectedSha256 $expectedSha256 `+ -Label 'Python embeddable package' `+ -CurlPath $curlif ($Clean -and (Test-Path -LiteralPath $runtimeRoot)) {$resolvedRuntime = (Resolve-Path -LiteralPath $runtimeRoot).Path@@ -190,31 +283,10 @@ foreach ($directory in $pruneRoots) {Write-Host ("Pruned {0} packaged test files ({1:N1} MB)" -f $removedFiles, ($reclaimedBytes / 1MB))# WeasyPrint needs Pango/Cairo/GLib on Windows. Copy only the verified-# rendering dependency closure, not the GTK UI or developer payloads.-New-Item -ItemType Directory -Path $gtkCacheRoot -Force | Out-Null-if (-not (Test-Path -LiteralPath $gtkInstallerPath)) {- Invoke-WebRequest -UseBasicParsing -Uri $gtkInstallerUrl -OutFile $gtkInstallerPath-}-$actualGtkSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $gtkInstallerPath).Hash.ToLowerInvariant()-if ($actualGtkSha256 -ne $gtkInstallerSha256) {- throw "GTK runtime checksum mismatch. Expected $gtkInstallerSha256, got $actualGtkSha256"-}-$gtkGObject = Join-Path $gtkInstallRoot 'bin\libgobject-2.0-0.dll'-if (-not (Test-Path -LiteralPath $gtkGObject)) {- New-Item -ItemType Directory -Path $gtkInstallRoot -Force | Out-Null- $gtkInstall = Start-Process `- -FilePath $gtkInstallerPath `- -ArgumentList @('/S', "/D=$gtkInstallRoot") `- -Wait `- -PassThru- if ($gtkInstall.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $gtkGObject)) {- throw "GTK runtime extraction failed (exit code $($gtkInstall.ExitCode))."- }-}--$runtimeGtk = Join-Path $runtimeRoot 'gtk'-New-Item -ItemType Directory -Path (Join-Path $runtimeGtk 'bin') -Force | Out-Null-New-Item -ItemType Directory -Path (Join-Path $runtimeGtk 'etc') -Force | Out-Null+# rendering dependency closure, not the GTK UI or developer payloads. The+# upstream asset is an NSIS executable, but executing that legacy self-+# extractor intermittently access-violates or hangs on GitHub Windows images.+# Treat the checksum-pinned asset strictly as data and extract it with 7-Zip.$gtkRuntimeDlls = @('libbrotlicommon.dll', 'libbrotlidec.dll', 'libbz2-1.dll', 'libdatrie-1.dll','libexpat-1.dll', 'libffi-7.dll', 'libfontconfig-1.dll', 'libfreetype-6.dll',@@ -224,14 +296,61 @@ $gtkRuntimeDlls = @('libpangoft2-1.0-0.dll', 'libpcre-1.dll', 'libpng16-16.dll', 'libstdc++-6.dll','libthai-0.dll', 'libwinpthread-1.dll', 'zlib1.dll')+Get-VerifiedDownload `+ -Uri $gtkInstallerUrl `+ -DestinationPath $gtkInstallerPath `+ -ExpectedSha256 $gtkInstallerSha256 `+ -Label 'GTK runtime archive' `+ -CurlPath $curl++$gtkArchiveBin = Join-Path $gtkExtractRoot '$_63_'+$gtkArchiveFonts = Join-Path $gtkExtractRoot 'etc\fonts'+$gtkGObject = Join-Path $gtkArchiveBin 'libgobject-2.0-0.dll'+if (-not (Test-Path -LiteralPath $gtkGObject) -or -not (Test-Path -LiteralPath $gtkArchiveFonts)) {+ if (Test-Path -LiteralPath $gtkExtractRoot) {+ throw "Cached GTK archive extraction is incomplete: $gtkExtractRoot"+ }+ $sevenZip = Resolve-SevenZip+ $temporaryExtractRoot = "$gtkExtractRoot.tmp-$PID-$([Guid]::NewGuid().ToString('N'))"+ try {+ New-Item -ItemType Directory -Path $temporaryExtractRoot -Force | Out-Null+ if ($temporaryExtractRoot.Contains('"') -or $gtkInstallerPath.Contains('"')) {+ throw 'GTK archive paths must not contain quote characters.'+ }+ $sevenZipArguments = 'x -y "-o{0}" "{1}"' -f $temporaryExtractRoot, $gtkInstallerPath+ Invoke-BoundedProcess `+ -FilePath $sevenZip `+ -Arguments $sevenZipArguments `+ -TimeoutSeconds 120 `+ -Label 'GTK archive extraction'++ $temporaryBin = Join-Path $temporaryExtractRoot '$_63_'+ $missingDlls = @(+ $gtkRuntimeDlls |+ Where-Object { -not (Test-Path -LiteralPath (Join-Path $temporaryBin $_)) }+ )+ $temporaryFonts = Join-Path $temporaryExtractRoot 'etc\fonts'+ if ($missingDlls.Count -gt 0 -or -not (Test-Path -LiteralPath $temporaryFonts)) {+ throw "GTK archive is missing required runtime files: $($missingDlls -join ', ')"+ }+ Move-Item -LiteralPath $temporaryExtractRoot -Destination $gtkExtractRoot+ }+ finally {+ Remove-Item -LiteralPath $temporaryExtractRoot -Recurse -Force -ErrorAction SilentlyContinue+ }+}++$runtimeGtk = Join-Path $runtimeRoot 'gtk'+New-Item -ItemType Directory -Path (Join-Path $runtimeGtk 'bin') -Force | Out-Null+New-Item -ItemType Directory -Path (Join-Path $runtimeGtk 'etc') -Force | Out-Nullforeach ($gtkDll in $gtkRuntimeDlls) {Copy-Item `- -LiteralPath (Join-Path $gtkInstallRoot "bin\$gtkDll") `+ -LiteralPath (Join-Path $gtkArchiveBin $gtkDll) `-Destination (Join-Path $runtimeGtk 'bin') `-Force}Copy-Item `- -LiteralPath (Join-Path $gtkInstallRoot 'etc\fonts') `+ -LiteralPath $gtkArchiveFonts `-Destination (Join-Path $runtimeGtk 'etc') `-Recurse `-Forcediff --git a/desktop/electron/scripts/prepare-electron.mjs b/desktop/electron/scripts/prepare-electron.mjsindex d41384b22..05e05156d 100644--- a/desktop/electron/scripts/prepare-electron.mjs+++ b/desktop/electron/scripts/prepare-electron.mjs@@ -1,74 +1,220 @@-import { createHash } from "node:crypto";-import { copyFile, mkdir, readFile } from "node:fs/promises";+import { createHash, randomUUID } from "node:crypto";+import { createReadStream } from "node:fs";+import {+ access,+ copyFile,+ mkdir,+ readFile,+ rename,+ rm,+ writeFile,+} from "node:fs/promises";import path from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";+import extractZip from "@electron-internal/extract-zip";import { downloadArtifact } from "@electron/get";-const electronRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");-const electronPackage = JSON.parse(- await readFile(path.join(electronRoot, "node_modules", "electron", "package.json"), "utf8"),-);-const checksums = JSON.parse(- await readFile(path.join(electronRoot, "node_modules", "electron", "checksums.json"), "utf8"),-);-const version = electronPackage.version;-const archiveName = `electron-v${version}-win32-x64.zip`;-const expected = checksums[archiveName];-if (!expected) throw new Error(`Official checksum is missing for ${archiveName}`);--const targetDirectory = path.join(electronRoot, ".cache", "electron-dist");-const target = path.join(targetDirectory, archiveName);-await mkdir(targetDirectory, { recursive: true });--if (await sha256(target) !== expected) {- let lastError;- for (let attempt = 1; attempt <= 4; attempt += 1) {- try {- let lastReportedPercent = -10;- const downloaded = await downloadArtifact({+const DOWNLOAD_ATTEMPTS = 4;+const DOWNLOAD_TIMEOUT_MS = 180_000;+const WINDOWS_EXECUTABLE = "electron.exe";++export async function prepareElectron() {+ const electronRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+ const electronModule = path.join(electronRoot, "node_modules", "electron");+ const electronPackage = JSON.parse(+ await readFile(path.join(electronModule, "package.json"), "utf8"),+ );+ const checksums = JSON.parse(+ await readFile(path.join(electronModule, "checksums.json"), "utf8"),+ );+ const version = electronPackage.version;+ const archiveName = `electron-v${version}-win32-x64.zip`;+ const expected = checksums[archiveName];+ if (!expected) throw new Error(`Official checksum is missing for ${archiveName}`);++ const cacheRoot = path.join(electronRoot, ".cache");+ const targetDirectory = path.join(cacheRoot, "electron-dist");+ const target = path.join(targetDirectory, archiveName);+ await mkdir(targetDirectory, { recursive: true });+ let currentAttempt = 0;+ let lastReportedPercent = -10;++ await acquireVerifiedArchive({+ target,+ expected,+ attempts: DOWNLOAD_ATTEMPTS,+ timeoutMs: DOWNLOAD_TIMEOUT_MS,+ download: ({ signal }) =>+ downloadArtifact({version,artifactName: "electron",platform: "win32",arch: "x64",+ checksums,+ cacheRoot: path.join(cacheRoot, "electron-get"),downloadOptions: {- signal: AbortSignal.timeout(180_000),+ signal,getProgressCallback: async ({ percent }) => {const currentPercent = Math.min(100, Math.floor(percent * 10) * 10);if (currentPercent >= lastReportedPercent + 10) {lastReportedPercent = currentPercent;- console.log(`Electron download attempt ${attempt}/4: ${currentPercent}%`);+ console.log(+ `Electron download attempt ${currentAttempt}/${DOWNLOAD_ATTEMPTS}: ` ++ `${currentPercent}%`,+ );}},},- });- await copyFile(downloaded, target);- lastError = undefined;- break;+ }),+ onAttempt: (attempt) => {+ currentAttempt = attempt;+ lastReportedPercent = -10;+ },+ });++ await installElectronRuntime({ electronModule, archive: target, version });+ console.log(`Electron archive and source runtime ready: ${target}`);+}++export async function acquireVerifiedArchive({+ target,+ expected,+ download,+ attempts = DOWNLOAD_ATTEMPTS,+ timeoutMs = DOWNLOAD_TIMEOUT_MS,+ sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),+ onAttempt = () => {},+}) {+ if (await sha256(target) === expected) return;++ let lastError;+ for (let attempt = 1; attempt <= attempts; attempt += 1) {+ onAttempt(attempt);+ try {+ const downloaded = await download({ signal: AbortSignal.timeout(timeoutMs), attempt });+ const actual = await sha256(downloaded);+ if (actual !== expected) {+ throw new Error(`checksum mismatch: expected ${expected}, got ${actual}`);+ }+ await replaceVerifiedFile(downloaded, target, expected);+ return;} catch (error) {lastError = error;- if (attempt < 4) {+ if (attempt < attempts) {const delayMs = attempt * 2_000;console.warn(- `Electron download attempt ${attempt}/4 failed; retrying in ${delayMs / 1_000}s`,+ `Electron download attempt ${attempt}/${attempts} failed: ${formatError(error)}; ` ++ `retrying in ${delayMs / 1_000}s`,);- await new Promise((resolve) => setTimeout(resolve, delayMs));+ await sleep(delayMs);}}}- if (lastError) throw lastError;+ throw new Error(+ `Electron download failed after ${attempts} bounded attempts: ${formatError(lastError)}`,+ { cause: lastError },+ );+}++export async function installElectronRuntime({ electronModule, archive, version }) {+ const dist = path.join(electronModule, "dist");+ const executable = path.join(dist, WINDOWS_EXECUTABLE);+ const versionFile = path.join(dist, "version");+ const pathFile = path.join(electronModule, "path.txt");+ if (+ (await readTrimmed(versionFile))?.replace(/^v/u, "") === version &&+ (await readTrimmed(pathFile)) === WINDOWS_EXECUTABLE &&+ (await exists(executable))+ ) {+ return;+ }++ const temporaryDist = `${dist}.tmp-${process.pid}-${randomUUID()}`;+ const temporaryPathFile = `${pathFile}.tmp-${process.pid}-${randomUUID()}`;+ try {+ await rm(temporaryDist, { recursive: true, force: true });+ await mkdir(temporaryDist, { recursive: true });+ await extractZip(archive, { dir: temporaryDist });++ const extractedExecutable = path.join(temporaryDist, WINDOWS_EXECUTABLE);+ const extractedVersion = (await readTrimmed(path.join(temporaryDist, "version")))?.replace(+ /^v/u,+ "",+ );+ if (!(await exists(extractedExecutable)) || extractedVersion !== version) {+ throw new Error(+ `Electron archive did not contain the expected Windows ${version} runtime`,+ );+ }++ const extractedTypes = path.join(temporaryDist, "electron.d.ts");+ if (await exists(extractedTypes)) {+ await copyFile(extractedTypes, path.join(electronModule, "electron.d.ts"));+ await rm(extractedTypes, { force: true });+ }++ await rm(dist, { recursive: true, force: true });+ await rename(temporaryDist, dist);+ await writeFile(temporaryPathFile, WINDOWS_EXECUTABLE, "utf8");+ await rm(pathFile, { force: true });+ await rename(temporaryPathFile, pathFile);+ } finally {+ await rm(temporaryDist, { recursive: true, force: true });+ await rm(temporaryPathFile, { force: true });+ }}-const actual = await sha256(target);-if (actual !== expected) {- throw new Error(`Electron checksum mismatch: expected ${expected}, got ${actual}`);+async function replaceVerifiedFile(source, target, expected) {+ const temporaryTarget = `${target}.tmp-${process.pid}-${randomUUID()}`;+ try {+ await copyFile(source, temporaryTarget);+ const copied = await sha256(temporaryTarget);+ if (copied !== expected) {+ throw new Error(`copied archive checksum mismatch: expected ${expected}, got ${copied}`);+ }+ await rm(target, { force: true });+ await rename(temporaryTarget, target);+ } finally {+ await rm(temporaryTarget, { force: true });+ }}-console.log(`Electron archive ready and verified: ${target}`);async function sha256(file) {try {- return createHash("sha256").update(await readFile(file)).digest("hex");+ await access(file);} catch (error) {if (error && error.code === "ENOENT") return undefined;throw error;}+ const hash = createHash("sha256");+ for await (const chunk of createReadStream(file)) hash.update(chunk);+ return hash.digest("hex");}++async function readTrimmed(file) {+ try {+ return (await readFile(file, "utf8")).trim();+ } catch (error) {+ if (error && error.code === "ENOENT") return undefined;+ throw error;+ }+}++async function exists(file) {+ try {+ await access(file);+ return true;+ } catch (error) {+ if (error && error.code === "ENOENT") return false;+ throw error;+ }+}++function formatError(error) {+ return error instanceof Error ? error.message : String(error);+}++const invokedAsScript = process.argv[1]+ ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url+ : false;+if (invokedAsScript) await prepareElectron();diff --git a/desktop/electron/scripts/test-packaging-preparation.mjs b/desktop/electron/scripts/test-packaging-preparation.mjsnew file mode 100644index 000000000..d3ce4c1c1--- /dev/null+++ b/desktop/electron/scripts/test-packaging-preparation.mjs@@ -0,0 +1,57 @@+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { acquireVerifiedArchive } from "./prepare-electron.mjs";++const temporaryRoot = await mkdtemp(path.join(os.tmpdir(), "vibe-electron-preparation-"));+try {+ const source = path.join(temporaryRoot, "source.zip");+ const target = path.join(temporaryRoot, "target.zip");+ const payload = Buffer.from("verified Electron fixture", "utf8");+ const expected = createHash("sha256").update(payload).digest("hex");+ await writeFile(source, payload);++ let attempts = 0;+ await acquireVerifiedArchive({+ target,+ expected,+ attempts: 3,+ sleep: async () => {},+ download: async ({ signal, attempt }) => {+ attempts += 1;+ assert.equal(attempt, attempts);+ assert.equal(signal.aborted, false);+ if (attempts < 3) throw new TypeError("fetch failed");+ return source;+ },+ });+ assert.equal(attempts, 3);+ assert.deepEqual(await readFile(target), payload);++ await acquireVerifiedArchive({+ target,+ expected,+ download: async () => {+ throw new Error("a verified cache hit must not download");+ },+ });++ const corrupt = path.join(temporaryRoot, "corrupt.zip");+ await writeFile(corrupt, "corrupt", "utf8");+ await assert.rejects(+ acquireVerifiedArchive({+ target: path.join(temporaryRoot, "rejected.zip"),+ expected,+ attempts: 2,+ sleep: async () => {},+ download: async () => corrupt,+ }),+ /failed after 2 bounded attempts: checksum mismatch/u,+ );++ console.log("Electron packaging preparation retries and checksum gates: OK");+} finally {+ await rm(temporaryRoot, { recursive: true, force: true });+}