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/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/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 edde606ce..3f1c5ad2f 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -130,6 +130,57 @@ 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()}`); + } + } + // 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`); + } + // 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"); + 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"); + 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 () => { 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..8f77129a2 100644 --- a/native/tray/Program.cs +++ b/native/tray/Program.cs @@ -253,10 +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, - WorkingDirectory = _repoRoot, + WorkingDirectory = workingDirectory, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, @@ -271,10 +283,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/install-tray.ps1 b/scripts/windows/install-tray.ps1 index 06ebd374c..539a055d4 100644 --- a/scripts/windows/install-tray.ps1 +++ b/scripts/windows/install-tray.ps1 @@ -30,6 +30,16 @@ $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 +# 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) { Write-Host $msg @@ -172,7 +182,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 +203,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 +225,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 +303,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..6c2452872 100644 --- a/scripts/windows/omp-web-host.ps1 +++ b/scripts/windows/omp-web-host.ps1 @@ -15,6 +15,16 @@ 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 +# 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 try { $script:AppMutex = New-Object System.Threading.Mutex($true, "Local\OmpWebHostDaemon_Instance_Mutex", [ref]$createdNew) } catch { $createdNew = $true } @@ -47,7 +57,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..816c55d95 100644 --- a/scripts/windows/omp-web-service.ps1 +++ b/scripts/windows/omp-web-service.ps1 @@ -13,6 +13,16 @@ 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 +# 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 { } @@ -119,7 +129,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 @@ -128,11 +138,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 07f9d7d2f..79c1260b5 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -38,6 +38,16 @@ 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 +# 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 { @@ -236,7 +246,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 @@ -246,13 +256,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 @@ -363,7 +377,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" }