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: 13 additions & 0 deletions .changeset/windows-scheduled-task.md
Original file line number Diff line number Diff line change
@@ -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:<pid>`, the pid being the launcher's.
29 changes: 22 additions & 7 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ sessionpipe control keys [remove <id>]
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.
Expand Down Expand Up @@ -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.
Expand All @@ -277,9 +287,9 @@ says what to type next (into a pipe: one line, with `Next: <command>` at its end
| npm can't write the prefix (installed with sudo) | `sudo npm install -g --prefix <prefix> sessionpipe@<version> && 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
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1471,10 +1471,13 @@ async function checkup(deep: boolean): Promise<{ report: Record<string, unknown>
value: loaded
? "started but not answering"
: look
? `not loaded: ${look.manager} doesn't have it`
? `not loaded: ${managerName(look.manager as NonNullable<typeof look.manager>)} 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<typeof look.manager>)} doesn't have it`,
);
if (loaded)
todo.push({
order: 1,
Expand Down
26 changes: 12 additions & 14 deletions packages/cli/src/control/autoupdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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. */
Expand Down
12 changes: 10 additions & 2 deletions packages/cli/src/control/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -508,7 +516,7 @@ async function runDaemon(out: (s?: string) => void, distDir: string): Promise<vo
await d.stop();
const via = restartVia({ env: process.env, platform: process.platform, pid: process.pid, ppid: process.ppid });
if (via) {
log(`exiting ${UPDATE_EXIT} so ${via === "supervisor" ? "the supervising sessionpipe" : via} starts ${to}`);
log(`exiting ${UPDATE_EXIT} so ${restartedBy(via)} starts ${to}`);
process.exit(UPDATE_EXIT);
}
// Nobody restarts this process: it stays, as the new daemon's parent.
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/control/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export function serviceSeen(
...(o.exec ? { exec: o.exec } : {}),
...(o.platform ? { platform: o.platform } : {}),
...(o.home ? { home: o.home } : {}),
...(o.env ? { shell: o.env } : {}),
})
: null;
}
Expand Down
Loading
Loading