From 78e38a964241b5ae632cd6786b8d9ef25bc8031f Mon Sep 17 00:00:00 2001 From: 0721-art Date: Tue, 17 Nov 2026 16:21:06 +0800 Subject: [PATCH 1/3] fix(windows): start launchers outside the installation directory On Windows a directory cannot be renamed while it is a live process's working directory, so anything long-lived that starts inside the install tree blocks the updater's replacement of that tree (ERROR_SHARING_VIOLATION; npm reports it as EBUSY). The native tray, both PowerShell supervisors, the launcher the tray starts, the host daemon the web server starts and the shortcuts' "Start in" folder all pointed at the installation. Start them from %USERPROFILE% instead (homedir() on the Node side), which is the rule server-update-worker.ts already states for the processes it launches. Every one of them resolves its files from absolute paths, so the working directory only has to be somewhere else. Adds a static test over the Windows launchers for that rule. --- lib/hosts/local-daemon-start.test.mjs | 6 +++--- lib/hosts/local-daemon-start.ts | 5 +++-- lib/windows-service.test.mjs | 19 +++++++++++++++++++ lib/windows-service.ts | 7 ++++--- native/tray/Program.cs | 3 ++- scripts/windows/install-tray.ps1 | 15 +++++++++++---- scripts/windows/omp-web-host.ps1 | 7 ++++++- scripts/windows/omp-web-service.ps1 | 7 ++++++- scripts/windows/omp-web-tray.ps1 | 9 +++++++-- 9 files changed, 61 insertions(+), 17 deletions(-) diff --git a/lib/hosts/local-daemon-start.test.mjs b/lib/hosts/local-daemon-start.test.mjs index b65166519..6db1b342a 100644 --- a/lib/hosts/local-daemon-start.test.mjs +++ b/lib/hosts/local-daemon-start.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import test, { after } from "node:test"; @@ -237,7 +237,7 @@ test("an endpoint that cannot be probed is an error, never a second daemon", { s }); test("the host runs as this binary's host command, or the package entrypoint on Node, never as Bun", () => { - assert.deepEqual(localHostLaunch({ OMP_WEB_PACKAGE_DIR: "/opt/ompweb", OMP_WEB_NODE_BIN: "/usr/bin/node" }), { command: "/usr/bin/node", args: [join(resolve("/opt/ompweb"), "bin", "omp-web-host.js")], cwd: process.cwd() }); + assert.deepEqual(localHostLaunch({ OMP_WEB_PACKAGE_DIR: "/opt/ompweb", OMP_WEB_NODE_BIN: "/usr/bin/node" }), { command: "/usr/bin/node", args: [join(resolve("/opt/ompweb"), "bin", "omp-web-host.js")], cwd: homedir() }); assert.equal(localHostLaunch({ OMP_WEB_PACKAGE_DIR: "/opt/ompweb" }).command, process.versions.bun ? "node" : process.execPath); - assert.deepEqual(localHostLaunch({}), { command: process.versions.bun ? "node" : process.execPath, args: [join(process.cwd(), "bin", "omp-web-host.js")], cwd: process.cwd() }); + assert.deepEqual(localHostLaunch({}), { command: process.versions.bun ? "node" : process.execPath, args: [join(process.cwd(), "bin", "omp-web-host.js")], cwd: homedir() }); }); diff --git a/lib/hosts/local-daemon-start.ts b/lib/hosts/local-daemon-start.ts index cb1b19f42..a8c1116de 100644 --- a/lib/hosts/local-daemon-start.ts +++ b/lib/hosts/local-daemon-start.ts @@ -1,5 +1,6 @@ // Starts this machine's host daemon for the web server unless one already answers its private control endpoint. // Pure Node: no Next or `@/` imports (instrumentation.node.ts loads it). +import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { isProcessAlive } from "../process-identity"; import { isActiveLease, leasePath, readStateJson, statusPath, type StoredStatus } from "../self-update-state"; @@ -53,11 +54,11 @@ async function probe(): Promise { /** This install's host command: the standalone binary's `host`, or the package's entrypoint under the Node runtime. */ export function localHostLaunch(env: NodeJS.ProcessEnv = process.env): UpgradeLaunch { - if (typeof Bun !== "undefined" && Bun.isStandaloneExecutable) return { command: process.execPath, args: ["host"], cwd: process.cwd() }; + if (typeof Bun !== "undefined" && Bun.isStandaloneExecutable) return { command: process.execPath, args: ["host"], cwd: homedir() }; const packageDir = env.OMP_WEB_PACKAGE_DIR ?? process.cwd(); // The daemon is Node-only: a web server running on Bun must start it with the launcher's Node binary. const command = env.OMP_WEB_NODE_BIN || (process.versions.bun ? "node" : process.execPath); - return { command, args: [join(resolve(packageDir), "bin", "omp-web-host.js")], cwd: process.cwd() }; + return { command, args: [join(resolve(packageDir), "bin", "omp-web-host.js")], cwd: homedir() }; } function daemonEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { diff --git a/lib/windows-service.test.mjs b/lib/windows-service.test.mjs index edde606ce..0f86b507d 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -130,6 +130,25 @@ test("getWindowsServiceDefinitions names the web service and the host daemon, an assert.match(readFileSync(host.script, "utf8"), /\$LauncherJs`" host >>/); }); +test("Windows launchers never keep the installation directory as a working directory", () => { + const root = path.resolve(import.meta.dirname, ".."); + const windows = path.join(root, "scripts", "windows"); + for (const name of ["omp-web-tray.ps1", "omp-web-service.ps1", "omp-web-host.ps1", "install-tray.ps1"]) { + const source = readFileSync(path.join(windows, name), "utf8"); + const assignments = source.match(/\.WorkingDirectory\s*=\s*[^\r\n]+/g) ?? []; + assert.ok(assignments.length > 0, `${name} sets a working directory`); + for (const line of assignments) { + // A process whose working directory is inside the installation blocks the next + // update on Windows (ERROR_SHARING_VIOLATION on the directory rename). + assert.doesNotMatch(line, /\$RepoRoot/, `${name}: ${line.trim()}`); + } + } + const hooks = readFileSync(path.join(root, "lib", "windows-service.ts"), "utf8"); + assert.doesNotMatch(hooks, /\$sc\.WorkingDirectory = '\$\{repoRoot/, "the startup shortcut starts outside the installation"); + const tray = readFileSync(path.join(root, "native", "tray", "Program.cs"), "utf8"); + assert.doesNotMatch(tray, /WorkingDirectory = _repoRoot/, "the native tray starts the launcher outside the installation"); +}); + test("getHostDaemonStatus reports no daemon off Windows", async () => { if (process.platform === "win32") return; assert.deepEqual(await getHostDaemonStatus(), { isInstalled: false, isRunning: false }); diff --git a/lib/windows-service.ts b/lib/windows-service.ts index 4e70e2a7f..8267f3a91 100644 --- a/lib/windows-service.ts +++ b/lib/windows-service.ts @@ -503,7 +503,7 @@ export async function toggleAutostart(enable: boolean): Promise<{ success: boole $sc = $wsh.CreateShortcut('${startupLnk.replace(/'/g, "''")}') $sc.TargetPath = '${wscriptExe.replace(/'/g, "''")}' $sc.Arguments = '"${launchVbs.replace(/"/g, '`"')}" -Startup' - $sc.WorkingDirectory = '${repoRoot.replace(/'/g, "''")}' + $sc.WorkingDirectory = '${homedir().replace(/'/g, "''")}' if (Test-Path '${icoPath.replace(/'/g, "''")}') { $sc.IconLocation = '${icoPath.replace(/'/g, "''")},0' } $sc.Description = 'omp-web Background Tray Service' $sc.Save() @@ -559,7 +559,8 @@ export async function startTrayService(options: { openBrowser?: boolean } = {}): const nativeArgs: string[] = []; if (options.openBrowser) nativeArgs.push("-OpenBrowser"); const child = spawn(nativeExe, nativeArgs, { - cwd: getRepoRoot(), + // Never from inside the installation: a cwd there blocks the next replacement on Windows. + cwd: homedir(), detached: true, stdio: "ignore", windowsHide: true, @@ -600,7 +601,7 @@ export async function startTrayService(options: { openBrowser?: boolean } = {}): return new Promise<{ success: boolean; message?: string }>((resolve) => { try { const child = spawn(wscriptExe, vbsArgs, { - cwd: repoRoot, + cwd: homedir(), detached: true, stdio: "ignore", windowsHide: true, diff --git a/native/tray/Program.cs b/native/tray/Program.cs index 967f0a3c4..9b95fb461 100644 --- a/native/tray/Program.cs +++ b/native/tray/Program.cs @@ -256,7 +256,8 @@ private void StartWebServer() var psi = new ProcessStartInfo { FileName = _nodeExe, - WorkingDirectory = _repoRoot, + // Never from inside the installation: a cwd there blocks the next replacement on Windows. + WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, diff --git a/scripts/windows/install-tray.ps1 b/scripts/windows/install-tray.ps1 index 06ebd374c..165cca369 100644 --- a/scripts/windows/install-tray.ps1 +++ b/scripts/windows/install-tray.ps1 @@ -30,6 +30,11 @@ $IcoPath = Join-Path $RepoRoot "public\omp-web.ico" $PngPath = Join-Path $RepoRoot "public\icon.png" $LaunchVbs = Join-Path $RepoRoot "scripts\windows\launch-tray.vbs" +# The updater replaces this installation in place, and Windows refuses to rename a +# directory that is a live process's working directory (ERROR_SHARING_VIOLATION). +# The shortcuts launch absolute targets, so they start outside the installation. +$ShortcutWorkingDirectory = $env:USERPROFILE + function Log-Message([string]$msg) { if (!$Quiet) { Write-Host $msg @@ -172,7 +177,7 @@ try { $sc.TargetPath = $wscriptExe $sc.Arguments = "`"$LaunchVbs`" -OpenBrowser" } - $sc.WorkingDirectory = $RepoRoot + $sc.WorkingDirectory = $ShortcutWorkingDirectory if (Test-Path $IcoPath) { $sc.IconLocation = "$IcoPath,0" } $sc.Description = "Open omp-web AI Coding Agent Web Interface" $sc.Save() @@ -193,7 +198,7 @@ try { $sc.TargetPath = $wscriptExe $sc.Arguments = "`"$LaunchVbs`" -OpenBrowser" } - $sc.WorkingDirectory = $RepoRoot + $sc.WorkingDirectory = $ShortcutWorkingDirectory if (Test-Path $IcoPath) { $sc.IconLocation = "$IcoPath,0" } $sc.Description = "omp-web System Tray & Web Interface" $sc.Save() @@ -215,7 +220,7 @@ if (!$NoAutostart) { $sc.TargetPath = $wscriptExe $sc.Arguments = "`"$LaunchVbs`" -Startup" } - $sc.WorkingDirectory = $RepoRoot + $sc.WorkingDirectory = $ShortcutWorkingDirectory if (Test-Path $IcoPath) { $sc.IconLocation = "$IcoPath,0" } $sc.Description = "omp-web Background Tray Service" $sc.Save() @@ -293,5 +298,7 @@ if (Test-Path $HostPs1) { # ----------------------------------------------------------------------------- if ($StartImmediately) { Log-Message "Starting background service and opening browser..." - $wsh.Run("`"$wscriptExe`" `"$LaunchVbs`" -OpenBrowser", 0, $false) + # Start it from outside the installation too, or the tray inherits this directory as + # its working directory and blocks the next replacement. + Start-Process -FilePath $wscriptExe -ArgumentList "`"$LaunchVbs`" -OpenBrowser" -WorkingDirectory $ShortcutWorkingDirectory -WindowStyle Hidden } diff --git a/scripts/windows/omp-web-host.ps1 b/scripts/windows/omp-web-host.ps1 index 3d2494834..d0692de34 100644 --- a/scripts/windows/omp-web-host.ps1 +++ b/scripts/windows/omp-web-host.ps1 @@ -15,6 +15,11 @@ param( $RepoRoot = (Resolve-Path "$PSScriptRoot\..\..").Path $LauncherJs = Join-Path $RepoRoot "bin\omp-web.js" +# The updater replaces this installation in place, and Windows refuses to rename a +# directory that is a live process's working directory (ERROR_SHARING_VIOLATION). +# Every path below is absolute, so the children start outside the installation. +$LaunchWorkingDirectory = $env:USERPROFILE + # One daemon supervisor per logon session. $createdNew = $false try { $script:AppMutex = New-Object System.Threading.Mutex($true, "Local\OmpWebHostDaemon_Instance_Mutex", [ref]$createdNew) } catch { $createdNew = $true } @@ -47,7 +52,7 @@ try { $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $env:ComSpec $psi.Arguments = "/d /s /c `"`"$NodeExe`" `"$LauncherJs`" host >> `"$LogFile`" 2>&1`"" - $psi.WorkingDirectory = $RepoRoot + $psi.WorkingDirectory = $LaunchWorkingDirectory $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $proc = [System.Diagnostics.Process]::Start($psi) diff --git a/scripts/windows/omp-web-service.ps1 b/scripts/windows/omp-web-service.ps1 index a34f46118..4c9df6a63 100644 --- a/scripts/windows/omp-web-service.ps1 +++ b/scripts/windows/omp-web-service.ps1 @@ -13,6 +13,11 @@ param( $RepoRoot = (Resolve-Path "$PSScriptRoot\..\..").Path $PkgJsonPath = Join-Path $RepoRoot "package.json" + +# The updater replaces this installation in place, and Windows refuses to rename a +# directory that is a live process's working directory (ERROR_SHARING_VIOLATION). +# Every path below is absolute, so the server starts outside the installation. +$LaunchWorkingDirectory = $env:USERPROFILE $PkgVersion = "0.0.0" if (Test-Path $PkgJsonPath) { try { $pkg = Get-Content $PkgJsonPath -Raw | ConvertFrom-Json; if ($pkg.version) { $PkgVersion = $pkg.version } } catch { } @@ -119,7 +124,7 @@ function Start-WebServer { } $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $NodeExe - $psi.WorkingDirectory = $RepoRoot + $psi.WorkingDirectory = $LaunchWorkingDirectory $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $psi.RedirectStandardOutput = $false diff --git a/scripts/windows/omp-web-tray.ps1 b/scripts/windows/omp-web-tray.ps1 index 07f9d7d2f..31a0d131a 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -38,6 +38,11 @@ Add-Type -AssemblyName System.Drawing # ----------------------------------------------------------------------------- $RepoRoot = (Resolve-Path "$PSScriptRoot\..\..").Path $PkgJsonPath = Join-Path $RepoRoot "package.json" + +# The updater replaces this installation in place, and Windows refuses to rename a +# directory that is a live process's working directory (ERROR_SHARING_VIOLATION). +# Every path below is absolute, so the server and the shortcuts start outside it. +$LaunchWorkingDirectory = $env:USERPROFILE $PkgVersion = "0.0.0" if (Test-Path $PkgJsonPath) { try { @@ -236,7 +241,7 @@ function Start-WebServer { $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $NodeExe - $psi.WorkingDirectory = $RepoRoot + $psi.WorkingDirectory = $LaunchWorkingDirectory $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $psi.RedirectStandardOutput = $false @@ -363,7 +368,7 @@ function Set-AutostartShortcut([bool]$enable) { $shortcut = $wsh.CreateShortcut($startupLnk) $shortcut.TargetPath = $wscriptExe $shortcut.Arguments = "`"$launchVbs`" -Startup" - $shortcut.WorkingDirectory = $RepoRoot + $shortcut.WorkingDirectory = $LaunchWorkingDirectory if (Test-Path $IcoPath) { $shortcut.IconLocation = "$IcoPath,0" } From 5047ee1283575d296025b0d2ff332224df78d6b2 Mon Sep 17 00:00:00 2001 From: 0721-art Date: Tue, 17 Nov 2026 16:51:49 +0800 Subject: [PATCH 2/3] fix(windows): keep the dev fallback working outside the installation The launchers start outside the installation now, so the dev branch cannot rely on the working directory: pass the entry and bunfig.toml as absolute paths, and name the installation in OMP_WEB_PACKAGE_DIR so server/dev.ts resolves its root without a cwd. Verified on Windows 11: with the working directory at C:\\Users\\, `node bin/bun-runtime.js --config=\\bunfig.toml --hot \\server\\dev.ts -H 127.0.0.1 -p 30190` serves HTTP 200; without the absolute config and entry it returns 500 "the page has no stylesheet link" because Bun had not found bunfig.toml. --- lib/windows-service.test.mjs | 12 ++++++++++++ native/tray/Program.cs | 8 +++++++- scripts/windows/omp-web-service.ps1 | 6 +++++- scripts/windows/omp-web-tray.ps1 | 6 +++++- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/windows-service.test.mjs b/lib/windows-service.test.mjs index 0f86b507d..48fd45666 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -143,10 +143,22 @@ test("Windows launchers never keep the installation directory as a working direc assert.doesNotMatch(line, /\$RepoRoot/, `${name}: ${line.trim()}`); } } + // The working directory is outside the installation, so a relative dev entry would resolve + // against the user profile instead of the installation (breaking dev launches, or worse, + // running a server/dev.ts planted there). + for (const name of ["omp-web-tray.ps1", "omp-web-service.ps1"]) { + const source = readFileSync(path.join(windows, name), "utf8"); + assert.doesNotMatch(source, /--hot "?server[\\/]dev\.ts/, `${name}: the dev entry is not relative`); + assert.match(source, /--hot .*Join-Path \$RepoRoot/, `${name}: the dev entry resolves from the installation`); + assert.match(source, /--config=\$\(Join-Path \$RepoRoot 'bunfig\.toml'\)/, `${name}: Bun is told where bunfig.toml is`); + } const hooks = readFileSync(path.join(root, "lib", "windows-service.ts"), "utf8"); assert.doesNotMatch(hooks, /\$sc\.WorkingDirectory = '\$\{repoRoot/, "the startup shortcut starts outside the installation"); const tray = readFileSync(path.join(root, "native", "tray", "Program.cs"), "utf8"); assert.doesNotMatch(tray, /WorkingDirectory = _repoRoot/, "the native tray starts the launcher outside the installation"); + assert.doesNotMatch(tray, /--hot "?server[\\/]dev\.ts/, "the native tray passes an absolute dev entry"); + assert.match(tray, /Path\.Combine\(_repoRoot, "server", "dev\.ts"\)/, "the native tray resolves the dev entry from the installation"); + assert.match(tray, /--config=\{bunfig\}/, "the native tray tells Bun where bunfig.toml is"); }); test("getHostDaemonStatus reports no daemon off Windows", async () => { diff --git a/native/tray/Program.cs b/native/tray/Program.cs index 9b95fb461..85eb6df93 100644 --- a/native/tray/Program.cs +++ b/native/tray/Program.cs @@ -272,10 +272,16 @@ private void StartWebServer() else { var bunLauncher = Path.Combine(_repoRoot, "bin", "bun-runtime.js"); - psi.Arguments = $"\"{bunLauncher}\" --hot server/dev.ts -H {_effectiveHostname} -p {_effectivePort}"; + // The working directory is outside the installation, so both the dev entry and the config + // (Bun reads bunfig.toml from the working directory) are passed as absolute paths. + var bunfig = Path.Combine(_repoRoot, "bunfig.toml"); + var devEntry = Path.Combine(_repoRoot, "server", "dev.ts"); + psi.Arguments = $"\"{bunLauncher}\" \"--config={bunfig}\" --hot \"{devEntry}\" -H {_effectiveHostname} -p {_effectivePort}"; } psi.EnvironmentVariables["OMP_WEB_PORT"] = _effectivePort.ToString(); + // The child runs outside the installation, so name it explicitly (dev mode derives its root from this). + psi.EnvironmentVariables["OMP_WEB_PACKAGE_DIR"] = _repoRoot; psi.EnvironmentVariables["OMP_WEB_HOSTNAME"] = _effectiveHostname; psi.EnvironmentVariables["OMP_WEB_SERVICE"] = "1"; psi.EnvironmentVariables["PORT"] = _effectivePort.ToString(); diff --git a/scripts/windows/omp-web-service.ps1 b/scripts/windows/omp-web-service.ps1 index 4c9df6a63..f75f68699 100644 --- a/scripts/windows/omp-web-service.ps1 +++ b/scripts/windows/omp-web-service.ps1 @@ -133,11 +133,15 @@ function Start-WebServer { $launcherJs = Join-Path $RepoRoot "bin\omp-web.js" $inner = "`"$NodeExe`" `"$launcherJs`" -p $EffectivePort -H $EffectiveHostname --no-open" } else { - $inner = "`"$NodeExe`" `"$(Join-Path $RepoRoot 'bin\bun-runtime.js')`" --hot server\dev.ts -H $EffectiveHostname -p $EffectivePort" + # The working directory is outside the installation, so both the dev entry and the config + # (Bun reads bunfig.toml from the working directory) are passed as absolute paths. + $inner = "`"$NodeExe`" `"$(Join-Path $RepoRoot 'bin\bun-runtime.js')`" `"--config=$(Join-Path $RepoRoot 'bunfig.toml')`" --hot `"$(Join-Path $RepoRoot 'server\dev.ts')`" -H $EffectiveHostname -p $EffectivePort" } $psi.FileName = $env:ComSpec $psi.Arguments = "/d /s /c `"$inner >> `"$childOutLog`" 2>&1`"" $psi.EnvironmentVariables["OMP_WEB_PORT"] = [string]$EffectivePort + # The child runs outside the installation, so name it explicitly (dev mode derives its root from this). + $psi.EnvironmentVariables["OMP_WEB_PACKAGE_DIR"] = $RepoRoot $psi.EnvironmentVariables["OMP_WEB_HOSTNAME"] = [string]$EffectiveHostname $psi.EnvironmentVariables["OMP_WEB_SERVICE"] = "1" $psi.EnvironmentVariables["PORT"] = [string]$EffectivePort diff --git a/scripts/windows/omp-web-tray.ps1 b/scripts/windows/omp-web-tray.ps1 index 31a0d131a..e14702e75 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -251,13 +251,17 @@ function Start-WebServer { $launcherJs = Join-Path $RepoRoot "bin\omp-web.js" $inner = "`"$NodeExe`" `"$launcherJs`" -p $EffectivePort -H $EffectiveHostname --no-open" } else { - $inner = "`"$NodeExe`" `"$(Join-Path $RepoRoot 'bin\bun-runtime.js')`" --hot server\dev.ts -H $EffectiveHostname -p $EffectivePort" + # The working directory is outside the installation, so both the dev entry and the config + # (Bun reads bunfig.toml from the working directory) are passed as absolute paths. + $inner = "`"$NodeExe`" `"$(Join-Path $RepoRoot 'bin\bun-runtime.js')`" `"--config=$(Join-Path $RepoRoot 'bunfig.toml')`" --hot `"$(Join-Path $RepoRoot 'server\dev.ts')`" -H $EffectiveHostname -p $EffectivePort" } $psi.FileName = $env:ComSpec $psi.Arguments = "/d /s /c `"$inner >> `"$childOutLog`" 2>&1`"" # Environment variables $psi.EnvironmentVariables["OMP_WEB_PORT"] = [string]$EffectivePort + # The child runs outside the installation, so name it explicitly (dev mode derives its root from this). + $psi.EnvironmentVariables["OMP_WEB_PACKAGE_DIR"] = $RepoRoot $psi.EnvironmentVariables["OMP_WEB_HOSTNAME"] = [string]$EffectiveHostname $psi.EnvironmentVariables["OMP_WEB_SERVICE"] = "1" $psi.EnvironmentVariables["PORT"] = [string]$EffectivePort From b78d172a6920db66bc6d5303d4045912633d3875 Mon Sep 17 00:00:00 2001 From: 0721-art Date: Tue, 17 Nov 2026 17:20:25 +0800 Subject: [PATCH 3/3] fix(windows): keep the web server out of the installation directory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit spawnServer started the Bun server with cwd: pkgDir, so the long-lived server — not only the launchers — held the installation as its working directory and blocked the directory rename an in-place update performs on Windows (ERROR_SHARING_VIOLATION). The server needs no relative path: serverCommand passes an absolute server/main.ts and OMP_WEB_PACKAGE_DIR names the installation; server/app.ts falls back to process.cwd() only when that variable is unset. Verified on Windows 11 by starting bin/omp-web.js from C:\\\\Users\\\\: HTTP 200, and the launcher and the bun child both report that directory. Also refuse an empty user profile instead of letting a shortcut or ProcessStartInfo inherit the current (installation) directory, and pin the working-directory variables to $env:USERPROFILE in the static test. --- bin/omp-web-options.js | 13 ++++++++++++- bin/omp-web.js | 7 +++++-- lib/omp-web-options.test.mjs | 17 ++++++++++++++++- lib/windows-service.test.mjs | 20 ++++++++++++++++++++ native/tray/Program.cs | 15 +++++++++++++-- scripts/windows/install-tray.ps1 | 5 +++++ scripts/windows/omp-web-host.ps1 | 5 +++++ scripts/windows/omp-web-service.ps1 | 5 +++++ scripts/windows/omp-web-tray.ps1 | 5 +++++ 9 files changed, 86 insertions(+), 6 deletions(-) diff --git a/bin/omp-web-options.js b/bin/omp-web-options.js index 05f4c132d..af13f322d 100644 --- a/bin/omp-web-options.js +++ b/bin/omp-web-options.js @@ -6,6 +6,8 @@ const { parseArgs } = require("util"); const { hashPassword, isPasswordHash } = require("./omp-web-password-hash"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { isLoopbackHost } = require("./network-addresses"); +// eslint-disable-next-line @typescript-eslint/no-require-imports +const os = require("node:os"); const TRUE_VALUES = new Set(["1", "true", "yes", "on"]); @@ -175,4 +177,13 @@ function checkLaunchSecurity(launchOptions) { return passwordHash; } -module.exports = { checkLaunchSecurity, parseLaunchOptions, printHelp }; +// The server must not start inside the installation: on Windows a live process whose working +// directory is the package blocks the rename an in-place update performs +// (ERROR_SHARING_VIOLATION). The entry point and OMP_WEB_PACKAGE_DIR are absolute, so the +// server does not need the installation as its directory. +function serverWorkingDirectory(home = os.homedir()) { + if (!home) throw new Error("Cannot start ompweb: the home directory is empty, and the server must not run inside its installation."); + return home; +} + +module.exports = { checkLaunchSecurity, parseLaunchOptions, printHelp, serverWorkingDirectory }; diff --git a/bin/omp-web.js b/bin/omp-web.js index c4bc7eb97..c4976631f 100755 --- a/bin/omp-web.js +++ b/bin/omp-web.js @@ -95,7 +95,7 @@ const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports const fs = require("node:fs"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { checkLaunchSecurity, parseLaunchOptions } = require("./omp-web-options"); +const { checkLaunchSecurity, parseLaunchOptions, serverWorkingDirectory } = require("./omp-web-options"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { isPortAvailable } = require("./port-availability"); // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -205,7 +205,10 @@ function trackServer(child) { function spawnServer(command) { return trackServer(spawn(command[0], command.slice(1), { - cwd: pkgDir, + // Never the installation: on Windows a working directory there blocks the rename an + // in-place update performs, and the server needs no relative path (the entry point and + // OMP_WEB_PACKAGE_DIR below are absolute). + cwd: serverWorkingDirectory(), stdio: ["inherit", "pipe", "inherit"], env: serverEnvironment(), })); diff --git a/lib/omp-web-options.test.mjs b/lib/omp-web-options.test.mjs index 454a4785c..cb9fe3b40 100644 --- a/lib/omp-web-options.test.mjs +++ b/lib/omp-web-options.test.mjs @@ -1,11 +1,26 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { createRequire } from "node:module"; +import { homedir } from "node:os"; +import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; const require = createRequire(import.meta.url); -const { parseLaunchOptions } = require("../bin/omp-web-options.js"); +const { parseLaunchOptions, serverWorkingDirectory } = require("../bin/omp-web-options.js"); + +test("starts the server outside the installation directory", () => { + // A server whose working directory is the package blocks the directory rename an in-place + // update performs on Windows (ERROR_SHARING_VIOLATION). + const packageDir = path.resolve(fileURLToPath(new URL("..", import.meta.url))); + const cwd = serverWorkingDirectory(); + assert.equal(cwd, homedir()); + assert.notEqual(path.resolve(cwd), packageDir); +}); + +test("refuses to start the server without a directory outside the installation", () => { + assert.throws(() => serverWorkingDirectory(""), /home directory is empty/); +}); test("opens the browser by default", () => { const parsed = parseLaunchOptions([], {}); diff --git a/lib/windows-service.test.mjs b/lib/windows-service.test.mjs index 48fd45666..3f1c5ad2f 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -152,6 +152,23 @@ test("Windows launchers never keep the installation directory as a working direc assert.match(source, /--hot .*Join-Path \$RepoRoot/, `${name}: the dev entry resolves from the installation`); assert.match(source, /--config=\$\(Join-Path \$RepoRoot 'bunfig\.toml'\)/, `${name}: Bun is told where bunfig.toml is`); } + // Rejecting the text "$RepoRoot" alone would pass "$LaunchWorkingDirectory = $RepoRoot" followed + // by ".WorkingDirectory = $LaunchWorkingDirectory", so pin the variable to the user profile and + // require the refusal when it is empty. + const workingDirectories = { + "omp-web-tray.ps1": "LaunchWorkingDirectory", + "omp-web-service.ps1": "LaunchWorkingDirectory", + "omp-web-host.ps1": "LaunchWorkingDirectory", + "install-tray.ps1": "ShortcutWorkingDirectory", + }; + for (const [name, variable] of Object.entries(workingDirectories)) { + const source = readFileSync(path.join(windows, name), "utf8"); + assert.match(source, new RegExp(`^\\$${variable} = \\$env:USERPROFILE$`, "m"), `${name}: ${variable} is the user profile`); + for (const line of source.match(/\.WorkingDirectory\s*=\s*[^\r\n]+/g) ?? []) { + assert.match(line, new RegExp(`\\$${variable}`), `${name}: ${line.trim()} uses ${variable}`); + } + assert.match(source, new RegExp(`IsNullOrWhiteSpace\\(\\$${variable}\\)`), `${name}: refuses an empty ${variable}`); + } const hooks = readFileSync(path.join(root, "lib", "windows-service.ts"), "utf8"); assert.doesNotMatch(hooks, /\$sc\.WorkingDirectory = '\$\{repoRoot/, "the startup shortcut starts outside the installation"); const tray = readFileSync(path.join(root, "native", "tray", "Program.cs"), "utf8"); @@ -159,6 +176,9 @@ test("Windows launchers never keep the installation directory as a working direc assert.doesNotMatch(tray, /--hot "?server[\\/]dev\.ts/, "the native tray passes an absolute dev entry"); assert.match(tray, /Path\.Combine\(_repoRoot, "server", "dev\.ts"\)/, "the native tray resolves the dev entry from the installation"); assert.match(tray, /--config=\{bunfig\}/, "the native tray tells Bun where bunfig.toml is"); + assert.match(tray, /var workingDirectory = Environment\.GetFolderPath\(Environment\.SpecialFolder\.UserProfile\);/, "the native tray resolves the user profile"); + assert.match(tray, /string\.IsNullOrWhiteSpace\(workingDirectory\)/, "the native tray refuses an empty working directory"); + assert.match(tray, /WorkingDirectory = workingDirectory,/, "the native tray starts the launcher outside the installation"); }); test("getHostDaemonStatus reports no daemon off Windows", async () => { diff --git a/native/tray/Program.cs b/native/tray/Program.cs index 85eb6df93..8f77129a2 100644 --- a/native/tray/Program.cs +++ b/native/tray/Program.cs @@ -253,11 +253,22 @@ private void StartWebServer() if (_nodeExe == null) _nodeExe = FindNodeExecutable(); + // Never from inside the installation: a cwd there blocks the next replacement on Windows. + var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (string.IsNullOrWhiteSpace(workingDirectory)) + { + // An empty value starts the child in the target's directory (or in this process's + // current one), and both of those are the installation. + WriteLog("USERPROFILE is empty: refusing to start the web server inside the installation."); + _state = "Stopped"; + UpdateTrayUI(); + return; + } + var psi = new ProcessStartInfo { FileName = _nodeExe, - // Never from inside the installation: a cwd there blocks the next replacement on Windows. - WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + WorkingDirectory = workingDirectory, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, diff --git a/scripts/windows/install-tray.ps1 b/scripts/windows/install-tray.ps1 index 165cca369..539a055d4 100644 --- a/scripts/windows/install-tray.ps1 +++ b/scripts/windows/install-tray.ps1 @@ -34,6 +34,11 @@ $LaunchVbs = Join-Path $RepoRoot "scripts\windows\launch-tray.vbs" # directory that is a live process's working directory (ERROR_SHARING_VIOLATION). # The shortcuts launch absolute targets, so they start outside the installation. $ShortcutWorkingDirectory = $env:USERPROFILE +# A shortcut with an empty working directory starts in its target's directory, which is the +# installation; refuse instead of silently reintroducing the lock. +if ([string]::IsNullOrWhiteSpace($ShortcutWorkingDirectory)) { + throw "USERPROFILE is empty: refusing to create omp-web shortcuts that start inside the installation." +} function Log-Message([string]$msg) { if (!$Quiet) { diff --git a/scripts/windows/omp-web-host.ps1 b/scripts/windows/omp-web-host.ps1 index d0692de34..6c2452872 100644 --- a/scripts/windows/omp-web-host.ps1 +++ b/scripts/windows/omp-web-host.ps1 @@ -19,6 +19,11 @@ $LauncherJs = Join-Path $RepoRoot "bin\omp-web.js" # directory that is a live process's working directory (ERROR_SHARING_VIOLATION). # Every path below is absolute, so the children start outside the installation. $LaunchWorkingDirectory = $env:USERPROFILE +# An empty value would make the child inherit the process's own directory, which is the +# installation; refuse instead of silently reintroducing the lock. +if ([string]::IsNullOrWhiteSpace($LaunchWorkingDirectory)) { + throw "USERPROFILE is empty: refusing to start omp-web from inside its installation directory." +} # One daemon supervisor per logon session. $createdNew = $false diff --git a/scripts/windows/omp-web-service.ps1 b/scripts/windows/omp-web-service.ps1 index f75f68699..816c55d95 100644 --- a/scripts/windows/omp-web-service.ps1 +++ b/scripts/windows/omp-web-service.ps1 @@ -18,6 +18,11 @@ $PkgJsonPath = Join-Path $RepoRoot "package.json" # directory that is a live process's working directory (ERROR_SHARING_VIOLATION). # Every path below is absolute, so the server starts outside the installation. $LaunchWorkingDirectory = $env:USERPROFILE +# An empty value would make the child inherit the process's own directory, which is the +# installation; refuse instead of silently reintroducing the lock. +if ([string]::IsNullOrWhiteSpace($LaunchWorkingDirectory)) { + throw "USERPROFILE is empty: refusing to start omp-web from inside its installation directory." +} $PkgVersion = "0.0.0" if (Test-Path $PkgJsonPath) { try { $pkg = Get-Content $PkgJsonPath -Raw | ConvertFrom-Json; if ($pkg.version) { $PkgVersion = $pkg.version } } catch { } diff --git a/scripts/windows/omp-web-tray.ps1 b/scripts/windows/omp-web-tray.ps1 index e14702e75..79c1260b5 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -43,6 +43,11 @@ $PkgJsonPath = Join-Path $RepoRoot "package.json" # directory that is a live process's working directory (ERROR_SHARING_VIOLATION). # Every path below is absolute, so the server and the shortcuts start outside it. $LaunchWorkingDirectory = $env:USERPROFILE +# An empty value would make the child inherit the process's own directory, which is the +# installation; refuse instead of silently reintroducing the lock. +if ([string]::IsNullOrWhiteSpace($LaunchWorkingDirectory)) { + throw "USERPROFILE is empty: refusing to start omp-web from inside its installation directory." +} $PkgVersion = "0.0.0" if (Test-Path $PkgJsonPath) { try {