Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Scope installer cleanup and public native test coverage
wyt6b4713fbea58
diff --git a/docs/test/windows-runtime-regression.md b/docs/test/windows-runtime-regression.mdindex 44a37c57..1e9b4903 100644--- a/docs/test/windows-runtime-regression.md+++ b/docs/test/windows-runtime-regression.md@@ -8,12 +8,12 @@ native smoke separately because it executes the bundled Whisper model.| Boundary | Windows difference and user risk | Automated regression / discovery probe | Packaged/manual residual || --- | --- | --- | --- |-| Paths and filesystems | Drive letters, case-insensitive NTFS, junctions, reserved names, quoted/space-containing PATH entries, file locks, and long paths can reject valid files, escape a workspace, or leave data undeletable. | Install pins accept only `<drive>:\.orkas`; path sandbox uses native case-insensitive containment and a real junction escape negative-control; conversation slugs reject reserved names; CLI lookup covers PATHEXT and quoted PATH; cleanup paths retry `EPERM`/`EBUSY`. | Exercise a non-ASCII/space-containing install and workspace, a path over 260 characters, OneDrive-controlled folders, and Defender-held temporary files. |+| Paths and filesystems | Drive letters, case-insensitive NTFS, junctions, reserved names, quoted/space-containing PATH entries, file locks, and long paths can reject valid files, escape a workspace, or leave data undeletable. | Path sandbox uses native case-insensitive containment and a real junction escape negative-control; conversation slugs reject reserved names; CLI lookup covers PATHEXT and quoted PATH; cleanup paths retry `EPERM`/`EBUSY`; source-data migration preserves the prior copy on publication failure and redacts early-boot errors. | Exercise a non-ASCII/space-containing install and workspace, a path over 260 characters, OneDrive-controlled folders, and Defender-held temporary files. || Processes and shells | PowerShell and cmd have different quoting, encoding, shim, signal, and descendant semantics; POSIX `mkdir -p` can bind as PowerShell `-Path` and fail after partial interpretation; killing the parent alone leaks work and locks files. | Preflight rejects high-confidence POSIX syntax (including `mkdir -p`) with PowerShell rewrite guidance; real PowerShell UTF-8 and npm-style `.cmd` argv round trips; OAuth and relaunch use bounded argv-only launch contracts; every production child-process owner has a focused suite in the serialized native lane; real parent/grandchild sentinels prove whole-tree termination. The local-CLI lane executes the governed Lark multiline/MCP stdio contracts with native Windows process semantics. | Inspect Task Manager after repeated cancel/timeout/relaunch cycles and confirm no console flashes, descendants, or locked work directories. |-| Official connector CLIs | A package may advertise Node compatibility but omit its Windows executable, fail behind `npx`, emit a startup warning as false success, or leave its cache locked after exit. | A Windows x64 canary uses the production authorization helper and direct `node npx-cli.js` path to verify the exact integrity-pinned WeCom, Feishu/Lark, DingTalk, and Xero packages: registry integrity, isolated download, executable discovery, real `--help` startup, clean stderr, and immediate cache removal. | Real account authorization and business API calls require provider accounts and remain release canaries; verify browser/device login, one read, one confirmed write, logout, and reconnect for each provider without using personal production data. |+| Official connector CLIs | A package may advertise Node compatibility but omit its Windows executable, fail behind `npx`, emit a startup warning as false success, or leave its cache locked after exit. | A Windows x64 canary uses the production authorization helper and direct `node npx-cli.js` path to verify the exact integrity-pinned WeCom, Feishu/Lark, DingTalk, and Xero packages: a child PATH containing only bundled Node and Windows system tools (never CI/system Node), a no-Node negative control, exact bundled-Node resolution, registry integrity, isolated download, executable discovery, real `--help` startup, clean stderr, and immediate cache removal. The owning cross-platform cases also run real offline npm lifecycle scripts with missing/shadowing system Node, space/non-ASCII runtime paths, install failure without a ready marker, and successful retry before authorization/MCP access. | Real account authorization and business API calls require provider accounts and remain release canaries; verify browser/device login, one read, one confirmed write, logout, and reconnect for each provider without using personal production data. || Source startup without system Node | `run.cmd` must bootstrap the pinned runtime before any JavaScript can execute; a partial download, corrupt marker, bad hash, or failed directory swap can otherwise leave development startup permanently broken. | Cross-platform wiring/manifest contract plus a real Windows PowerShell integration using an actual zip and Node executable: first install, verified cache, corrupt-marker repair, hash rejection, temp cleanup, and failed-swap rollback. | On clean x64 and Arm64 hosts with Node removed from PATH, launch `run.cmd` through Explorer and a path containing spaces/non-ASCII characters. || Window and OS integration | Negative monitor coordinates, DPI/topology changes, minimized close bounds, registry command parsing, AppUserModelID, notification policy, and protocol cold launch differ from macOS. | Window state preserves visible left-monitor coordinates, drops disconnected positions, and ignores minimized sentinel bounds; registry cleanup rejects executable look-alikes; notification probes are hidden/bounded and escape the app id; deep-link registration has argv/error coverage. | Verify mixed-DPI monitor removal/reconnect, sleep/resume, notification Group Policy, default-app changes, and cold/second-instance `orkas://` activation. |-| Install, update, and packaging | NSIS pending-cache shape, app-local VC DLL closure, PE architecture, native ABI, signing, installer elevation, and antivirus scanning can make a build pass source tests but fail after install. | Windows pending `.exe` restore and stale/traversal rejection; PE/ABI/DLL/license/package gates; an unsigned release-shaped NSIS build runs packaged-app and native smokes in CI. | Test signed upgrade/downgrade/reinstall/uninstall as standard and admin users; verify data retention and rollback after interrupted install. |+| Install and packaging | App-local VC DLL closure, PE architecture, native ABI, signing, installer elevation, and antivirus scanning can make a build pass source tests but fail after install. | PE/ABI/DLL/license/package gates; Windows shutdown and installer process ownership; NSIS compilation requires an installed public compiler; installer execution remains Windows-only. | Build the public Windows package and run packaged-app/native checks; test signed upgrade/downgrade/reinstall/uninstall as standard and admin users, including data retention and interrupted installation. || Performance and recovery | Process creation is slower, file handles are retained longer, and native CPU dispatch can regress latency or destabilize concurrent tests. | Windows unit workers are serialized; native Whisper has a 60-second budget/90-second hard limit; high-risk process-tree cases repeat three times in isolated Vitest processes so forced handle closure cannot contaminate the next owner. | Record cold/warm startup, handle/process count, working set, Whisper latency, and cleanup time with Defender enabled and after sleep/resume. |## Embedded-browser phone passkey canary (pending hardware)@@ -52,14 +52,26 @@ results are recorded.## Automated coverage+`npm run test:runtime-path` runs the focused environment regression entry through+the Electron test runner: missing/shadowing system Node, offline npm lifecycle+scripts, space/non-ASCII runtime paths, nested Skill commands, and bundled+runtime/reference-process contracts. This is a local focused entry; neither+public workflow currently invokes it. `Native dependency repair` runs its listed+native/ABI regression suites on Windows, macOS and Linux; `Linux source smoke`+also runs the Linux desktop/native lane. Run and retain the Windows-native,+stability and packaged-app checks separately; those workflows do not establish+their results.++The process-owner inventory covers shipped `bin` JavaScript helpers as well as+`src` modules. A new child-process owner requires a behavioral suite in each+applicable native lane; negative controls check discovery and failure propagation.+- Process lifecycle: OfficeCLI, ffmpeg/ffprobe, VideoStudio native helpers,package commands, and local-agent version probes use hidden windows, boundedoutput, prompt timeout/abort settlement, and whole-tree termination. Realparent/grandchild cases verify that a descendant cannot outlive its parent andwrite a delayed sentinel file.-- Windows paths: install pins reject UNC, device-namespace, nested, and- prefix-look-alike paths; the drive probe resolves through the actual- `SystemRoot`; registry cleanup matches the exact executable token; sandbox+- Windows paths: sandboxcontainment and skill imports compare case-insensitively without prefix falsepositives; a real junction cannot escape the workspace.- Shell and launch integrity: local-agent `.cmd` shims round-trip hostile argv;@@ -71,12 +83,14 @@ results are recorded.- No-Node source startup: `run.cmd` invokes the PowerShell bootstrap beforedependency preparation; the pinned manifest selects x64/Arm64, cache reuserequires marker/files/executable version, and download size/SHA plus Node- self-check complete before an atomic swap. Windows native CI injects a failed- swap and proves the prior runnable payload returns.-- Desktop state and updates: negative-coordinate monitor positions remain- usable, minimized shutdown does not persist Windows sentinel bounds, and a- packaged NSIS `.exe` is restored only from the validated updater pending- directory.+ self-check complete before an atomic swap. The Windows bootstrap integration+ injects a failed swap and requires the prior runnable payload to return. Run+ it through `npm run test:windows-native` on Windows and retain its result;+ the existing public CI workflows do not execute that integration.+- Desktop state and installation: negative-coordinate monitor positions remain+ usable and minimized shutdown does not persist Windows sentinel bounds.+ Shutdown and installer cleanup target this installation's process tree;+ failure and retry cases preserve unrelated running applications.- Document recognition: local OCR installation and execution are retired.Images use model input and scanned PDFs use bounded page rendering; atext-only model requests readable text or a vision-capable model.@@ -92,9 +106,14 @@ Primary suites:- `src/core-agent/test/oauth-flow.test.ts`- `src/core-agent/test/process-session.test.ts`-- `test/main/features/app_update.test.ts`-- `test/main/features/account/windows_protocol.test.ts`-- `test/main/features/dev_relaunch.test.ts`+- `test/main/features/connectors/protocol.test.ts`+- `test/main/features/connectors/oauth-dcr.test.ts`+- `test/main/features/connectors/local-cli.test.ts`+- `test/main/index-process.test.ts`+- `test/main/util/shutdown.test.ts`+- `test/main/util/windows-shutdown-processes.test.ts`+- `test/main/util/windows-installer-processes.test.ts`+- `test/main/util/nsis-installer-processes.test.ts`- `test/main/features/local_agents/version.test.ts`- `test/main/features/local_agents/which.test.ts`- `test/main/features/office/office_engine.test.ts`@@ -104,7 +123,8 @@ Primary suites:- `test/main/features/video_gen.test.ts`- `test/main/features/video_studio_native_qa.test.ts`- `test/main/features/window_state.test.ts`-- `test/main/install-data-root.test.ts`+- `test/main/util/migrate-source-data-root.test.ts`+- `test/main/ipc/app-data-root.test.ts`- `test/main/platform-process-coverage.test.ts`- `test/main/quality/report.test.ts`- `test/main/util/fetch-whisper.test.ts`@@ -112,47 +132,55 @@ Primary suites:- `test/main/util/path-sandbox.test.ts`- `test/main/util/prepare-win-native-deps.test.ts`- `test/main/util/windows-node-bootstrap-contract.test.ts`-- the separately authorized model canary-- the separately authorized model canary-- the separately authorized model canary-- the separately authorized model canary- `test/windows/windows-node-bootstrap.integration.ps1` (real Windows lane)- `test/windows/windows-local-cli.integration.mjs` (real Windows x64 package lane)## Required commands+The compiled NSIS suite requires a working public `makensis` on PATH, or an+absolute `ORKAS_TEST_MAKENSIS` path. For an extracted electron-builder NSIS+toolchain, set `ELECTRON_BUILDER_NSIS_DIR` to its resource root; this also supplies+`NSISDIR`. Tests do not download a compiler or depend on a private `product/`+directory. Missing or failed compilation is a test infrastructure failure, not a+skipped pass. macOS compiles the production hook and all four fault fixtures;+only Windows executes the installers and verifies file-lock release and retry.++On macOS 14 or newer, use a compiler containing the upstream+[UTF-32 conversion fix](https://github.com/NSIS-Dev/nsis/commit/2532ccae34d3fdd183575177f2486bc9e2922642)+and its [function-order correction](https://github.com/NSIS-Dev/nsis/commit/f0bfe3e0062c57dc1ef90f1d235c7c0bd5a43be4).+Unpatched 3.13 can abort while generating language tables; a successful+`makensis -VERSION` alone does not prove compilation works.+1. Run `npm run typecheck`.2. Run `npm test` for the full JavaScript and Python resource suites.-3. Run `npm run test:model-regression:windows` for the deterministic Windows- model-evaluation contracts and host-sensitive fixtures.-4. Run `npm run eval:model:regression:windows:validate` to verify that every- required live case, Agent, fixture, tool, and reality contract is runnable.-5. Run `npm run test:platform-native` so every system/command owner is repeated- in one serialized native-host process lane.-6. Run `npm run test:coverage` and investigate every failure; do not accept a+3. Run `npm run test:platform-native` in a desktop session. The serialized+ native-host suites are followed by real Electron composition-inspect and+ background-browser-input canaries; a missing display fails the lane.+4. Run `npm run test:coverage` and investigate every failure; do not accept aworker crash, unhandled rejection, `EPERM`, or leaked-handle warning as anunrelated test issue.-7. Run `npm run test:windows-native`. The real PowerShell no-Node bootstrap+5. On Windows, run `npm run test:windows-native`. The real PowerShell no-Node bootstrapintegration runs first; the Windows x64 connector canary then downloads andstarts every exact official CLI package without accessing an account; bundledWhisper must finally finish within its 60-second performance budget andbefore the 90-second hard limit.-8. Run `npm run test:windows-stability`. It repeats the real persistent-process+6. On Windows, run `npm run test:windows-stability`. It repeats the real persistent-processand descendant-termination cases three times. After the loop, no test-owned`node.exe`, `cmd.exe`, ffmpeg, ffprobe, OfficeCLI, or delayed sentinel shouldremain.-Before a Windows release, and whenever a listed Agent prompt, tool surface,-fixture, native runtime, renderer, or acceptance contract changes, also run-`npm run eval:model:regression:windows -- --save` and inspect the full model,-tool, artifact, render, cleanup, and process logs.+The Windows-only commands report a skip on other hosts; that is not Windows+execution evidence. Record the actual OS, commands, skips, diagnostics and+process cleanup for a Windows release. These deterministic/native commands do+not call a chat or generation provider; the bundled Whisper smoke performs+local inference. Real connector authorization and phone-passkey journeys remain+the manual checks described above.-The cross-platform unit workflow enforces type-checking, the native-host lane,-the real bundled Windows Whisper smoke, and the repeated Windows stability-lane. The `Windows release gates` workflow also runs Windows coverage on its-scheduled/manual lane and builds an unsigned release-shaped NSIS package when-packaging/runtime inputs change, weekly, or on demand. That package job uses the-same final-artifact validators and packaged-app smokes as a local product build.+The public `Native dependency repair` workflow exercises native repair and+focused Electron regressions on Windows, macOS and Linux. The `Linux source+smoke` workflow additionally runs the Linux desktop/native lane. Windows+coverage, stability, native inference and packaged-app acceptance must be run+and recorded separately; these workflows do not establish those results.The review found that `bootstrap-node.ps1` was a production startup entry withno test owner. It also exited the caller on a cache hit, preventing safe@@ -164,7 +192,7 @@ cross-platform contract only guards wiring and pinned inventory.## Manual packaged-app checks1. Launch from Explorer with no developer-shell PATH and confirm local CLIs,- registry protocol handling, notifications, OfficeCLI, ffmpeg/ffprobe, and+ connector OAuth callbacks, notifications, OfficeCLI, ffmpeg/ffprobe, andWhisper resolve without a visible console window.2. Cancel and time out one Office, video, media-probe, and package operation.Confirm Task Manager shows no descendants and the working files can bediff --git a/package.json b/package.jsonindex 684828ab..68734376 100644--- a/package.json+++ b/package.json@@ -337,6 +337,9 @@],"rfc3161TimeStampServer": "http://ts.ssl.com"}+ },+ "nsis": {+ "include": "scripts/windows-installer.nsh"}},"license": "MIT",diff --git a/scripts/run-platform-native-tests.mjs b/scripts/run-platform-native-tests.mjsindex 800fc348..4340eece 100644--- a/scripts/run-platform-native-tests.mjs+++ b/scripts/run-platform-native-tests.mjs@@ -35,6 +35,7 @@ const commonSuites = ['test/main/model/core-agent/html-preview-tool.test.ts','test/main/features/html_preview.test.ts','test/main/features/connectors/local-cli.test.ts',+ 'test/main/features/connectors/local-cli-stdio-adapter.test.ts','test/main/model/local-tools.test.ts','test/main/model/core-agent/video-studio-state-tool.test.ts','test/main/model/core-agent/image-studio-tool.test.ts',@@ -42,30 +43,37 @@ const commonSuites = ['test/main/model/core-agent/pdf-tools.test.ts','test/main/features/office/office_engine.test.ts','test/main/features/notification_permissions.test.ts',+ 'test/main/features/connectors/mcp-client.test.ts',+ 'test/main/util/shutdown.test.ts','test/main/features/generation_reference_assets.test.ts','test/main/index-process.test.ts','test/main/features/local_agents/base.test.ts',+ 'test/main/features/local_agents/bridge_skill_runner.test.ts','test/main/features/local_agents/spawn-command.test.ts','test/main/features/local_agents/version.test.ts','test/main/features/local_agents/upgrade.test.ts','test/main/util/bundled-runtime.test.ts','test/main/util/run-skill.test.ts',+ 'test/main/util/orkas-pkg.test.ts',+ 'test/main/util/sharp-runtime.test.ts','test/main/features/packages.test.ts','test/main/util/extract-xls.test.ts','test/main/util/media_probe.test.ts','test/main/features/video_studio_native_qa.test.ts','test/main/features/video_studio_delivery.test.ts','test/main/paths.test.ts',- 'test/main/install-data-root.test.ts',+ 'test/main/util/migrate-source-data-root.test.ts','test/main/features/web_assist_passkey.test.ts',];const platformSuites = process.platform === 'win32'? ['test/main/features/connectors/local-cli-lark-contract.test.ts',- 'test/main/features/connectors/local-cli-stdio-adapter.test.ts','test/main/util/prepare-win-native-deps.test.ts','test/main/util/fetch-win-vc-runtime.test.ts',+ 'test/main/util/windows-shutdown-processes.test.ts',+ 'test/main/util/windows-installer-processes.test.ts',+ 'test/main/util/nsis-installer-processes.test.ts',]: process.platform === 'darwin'? [diff --git a/scripts/run-windows-stability-tests.mjs b/scripts/run-windows-stability-tests.mjsindex 7cfa359a..d31fb3a0 100644--- a/scripts/run-windows-stability-tests.mjs+++ b/scripts/run-windows-stability-tests.mjs@@ -21,6 +21,10 @@ const testNamePattern = ['terminates the complete Windows FFmpeg process tree','kills a real Windows ffprobe-style process tree','P1 terminates a real Windows video subprocess tree',+ 'stops orphaned and late Windows descendants',+ 'releases a Windows MCP descendant file lock',+ 'stops only this installation',+ 'releases orphaned app/runtime executables',].join('|');const suites = ['src/core-agent/test/process-session.test.ts',@@ -29,6 +33,9 @@ const suites = ['test/main/features/packages.test.ts','test/main/features/generation_reference_assets.test.ts','test/main/util/media_probe.test.ts',+ 'test/main/util/windows-shutdown-processes.test.ts',+ 'test/main/util/windows-installer-processes.test.ts',+ 'test/main/features/connectors/mcp-client.test.ts','test/main/features/video_studio_native_qa.test.ts',];diff --git a/scripts/windows-installer-processes.ps1 b/scripts/windows-installer-processes.ps1new file mode 100644index 00000000..fd843979--- /dev/null+++ b/scripts/windows-installer-processes.ps1@@ -0,0 +1,98 @@+param(+ [Parameter(Mandatory = $true)][string]$InstallDir,+ [Parameter(Mandatory = $true)][int]$InstallerProcessId+)++$ErrorActionPreference = 'Stop'+$clock = [Diagnostics.Stopwatch]::StartNew()+try {+ $directory = [IO.Path]::GetFullPath($InstallDir).TrimEnd('\')+ if (-not [IO.Path]::IsPathRooted($InstallDir) -or+ $directory -eq [IO.Path]::GetPathRoot($directory).TrimEnd('\') -or+ $InstallerProcessId -le 0) { throw 'invalid_target' }+ # Fresh installs have nothing to stop. Do not interpret an arbitrary parent+ # directory as an installation and terminate programs in its child folders.+ # Accept either marker so a partially removed old executable can recover.+ if (-not [IO.File]::Exists([IO.Path]::Combine($directory, 'Orkas.exe')) -and+ -not [IO.File]::Exists([IO.Path]::Combine($directory, 'resources', 'app.asar'))) { exit 0 }+ # A separator boundary protects sibling installations such as Orkas-other.+ $prefix = $directory + '\'+ for ($pass = 0; $pass -lt 4; $pass++) {+ $targets = [Collections.Generic.List[object]]::new()+ $ancestry = @{}+ $query = [System.Management.ManagementObjectSearcher]::new('SELECT ProcessId,ParentProcessId,ExecutablePath,CreationDate FROM Win32_Process')+ $rows = $null+ try {+ $rows = $query.Get()+ foreach ($row in $rows) {+ $candidate = $null+ try {+ $id = [int]$row.ProcessId+ $image = [string]$row.ExecutablePath+ if ([string]::IsNullOrWhiteSpace([string]$row.CreationDate)) {+ if ($image.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw 'process_identity_unavailable' }+ continue+ }+ if ($ancestry.Count -ge 16384 -or $clock.ElapsedMilliseconds -ge 12000) { throw 'snapshot_limit' }+ $snapshotStarted = [System.Management.ManagementDateTimeConverter]::ToDateTime([string]$row.CreationDate).ToUniversalTime()+ $ancestry[$id] = @{ Parent = [int]$row.ParentProcessId; Started = $snapshotStarted }+ if ($id -eq $PID -or $id -eq $InstallerProcessId -or+ -not $image.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { continue }+ if ($targets.Count -ge 4096 -or $clock.ElapsedMilliseconds -ge 12000) { throw 'cleanup_limit' }+ try {+ $candidate = [Diagnostics.Process]::GetProcessById($id)+ # Pin the handle and verify creation time before acting on a WMI PID.+ $null = $candidate.Handle+ $started = $candidate.StartTime.ToUniversalTime()+ } catch [ArgumentException] { continue } # The process already exited.+ catch [InvalidOperationException] { continue }+ if (($started.Ticks - ($started.Ticks % 10)) -ne $snapshotStarted.Ticks) { continue }+ $targets.Add($candidate)+ $candidate = $null+ } finally {+ if ($null -ne $candidate) { $candidate.Dispose() }+ $row.Dispose()+ }+ }+ # A new uninstaller can be called by an installer stored inside the app+ # directory. Preserve the helper's real control ancestry, not just one PID.+ $protected = [Collections.Generic.HashSet[int]]::new()+ $null = $protected.Add($PID)+ $null = $protected.Add($InstallerProcessId)+ $visited = [Collections.Generic.HashSet[int]]::new()+ $null = $visited.Add($PID)+ $cursor = $PID+ for ($depth = 0; $depth -lt 32; $depth++) {+ $record = $ancestry[$cursor]+ if ($null -eq $record -or $record.Parent -le 0) { break }+ $parent = $ancestry[$record.Parent]+ # A recycled parent PID starts after its old child and is not ancestry.+ if ($null -eq $parent -or $parent.Started -gt $record.Started) { break }+ if (-not $visited.Add($record.Parent)) { break }+ $null = $protected.Add($record.Parent)+ $cursor = $record.Parent+ }+ $remaining = @($targets | Where-Object { -not $protected.Contains($_.Id) })+ if ($remaining.Count -eq 0) { exit 0 }+ foreach ($target in $remaining) {+ if ($clock.ElapsedMilliseconds -ge 12000) { throw 'cleanup_timeout' }+ try {+ if (-not $target.HasExited) { $target.Kill() }+ if (-not $target.WaitForExit(500)) { throw 'termination_incomplete' }+ } catch {+ if (-not $target.HasExited) { throw }+ }+ }+ } finally {+ foreach ($target in $targets) { $target.Dispose() }+ if ($null -ne $rows) { $rows.Dispose() }+ $query.Dispose()+ }+ # Recheck after termination to catch a helper spawned during the sweep.+ Start-Sleep -Milliseconds 200+ }+ throw 'cleanup_incomplete'+} catch {+ [Console]::Error.WriteLine('Installer process cleanup failed.')+ exit 1+}diff --git a/scripts/windows-installer.nsh b/scripts/windows-installer.nshnew file mode 100644index 00000000..16002538--- /dev/null+++ b/scripts/windows-installer.nsh@@ -0,0 +1,40 @@+!define ORKAS_INSTALLER_CLEANUP "${__FILEDIR__}\windows-installer-processes.ps1"++; One scoped check owns both installer and uninstaller cleanup. Do not fall+; through to the upstream directory-prefix/image-name process check.+!macro orkasCheckAppProcesses+ InitPluginsDir+ File /oname=$PLUGINSDIR\orkas-installer-cleanup.ps1 "${ORKAS_INSTALLER_CLEANUP}"+ Push $R0+ Push $0+ System::Call 'kernel32::GetCurrentProcessId() i .r0'+ ${if} ${isUpdated}+ ; The app has already saved its state; allow its normal exit to finish.+ Sleep 1000+ ${endif}++ orkas_cleanup_retry:+ ${if} ${RunningX64}+ ${DisableX64FSRedirection}+ ${endif}+ nsExec::Exec /TIMEOUT=20000 '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\orkas-installer-cleanup.ps1" -InstallDir "$INSTDIR" -InstallerProcessId $0'+ Pop $R0+ ${if} ${RunningX64}+ ${EnableX64FSRedirection}+ ${endif}+ ${if} $R0 != 0+ MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "$(appCannotBeClosed)" /SD IDCANCEL IDRETRY orkas_cleanup_retry+ SetErrorLevel 2+ Quit+ ${endif}+ Pop $0+ Pop $R0+!macroend++!macro customInit+ !insertmacro orkasCheckAppProcesses+!macroend++!macro customCheckAppRunning+ !insertmacro orkasCheckAppProcesses+!macroenddiff --git a/test/helpers/nsis-installer-scenario.ts b/test/helpers/nsis-installer-scenario.tsnew file mode 100644index 00000000..54988a6b--- /dev/null+++ b/test/helpers/nsis-installer-scenario.ts@@ -0,0 +1,165 @@+import assert from 'node:assert/strict';+import { spawn, spawnSync, type ChildProcess } from 'node:child_process';+import { once } from 'node:events';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++export type CleanupFixture = 'real' | 'failed' | 'timeout' | 'disabled';+export type InstallerFixtures = Record<CleanupFixture, string>;++export interface NsisTool {+ path: string;+ env?: NodeJS.ProcessEnv;+}++/** Use an installed public compiler; resolving a test tool never downloads it. */+export function resolveNsisTool(env: NodeJS.ProcessEnv = process.env, platform = process.platform): NsisTool {+ const configured = env.ORKAS_TEST_MAKENSIS?.trim();+ const directory = env.ELECTRON_BUILDER_NSIS_DIR?.trim();+ if (configured && !path.isAbsolute(configured)) throw new Error('ORKAS_TEST_MAKENSIS must be an absolute compiler path');+ if (directory && !path.isAbsolute(directory)) throw new Error('ELECTRON_BUILDER_NSIS_DIR must be an absolute toolchain path');+ return {+ path: configured || (directory+ ? path.join(directory, platform === 'darwin' ? 'mac' : platform === 'win32' ? 'Bin' : 'linux',+ platform === 'win32' ? 'makensis.exe' : 'makensis')+ : platform === 'win32' ? 'makensis.exe' : 'makensis'),+ ...(directory ? { env: { NSISDIR: directory } } : {}),+ };+}++/** Compile the production hook; substitute only the helper for explicit fault+ * fixtures. No registry, real installation, certificate, or user profile writes. */+export async function buildInstallerFixtures(+ pcRoot: string, destination: string, tool: NsisTool = resolveNsisTool(),+): Promise<InstallerFixtures> {+ const escape = (value: string) => value.replaceAll('$', '$$');+ const payload = path.join(destination, 'runtime-payload.txt');+ fs.writeFileSync(payload, 'new-runtime');+ const result = {} as InstallerFixtures;+ for (const fault of ['real', 'failed', 'timeout', 'disabled'] as const) {+ const cleanup = path.join(destination, `${fault}.ps1`);+ if (fault !== 'real') fs.writeFileSync(cleanup, {+ failed: 'exit 1', timeout: 'Start-Sleep -Seconds 60', disabled: 'exit 0',+ }[fault]);+ const executable = path.join(destination, `${fault}.exe`);+ const script = path.join(destination, `${fault}.nsi`);+ fs.writeFileSync(script, `Unicode true+RequestExecutionLevel user+!include LogicLib.nsh+!include x64.nsh+!define isUpdated '"1" == "1"'+Name "Orkas installation regression"+OutFile "${escape(executable)}"+InstallDir "$TEMP\\Orkas-installation-test"+LangString appCannotBeClosed 1033 "Orkas cannot be closed."+!include "${escape(path.join(pcRoot, 'scripts/windows-installer.nsh'))}"+${fault === 'real' ? '' : `!undef ORKAS_INSTALLER_CLEANUP\n!define ORKAS_INSTALLER_CLEANUP "${escape(cleanup)}"`}+Function .onInit+ !insertmacro customInit+FunctionEnd+Function .onInstFailed+ SetErrorLevel 2+FunctionEnd+Section+ SetOutPath "$INSTDIR\\runtime"+ File /oname=node.exe "${escape(payload)}"+ SetOutPath "$INSTDIR"+ FileOpen $0 "$INSTDIR\\version.txt" w+ FileWrite $0 "version-2"+ FileClose $0+SectionEnd+`);+ const compiled = spawnSync(tool.path, ['-V3', script], {+ env: { ...process.env, ...tool.env }, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024, windowsHide: true,+ });+ assert.equal(compiled.error, undefined,+ 'NSIS compiler unavailable; install makensis or set ORKAS_TEST_MAKENSIS / ELECTRON_BUILDER_NSIS_DIR');+ assert.equal(compiled.status, 0,+ `NSIS fixture compilation failed (signal ${compiled.signal || 'none'}):\n${compiled.stdout}\n${compiled.stderr}`);+ assert.equal(compiled.stderr, '');+ assert.doesNotMatch(compiled.stdout, /warning \d+:/i);+ assert.equal(fs.readFileSync(executable).subarray(0, 2).toString(), 'MZ');+ result[fault] = executable;+ }+ return result;+}++export async function exerciseNsisInstaller(node: string, fixtures: InstallerFixtures, fault: CleanupFixture) {+ assert.equal(process.platform, 'win32');+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "Orkas NSIS 测试 ' "));+ const install = path.join(root, 'Orkas');+ const sibling = `${install}-other`;+ fs.mkdirSync(path.join(install, 'runtime'), { recursive: true });+ fs.mkdirSync(sibling);+ const images = [path.join(install, 'Orkas.exe'), path.join(install, 'runtime/node.exe'), path.join(sibling, 'Orkas.exe')];+ const children: ChildProcess[] = [];+ const errors: string[] = [];+ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };+ const version = path.join(install, 'version.txt');+ const data = path.join(install, 'data.json');+ fs.writeFileSync(version, 'version-1');+ fs.writeFileSync(data, '{"retained":true}');+ const run = (kind: CleanupFixture) => {+ // Execute inside the installation directory to test the real PID exclusion.+ const installer = path.join(install, 'setup.exe');+ fs.copyFileSync(fixtures[kind], installer);+ return spawnSync(installer, ['/S', '/D=' + install], {+ windowsVerbatimArguments: true, windowsHide: true, timeout: 30_000, encoding: 'utf8', maxBuffer: 64 * 1024,+ });+ };+ const verifyInstalled = (installed: ReturnType<typeof run>) => {+ assert.equal(installed.error, undefined);+ assert.equal(installed.status, 0);+ assert.equal(installed.stdout + installed.stderr, '');+ assert.equal(fs.readFileSync(version, 'utf8'), 'version-2');+ assert.equal(fs.readFileSync(images[1], 'utf8'), 'new-runtime');+ assert.equal(alive(children[0].pid!), false);+ assert.equal(alive(children[1].pid!), false);+ assert.equal(alive(children[2].pid!), true);+ assert.equal(fs.readFileSync(data, 'utf8'), '{"retained":true}');+ };+ try {+ for (const image of images) {+ fs.copyFileSync(node, image);+ const child = spawn(image, ['-e', "console.log('ready');setTimeout(()=>{},90000)"], {+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,+ env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined },+ });+ children.push(child);+ child.stderr!.on('data', bytes => errors.push(String(bytes)));+ await once(child.stdout!, 'data', { signal: AbortSignal.timeout(5000) });+ }+ // Prove that skipping cleanup would encounter a real locked executable.+ assert.throws(() => fs.writeFileSync(images[1], 'new-runtime'));+ if (fault !== 'real') {+ const oldImage = fs.readFileSync(images[1]);+ const failed = run(fault);+ assert.equal(failed.error, undefined, 'Installer must stop by itself before the harness deadline');+ assert.equal(failed.stdout + failed.stderr, '');+ if (fault === 'disabled') {+ // Mutation control: a silent NSIS File instruction can ignore a locked+ // image and still return zero/write the version marker. The exact same+ // success oracle must reject this incomplete installation.+ assert.throws(() => verifyInstalled(failed), 'The oracle accepted disabled cleanup');+ } else {+ assert.equal(failed.status, 2);+ assert.equal(fs.readFileSync(version, 'utf8'), 'version-1');+ }+ assert.deepEqual(fs.readFileSync(images[1]), oldImage);+ assert.equal(children.every(child => alive(child.pid!)), true);+ }+ const installed = run('real');+ verifyInstalled(installed);+ assert.deepEqual(errors, []);+ return { fault, installedVersion: 2, siblingPreserved: true, userDataPreserved: true };+ } finally {+ await Promise.all(children.map(async child => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const closed = once(child, 'close', { signal: AbortSignal.timeout(5000) });+ child.kill();+ await closed;+ }));+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ }+}diff --git a/test/helpers/windows-installer-scenario.ts b/test/helpers/windows-installer-scenario.tsnew file mode 100644index 00000000..1511d7cd--- /dev/null+++ b/test/helpers/windows-installer-scenario.ts@@ -0,0 +1,96 @@+import assert from 'node:assert/strict';+import { spawn, spawnSync, type ChildProcess } from 'node:child_process';+import { once } from 'node:events';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++// Shared by the native test lane and the isolated remote Windows probe.+export async function exerciseWindowsInstaller(node: string, script: string) {+ assert.equal(process.platform, 'win32');+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "Orkas install 测试 ' "));+ const install = path.join(root, 'Orkas');+ const sibling = `${install}-other`;+ const runtime = path.join(install, 'resources/runtime/node');+ fs.mkdirSync(runtime, { recursive: true });+ fs.mkdirSync(sibling);+ const stockNode = node;+ assert.ok(stockNode);+ const executables = [+ path.join(install, 'Orkas.exe'), path.join(runtime, 'node.exe'),+ path.join(sibling, 'Orkas.exe'), path.join(install, 'installer.exe'),+ ];+ for (const file of executables) fs.copyFileSync(stockNode, file);+ const children: ChildProcess[] = [];+ const errors: string[] = [];+ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };+ try {+ for (const file of executables) {+ const child = spawn(file, ['-e', "console.log('ready');setTimeout(()=>{},60000)"], {+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,+ env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined },+ });+ children.push(child);+ child.stderr!.on('data', bytes => errors.push(String(bytes)));+ await once(child.stdout!, 'data', { signal: AbortSignal.timeout(5000) });+ }+ // Independent negative control: a running image cannot be overwritten.+ assert.throws(() => fs.copyFileSync(stockNode, executables[1]));+ const powershell = path.win32.join(process.env.SystemRoot!, 'System32/WindowsPowerShell/v1.0/powershell.exe');+ const run = (target: string) => spawnSync(powershell, [+ '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',+ '-File', script, '-InstallDir', target, '-InstallerProcessId', String(children[3].pid),+ ], { timeout: 25_000, encoding: 'utf8', windowsHide: true });+ const invalid = run(path.parse(install).root);+ assert.equal(invalid.status, 1);+ assert.equal(invalid.stdout, '');+ assert.equal(invalid.stderr.trim(), 'Installer process cleanup failed.');+ assert.equal(children.every(child => alive(child.pid!)), true);+ // A parent folder is not the installed app, even when it contains one.+ // Selecting it must not expand cleanup to all sibling installations.+ const parent = run(root);+ assert.equal(parent.status, 0);+ assert.equal(parent.stdout + parent.stderr, '');+ assert.equal(children.every(child => alive(child.pid!)), true, 'A non-installation parent directory broadened cleanup');+ const result = run(install);+ assert.equal(result.error, undefined);+ assert.equal(result.status, 0);+ assert.equal(result.stdout + result.stderr, '');+ assert.equal(alive(children[0].pid!), false);+ assert.equal(alive(children[1].pid!), false);+ assert.equal(alive(children[2].pid!), true);+ assert.equal(alive(children[3].pid!), true);+ fs.copyFileSync(stockNode, executables[1]);+ // An interrupted uninstall can remove Orkas.exe first. Its ASAR still+ // identifies the installation; a subsequently orphaned runtime must close.+ fs.unlinkSync(executables[0]);+ fs.writeFileSync(path.join(install, 'resources', 'app.asar'), 'fixture app marker');+ const residual = spawn(executables[1], ['-e', "console.log('ready');setTimeout(()=>{},60000)"], {+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,+ env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined },+ });+ children.push(residual);+ residual.stderr!.on('data', bytes => errors.push(String(bytes)));+ await once(residual.stdout!, 'data', { signal: AbortSignal.timeout(5000) });+ const retry = run(install);+ assert.equal(retry.status, 0);+ assert.equal(retry.stdout + retry.stderr, '');+ assert.equal(alive(residual.pid!), false, 'A partial installation retained its orphaned runtime');+ assert.equal(alive(children[2].pid!), true);+ assert.equal(alive(children[3].pid!), true);+ fs.copyFileSync(stockNode, executables[1]);+ const emptyRetry = run(install);+ assert.equal(emptyRetry.status, 0);+ assert.equal(emptyRetry.stdout + emptyRetry.stderr, '');+ } finally {+ await Promise.all(children.map(async child => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const closed = once(child, 'close', { signal: AbortSignal.timeout(5000) });+ child.kill();+ await closed;+ }));+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ }+ assert.deepEqual(errors, []);+ return { fileReplaced: true, siblingPreserved: true, installerPreserved: true, invalidTargetRejected: true, parentDirectoryPreserved: true, partialInstallRecovered: true, retrySucceeded: true };+}diff --git a/test/main/platform-process-coverage.test.ts b/test/main/platform-process-coverage.test.tsindex 2cf01429..838b717a 100644--- a/test/main/platform-process-coverage.test.ts+++ b/test/main/platform-process-coverage.test.ts@@ -1,10 +1,43 @@import * as fs from 'node:fs';import * as path from 'node:path';+import * as os from 'node:os';++import * as vm from 'node:vm';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';+import * as ts from 'typescript';import { describe, expect, it } from 'vitest';+const nativeRequire = createRequire(import.meta.url);+function nativeSuiteSelection(source: string, platform: 'darwin' | 'win32' | 'linux', childStatus = 0): string[] {+ const runner = path.resolve('scripts/run-platform-native-tests.mjs');+ const calls: string[][] = [];+ const exit = Symbol('runner exit');+ const code = ts.transpileModule(source.replaceAll('import.meta.url', JSON.stringify(pathToFileURL(runner).href)), {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ try {+ vm.runInNewContext(code, {+ exports: {},+ require: (name: string) => name === 'node:child_process'+ ? { spawnSync: (_executable: string, args: string[]) => { calls.push(args); return { status: childStatus }; } }+ : nativeRequire(name),+ process: { platform, execPath: process.execPath, env: {}, exit: (code: number) => {+ if (code !== 0) throw new Error('Native runner failed');+ throw exit;+ } },+ console: { log() {}, error() { throw new Error('Native runner emitted an error'); } },+ }, { filename: runner });+ } catch (error) { if (error !== exit) throw error; }+ const invocation = calls.find(args => args[0].endsWith('run-tests.mjs'));+ if (!invocation) throw new Error('Native suite invocation was missing');+ return invocation;+}+type ProcessOwner = {suite: string;evidence: string;+ platforms?: readonly ('darwin' | 'win32' | 'linux')[];};/**@@ -14,6 +47,30 @@ type ProcessOwner = {* hidden windows, process-tree cleanup, output encoding, and locked files.*/const PROCESS_OWNER_SUITE: Record<string, ProcessOwner> = {+ 'bin/bridge-skill-runner.cjs': {+ suite: 'test/main/features/local_agents/bridge_skill_runner.test.ts',+ evidence: 'createBridgeSkillRunner',+ },+ 'bin/local-cli-auth.cjs': {+ suite: 'test/main/features/connectors/local-cli.test.ts',+ evidence: 'local-cli-auth.cjs',+ },+ 'bin/local-cli-mcp-server.cjs': {+ suite: 'test/main/features/connectors/local-cli-stdio-adapter.test.ts',+ evidence: 'local-cli-mcp-server.cjs',+ },+ 'bin/orkas-pkg.cjs': {+ suite: 'test/main/util/orkas-pkg.test.ts',+ evidence: 'orkas-pkg.cjs',+ },+ 'bin/run-skill.cjs': {+ suite: 'test/main/util/run-skill.test.ts',+ evidence: 'run-skill.cjs',+ },+ 'bin/sharp-worker.cjs': {+ suite: 'test/main/util/sharp-runtime.test.ts',+ evidence: 'sharp-worker.cjs',+ },'src/core-agent/src/auth/oauth-flow.ts': {suite: 'src/core-agent/test/oauth-flow.test.ts',evidence: 'browserOpenCommand',@@ -62,6 +119,11 @@ const PROCESS_OWNER_SUITE: Record<string, ProcessOwner> = {suite: 'test/main/index-process.test.ts',evidence: 'ORKAS_RELAUNCH_OWNER_PID',},+ 'src/main/install-data-root.cjs': {+ platforms: ['win32'],+ suite: 'test/main/util/migrate-source-data-root.test.ts',+ evidence: 'Get-CimInstance Win32_LogicalDisk',+ },'src/main/features/video_studio.ts': {suite: 'test/main/features/video_studio_native_qa.test.ts',evidence: 'runVideoProcessForTest',@@ -86,6 +148,11 @@ const PROCESS_OWNER_SUITE: Record<string, ProcessOwner> = {suite: 'test/main/util/extract-xls.test.ts',evidence: 'xlsBufferToMarkdown',},+ 'src/main/util/windows-shutdown-processes.ts': {+ platforms: ['win32'],+ suite: 'test/main/util/windows-shutdown-processes.test.ts',+ evidence: 'captureWindowsShutdownProcesses',+ },'src/main/util/media_probe.ts': {suite: 'test/main/util/media_probe.test.ts',evidence: 'runMediaProbeProcessForTest',@@ -97,29 +164,68 @@ function walk(dir: string): string[] {for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {const abs = path.join(dir, entry.name);if (entry.isDirectory()) files.push(...walk(abs));- else if (entry.isFile() && entry.name.endsWith('.ts')) files.push(abs);+ else if (entry.isFile() && /\.(?:ts|[cm]?js)$/.test(entry.name)) files.push(abs);}return files;}+function processOwnerFiles(root: string, excluded: string[]): string[] {+ return ['src/core-agent/src', 'src/main', 'bin'].flatMap(dir => walk(path.join(root, dir)))+ .filter(file => /(?:from\s+|import\s*\(|require\s*\()\s*['"](?:node:)?child_process['"]/+ .test(fs.readFileSync(file, 'utf8')))+ .map(file => path.relative(root, file).split(path.sep).join('/'))+ // Only exact packaging exclusions may remove a build-time bin helper.+ // A new helper remains unowned until it receives a behavioral suite.+ .filter(file => !file.startsWith('bin/') || !excluded.includes(`!${file}`))+ .sort();+}+describe('platform process test ownership', () => {- it('assigns every child-process production module to a focused behavior suite', () => {- const roots = [- 'src/core-agent/src',- 'src/main',- ].map((dir) => path.resolve(process.cwd(), dir));- const processOwners = roots- .flatMap(walk)- .filter((file) => (- /(?:from\s+|import\s*\(|require\s*\()\s*['"](?:node:)?child_process['"]/- .test(fs.readFileSync(file, 'utf8'))- ))- .map((file) => path.relative(process.cwd(), file).split(path.sep).join('/'))- .sort();+ it.each(['darwin', 'win32', 'linux'] as const)('runs existing MCP, migration and graceful exit contracts in the actual %s native selection', platform => {+ const source = fs.readFileSync(path.resolve('scripts/run-platform-native-tests.mjs'), 'utf8');+ const selected = nativeSuiteSelection(source, platform);+ for (const suite of [+ 'test/main/features/connectors/mcp-client.test.ts',+ 'test/main/util/shutdown.test.ts',+ 'test/main/util/migrate-source-data-root.test.ts',+ ]) expect(selected).toContain(suite);+ for (const suite of selected.filter(arg => arg.endsWith('.test.ts'))) {+ expect(fs.existsSync(path.resolve(suite)), `native selection has a missing suite: ${suite}`).toBe(true);+ }+ });+ it('detects the missing macOS MCP lane when a suite is Windows-only', () => {+ const source = fs.readFileSync(path.resolve('scripts/run-platform-native-tests.mjs'), 'utf8');+ // Negative control: a suite present only in the Windows branch must not+ // make the macOS lane appear covered through a source-text match.+ const windowsOnly = source.replace(/^[ \t]*'test\/main\/features\/connectors\/mcp-client\.test\.ts',\r?\n/m, '')+ .replace(" 'test/main/util/windows-shutdown-processes.test.ts',", " 'test/main/util/windows-shutdown-processes.test.ts',\n 'test/main/features/connectors/mcp-client.test.ts',");+ expect(nativeSuiteSelection(windowsOnly, 'win32')).toContain('test/main/features/connectors/mcp-client.test.ts');+ expect(nativeSuiteSelection(windowsOnly, 'darwin')).not.toContain('test/main/features/connectors/mcp-client.test.ts');+ });+++ it('assigns every child-process production module to a focused behavior suite', () => {+ const pkg = JSON.parse(fs.readFileSync(path.resolve('package.json'), 'utf8'));+ const processOwners = processOwnerFiles(process.cwd(), pkg.build.files);expect(Object.keys(PROCESS_OWNER_SUITE).sort()).toEqual(processOwners);});+ it('discovers unowned helpers in new and generic directories instead of silently excluding them', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-process-inventory-'));+ try {+ const expected = ['bin/new/helper.cjs', 'src/core-agent/src/data/worker.js', 'src/main/build/worker.mjs'];+ for (const file of [...expected, 'bin/build-only.cjs']) {+ fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });+ fs.writeFileSync(path.join(root, file), "const { spawn } = require('node:child_process');\n");+ }+ expect(processOwnerFiles(root, ['!bin/build-only.cjs'])).toEqual(expected);+ expect(expected.every(file => !(file in PROCESS_OWNER_SUITE))).toBe(true);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+ });+it('requires direct evidence in each named suite', () => {const invalid: string[] = [];for (const [source, owner] of Object.entries(PROCESS_OWNER_SUITE)) {@@ -135,11 +241,20 @@ describe('platform process test ownership', () => {expect(invalid).toEqual([]);});- it('runs every child-process owner suite in the serialized native-host lane', () => {+ it.each(['darwin', 'win32', 'linux'] as const)('runs every applicable process owner in the actual %s native lane', platform => {const runner = fs.readFileSync(path.resolve(process.cwd(), 'scripts/run-platform-native-tests.mjs'), 'utf8');- const missing = [...new Set(Object.values(PROCESS_OWNER_SUITE).map(({ suite }) => suite))]- .filter((suite) => !runner.includes(suite));+ const selected = nativeSuiteSelection(runner, platform);+ const missing = [...new Set(Object.values(PROCESS_OWNER_SUITE)+ .filter(owner => !owner.platforms || owner.platforms.includes(platform))+ .map(({ suite }) => suite))]+ .filter(suite => !selected.includes(suite));expect(missing).toEqual([]);+ expect(selected).toContain('--maxWorkers=1');+ });++ it.each(['darwin', 'win32', 'linux'] as const)('fails the %s native lane when a selected suite fails', platform => {+ const source = fs.readFileSync(path.resolve('scripts/run-platform-native-tests.mjs'), 'utf8');+ expect(() => nativeSuiteSelection(source, platform, 1)).toThrow('Native runner failed');});it('repeats every real Windows descendant-termination suite three times', () => {@@ -147,6 +262,8 @@ describe('platform process test ownership', () => {expect(runner).toContain('const repetitions = 3');expect(runner).toContain("'-t'");expect(runner).toContain('for (const suite of suites)');+ expect(runner).toContain('stops only this installation');+ expect(runner).toContain('releases orphaned app/runtime executables');for (const suite of ['src/core-agent/test/process-session.test.ts','test/main/features/local_agents/version.test.ts',@@ -154,9 +271,13 @@ describe('platform process test ownership', () => {'test/main/features/packages.test.ts','test/main/features/generation_reference_assets.test.ts','test/main/util/media_probe.test.ts',+ 'test/main/util/windows-shutdown-processes.test.ts',+ 'test/main/util/windows-installer-processes.test.ts',+ 'test/main/features/connectors/mcp-client.test.ts','test/main/features/video_studio_native_qa.test.ts',]) {expect(runner, `${suite} is not in the repeated Windows lane`).toContain(suite);}});+});diff --git a/test/main/util/fetch-win-vc-runtime.test.ts b/test/main/util/fetch-win-vc-runtime.test.tsindex 10ed9350..a418ff6d 100644--- a/test/main/util/fetch-win-vc-runtime.test.ts+++ b/test/main/util/fetch-win-vc-runtime.test.ts@@ -178,7 +178,7 @@ describe('fetch-win-vc-runtime', () => {// The shared installer cleanup hook is independent of app-local VC deployment.expect(pkg.build.nsis?.include).toBe('scripts/windows-installer.nsh');const include = fs.readFileSync(path.join(process.cwd(), pkg.build.nsis.include), 'utf8');- expect(include).not.toMatch(/vc_redist|whisper-runtime|msiexec/i);+ expect(include).not.toMatch(/vc_?redist|whisper-runtime|msiexec/i);expect(fs.existsSync(path.join(process.cwd(), 'product', 'whisper-runtime.nsh'))).toBe(false);});diff --git a/test/main/util/nsis-installer-processes.test.ts b/test/main/util/nsis-installer-processes.test.tsnew file mode 100644index 00000000..8243a5b5--- /dev/null+++ b/test/main/util/nsis-installer-processes.test.ts@@ -0,0 +1,76 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { createHash } from 'node:crypto';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { buildInstallerFixtures, exerciseNsisInstaller, resolveNsisTool, type InstallerFixtures, type CleanupFixture } from '../../helpers/nsis-installer-scenario';++const pcRoot = path.resolve(__dirname, '../../..');++describe('public NSIS compiler selection', () => {+ it.each(['darwin', 'win32'] as const)('uses the standard installed compiler on %s without private build dependencies', platform => {+ expect(resolveNsisTool({}, platform)).toEqual({ path: platform === 'win32' ? 'makensis.exe' : 'makensis' });+ });++ it.each(['darwin', 'win32', 'linux'] as const)('supports the explicit electron-builder compiler directory on %s', platform => {+ const directory = path.resolve(os.tmpdir(), 'public-nsis-toolchain');+ expect(resolveNsisTool({ ELECTRON_BUILDER_NSIS_DIR: directory }, platform)).toEqual({+ path: path.join(directory, platform === 'darwin' ? 'mac' : platform === 'win32' ? 'Bin' : 'linux',+ platform === 'win32' ? 'makensis.exe' : 'makensis'),+ env: { NSISDIR: directory },+ });+ });++ it('lets an explicit compiler override directory discovery while preserving its resource root', () => {+ const compiler = path.resolve(os.tmpdir(), 'public-nsis', 'makensis');+ const directory = path.resolve(os.tmpdir(), 'public-nsis-toolchain');+ expect(resolveNsisTool({ ORKAS_TEST_MAKENSIS: compiler, ELECTRON_BUILDER_NSIS_DIR: directory })).toEqual({+ path: compiler, env: { NSISDIR: directory },+ });+ });++ it.each(['ORKAS_TEST_MAKENSIS', 'ELECTRON_BUILDER_NSIS_DIR'])('rejects an ambiguous relative %s configuration', key => {+ expect(() => resolveNsisTool({ [key]: 'relative-toolchain' })).toThrow('must be an absolute');+ });++ it('fails compilation when the configured compiler is absent instead of skipping the contract', async () => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-missing-nsis-'));+ try {+ await expect(buildInstallerFixtures(pcRoot, directory, {+ path: path.join(directory, 'absent-compiler'),+ })).rejects.toThrow('NSIS compiler unavailable');+ expect(fs.existsSync(path.join(directory, 'real.exe'))).toBe(false);+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }+ });+});++describe.skipIf(!['darwin', 'win32'].includes(process.platform))('compiled NSIS update installation', () => {+ let root: string;+ let fixtures: InstallerFixtures;+ beforeAll(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-nsis-fixtures-'));+ fixtures = await buildInstallerFixtures(pcRoot, root);+ }, 60_000);+ afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); });++ it('compiles the production hook and explicit failure controls with the configured public toolchain', () => {+ expect(Object.keys(fixtures)).toEqual(['real', 'failed', 'timeout', 'disabled']);+ console.info('NSIS compilation proof:', JSON.stringify(Object.entries(fixtures).map(([fault, file]) => {+ const bytes = fs.readFileSync(file);+ return { fault, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };+ })));+ });++ it.runIf(process.platform === 'win32').each<CleanupFixture>(['real', 'failed', 'timeout'])(+ 'preserves the old installation on %s cleanup and safely installs on retry', async fault => {+ const result = await exerciseNsisInstaller(process.env.ORKAS_TEST_NODE!, fixtures, fault);+ expect(result).toMatchObject({ installedVersion: 2, siblingPreserved: true, userDataPreserved: true });+ console.info('NSIS installation proof:', JSON.stringify(result));+ }, 60_000,+ );++ it.runIf(process.platform === 'win32')('rejects a false-success control with cleanup disabled, then recovers', async () => {+ const result = await exerciseNsisInstaller(process.env.ORKAS_TEST_NODE!, fixtures, 'disabled');+ console.info('NSIS false-success control rejected:', JSON.stringify(result));+ }, 60_000);+});diff --git a/test/main/util/windows-installer-processes.test.ts b/test/main/util/windows-installer-processes.test.tsnew file mode 100644index 00000000..78dfeed7--- /dev/null+++ b/test/main/util/windows-installer-processes.test.ts@@ -0,0 +1,55 @@+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import { spawnSync } from 'node:child_process';+import { describe, expect, it } from 'vitest';+import { exerciseWindowsInstaller } from '../../helpers/windows-installer-scenario';++const pcRoot = path.resolve(__dirname, '../../..');+const script = path.join(pcRoot, 'scripts/windows-installer-processes.ps1');++describe('Windows installer residual process cleanup', () => {+ it('wires cleanup into the installer before old-version removal', () => {+ const manifest = JSON.parse(fs.readFileSync(path.join(pcRoot, 'package.json'), 'utf8'));+ expect(manifest.build.nsis?.include).toBe('scripts/windows-installer.nsh');+ const include = fs.readFileSync(path.join(pcRoot, manifest.build.nsis.include), 'utf8');+ // customInit is an installer-only hook, before CHECK_APP_RUNNING and the+ // old uninstaller. customInstall would run after the locked-file failure.+ expect(include).toContain('!macro customInit');+ expect(include).toContain('windows-installer-processes.ps1');+ expect(fs.existsSync(script)).toBe(true);+ });++ it('replaces the upstream prefix/name check in both installer and uninstaller with the scoped helper', () => {+ const include = fs.readFileSync(path.join(pcRoot, 'scripts/windows-installer.nsh'), 'utf8');+ expect(include).toContain('!macro customCheckAppRunning');+ expect(include).not.toContain('!insertmacro _CHECK_APP_RUNNING');+ });++ it.runIf(process.platform === 'win32')('preserves the installer ancestor when an uninstaller requests cleanup', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-control-ancestor-'));+ try {+ fs.writeFileSync(path.join(root, 'Orkas.exe'), 'fixture installation marker');+ const ancestor = path.join(root, 'installer.exe');+ fs.copyFileSync(process.env.ORKAS_TEST_NODE!, ancestor);+ const powershell = path.win32.join(process.env.SystemRoot!, 'System32/WindowsPowerShell/v1.0/powershell.exe');+ const uninstaller = `const r = require('node:child_process').spawnSync(${JSON.stringify(powershell)}, ${JSON.stringify(['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, '-InstallDir', root, '-InstallerProcessId'])}.concat(String(process.pid)), {timeout:15000, encoding:'utf8', windowsHide:true}); if(r.stdout || r.stderr) process.stderr.write(r.stdout+r.stderr); process.exit(r.status ?? 9);`;+ const parent = `const r = require('node:child_process').spawnSync(${JSON.stringify(process.env.ORKAS_TEST_NODE)}, ['-e', ${JSON.stringify(uninstaller)}], {timeout:18000,encoding:'utf8',windowsHide:true}); process.stdout.write('installer-alive:' + r.status); if(r.stderr) process.stderr.write(r.stderr); process.exit(r.status ?? 8);`;+ const result = spawnSync(ancestor, ['-e', parent], {+ timeout: 20000, encoding: 'utf8', windowsHide: true,+ env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined },+ });+ expect(result.status, result.stderr).toBe(0);+ expect(result.stdout).toBe('installer-alive:0');+ expect(result.stderr).toBe('');+ } finally { fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }+ }, 25000);++ it.runIf(process.platform === 'win32')(+ 'releases orphaned app/runtime executables while preserving a sibling install and the installer',+ async () => {+ await exerciseWindowsInstaller(process.env.ORKAS_TEST_NODE!, script);+ }, 60_000,+ );++});