Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion bin/omp-web-options.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);

Expand Down Expand Up @@ -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 };
7 changes: 5 additions & 2 deletions bin/omp-web.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
}));
Expand Down
6 changes: 3 additions & 3 deletions lib/hosts/local-daemon-start.test.mjs
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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() });
});
5 changes: 3 additions & 2 deletions lib/hosts/local-daemon-start.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -53,11 +54,11 @@ async function probe(): Promise<HostControlStatus | null> {

/** 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 {
Expand Down
17 changes: 16 additions & 1 deletion lib/omp-web-options.test.mjs
Original file line number Diff line number Diff line change
@@ -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([], {});
Expand Down
51 changes: 51 additions & 0 deletions lib/windows-service.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
7 changes: 4 additions & 3 deletions lib/windows-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
22 changes: 20 additions & 2 deletions native/tray/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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();
Expand Down
20 changes: 16 additions & 4 deletions scripts/windows/install-tray.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand Down Expand Up @@ -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
}
12 changes: 11 additions & 1 deletion scripts/windows/omp-web-host.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading