diff --git a/.changeset/windows-scheduled-task.md b/.changeset/windows-scheduled-task.md new file mode 100644 index 00000000..dcaebee4 --- /dev/null +++ b/.changeset/windows-scheduled-task.md @@ -0,0 +1,13 @@ +--- +"sessionpipe": minor +"sessionpipe-core": minor +--- + +On Windows the control daemon now keeps running: a scheduled task at your logon, beside launchd and systemd + +- `control pair`, `connect`, `pool on` and `ask on` used to end with `no service manager for this platform yet; run sessionpipe control run yourself` on Windows, so the daemon lived as long as the terminal it was started in. They now register a per-user task, `\sessionpipe\org.sessionpipe.control` in Task Scheduler, that starts the daemon when you log on. No administrator is needed: the task is created from a definition with a logon trigger that names you, which Windows lets a standard user do. `control off` removes it, and `--no-service` still leaves it out. +- It opens no window. A task that runs `node.exe` directly opens a terminal window at every logon (measured on Windows 11); the task runs it under `conhost.exe --headless` instead. +- Task Scheduler gives a program no environment, keeps none of its output and restarts it on no exit code, so the task runs a small launcher, `%LOCALAPPDATA%\sessionpipe\service\org.sessionpipe.control.cjs`. It gives the daemon the PATH of the shell that paired, appends its output to `control\daemon.log`, starts it again at once when it exits 75 for an update and after 5 seconds when it fails, and ends when it exits 0. What it runs is one line of JSON in that file, so no path, argument or variable is read by `cmd.exe`. A Node or a profile folder with a `"` or a `%` in its path can't be carried on the task's own command line: pairing says so and installs no task. +- `sessionpipe update` moves the task onto the copy you type, as it does a launchd or systemd service, and the daemon's own daily update restarts through the launcher. `status` and `doctor` no longer say updates on Windows run only while `sessionpipe control run` is running, and `doctor` says when Task Scheduler doesn't have the task. Before it replaces the task, `update` writes down which sessions are mid-turn, as it does for a daemon from before 0.15: replacing a task ends its processes outright, before the daemon can write that down itself. `sessionpipe reinstall` still does not run on Windows. +- A sessionpipe with a service of its own (`SESSIONPIPE_SERVICE_LABEL`) now gives it `APPDATA` and `LOCALAPPDATA` too. On Windows its files are under those, and without them such a service came up on the account's real files. +- `sessionpipe-core/service`: `installService`, `serviceState` and `uninstallService` take `platform: "win32"`; `ServicePlan.manager` and `ServiceState.manager` may be `"schtasks"`; `serviceFiles` also answers the `launcher`; `ServiceSpec.node` names the Node that runs it. The process is told `SESSIONPIPE_SERVICE=schtasks:`, the pid being the launcher's. diff --git a/packages/cli/README.md b/packages/cli/README.md index f4341b51..532d7304 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -69,6 +69,15 @@ sessionpipe control keys [remove ] sessionpipe control off # tell the receiver, forget its token and keys ``` +Pairing keeps the daemon running without a terminal: a launchd agent on macOS, a systemd +user unit on Linux, and on Windows a scheduled task at your logon +(`\sessionpipe\org.sessionpipe.control` in Task Scheduler). None of them needs root or an +administrator. The Windows task opens no window: it runs Node under `conhost.exe +--headless`, on a small launcher +(`%LOCALAPPDATA%\sessionpipe\service\org.sessionpipe.control.cjs`) that gives the daemon +the PATH of the shell that paired, appends its output to `daemon.log`, and starts it again +when it exits for an update or fails. `control off` removes it. + Pairing through `npx` first installs that version globally and runs pairing from that persistent copy. On Homebrew, the daemon uses a matching stable Node link so a Node upgrade does not leave it pointing at a removed Cellar version. @@ -256,7 +265,8 @@ receivers; and the last line says so. It does four things, in order: 2. Writes the hooks again from this copy. 3. Puts the background service on this copy, the same one you type, so the two cannot drift apart. How depends on who runs it: - - **launchd or systemd has it, and it runs another copy or doesn't answer.** It is + - **launchd, systemd or Task Scheduler has it, and it runs another copy or doesn't + answer.** It is replaced. It keeps the environment its service file gave it (its PATH, a `SESSIONPIPE_CLAUDE` you added by hand); only the program changes. - **Its service file is there and nothing runs** (a start that failed). It is put back. @@ -277,9 +287,9 @@ says what to type next (into a pipe: one line, with `Next: ` at its end | npm can't write the prefix (installed with sudo) | `sudo npm install -g --prefix sessionpipe@ && sessionpipe update`. On Windows there is no sudo: `sessionpipe update`, from a terminal opened as administrator | | This copy isn't an npm install (a git checkout, a dev build) | `npx sessionpipe@latest update` | | The hooks couldn't be written | `sessionpipe install` | -| Nothing runs the service and there is no service file for it: you run it yourself, or nothing manages services here (Windows, a container) | `sessionpipe control run` | +| Nothing runs the service and there is no service file for it: you run it yourself, or nothing manages services here (a container) | `sessionpipe control run` | | You run the service yourself and it didn't restart | `sessionpipe control run`, after stopping it where it runs | -| launchd or systemd refused the new service. The one that was there before is put back and started again | `sessionpipe update` when a service answers again; `sessionpipe control run` when nothing answers | +| launchd, systemd or Task Scheduler refused the new service. The one that was there before is put back and started again | `sessionpipe update` when a service answers again; `sessionpipe control run` when nothing answers | | The service was started and doesn't answer, or answers as another version | `sessionpipe doctor` | A receiver that hasn't answered the service is not a failed update. The last line still @@ -297,7 +307,7 @@ it is mid-turn, so a message to it still waits for its Stop. A service from before 0.15 has neither habit. It forgets who is mid-turn when it stops, and it restarts itself only once no session on the computer is mid-turn, which on a busy -computer never comes. So where launchd or systemd has it, `update` replaces it at once, +computer never comes. So where a service manager has it, `update` replaces it at once, after writing down for the new one who is mid-turn. One that someone runs by hand can only restart itself, by its older rule: `update` says so, and that nothing more is to be typed. @@ -342,6 +352,8 @@ How it restarts depends on how it runs: - **launchd (macOS) or systemd (Linux)**, as `control pair` / `connect` set it up: the daemon exits with code 75 and the service starts it again. Every service file sessionpipe has written restarts on a non-zero exit, so older installs need nothing. +- **Task Scheduler (Windows)**: the daemon exits with code 75 and the task's launcher + starts it again at once, as it does 5 seconds after a failure. - **Anything else** (a terminal, tmux, a container that starts `sessionpipe control run` itself): the old process stays as the new daemon's parent, with the same environment and output, and restarts it the same way after each later update. Whatever waits on @@ -354,7 +366,8 @@ Only a global npm install that this user can write updates itself; a copy in the cache, a git checkout or a dev build is left alone. `sessionpipe doctor` says whether it's on, when it last checked and what it found; the daemon's log (`~/.local/state/sessionpipe/control/daemon.log` under launchd, -`journalctl --user -u sessionpipe-control.service` under systemd) has one line per check +`journalctl --user -u sessionpipe-control.service` under systemd, +`%LOCALAPPDATA%\sessionpipe\control\daemon.log` on Windows) has one line per check and per update. ```sh @@ -363,7 +376,8 @@ sessionpipe update on ``` `SESSIONPIPE_NO_UPDATE_CHECK=1` turns the daily update off too, but only where the -service can see it: a launchd or systemd service doesn't inherit your shell's variables, +service can see it: a service that launchd, systemd or Task Scheduler starts doesn't +inherit your shell's variables, while `sessionpipe update off` reaches it (it re-reads the config every ten minutes). Set in your shell, it makes `sessionpipe update` there change nothing (above). The registry asked is npm's own, or the one `npm_config_registry` names. @@ -516,7 +530,8 @@ What only the service's log used to know is on that page: a disk that filled up, it can't read from the keychain, a pool with no account left to try, a receiver that hasn't answered. Whether Claude Code is signed in is asked of the running service over its socket, since a shell over ssh can't read a Mac's login keychain and would only -guess; and a service that launchd or systemd doesn't have at all is said to be that, +guess; and a service that launchd, systemd or Task Scheduler doesn't have at all is said +to be that, not merely "offline". `sessionpipe control status` is a page for a person at a terminal, and the JSON it diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 190dfff9..750ca892 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -74,7 +74,7 @@ import { type Trouble, } from "./control/health.js"; import { ask, type Health, socketPath } from "./control/local.js"; -import { placeService } from "./control/pair.js"; +import { managerName, placeService } from "./control/pair.js"; import { controlFile, controlState, @@ -1471,10 +1471,13 @@ async function checkup(deep: boolean): Promise<{ report: Record value: loaded ? "started but not answering" : look - ? `not loaded: ${look.manager} doesn't have it` + ? `not loaded: ${managerName(look.manager as NonNullable)} doesn't have it` : "not running", }); - if (look && !loaded) warnings.push(`the background service isn't loaded: ${look.manager} doesn't have it`); + if (look && !loaded) + warnings.push( + `the background service isn't loaded: ${managerName(look.manager as NonNullable)} doesn't have it`, + ); if (loaded) todo.push({ order: 1, diff --git a/packages/cli/src/control/autoupdate.ts b/packages/cli/src/control/autoupdate.ts index c290cf37..cadf8eca 100644 --- a/packages/cli/src/control/autoupdate.ts +++ b/packages/cli/src/control/autoupdate.ts @@ -14,6 +14,7 @@ // restart: // // launchd / systemd exit UPDATE_EXIT; the service restarts it on the new code +// Task Scheduler exit UPDATE_EXIT; the task's launcher restarts it on the new code // (every plist and unit sessionpipe ever wrote restarts on a // non-zero exit). // anything else this process stops being the daemon and becomes its parent: @@ -103,24 +104,14 @@ export function updateSummary(o: { off: string | null; paired: boolean; rec: UpdateRecord; - platform?: NodeJS.Platform; }): UpdateSummary { const daemonEnv = o.rec.off?.startsWith("SESSIONPIPE_NO_UPDATE_CHECK") ? "SESSIONPIPE_NO_UPDATE_CHECK is set in the daemon's environment" : null; - // No service manager runs the daemon on Windows yet (pair says so): it checks only while - // someone keeps `sessionpipe control run` going, which is not "automatic". - // These two reasons are the value of `update.off` in `status --json` and `doctor - // --json`, which programs read: they keep the words they have always had there. - const byHand = - (o.platform ?? process.platform) === "win32" - ? "it runs in the control daemon, which has no service on Windows yet: it checks while `sessionpipe control run` is running" - : null; + // This reason is the value of `update.off` in `status --json` and `doctor --json`, + // which programs read: it keeps the words it has always had there. const off = - o.off ?? - (o.paired - ? (daemonEnv ?? byHand) - : "it runs in the control daemon, which isn't set up here (`sessionpipe connect`)"); + o.off ?? (o.paired ? daemonEnv : "it runs in the control daemon, which isn't set up here (`sessionpipe connect`)"); return { auto: !off, off, @@ -142,7 +133,7 @@ export function ago(iso: string, now: number): string { return `${Math.round(ms / DAY_MS)} days ago`; } -export type RestartVia = "launchd" | "systemd" | "supervisor"; +export type RestartVia = "launchd" | "systemd" | "schtasks" | "supervisor"; /** Who restarts this process when it exits UPDATE_EXIT, or null when nobody will (it * then supervises the new daemon itself). A wrong "nobody" costs one extra process; a @@ -170,9 +161,16 @@ export function restartVia(o: { const mainPid = !o.env.SYSTEMD_EXEC_PID || o.env.SYSTEMD_EXEC_PID === String(o.pid); if (inUnit && mainPid) return "systemd"; } + // The scheduled task's launcher (sessionpipe-core/service) names itself by its pid, as + // the supervisor does: only the process it started has it for a parent. + if (o.platform === "win32" && s === `schtasks:${o.ppid}`) return "schtasks"; return null; } +/** Who starts the daemon again after it exits UPDATE_EXIT, as its log names them. */ +export const restartedBy = (via: RestartVia): string => + via === "supervisor" ? "the supervising sessionpipe" : via === "schtasks" ? "the scheduled task's launcher" : via; + /** What the daemon offers the updater. */ export interface Quiescent { /** Null when nothing is in hand; otherwise what is. */ diff --git a/packages/cli/src/control/cli.ts b/packages/cli/src/control/cli.ts index 81d2a05d..e7ab7c9a 100644 --- a/packages/cli/src/control/cli.ts +++ b/packages/cli/src/control/cli.ts @@ -29,7 +29,15 @@ import { controlAccount, secretGet, sinkWithSecrets } from "../secrets.js"; import { shq } from "../shell.js"; import { clean, PLAIN, table, tint, type Ui } from "../style.js"; import { copyOnPath, installEverywhere, installedVersion, latestVersion } from "../update.js"; -import { AutoUpdater, autoUpdateOff, restartVia, supervise, UPDATE_EXIT, updateFile } from "./autoupdate.js"; +import { + AutoUpdater, + autoUpdateOff, + restartedBy, + restartVia, + supervise, + UPDATE_EXIT, + updateFile, +} from "./autoupdate.js"; import { namedAsChannel, parentArgv, runChannel } from "./channel.js"; import { ControlDaemon, DaemonRunning, type Status } from "./daemon.js"; import { ask, socketPath } from "./local.js"; @@ -508,7 +516,7 @@ async function runDaemon(out: (s?: string) => void, distDir: string): Promise`: a key enters this machine's trust store only // from this terminal (spec/CONTROL.md §2). The receiver hands back a passkey and a // proof over sha256("sessionpipe.pair::"); the key is trusted only once -// the proof verifies here. Also the service files (launchd / systemd) that keep the +// the proof verifies here. Also the service files (launchd / systemd / Task Scheduler) that keep the // daemon running, and `control off`. import { randomBytes } from "node:crypto"; import { chmodSync, closeSync, mkdirSync, openSync, readFileSync } from "node:fs"; @@ -345,16 +345,17 @@ export function removeKey(id: string, env?: NodeJS.ProcessEnv): number { } // --- the service ------------------------------------------------------------------- -// The launchd agent and the systemd user unit are core's (sessionpipe-core/service); +// The launchd agent, the systemd user unit and the Windows scheduled task are core's +// (sessionpipe-core/service); // this is the daemon's: its label, its command line, and what to tell the person. const DESCRIPTION = "sessionpipe control daemon (signed messages to your coding sessions)"; export { type Exec, ensureLinger } from "@sessionpipe/core/service"; -/** The daemon's service: ` control run`, logging to the state dir. Both files - * restart it when it exits non-zero; an update exits UPDATE_EXIT (75) to come back on - * the new code. SESSIONPIPE_SERVICE tells the daemon which manager that is. */ +/** The daemon's service: ` control run`, logging to the state dir. Each + * manager restarts it when it exits non-zero; an update exits UPDATE_EXIT (75) to come + * back on the new code. SESSIONPIPE_SERVICE tells the daemon which manager that is. */ const spec = (o: { node: string; cli: string; @@ -367,6 +368,8 @@ const spec = (o: { unit: o.names?.unit ?? UNIT, description: DESCRIPTION, argv: [o.node, o.cli, "control", "run"], + // Windows: the node that runs the daemon runs the task's launcher too. + node: o.node, logPath: path.join(o.logDir, "daemon.log"), ...(o.home ? { home: o.home } : {}), ...(o.env ? { env: o.env } : {}), @@ -374,23 +377,26 @@ const spec = (o: { /** What the service file carries beside SESSIONPIPE_SERVICE: the PATH of the shell that * paired (launchd's and systemd's own is a bare /usr/bin:/bin, where a `claude` under nvm - * or Homebrew is not), and the `claude` that shell could see, pinned for the daemon as + * or Homebrew is not; a Windows task's is the one the account logs on with, without what + * that shell added), and the `claude` that shell could see, pinned for the daemon as * SESSIONPIPE_CLAUDE (a path that stops existing is skipped and looked for again). */ export function serviceEnv(env: NodeJS.ProcessEnv = process.env): Record { const out: Record = {}; // A sessionpipe with a service of its own (SESSIONPIPE_SERVICE_LABEL: a throwaway // world) gives that service the same world: where its files are, whose home it is and // which registry npm asks. Without this the service would come up in this computer's - // real home, beside the real one. + // real home, beside the real one (on Windows its files are under LOCALAPPDATA and + // APPDATA, which a task gets from the account and not from this shell). if (env.SESSIONPIPE_SERVICE_LABEL) for (const [k, v] of Object.entries(env)) if (v !== undefined && WORLD.test(k)) out[k] = v; - if (env.PATH) out.PATH = env.PATH; + const pathVal = env.PATH ?? Object.entries(env).find(([k, v]) => v !== undefined && k.toLowerCase() === "path")?.[1]; + if (pathVal) out.PATH = pathVal; const claude = claudeControl.findClaude(env); if (claude) out.SESSIONPIPE_CLAUDE = claude; return out; } const WORLD = - /^(SESSIONPIPE_.+|HOME|USERPROFILE|XDG_[A-Z]+_HOME|CLAUDE_CONFIG_DIR|CODEX_HOME|GEMINI_CLI_HOME|GROK_HOME|npm_config_registry)$/; + /^(SESSIONPIPE_.+|HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z]+_HOME|CLAUDE_CONFIG_DIR|CODEX_HOME|GEMINI_CLI_HOME|GROK_HOME|npm_config_registry)$/i; export function serviceFiles(o: { node: string; @@ -423,14 +429,17 @@ interface Placing { function put( o: Placing, keep: boolean, -): { plan: core.ServicePlan; label: string; unit: string; file: string; log: string } | { left: string } { +): + | { plan: core.ServicePlan; label: string; unit: string; file: string; log: string; platform: NodeJS.Platform } + | { left: string } { const names = serviceNames(o.env) ?? (o.exec ? { label: LABEL, unit: UNIT } : null); if (!names) return { left: noService(o.env) as string }; const { label, unit } = names; const logDir = controlState(o.env); const here = spec({ node: o.node, cli: o.cli, logDir, names }); const files = core.serviceFiles(here); - const file = (o.platform ?? process.platform) === "darwin" ? files.plist.path : files.unit.path; + const platform = o.platform ?? process.platform; + const file = (platform === "darwin" ? files.plist : platform === "win32" ? files.launcher : files.unit).path; let old: string | null = null; try { old = readFileSync(file, "utf8"); @@ -442,7 +451,8 @@ function put( return { left: `${file} is another program's service (it runs ${was.join(" ")}), and is left as it is` }; mkdirSync(logDir, { recursive: true, mode: 0o700 }); const log = path.join(logDir, "daemon.log"); - // launchd and systemd create this file themselves, with whatever the umask says. It + // launchd and systemd create this file themselves, with whatever the umask says (and + // so does the Windows launcher, under the profile's own permissions). It // sits beside the nonces and the acks, which are 0600 (CONTROL.md §8), and it holds // message ids, session ids and folder paths — so it is created here, private, before // the service can make a readable one. @@ -461,12 +471,17 @@ function put( env: given ? kept : serviceEnv(o.env), ...(o.exec ? { exec: o.exec } : {}), ...(o.platform ? { platform: o.platform } : {}), + ...(o.env ? { shell: o.env } : {}), }); - return { plan, label, unit, file, log }; + return { plan, label, unit, file, log, platform }; } const NO_MANAGER = "no service manager for this platform yet; run `sessionpipe control run` yourself"; -const managed = (platform: NodeJS.Platform = process.platform) => platform === "darwin" || platform === "linux"; +const managed = (platform: NodeJS.Platform = process.platform) => + platform === "darwin" || platform === "linux" || platform === "win32"; +/** A manager as a sentence names it. */ +export const managerName = (manager: "launchd" | "systemd" | "schtasks"): string => + manager === "schtasks" ? "Task Scheduler" : manager; /** Write and start the service for this platform (`control pair`, `pool on`, `ask on`): * it is given the PATH of the shell that ran this (`serviceEnv`). Returns what it did, @@ -475,13 +490,17 @@ export function installService(o: Placing): string { if (!managed(o.platform)) return NO_MANAGER; const r = put(o, false); if ("left" in r) return `left alone: ${r.left}; ${BY_HAND}`; - const { plan, label, unit, file, log } = r; + const { plan, label, unit, file, log, platform } = r; if (plan.manager === "launchd") return plan.domain === "gui" ? `launchd agent ${label} (log: ${log})` : `launchd agent ${label} in the background domain, since nobody is logged in at this Mac's screen; after a restart it starts again when someone logs in there (log: ${log})`; if (plan.manager === "systemd") return `systemd user unit ${unit}; ${plan.linger?.note} (journalctl --user -u ${unit})`; + if (plan.manager === "schtasks") + return `scheduled task ${core.taskName(label)}: it starts when you log on to Windows, with no window (log: ${log})`; + if (platform === "win32") + return `${plan.why ?? `${plan.restored ? `left ${file} as it was` : `wrote ${file}`}, but Task Scheduler didn't take the task`}; run \`sessionpipe control run\` yourself`; return `${plan.restored ? `left ${file} as it was` : `wrote ${file}`}, but systemd --user isn't reachable here; run \`sessionpipe control run\` yourself (tmux, screen)`; } @@ -503,11 +522,13 @@ export function placeService(o: Placing): void { if ("left" in r) throw new Error(r.left); if (!r.plan.manager) throw new Error( - `systemd --user didn't start it (it can't be reached from here, or it refused)${r.plan.restored ? back : ""}`, + r.platform === "win32" + ? (r.plan.why ?? `Task Scheduler didn't take the task (schtasks refused it)${r.plan.restored ? back : ""}`) + : `systemd --user didn't start it (it can't be reached from here, or it refused)${r.plan.restored ? back : ""}`, ); } export function uninstallService(env?: NodeJS.ProcessEnv): void { const names = serviceNames(env); - if (names) core.uninstallService(names); + if (names) core.uninstallService({ ...names, ...(env ? { shell: env } : {}) }); } diff --git a/packages/cli/src/current.ts b/packages/cli/src/current.ts index 5d7fd671..dff2b7d3 100644 --- a/packages/cli/src/current.ts +++ b/packages/cli/src/current.ts @@ -309,7 +309,10 @@ export async function bringCurrent(d: CurrentDeps, o: { installed?: boolean } = // A service from before 0.15 writes nothing down when it is stopped, and the one // that replaces it would copy a session it didn't know was mid-turn. It is told // apart by what it answers: only one that remembers says which copy it is. - if (running && !remembers) { + // On Windows none gets to write it down: nothing there asks a process to stop + // (replacing the scheduled task ends its processes outright), so it is written + // for that one too. + if (running && (!remembers || d.platform === "win32")) { const turns = running.mid_turn ?? []; if (turns.length) d.seed(turns); } @@ -359,10 +362,10 @@ export async function bringCurrent(d: CurrentDeps, o: { installed?: boolean } = // It runs this copy already, or someone runs it by hand: it restarts itself. const copy = (await d.health())?.copy; if (copy && !d.same(copy.cli, d.cli)) - return copy.via === "launchd" || copy.via === "systemd" + return copy.via === "launchd" || copy.via === "systemd" || copy.via === "schtasks" ? { state: "failed", - error: `the background service runs another copy (${copy.cli}) on sessionpipe ${before.version}, and ${copy.via} can't be asked from this shell to move it onto this one. Run this from a terminal you opened on this computer yourself`, + error: `the background service runs another copy (${copy.cli}) on sessionpipe ${before.version}, and ${copy.via === "schtasks" ? "Task Scheduler" : copy.via} can't be asked from this shell to move it onto this one. Run this from a terminal you opened on this computer yourself`, next: "sessionpipe update", } : { diff --git a/packages/cli/test/control-autoupdate.test.ts b/packages/cli/test/control-autoupdate.test.ts index 244a03cd..87f16695 100644 --- a/packages/cli/test/control-autoupdate.test.ts +++ b/packages/cli/test/control-autoupdate.test.ts @@ -114,12 +114,7 @@ describe("what status says", () => { latest: null, last_error: "ENOTFOUND", }); - const byHand = updateSummary({ off: null, paired: true, rec: {}, platform: "win32" }); - expect(byHand.auto).toBe(false); - expect(byHand.off).toBe( - "it runs in the control daemon, which has no service on Windows yet: it checks while `sessionpipe control run` is running", - ); - expect(updateSummary({ off: null, paired: true, rec: {}, platform: "linux" }).auto).toBe(true); + expect(updateSummary({ off: null, paired: true, rec: {} }).auto).toBe(true); // Why it is off is this copy's own reason first; what failed and what was done both stay. const failed = { version: "0.6.0", at: checked, error: "npm: 403" }; const updated = { from: "0.4.0", to: "0.5.0", at: checked, ms: 1 }; diff --git a/packages/cli/test/control-health.test.ts b/packages/cli/test/control-health.test.ts index fe57bb81..988d15bc 100644 --- a/packages/cli/test/control-health.test.ts +++ b/packages/cli/test/control-health.test.ts @@ -210,7 +210,7 @@ describe.runIf(process.platform !== "win32")("the service as its file says it", pid: null, }); // A platform with no manager: nothing to run, and nothing seen but that. - expect(serviceSeen({ env: {}, platform: "win32" })).toEqual({ + expect(serviceSeen({ env: {}, platform: "freebsd" })).toEqual({ manager: null, file: null, installed: false, @@ -218,7 +218,7 @@ describe.runIf(process.platform !== "win32")("the service as its file says it", argv: null, pid: null, }); - expect(serviceLook({ env: {}, platform: "win32" })).toBeNull(); + expect(serviceLook({ env: {}, platform: "freebsd" })).toBeNull(); }); }); diff --git a/packages/cli/test/control-pair.test.ts b/packages/cli/test/control-pair.test.ts index 8ef08619..9784f4e0 100644 --- a/packages/cli/test/control-pair.test.ts +++ b/packages/cli/test/control-pair.test.ts @@ -13,6 +13,7 @@ import { discover, ensureLinger, installService, + managerName, off, type PairOptions, pair, @@ -708,6 +709,10 @@ describe("the service that keeps the daemon running", () => { const e = serviceEnv({ PATH: shellPath }); if (process.platform !== "win32") expect(e).toEqual({ PATH: shellPath, SESSIONPIPE_CLAUDE: path.join(bin, "claude") }); + // Windows shells often spell it `Path` in a copied env object. + expect(serviceEnv({ Path: "C:\\Windows\\System32", PATH: undefined })).toMatchObject({ + PATH: "C:\\Windows\\System32", + }); expect(serviceEnv({})).toEqual({}); // Both files carry it (the unit's quoting escapes a backslash, so a POSIX path here). const posix = { PATH: "/opt/nvm/bin:/usr/bin:/bin", SESSIONPIPE_CLAUDE: "/opt/nvm/bin/claude" }; @@ -830,23 +835,91 @@ describe("the service that keeps the daemon running", () => { expect(installService({ node: "/n", cli: "/c.js", env, exec, platform: "freebsd" })).toBe( "no service manager for this platform yet; run `sessionpipe control run` yourself", ); - on("win32"); + on("freebsd"); expect(installService({ node: "/n", cli: "/c.js", env, exec })).toContain("no service manager for this platform"); expect(existsSync(path.join(tmp, "state"))).toBe(false); expect(exec.mock.calls.length).toBeGreaterThan(0); }); + it("windows: a scheduled task at logon runs the launcher; says so when Task Scheduler won't take it", () => { + const launcher = path.join(home, "AppData", "Local", "sessionpipe", "service", "org.sessionpipe.control.cjs"); + const log = path.join(tmp, "state", "control", "daemon.log"); + // Task Scheduler stood in: PowerShell has nothing to say, and schtasks takes what it is given. + let refuse = ""; + exec.mockImplementation((cmd, args) => { + if (cmd.endsWith("powershell.exe") || args[0] === refuse) throw new Error("ERROR: Access is denied."); + return ""; + }); + on("win32"); + let r = installService({ node: "C:\\node\\node.exe", cli: "C:\\sp\\cli.js", env, exec }); + expect(r).toBe( + `scheduled task \\sessionpipe\\org.sessionpipe.control: it starts when you log on to Windows, with no window (log: ${log})`, + ); + on(platform); + const text = readFileSync(launcher, "utf8"); + expect(text).toContain( + '"node":"C:\\\\node\\\\node.exe","argv":["C:\\\\node\\\\node.exe","C:\\\\sp\\\\cli.js","control","run"]', + ); + expect(text).toContain(`"log":${JSON.stringify(log)}`); + expect(existsSync(log)).toBe(true); + expect(exec.mock.calls.map((c) => `${path.win32.basename(c[0])} ${c[1][0]}`)).toEqual([ + "powershell.exe -NoProfile", + "schtasks.exe /End", + "schtasks.exe /Create", + "schtasks.exe /Run", + ]); + expect(exec.mock.calls[2]?.[1].slice(0, 3)).toEqual(["/Create", "/TN", "\\sessionpipe\\org.sessionpipe.control"]); + expect(managerName("schtasks")).toBe("Task Scheduler"); + expect(managerName("launchd")).toBe("launchd"); + // `update` places it the same way, and keeps what the launcher gave the daemon. + expect( + placeService({ node: "C:\\node2\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" }), + ).toBeUndefined(); + expect(readFileSync(launcher, "utf8")).toContain('"node":"C:\\\\node2\\\\node.exe"'); + // Refused: the same launcher again has nothing to take back; another one is taken back. + refuse = "/Create"; + const placed = readFileSync(launcher, "utf8"); + r = installService({ node: "C:\\node2\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" }); + expect(r).toBe( + `wrote ${launcher}, but Task Scheduler didn't take the task; run \`sessionpipe control run\` yourself`, + ); + r = installService({ node: "C:\\node3\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" }); + expect(r).toBe( + `left ${launcher} as it was, but Task Scheduler didn't take the task; run \`sessionpipe control run\` yourself`, + ); + expect(readFileSync(launcher, "utf8")).toBe(placed); + expect(() => + placeService({ node: "C:\\node3\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" }), + ).toThrow( + /^Task Scheduler didn't take the task \(schtasks refused it\); the service file that was there before was put back$/, + ); + rmSync(launcher); + expect(() => + placeService({ node: "C:\\node3\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" }), + ).toThrow(/^Task Scheduler didn't take the task \(schtasks refused it\)$/); + // A node the task's command line can't carry: nothing is written, and why is said. + rmSync(launcher); + const why = + 'a scheduled task can\'t carry "C:\\\\100%\\\\node.exe" on its command line (a quote, a % or a line end)'; + expect(installService({ node: "C:\\100%\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" })).toBe( + `${why}; run \`sessionpipe control run\` yourself`, + ); + expect(existsSync(launcher)).toBe(false); + expect(() => + placeService({ node: "C:\\100%\\node.exe", cli: "C:\\sp\\cli.js", env, exec, platform: "win32" }), + ).toThrow(why); + }); + it("update places the service or throws with why: it never answers words that could be passed over", () => { const plist = path.join(home, "Library", "LaunchAgents", "org.sessionpipe.control.plist"); const unit = path.join(home, ".config", "systemd", "user", "sessionpipe-control.service"); expect(placeService({ node: "/n", cli: "/c.js", env, exec, platform: "darwin" })).toBeUndefined(); expect(readFileSync(plist, "utf8")).toContain("/c.js"); // Where nothing manages services there is none to place. - for (const p of ["win32", "freebsd"] as const) - expect(() => placeService({ node: "/n", cli: "/c.js", env, exec, platform: p })).toThrow( - "nothing on this computer starts the background service by itself", - ); - on("win32"); + expect(() => placeService({ node: "/n", cli: "/c.js", env, exec, platform: "freebsd" })).toThrow( + "nothing on this computer starts the background service by itself", + ); + on("freebsd"); expect(() => placeService({ node: "/n", cli: "/c.js", env, exec })).toThrow("nothing on this computer starts"); on(platform); // A sessionpipe pointed away from this computer's files, with nothing stood in: left alone. @@ -961,5 +1034,24 @@ describe("the service that keeps the daemon running", () => { vi.mocked(execFileSync).mockClear(); uninstallService(real); expect(execFileSync).not.toHaveBeenCalled(); + mkdirSync(path.dirname(f.launcher.path), { recursive: true }); + writeFileSync(f.launcher.path, "// launcher"); + vi.mocked(execFileSync).mockImplementation(() => "" as never); + uninstallService({ ...real, SystemRoot: "D:\\Win" }); + expect(existsSync(f.launcher.path)).toBe(false); + expect(vi.mocked(execFileSync).mock.calls.some((c) => c[0] === "D:\\Win\\System32\\schtasks.exe")).toBe(true); + // Without an explicit env argument, both installService and uninstallService use process.env. + vi.stubEnv("SESSIONPIPE_SERVICE_LABEL", "org.sessionpipe.control"); + vi.stubEnv("SESSIONPIPE_STATE", path.join(tmp, "state")); + try { + expect(installService({ node: "C:\\node\\node.exe", cli: "C:\\sp\\cli.js", exec: () => "" })).toContain( + "scheduled task \\sessionpipe\\org.sessionpipe.control", + ); + expect(existsSync(f.launcher.path)).toBe(true); + uninstallService(); + expect(existsSync(f.launcher.path)).toBe(false); + } finally { + vi.unstubAllEnvs(); + } }); }); diff --git a/packages/cli/test/control-service-world.test.ts b/packages/cli/test/control-service-world.test.ts index ab44103a..8ce060e4 100644 --- a/packages/cli/test/control-service-world.test.ts +++ b/packages/cli/test/control-service-world.test.ts @@ -298,7 +298,7 @@ describe.runIf(posix)("a look at the service", () => { it("is null where there is no manager, and in a world with no service of its own", () => { // Nothing stood in: on a platform with no manager nothing is run. - expect(serviceLook({ env: {}, platform: "win32" })).toBeNull(); + expect(serviceLook({ env: {}, platform: "freebsd" })).toBeNull(); expect(serviceLook({ env: { SESSIONPIPE_STATE: tmp }, platform: "darwin" })).toBeNull(); // A world with a service of its own, on whatever this platform is: asked, never changed. const asked: string[] = []; @@ -311,7 +311,9 @@ describe.runIf(posix)("a look at the service", () => { }); expect(look?.loaded ?? false).toBe(false); for (const a of asked) - expect(a).toMatch(/^(launchctl print |systemctl --user is-active |systemctl --user show --property=Version$)/); + expect(a).toMatch( + /^(launchctl print |systemctl --user is-active |systemctl --user show --property=Version$|\S+powershell\.exe -NoProfile -NonInteractive -Command \$ErrorActionPreference='Stop';try\{\$t=Get-ScheduledTask )/, + ); }); }); @@ -357,6 +359,9 @@ describe.runIf(posix)("the service of a sessionpipe that keeps its files elsewhe ...world(), SESSIONPIPE_SERVICE_LABEL: "org.sessionpipe.racetest", HOME: path.join(tmp, "home"), + // Windows keeps a sessionpipe's files under these two, and a task gets the account's. + APPDATA: path.join(tmp, "roaming"), + LOCALAPPDATA: path.join(tmp, "local"), npm_config_registry: "http://127.0.0.1:4873", EDITOR: "vi", }; @@ -369,10 +374,27 @@ describe.runIf(posix)("the service of a sessionpipe that keeps its files elsewhe SESSIONPIPE_STATE: env.SESSIONPIPE_STATE, SESSIONPIPE_SERVICE_LABEL: "org.sessionpipe.racetest", HOME: env.HOME, + APPDATA: env.APPDATA, + LOCALAPPDATA: env.LOCALAPPDATA, npm_config_registry: "http://127.0.0.1:4873", PATH: "/usr/bin:/bin", }); expect(serviceEnv(env)).not.toHaveProperty("EDITOR"); + // Windows OS casing (AppData, LocalAppData, UserProfile) is preserved too. + expect( + serviceEnv({ + SESSIONPIPE_SERVICE_LABEL: "org.sessionpipe.racetest", + AppData: "C:\\Users\\a\\AppData\\Roaming", + LocalAppData: "C:\\Users\\a\\AppData\\Local", + UserProfile: "C:\\Users\\a", + Editor: "notepad", + }), + ).toMatchObject({ + SESSIONPIPE_SERVICE_LABEL: "org.sessionpipe.racetest", + AppData: "C:\\Users\\a\\AppData\\Roaming", + LocalAppData: "C:\\Users\\a\\AppData\\Local", + UserProfile: "C:\\Users\\a", + }); // Without a service of its own, only what every service gets. expect(Object.keys(serviceEnv({ ...world(), SESSIONPIPE_CLAUDE: path.join(tmp, "none") })).sort()).toEqual([ "PATH", diff --git a/packages/cli/test/current.test.ts b/packages/cli/test/current.test.ts index c257d623..d61154c7 100644 --- a/packages/cli/test/current.test.ts +++ b/packages/cli/test/current.test.ts @@ -452,6 +452,16 @@ describe("the service, made to run this copy", () => { const b = run({ look: other, status: [old, old, null, st("1.1.0")] }, { health: async () => ({ accounts: [] }) }); expect((await b.out).state).toBe("current"); expect(b.sim.seeded).toEqual([turns]); + // On Windows a service of this release is ended outright when it is replaced, before + // it can write anything down: it is written for that one too, and nowhere else. + const now = st("0.9.0", { mid_turn: turns }); + const win = run({ look: other, status: [now, now, null, st("1.1.0")] }, { platform: "win32" }); + expect((await win.out).state).toBe("current"); + expect(win.sim.seeded).toEqual([turns]); + expect(win.sim.did).toEqual(["quiesce", "seed", "place"]); + const mac = run({ look: other, status: [now, now, null, st("1.1.0")] }, { platform: "darwin" }); + expect((await mac.out).state).toBe("current"); + expect(mac.sim.seeded).toEqual([]); // With no session mid-turn, or a status that names none, there is nothing to write. for (const idle of [st("0.14.2", { mid_turn: [] }), st("0.14.2")]) { const c = run({ look: other, status: [idle, idle, null, st("1.1.0")] }, { health: async () => null }); @@ -777,6 +787,11 @@ describe("the service that runs this copy already", () => { { health: async () => ({ accounts: [], copy: { cli: `${THEIRS}/cli.js`, via: "launchd" } }) }, ); expect(((await mac.out) as { error: string }).error).toContain("and launchd can't be asked from this shell"); + const win = run( + { look: null }, + { health: async () => ({ accounts: [], copy: { cli: `${THEIRS}/cli.js`, via: "schtasks" } }) }, + ); + expect(((await win.out) as { error: string }).error).toContain("and Task Scheduler can't be asked from this shell"); // A supervisor of its own is somebody's hand too. const own = run( { look: null }, diff --git a/packages/cli/test/update.test.ts b/packages/cli/test/update.test.ts index 369d59a0..da0a77f5 100644 --- a/packages/cli/test/update.test.ts +++ b/packages/cli/test/update.test.ts @@ -25,6 +25,7 @@ import { DAY_MS, isDue, readUpdate, + restartedBy, restartVia, supervise, UPDATE_EXIT, @@ -913,7 +914,7 @@ describe("the daemon's auto-update", () => { it("status says what it does and what it found", () => { const now = Date.parse("2026-10-04T12:00:00Z"); const rec = { checked_at: new Date(now - 3 * 3600_000).toISOString(), latest: "0.6.0" }; - const on = updateSummary({ off: null, paired: true, rec, platform: "linux" }); + const on = updateSummary({ off: null, paired: true, rec }); expect(on.auto).toBe(true); expect(on).toMatchObject({ off: null, last_check: rec.checked_at, latest: "0.6.0", last_error: null }); const noDaemon = updateSummary({ off: null, paired: false, rec: {} }); @@ -933,6 +934,19 @@ describe("who restarts the daemon", () => { expect(restartVia({ ...base, ppid: 999, env: { XPC_SERVICE_NAME: "org.sessionpipe.control" } })).toBeNull(); expect(restartVia({ ...base, env: { XPC_SERVICE_NAME: "application.com.apple.Terminal.123" } })).toBeNull(); }); + it("Task Scheduler: the launcher named itself by its pid, and is this process's parent", () => { + const win = { pid: 4242, ppid: 4100, platform: "win32" as NodeJS.Platform }; + expect(restartVia({ ...win, env: { SESSIONPIPE_SERVICE: "schtasks:4100" } })).toBe("schtasks"); + // A session the daemon started inherits the variable, and has another parent. + expect(restartVia({ ...win, ppid: 4242, env: { SESSIONPIPE_SERVICE: "schtasks:4100" } })).toBeNull(); + expect(restartVia({ ...win, env: { SESSIONPIPE_SERVICE: "schtasks" } })).toBeNull(); + expect(restartVia({ ...win, env: {} })).toBeNull(); + // The words are the launcher's on Windows alone. + expect(restartVia({ ...win, platform: "darwin", env: { SESSIONPIPE_SERVICE: "schtasks:4100" } })).toBeNull(); + expect(restartedBy("schtasks")).toBe("the scheduled task's launcher"); + expect(restartedBy("supervisor")).toBe("the supervising sessionpipe"); + expect(restartedBy("systemd")).toBe("systemd"); + }); it("systemd: the process is our unit's main process (cgroup v2 and v1)", () => { const v2 = "0::/user.slice/user-1000.slice/user@1000.service/app.slice/sessionpipe-control.service\n"; const v1 = diff --git a/packages/core/gen/local-schemas.ts b/packages/core/gen/local-schemas.ts index a3d7435c..28ade7f9 100644 --- a/packages/core/gen/local-schemas.ts +++ b/packages/core/gen/local-schemas.ts @@ -477,7 +477,8 @@ export const LOCAL_REPLY_SCHEMA: JsonSchema = { "enum": [ "launchd", "systemd", - "supervisor" + "supervisor", + "schtasks" ] }, { diff --git a/packages/core/gen/local.ts b/packages/core/gen/local.ts index c665420d..bc9ea7c2 100644 --- a/packages/core/gen/local.ts +++ b/packages/core/gen/local.ts @@ -15,7 +15,7 @@ export type LocalDecisionBehavior = "allow" | "deny"; export type LocalPoolOutcome = "delivered" | "refused" | "failed" | "unsupported"; /** Service manager supervising the running control daemon. */ -export type LocalCopyVia = "launchd" | "systemd" | "supervisor"; +export type LocalCopyVia = "launchd" | "systemd" | "supervisor" | "schtasks"; /** A waiter parks on the local socket until a message arrives for its session. */ export interface LocalWaitRequest { diff --git a/packages/core/src/service/index.ts b/packages/core/src/service/index.ts index 725b95d3..83fb62b5 100644 --- a/packages/core/src/service/index.ts +++ b/packages/core/src/service/index.ts @@ -1,29 +1,50 @@ // SPDX-License-Identifier: Apache-2.0 /** sessionpipe-core/service — a per-user background service for a sessionpipe process: - * a launchd agent on macOS, a systemd user unit on Linux. The control daemon runs - * under it (`org.sessionpipe.control`), and so can a receiver of the person's own (a - * board on their machine), with the same files and the same commands. Node only: it - * writes files and runs launchctl, systemctl and loginctl, so it is never part of the - * root export, which stays Worker- and browser-safe. + * a launchd agent on macOS, a systemd user unit on Linux, a scheduled task at the + * user's logon on Windows (windows.ts). The control daemon runs under it + * (`org.sessionpipe.control`), and so can a receiver of the person's own (a board on + * their machine), with the same files and the same commands. Node only: it writes files + * and runs launchctl, systemctl and loginctl (on Windows schtasks, taskkill and + * PowerShell), so it is never part of the root export, which stays Worker- and + * browser-safe. * - * Both files restart the process when it exits non-zero, and when it exits + * Each of the three restarts the process when it exits non-zero, and when it exits * UPDATE_EXIT (75, sessionpipe-core/version) to come back on new code. The process is - * told which manager that is in SESSIONPIPE_SERVICE (`launchd`, `systemd`). Nothing - * here needs root, and a dry run touches nothing: it answers the files it would write - * and the commands it would run. + * told which manager that is in SESSIONPIPE_SERVICE (`launchd`, `systemd`; on Windows + * `schtasks:`, the pid being the launcher's, its parent). Nothing here needs root + * or an administrator, and a dry run touches nothing: it answers the files it would + * write and the commands it would run. * * Installing over a service that is there replaces it, and one that is running runs the * new file afterwards. Where the manager refuses the new one, the file that was there * before is put back and that service started again, so a refusal never leaves the * machine with the old one stopped and a file that names something else. */ import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { + envVar, + folderRemoveScript, + launched, + launcherText, + lookScript, + parseProcs, + system32, + TASK_RUNNING, + taskName, + taskProcs, + taskXml, + taskXmlBytes, + unsafeWord, +} from "./windows.js"; -/** One service, as both managers need it. */ +export { taskName } from "./windows.js"; + +/** One service, as each manager needs it. */ export interface ServiceSpec { - /** The launchd label, also the plist's name: `org.sessionpipe.control`. */ + /** The launchd label, also the plist's name: `org.sessionpipe.control`. On Windows the + * task's name under `\sessionpipe\`, and the launcher's file name. */ label: string; /** The systemd user unit's file name: `sessionpipe-control.service`. */ unit: string; @@ -33,10 +54,13 @@ export interface ServiceSpec { argv: string[]; /** More environment for the process, beside SESSIONPIPE_SERVICE. */ env?: Record; - /** Where launchd writes its stdout and stderr (journald keeps a unit's). */ + /** Where launchd writes its stdout and stderr, and the Windows launcher appends them + * (journald keeps a unit's). */ logPath: string; /** The home the files go under; the user's own by default. */ home?: string; + /** Windows: the node that runs the launcher; the one running this by default. */ + node?: string; } /** A file the service writes, and what is in it. */ @@ -49,7 +73,12 @@ export interface ServiceFile { export type Exec = (cmd: string, args: string[]) => string; const execQuiet: Exec = (cmd, args) => - execFileSync(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 15_000 }); + execFileSync(cmd, args, { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 15_000, + windowsHide: true, + }); /** Whether a command ran and said yes: a look that never throws. */ const answers = (exec: Exec, cmd: string, args: string[]): boolean => { @@ -74,8 +103,8 @@ const xml = (s: string) => s.replace(/&/g, "&").replace(/ `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`; -/** The plist and the unit for a service, and where each goes. */ -export function serviceFiles(s: ServiceSpec): { plist: ServiceFile; unit: ServiceFile } { +/** The plist, the unit and the Windows launcher for a service, and where each goes. */ +export function serviceFiles(s: ServiceSpec): { plist: ServiceFile; unit: ServiceFile; launcher: ServiceFile } { const home = s.home ?? os.homedir(); const env = (manager: string) => ({ SESSIONPIPE_SERVICE: manager, ...s.env }); const plistEnv = Object.entries(env("launchd")) @@ -117,6 +146,17 @@ WantedBy=default.target return { plist: { path: path.join(home, "Library", "LaunchAgents", `${s.label}.plist`), text: plist }, unit: { path: path.join(home, ".config", "systemd", "user", s.unit), text: unit }, + launcher: { + path: path.join(home, "AppData", "Local", "sessionpipe", "service", `${s.label}.cjs`), + text: launcherText({ + description: s.description, + label: s.label, + node: s.node ?? process.execPath, + argv: s.argv, + env: s.env ?? {}, + log: s.logPath, + }), + }, }; } @@ -151,7 +191,7 @@ export interface ServicePlan { * at what it has (`launchctl print`) between them aren't among them. */ commands: string[]; /** Which manager runs it now: null on a platform with none, or where it isn't reachable. */ - manager: "launchd" | "systemd" | null; + manager: "launchd" | "systemd" | "schtasks" | null; /** launchd: `gui` when someone is at the screen, else `user` (it starts again at the next login there). */ domain?: "gui" | "user"; /** systemd: whether it outlives the login, in words. */ @@ -161,6 +201,8 @@ export interface ServicePlan { unreachable?: string; /** That file is again the one that was there before: the new one was taken back. */ restored?: true; + /** Windows: why nothing was written at all, in a sentence. */ + why?: string; } /** launchd would not start a service. `message` names the launchctl commands that do it @@ -189,6 +231,10 @@ export interface InstallOptions extends ServiceSpec { user?: string; /** How a wait for launchd passes; this thread sleeps by default. */ sleep?: (ms: number) => void; + /** Windows: the environment of the shell this runs in, which says where Windows is + * (%SystemRoot%) and whose logon starts the task (USERDOMAIN, USERNAME); this + * process's own by default. */ + shell?: NodeJS.ProcessEnv; } const line = (cmd: string, args: string[]) => [cmd, ...args].join(" "); @@ -202,12 +248,61 @@ const sleepSync = (ms: number) => { const LET_GO_MS = 10_000; const LOOK_MS = 100; +const POWERSHELL = ["-NoProfile", "-NonInteractive", "-Command"]; + +/** The programs the Windows half runs, each by its full path (windows.ts `system32`). */ +const tools = (shell: NodeJS.ProcessEnv) => ({ + schtasks: system32(shell, "schtasks.exe"), + taskkill: system32(shell, "taskkill.exe"), + powershell: system32(shell, "WindowsPowerShell", "v1.0", "powershell.exe"), +}); + +/** What Task Scheduler has under a label, and what runs for it. */ +interface TaskLook { + /** The task's state as Task Scheduler numbers it; null when no task has the label. */ + state: number | null; + /** The processes a task of ours started: what stopping it ends, each with its tree. */ + roots: number[]; + /** Headless conhost processes for this task. */ + conhosts: number[]; + /** Node launcher processes for this task. */ + launchers: number[]; + /** The process the launcher runs now. */ + daemon: number | null; +} + +const taskMissing = (e: unknown): boolean => { + const o = Object(e) as { message?: unknown; stderr?: unknown; stdout?: unknown }; + return /cannot find the file specified|cannot find the path specified|does not exist/i.test( + [e, o.message, o.stderr, o.stdout].map(String).join("\n"), + ); +}; + +/** A look at the task and at the processes it started (windows.ts `lookScript`); throws + * where PowerShell can't be run, or doesn't answer as the script does. */ +function taskLook(exec: Exec, shell: NodeJS.ProcessEnv, label: string, launcher: string): TaskLook { + const tmp = mkdtempSync(path.join(os.tmpdir(), "sessionpipe-service-")); + const file = path.join(tmp, "processes.json"); + try { + const said = exec(tools(shell).powershell, [...POWERSHELL, lookScript(label, file)]).trim(); + if (said !== "none" && !/^\d+$/.test(said)) throw new Error(`unexpected answer: ${said.slice(0, 80)}`); + const node = launched(textOf(launcher) ?? "")?.node ?? null; + return { + state: said === "none" ? null : Number(said), + ...taskProcs(parseProcs(readFileSync(file, "utf8")), launcher, node), + }; + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +} + /** Write the service for this platform and start it now. A service already there is * replaced, and runs the new file afterwards (launchd: booted out first, and started * once the old one is gone; systemd: restarted where the unit was active, since - * `enable --now` leaves a running unit on the file it was started from). Where the - * manager will not have the new one, the file from before is put back and that service - * started again. */ + * `enable --now` leaves a running unit on the file it was started from; Windows: the + * task ended and what it started stopped, then the task registered again and run). + * Where the manager will not have the new one, the file from before is put back and + * that service started again. */ export function installService(o: InstallOptions): ServicePlan { const f = serviceFiles(o); const platform = o.platform ?? process.platform; @@ -330,6 +425,84 @@ export function installService(o: InstallOptions): ServicePlan { } return { files: [f.unit], commands, manager: "systemd", linger: ensureLinger(user, run) }; } + if (platform === "win32") { + const shell = o.shell ?? process.env; + const t = tools(shell); + const name = taskName(o.label); + const node = o.node ?? process.execPath; + // The two paths on the task's own command line are all that conhost reads. + const bad = unsafeWord([node, f.launcher.path]); + if (bad !== undefined) + return { + files: [], + commands, + manager: null, + why: `a scheduled task can't carry ${JSON.stringify(bad)} on its command line (a quote, a % or a line end)`, + }; + const prev = o.dryRun ? null : textOf(f.launcher.path); + const old = prev === f.launcher.text ? null : prev; + // A look, not a step: what runs for the task now is what replacing it stops. Where + // PowerShell can't be asked, schtasks is still told to end the task. + let was: TaskLook = { state: TASK_RUNNING, roots: [], conhosts: [], launchers: [], daemon: null }; + if (!o.dryRun) + try { + was = taskLook(real, shell, o.label, f.launcher.path); + } catch {} + // `schtasks /Create /XML` takes the definition from a file, which goes again after. + const definition = path.join(path.dirname(f.launcher.path), `${o.label}.xml`); + const domain = envVar(shell, "USERDOMAIN"); + const username = envVar(shell, "USERNAME"); + const user = o.user ?? (domain && username ? `${domain}\\${username}` : username || os.userInfo().username); + const conhost = system32(shell, "conhost.exe"); + let created = false; + let wroteDef = false; + try { + write(f.launcher); + if (!o.dryRun) { + writeFileSync( + definition, + taskXmlBytes(taskXml({ description: o.description, user, node, launcher: f.launcher.path, conhost })), + ); + wroteDef = true; + } + // Stop the launcher and its tree first (minimizing PID-reuse risk after `/End`), + // then ask Task Scheduler to end the task; only kill conhost directly if `/End` + // failed and no launcher PID was known. + for (const pid of was.launchers) answers(run, t.taskkill, ["/PID", String(pid), "/T", "/F"]); + const ended = !o.dryRun && was.state !== null ? answers(run, t.schtasks, ["/End", "/TN", name]) : true; + if (!ended && !was.launchers.length) + for (const pid of was.conhosts) answers(run, t.taskkill, ["/PID", String(pid), "/T", "/F"]); + run(t.schtasks, ["/Create", "/TN", name, "/XML", definition, "/F"]); + created = true; + run(t.schtasks, ["/Run", "/TN", name]); + } catch { + if (old === null) { + if (prev !== null && was.state === TASK_RUNNING) answers(run, t.schtasks, ["/Run", "/TN", name]); + return { files: [f.launcher], commands, manager: null, unreachable: f.launcher.path }; + } + // Restore the previous launcher and, if `/Create /F` already replaced the task + // definition, re-register the previous task XML before running it again so the + // task definition and launcher file never drift out of sync. + writeFileSync(f.launcher.path, old); + if (created) { + const prevNode = launched(old)?.node; + if (prevNode && unsafeWord([prevNode]) === undefined) { + writeFileSync( + definition, + taskXmlBytes( + taskXml({ description: o.description, user, node: prevNode, launcher: f.launcher.path, conhost }), + ), + ); + answers(run, t.schtasks, ["/Create", "/TN", name, "/XML", definition, "/F"]); + } + } + answers(run, t.schtasks, ["/Run", "/TN", name]); + return { files: [f.launcher], commands, manager: null, unreachable: f.launcher.path, restored: true }; + } finally { + if (wroteDef) rmSync(definition, { force: true }); + } + return { files: [f.launcher], commands, manager: "schtasks" }; + } return { files: [], commands, manager: null }; } @@ -337,13 +510,15 @@ export function installService(o: InstallOptions): ServicePlan { export interface ServiceState { /** The manager that can be asked here; null where this platform has none, and where * the one it has can't be asked from this process (no `launchctl` to run; no systemd - * user manager to reach: a container, WSL without systemd, a shell with no session). */ - manager: "launchd" | "systemd" | null; + * user manager to reach: a container, WSL without systemd, a shell with no session; + * no PowerShell that answers about Task Scheduler). */ + manager: "launchd" | "systemd" | "schtasks" | null; /** Where its file is, or would be. */ file: string | null; /** The file is there. */ installed: boolean; - /** The manager has the service now (launchd: in either domain; systemd: active). */ + /** The manager has the service now (launchd: in either domain; systemd: active; + * Task Scheduler: the task is running). */ loaded: boolean; /** The program and arguments the file names; null when there is no file or it has none. */ argv: string[] | null; @@ -356,11 +531,14 @@ const unxml = (s: string) => s.replace(/</g, "<").replace(/>/g, ">").repla const unsd = (s: string) => s.replace(/\\(.)/g, "$1").replace(/%%/g, "%"); /** The program and its arguments a service file names, as `serviceFiles` wrote them: a - * plist's ProgramArguments, a unit's ExecStart. Null when the text has neither. */ + * plist's ProgramArguments, a unit's ExecStart, what a Windows launcher runs. Null when + * the text has none of them. */ export function serviceArgv(text: string): string[] | null { const plist = /ProgramArguments<\/key>\s*([\s\S]*?)<\/array>/.exec(text)?.[1]; if (plist !== undefined) return [...plist.matchAll(/([\s\S]*?)<\/string>/g)].map((m) => unxml(m[1] as string)); + const launcher = launched(text); + if (launcher) return launcher.argv; const unit = /^ExecStart=(.*)$/m.exec(text)?.[1]; if (unit === undefined) return null; return [...unit.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => unsd(m[1] as string)); @@ -368,8 +546,8 @@ export function serviceArgv(text: string): string[] | null { /** The environment a service file gives its process, as `serviceFiles` wrote it and as * a person may have added to it by hand: a plist's EnvironmentVariables, a unit's - * `Environment=` lines (each assignment quoted or bare). SESSIONPIPE_SERVICE is among - * them. Null when the text is neither file. */ + * `Environment=` lines (each assignment quoted or bare), a Windows launcher's `env`. + * SESSIONPIPE_SERVICE is among them. Null when the text is none of those files. */ export function serviceEnvironment(text: string): Record | null { const plist = /EnvironmentVariables<\/key>\s*([\s\S]*?)<\/dict>/.exec(text)?.[1]; if (plist !== undefined) @@ -379,6 +557,8 @@ export function serviceEnvironment(text: string): Record | null unxml(m[2] as string), ]), ); + const launcher = launched(text); + if (launcher) return { SESSIONPIPE_SERVICE: "schtasks", ...launcher.env }; if (!/^ExecStart=/m.test(text)) return null; const env: Record = {}; // One line may hold several assignments, and systemd lets the quotes go round all of @@ -407,7 +587,8 @@ const notRun = (e: unknown): boolean => typeof (e as { code?: unknown } | null)? /** Whether this platform's manager has the service now. A look only: nothing is * written, started or stopped (`launchctl print`; `systemctl --user is-active`, and - * where that says no, `systemctl --user show` to learn whether systemd answered at all). */ + * where that says no, `systemctl --user show` to learn whether systemd answered at all; + * on Windows one PowerShell script that reads the task and the process list). */ export function serviceState(o: UninstallOptions): ServiceState { const f = serviceFiles({ ...o, description: "", argv: [], logPath: "" }); const platform = o.platform ?? process.platform; @@ -455,6 +636,20 @@ export function serviceState(o: UninstallOptions): ServiceState { pid: pidIn(main), }; } + if (platform === "win32") { + let seen: TaskLook | null = null; + try { + seen = taskLook(exec, o.shell ?? process.env, o.label, f.launcher.path); + } catch {} + return { + manager: seen ? "schtasks" : null, + file: f.launcher.path, + installed: existsSync(f.launcher.path) || (seen !== null && seen.state !== null), + loaded: seen?.state === TASK_RUNNING, + argv: argvOf(f.launcher.path), + pid: seen?.daemon ?? null, + }; + } return { manager: null, file: null, installed: false, loaded: false, argv: null, pid: null }; } @@ -469,6 +664,8 @@ export interface UninstallOptions { exec?: Exec; platform?: NodeJS.Platform; uid?: string; + /** Windows: the environment that says where Windows is; this process's own by default. */ + shell?: NodeJS.ProcessEnv; } /** Stop the service and remove its file, where this platform has one; nothing where @@ -501,5 +698,41 @@ export function uninstallService(o: UninstallOptions): { files: string[]; comman remove(f.unit.path); run("systemctl", ["--user", "daemon-reload"]); } + if (platform === "win32" && existsSync(f.launcher.path)) { + const shell = o.shell ?? process.env; + const t = tools(shell); + let seen: TaskLook | null = null; + if (!o.dryRun) + try { + seen = taskLook(real, shell, o.label, f.launcher.path); + } catch {} + const launchers = seen?.launchers ?? []; + for (const pid of launchers) run(t.taskkill, ["/PID", String(pid), "/T", "/F"]); + const endArgs = ["/End", "/TN", taskName(o.label)]; + commands.push(line(t.schtasks, endArgs)); + let ended = true; + if (!o.dryRun) { + try { + real(t.schtasks, endArgs); + } catch { + ended = false; + } + } + if (!ended && seen && !launchers.length) + for (const pid of seen.conhosts) run(t.taskkill, ["/PID", String(pid), "/T", "/F"]); + const delArgs = ["/Delete", "/TN", taskName(o.label), "/F"]; + commands.push(line(t.schtasks, delArgs)); + if (!o.dryRun) { + try { + real(t.schtasks, delArgs); + } catch (e) { + if (seen?.state !== null && !taskMissing(e)) throw e; + } + } + remove(f.launcher.path); + if (!o.dryRun) rmSync(path.join(path.dirname(f.launcher.path), `${o.label}.xml`), { force: true }); + // Best-effort (windows.ts): where the folder can't be removed it stays, empty. + run(t.powershell, [...POWERSHELL, folderRemoveScript()]); + } return { files, commands }; } diff --git a/packages/core/src/service/windows.ts b/packages/core/src/service/windows.ts new file mode 100644 index 00000000..d13e0004 --- /dev/null +++ b/packages/core/src/service/windows.ts @@ -0,0 +1,337 @@ +// SPDX-License-Identifier: Apache-2.0 +/** The Windows half of sessionpipe-core/service: a scheduled task at this user's logon, + * `\sessionpipe\