diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index fdd60495bfe..862af1648e1 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -904,6 +904,9 @@ to refresh its XML before it can hand off to a newer install. ### `ocx service [install|repair|restart|start|stop|status|uninstall|remove]` +If `ocx service start` reports that the Windows Task Scheduler service is not installed, +run `ocx service install` to register it. `start` exits with status 1 when the registration is missing. + On Windows Task Scheduler, the service wrapper restarts the proxy after five seconds even when an external tool terminates it with exit code 0. If another opencodex proxy already owns the port, the wrapper exits deliberately. Use `ocx stop` or diff --git a/src/service/cli.ts b/src/service/cli.ts index a891f052655..3cce746d4ca 100644 --- a/src/service/cli.ts +++ b/src/service/cli.ts @@ -24,7 +24,7 @@ import { ownershipMutationLeaseStatusLine } from "./ownership-mutation-lease.mjs import { foreignServiceOwnerRefusal, unknownServiceOwnerRefusal } from "./repair"; import type { ServiceBackend } from "./state"; import { unitPath } from "./systemd"; -import { inspectWindowsSchedulerServiceStatus, schtasksErrorDetail, probeWindowsSchedulerTask } from "./windows-scheduler"; +import { inspectWindowsSchedulerServiceStatus, schtasksErrorDetail, probeWindowsSchedulerTask, startWindowsSchedulerService, windowsSchedulerStartRecovery } from "./windows-scheduler"; import type { WindowsSchedulerTaskProbe } from "./windows-scheduler"; import { win32 } from "node:path"; import { serviceDiagnosticsSummary } from "./diagnostics"; @@ -393,7 +393,14 @@ export async function serviceCommand(...args: (string | undefined)[]): Promise { ops.start(); }, + process.platform === "win32" && backend === "scheduler" ? windowsSchedulerStartRecovery : () => null); + if (missingTask) { + console.error(`❌ ${missingTask}`); + process.exitCode = 1; + break; + } await reportServiceServing("started"); break; } diff --git a/src/service/windows-scheduler.ts b/src/service/windows-scheduler.ts index f04f8c62660..1f4834194ab 100644 --- a/src/service/windows-scheduler.ts +++ b/src/service/windows-scheduler.ts @@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process"; import { findLiveProxy } from "../server/proxy-liveness"; import { existsSync, readFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; -import { ELEVATION_REQUEST_TIMEOUT_MS, OCX_ELEVATED_PROTOCOL_FAILED, raceWithTimeout, resolveTrustedWindowsSchtasksExe, startElevatedSchtasksCreateAndRun, runWindowsElevated, toWindowsSchtasksError, WindowsElevationError, type ElevatedSchedulerOutcome, type ElevatedSchtasksCreateAndRunExecution, type ElevatedSchtasksCreateAndRunResult } from "../lib/windows-elevation"; +import { ELEVATION_REQUEST_TIMEOUT_MS, OCX_ELEVATED_PROTOCOL_FAILED, raceWithTimeout, resolveTrustedWindowsSchtasksExe, startElevatedSchtasksCreateAndRun, runWindowsElevated, toWindowsSchtasksError, WindowsElevationError, WindowsSchtasksError, type ElevatedSchedulerOutcome, type ElevatedSchtasksCreateAndRunExecution, type ElevatedSchtasksCreateAndRunResult } from "../lib/windows-elevation"; import { statusWinswRaw } from "../lib/winsw"; import { decodeWindowsTextBytes, type WindowsTextDecodeOptions } from "../lib/windows-text"; import { isTestHomeGuardArmed } from "../lib/test-home-guard"; @@ -257,6 +257,36 @@ export function probeWindowsSchedulerTask(taskName = TASK): WindowsSchedulerTask } } +/** Explain a missing registration at the CLI boundary while preserving other start failures. */ +export function windowsSchedulerStartRecovery( + error: unknown, + probe = probeWindowsSchedulerTask, +): string | null { + // /run uses the same exit code for multiple failures. Confirm registration independently + // so the install advice does not depend on the locale or mask an explicit access denial. + if (!(error instanceof WindowsSchtasksError) || error.operation !== "run" || error.reason !== "other" + || probe().status !== "absent") return null; + return "Service is not installed (Task Scheduler). Run 'ocx service install' first."; +} + +/** + * `ocx service start` on the Scheduler backend: run the start and return install advice only for a + * confirmed missing registration. Every other failure propagates unchanged; success returns null. + */ +export function startWindowsSchedulerService( + start: () => void, + recovery: (error: unknown) => string | null = windowsSchedulerStartRecovery, +): string | null { + try { + start(); + return null; + } catch (error) { + const advice = recovery(error); + if (!advice) throw error; + return advice; + } +} + /** True when the Task Scheduler registration for the default proxy task is proven present. */ export function windowsSchedulerTaskInstalled(taskName = TASK): boolean { return probeWindowsSchedulerTask(taskName).status === "present"; diff --git a/structure/ops/service-and-sidecars.md b/structure/ops/service-and-sidecars.md index 01b1e3deeb1..df1be91805e 100644 --- a/structure/ops/service-and-sidecars.md +++ b/structure/ops/service-and-sidecars.md @@ -22,7 +22,7 @@ any platform status probe. macOS and Linux choose from the registration file's p Windows combines the Task Scheduler and WinSW probes into `installed`, `absent`, or `unknown`. Only proven absence enters registration. A query failure refuses the bare command with status guidance, because treating `unknown` as absent can rerun elevated `schtasks /create` against an -existing task. Explicit `ocx service install` remains the operator-owned registration request. +existing task. Explicit `ocx service install` remains the operator-owned registration request. After a generic Scheduler `/run` failure, `ocx service start` uses the same registration probe before giving install advice. Confirmed absence returns exit 1 with the install command. Present or unreadable registrations and explicit access denials retain the original failure. `src/lib/windows-elevation.ts` formats scheduler exec failures without echoing child stderr; generic failures retain the numeric exit status. Delete, run and end access denials name the exact command to run from an elevated terminal. `src/service/windows-scheduler.ts` also classifies an owned-task delete exiting 1 as denied when a fresh probe proves the task survived; absent, unreadable and failed probes do not establish that classification. `src/service/windows-ops.ts` retains service assets until deletion is proven complete. `tests/windows/windows-scheduler-errors.test.ts` exercises these paths with injected runners. diff --git a/tests/windows/windows-scheduler-errors.test.ts b/tests/windows/windows-scheduler-errors.test.ts index fa41e83e202..7ed37c51040 100644 --- a/tests/windows/windows-scheduler-errors.test.ts +++ b/tests/windows/windows-scheduler-errors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { WindowsSchtasksError, WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER } from "../../src/lib/windows-elevation"; -import { schtasks, schtasksErrorDetail, type WindowsSchedulerTaskProbe } from "../../src/service/windows-scheduler"; +import { schtasks, schtasksErrorDetail, startWindowsSchedulerService, windowsSchedulerStartRecovery, type WindowsSchedulerTaskProbe } from "../../src/service/windows-scheduler"; import { isWindowsSchedulerEndBenign } from "../../src/service/windows-ops"; const task = "opencodex-proxy"; @@ -89,3 +89,40 @@ describe("Task Scheduler failure diagnostics (#7772)", () => { expect(schtasksErrorDetail(failure())).toBe("Task Scheduler command failed (exit code 1): schtasks /query"); }); }); + +describe("Windows Scheduler start recovery (#9038)", () => { + const runFailure = () => failedCommand(["/run", "/tn", task], failure(1, Buffer.from("ERROR: The system cannot find the file specified."))); + + test("proven absence returns install guidance after the start attempt fails", () => { + expect(windowsSchedulerStartRecovery(runFailure(), () => ({ status: "absent" }))) + .toBe("Service is not installed (Task Scheduler). Run 'ocx service install' first."); + }); + + for (const state of [{ status: "present" }, { status: "unknown", detail: "query failed" }] as const) { + test(`gives no install advice when the registration is ${state.status}`, () => { + expect(windowsSchedulerStartRecovery(runFailure(), () => state)).toBeNull(); + }); + } + + test("explicit permission and other command failures do not query registration", () => { + const probe = () => { throw new Error("unexpected registration probe"); }; + const denied = failedCommand(["/run", "/tn", task], failure(1, Buffer.from("ERROR: Access is denied."))); + expect(windowsSchedulerStartRecovery(denied, probe)).toBeNull(); + expect(windowsSchedulerStartRecovery(failedCommand(["/end", "/tn", task], failure()), probe)).toBeNull(); + }); + + test("the start runs once and only a confirmed missing registration becomes advice", () => { + let starts = 0; + const missing = runFailure(); + const advice = startWindowsSchedulerService(() => { starts++; throw missing; }, error => windowsSchedulerStartRecovery(error, () => ({ status: "absent" }))); + expect(advice).toBe("Service is not installed (Task Scheduler). Run 'ocx service install' first."); + expect(starts).toBe(1); + expect(startWindowsSchedulerService(() => { starts++; })).toBeNull(); + expect(starts).toBe(2); + // A present or unreadable registration rethrows the original Scheduler error, unchanged. + for (const state of [{ status: "present" }, { status: "unknown", detail: "query failed" }] as const) { + expect(() => startWindowsSchedulerService(() => { throw missing; }, error => windowsSchedulerStartRecovery(error, () => state))) + .toThrow(missing); + } + }); +});