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
3 changes: 3 additions & 0 deletions docs-site/src/content/docs/reference/cli/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions src/service/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -393,7 +393,14 @@ export async function serviceCommand(...args: (string | undefined)[]): Promise<v
process.exitCode = 1;
break;
}
ops.start();
// Only a confirmed missing Scheduler registration becomes advice; anything else still throws.
const missingTask = startWindowsSchedulerService(() => { ops.start(); },
process.platform === "win32" && backend === "scheduler" ? windowsSchedulerStartRecovery : () => null);
if (missingTask) {
console.error(`❌ ${missingTask}`);
process.exitCode = 1;
break;
}
await reportServiceServing("started");
break;
}
Expand Down
32 changes: 31 additions & 1 deletion src/service/windows-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion structure/ops/service-and-sidecars.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
39 changes: 38 additions & 1 deletion tests/windows/windows-scheduler-errors.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
}
});
});
Loading