From c0b246ffe0536b1641fe5a00b2c2cae7c6aa4dbf Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:08:06 +0100 Subject: [PATCH 01/25] test: an operator runs daemon install on Windows and the task runs the supervisor (#1698) Protocol: 100 --- src/cli/index-daemon-service.test.ts | 131 +++++++++++++++++++++++++++ src/contract/protocol.ts | 2 +- src/contract/report-schemas.ts | 2 +- src/core/doctor-types.ts | 4 +- src/ports/filesystem.ts | 7 ++ src/ports/index.ts | 1 + src/ports/service-manager.ts | 24 ++++- 7 files changed, 166 insertions(+), 5 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 44eca101b..7dc6c4db9 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -13,7 +13,9 @@ import { MemoryFilesystem, MemoryIpcTransport, serviceDefinition, + type ServiceManager, type ServiceState, + TaskSchedulerServiceManager, FakeSystemStats, } from "../ports/index.js"; import { SimlockError } from "../contract/index.js"; @@ -761,3 +763,132 @@ describe("CLI: a service manager call fails, or the platform has none (#830)", ( }); }); }); + +describe("CLI: daemon service on Windows (#1698)", () => { + const root = "/Users/me/.simlock"; + const name = "com.callstack.simlock.worker"; + const nodePath = "/opt/node/node.exe"; + const mainPath = "/opt/simlock/dist/daemon/main.js"; + const sid = "S-1-5-21-1-2-3-1001"; + const xmlPath = join(root, "service-task.xml"); + const done = { code: 0, stdout: "", stderr: "" }; + + it("an operator runs daemon install on Windows: the user's SID goes into a UTF-16 logon task that runs the supervisor hidden with the saved variables, the daemon answers, and install prints the name, Daemon running and the login hint", async () => { + const filesystem = new MemoryFilesystem(); + const ipcTransport = new MemoryIpcTransport(); + let written: { readonly text: string; readonly encoding: string } | undefined; + const runner = new ScriptedProcessRunner([ + { + match: { command: "whoami", args: ["/user", "/fo", "csv", "/nh"] }, + result: { ...done, stdout: `"desktop\\me","${sid}"\r\n` }, + }, + { + match: { command: "schtasks", args: ["/end", "/tn", name] }, + result: { code: 1, stdout: "", stderr: "ERROR: There are no running instances." }, + }, + { + match: { command: "schtasks", args: ["/create", "/tn", name, "/xml", xmlPath, "/f"] }, + result: done, + onSpawn: () => { + const encoding = filesystem.encodingOf(xmlPath); + void filesystem.readFile(xmlPath).then((text) => { + written = { text, encoding }; + }); + }, + }, + ]); + const tasks = new TaskSchedulerServiceManager({ + runner, + filesystem, + systemRoot: "C:\\Windows", + }); + const serviceManager: ServiceManager = { + manager: "task-scheduler", + state: (definition) => tasks.state(definition), + uninstall: (definition) => tasks.uninstall(definition), + start: (definition) => tasks.start(definition), + install: async (definition) => { + await tasks.install(definition); + await startInMemoryDaemon({ + adminTokenPath: join(root, "admin.token"), + filesystem, + ipcTransport, + socketPath: join(root, "daemon.sock"), + }); + }, + }; + const output = outputCapture( + { + filesystem, + clock: new FakeClock(0), + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: ipcTransport, + launcher: new FakeDaemonLauncher(), + daemonHome: { role: "worker", dataDirectory: root, gatewayPresent: false }, + homeDirectory: "C:\\Users\\me", + workingDirectory: "C:\\work", + hostPlatform: "linux", + runTool: async () => ({ outcome: "not-found" }), + service: { + manager: serviceManager, + platform: "win32", + home: "C:\\Users\\me", + user: () => "me", + root, + nodePath, + mainPath, + }, + }, + { PATH: "C:\\bin" }, + ); + + const exitCode = await runCli(["daemon", "install"], output.environmentWith()); + + expect(output.stderr).toBe(""); + expect(exitCode).toBe(0); + expect(runner.calls.map((call) => [call.command, call.args[0]])).toEqual([ + ["whoami", "/user"], + ["schtasks", "/end"], + ["schtasks", "/create"], + ]); + expect(output.stdout.split("\n").slice(0, 2)).toEqual([ + `Service installed: ${name} (task-scheduler)`, + "Daemon running", + ]); + expect(output.stdout.trimEnd().split("\n").at(-1)).toBe( + "To start after a reboot, turn on automatic login for this user.", + ); + expect(written?.encoding).toBe("utf16le"); + const xml = written?.text ?? ""; + expect(xml.startsWith('\uFEFF')).toBe(true); + for (const element of [ + `true${sid}`, + `${sid}InteractiveTokenLeastPrivilege`, + "IgnoreNew", + "false", + "false", + "PT0S", + "5", + "true", + "simlock worker daemon", + "C:\\Windows\\System32\\conhost.exe", + ]) { + expect(xml, element).toContain(element); + } + const args = /(.*)<\/Arguments>/.exec(xml)?.[1] ?? ""; + const parts = + /^--headless "([^"]*)" "([^"]*)" --task (\S+) --install-id ([0-9a-f-]{36}) --environment (\S+)$/.exec( + args, + ); + expect(parts?.slice(1, 4)).toEqual([ + nodePath, + "/opt/simlock/dist/daemon/service-main.js", + name, + ]); + expect(JSON.parse(Buffer.from(parts?.[5] ?? "", "base64url").toString("utf8"))).toEqual({ + SIMLOCK_HOME: root, + PATH: "C:\\bin", + }); + expect(await filesystem.exists(xmlPath), "the XML file is deleted after create").toBe(false); + }); +}); diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index bdcb73f12..4a6a6a8b4 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 99, max: 99 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 100, max: 100 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/report-schemas.ts b/src/contract/report-schemas.ts index 763e27188..34a7d5ac4 100644 --- a/src/contract/report-schemas.ts +++ b/src/contract/report-schemas.ts @@ -82,7 +82,7 @@ const doctorFindingSchema = z.discriminatedUnion("kind", [ }), z.object({ kind: z.literal("service-broken"), - manager: z.enum(["launchd", "systemd"]), + manager: z.enum(["launchd", "systemd", "task-scheduler"]), name: z.string(), missing: z.array(z.string()).min(1), remedy: z.string(), diff --git a/src/core/doctor-types.ts b/src/core/doctor-types.ts index ccdc05b54..1d1628089 100644 --- a/src/core/doctor-types.ts +++ b/src/core/doctor-types.ts @@ -79,7 +79,7 @@ export type DoctorFinding = * `driver-advisory` it is not drift: `--fix` never acts on it, and `doctor.reconciled` does not carry it. */ readonly kind: "service-broken"; - readonly manager: "launchd" | "systemd"; + readonly manager: "launchd" | "systemd" | "task-scheduler"; readonly name: string; readonly missing: readonly string[]; readonly remedy: string; @@ -104,7 +104,7 @@ export type DoctorFinding = * itself; `check` returns the paths the service names that are gone, none when whole or absent. */ export interface ServiceCheck { - readonly manager: "launchd" | "systemd"; + readonly manager: "launchd" | "systemd" | "task-scheduler"; readonly name: string; readonly check: () => Promise; } diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index 2cc36f8f8..2c2151025 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -38,6 +38,8 @@ export interface WriteFileAtomicOptions { * which would leave a window where the file exists world-readable. Omitted keeps Node's * default (governed by the process umask), unchanged from before this option existed. */ readonly mode?: number; + /** why: Task Scheduler refuses a task file that is not UTF-16. Omitted writes UTF-8. */ + readonly encoding?: "utf8" | "utf16le"; } /** why: Same shape as {@link WriteFileAtomicOptions}: `writeFileExclusive` publishes through a @@ -509,6 +511,11 @@ export class MemoryFilesystem implements Filesystem { this.#entries.set("/", this.#newEntry({ kind: "directory" })); } + /** why: lets a test read which encoding `writeFileAtomic` was asked to write. */ + encodingOf(_path: string): "utf8" | "utf16le" { + return "utf8"; + } + async readFile(path: string): Promise { this.#failIfDefined(path); const entry = this.#entryAt(path); diff --git a/src/ports/index.ts b/src/ports/index.ts index a33305674..19b5c5209 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -52,6 +52,7 @@ export { serviceDefinition, type ServiceManagerName, type ServiceState, + TaskSchedulerServiceManager, } from "./service-manager.js"; export { type LeaseSocket, type LeaseSocketAccept, MemoryLeaseSocket } from "./lease-socket.js"; export type { SessionConnection, SessionOutcome } from "./session-socket.js"; diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index e5d472c27..b9aeb9ed9 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -4,7 +4,7 @@ import { dirname, isAbsolute, join } from "node:path"; import type { Filesystem } from "./filesystem.js"; import { DATA_DIRECTORY_MODE, type DaemonRole } from "./paths.js"; import type { ProcessResult, ProcessRunner } from "./process-runner.js"; -export type ServiceManagerName = "launchd" | "systemd"; +export type ServiceManagerName = "launchd" | "systemd" | "task-scheduler"; export type ServiceState = | { readonly state: "not-installed" } @@ -400,3 +400,25 @@ export function productionServiceManager( if (platform === "linux") return new SystemdServiceManager(dependencies); return platform === "darwin" ? new LaunchdServiceManager(dependencies) : undefined; } + +export interface TaskSchedulerServiceManagerOptions { + readonly runner: ProcessRunner; + readonly filesystem: Filesystem; + readonly systemRoot?: string; +} + +export class TaskSchedulerServiceManager implements ServiceManager { + readonly manager = "task-scheduler"; + + constructor(private readonly options: TaskSchedulerServiceManagerOptions) {} + + async state(_definition: ServiceDefinition): Promise { + return { state: "not-installed" }; + } + + async install(_definition: ServiceDefinition): Promise {} + + async uninstall(_definition: ServiceDefinition): Promise {} + + async start(_definition: ServiceDefinition): Promise {} +} From ab49cb0ea0253f39e4c8fa9f48f07de91012452c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:09:49 +0100 Subject: [PATCH 02/25] feat(ports): daemon install on Windows registers a logon task that runs the supervisor (#1698) --- src/cli/index-daemon-service.test.ts | 2 +- src/ports/filesystem.ts | 16 +++- src/ports/service-manager.test.ts | 8 +- src/ports/service-manager.ts | 133 +++++++++++++++++++++++---- 4 files changed, 132 insertions(+), 27 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 7dc6c4db9..1b17d07e3 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -832,7 +832,7 @@ describe("CLI: daemon service on Windows (#1698)", () => { service: { manager: serviceManager, platform: "win32", - home: "C:\\Users\\me", + home: "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/Users/me", user: () => "me", root, nodePath, diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index 2c2151025..008c12893 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -284,7 +284,7 @@ export class NodeFilesystem implements Filesystem { try { await writeFile(temporaryPath, contents, { - encoding: "utf8", + encoding: options?.encoding ?? "utf8", flag: "wx", ...(options?.mode === undefined ? {} : { mode: options.mode }), }); @@ -480,7 +480,7 @@ interface MemoryAttributes { } type MemoryEntryKind = - | { readonly kind: "file"; contents: string; bytes?: Uint8Array } + | { readonly kind: "file"; contents: string; bytes?: Uint8Array; encoding?: "utf8" | "utf16le" } | { readonly kind: "directory" } | { readonly kind: "symlink"; readonly target: string }; @@ -512,8 +512,9 @@ export class MemoryFilesystem implements Filesystem { } /** why: lets a test read which encoding `writeFileAtomic` was asked to write. */ - encodingOf(_path: string): "utf8" | "utf16le" { - return "utf8"; + encodingOf(path: string): "utf8" | "utf16le" { + const entry = this.#entryAt(path); + return entry.kind === "file" ? (entry.encoding ?? "utf8") : "utf8"; } async readFile(path: string): Promise { @@ -612,8 +613,13 @@ export class MemoryFilesystem implements Filesystem { this.#failIfDefined(path); path = this.#underResolvedParent(path); this.#requireDirectory(parentPath(path)); + const encoding = options?.encoding ?? "utf8"; this.#entries.set(path, { - ...this.#newEntry({ kind: "file", contents }), + ...this.#newEntry({ + kind: "file", + contents, + ...(encoding === "utf8" ? {} : { bytes: Buffer.from(contents, encoding), encoding }), + }), mode: options?.mode ?? DEFAULT_FILE_MODE, }); } diff --git a/src/ports/service-manager.test.ts b/src/ports/service-manager.test.ts index a1e4d564a..3533ef8ea 100644 --- a/src/ports/service-manager.test.ts +++ b/src/ports/service-manager.test.ts @@ -13,6 +13,7 @@ import { LaunchdServiceManager, productionServiceManager, SystemdServiceManager, + TaskSchedulerServiceManager, serviceDefinition, ServiceFailedError, type ServiceDefinition, @@ -352,7 +353,7 @@ describe("LaunchdServiceManager (#830)", () => { await expect(install).rejects.toThrow("denied"); }); - it("productionServiceManager is the launchd adapter on macOS, the systemd adapter on Linux and nothing elsewhere", () => { + it("productionServiceManager is the launchd adapter on macOS, the systemd adapter on Linux, the Task Scheduler adapter on Windows and nothing elsewhere", () => { const dependencies = { runner: new ScriptedProcessRunner([]), filesystem: new MemoryFilesystem(), @@ -360,7 +361,10 @@ describe("LaunchdServiceManager (#830)", () => { }; expect(productionServiceManager("darwin", dependencies)).toBeInstanceOf(LaunchdServiceManager); expect(productionServiceManager("linux", dependencies)).toBeInstanceOf(SystemdServiceManager); - expect(productionServiceManager("win32", dependencies)).toBeUndefined(); + expect(productionServiceManager("win32", dependencies)).toBeInstanceOf( + TaskSchedulerServiceManager, + ); + expect(productionServiceManager("freebsd", dependencies)).toBeUndefined(); }); it("start kickstarts the loaded service", async () => { diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index b9aeb9ed9..795015fb0 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -1,4 +1,4 @@ -import { createHash } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { dirname, isAbsolute, join } from "node:path"; import type { Filesystem } from "./filesystem.js"; @@ -55,6 +55,16 @@ function unitDirectory(input: ServiceDefinitionInput): string { return join(config, "systemd", "user"); } +function servicePath( + manager: ServiceManagerName, + input: ServiceDefinitionInput, + name: string, +): string { + if (manager === "task-scheduler") return `\\${name}`; + if (manager === "systemd") return join(unitDirectory(input), `${name}.service`); + return join(input.home, "Library", "LaunchAgents", `${name}.plist`); +} + export function serviceDefinition(input: ServiceDefinitionInput): ServiceDefinition { const environment: Record = { SIMLOCK_HOME: input.root }; for (const variable of SAVED_VARIABLES) { @@ -68,12 +78,14 @@ export function serviceDefinition(input: ServiceDefinitionInput): ServiceDefinit return { role: input.role, name, - path: - manager === "systemd" - ? join(unitDirectory(input), `${name}.service`) - : join(input.home, "Library", "LaunchAgents", `${name}.plist`), + path: servicePath(manager, input, name), command: input.nodePath, - args: [input.mainPath, ...(input.role === "gateway" ? ["--gateway"] : [])], + args: [ + manager === "task-scheduler" + ? join(dirname(input.mainPath), "service-main.js") + : input.mainPath, + ...(input.role === "gateway" ? ["--gateway"] : []), + ], environment, logPath: join(input.dataDirectory, "daemon.log"), }; @@ -389,36 +401,119 @@ export class SystemdServiceManager implements ServiceManager { } } -export function productionServiceManager( - platform: NodeJS.Platform, - dependencies: { - readonly runner: ProcessRunner; - readonly filesystem: Filesystem; - readonly uid: number; - }, -): ServiceManager | undefined { - if (platform === "linux") return new SystemdServiceManager(dependencies); - return platform === "darwin" ? new LaunchdServiceManager(dependencies) : undefined; -} - export interface TaskSchedulerServiceManagerOptions { readonly runner: ProcessRunner; readonly filesystem: Filesystem; readonly systemRoot?: string; } +const TASK_NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task"; + +function quoted(value: string): string { + return `"${value}"`; +} + +function taskXml(input: { + readonly definition: ServiceDefinition; + readonly sid: string; + readonly installId: string; + readonly systemRoot: string; +}): string { + const { definition, sid, installId, systemRoot } = input; + const [supervisor = "", ...flags] = definition.args; + const environment = Buffer.from(JSON.stringify(definition.environment)).toString("base64url"); + const args = [ + "--headless", + quoted(definition.command), + quoted(supervisor), + ...flags, + "--task", + definition.name, + "--install-id", + installId, + "--environment", + environment, + ].join(" "); + return ` + + simlock ${definition.role} daemon + true${xmlText(sid)} + ${xmlText(sid)}InteractiveTokenLeastPrivilege + + IgnoreNew + false + false + PT0S + 5 + true + + ${xmlText(`${systemRoot}\\System32\\conhost.exe`)}${xmlText(args)} + +`; +} + export class TaskSchedulerServiceManager implements ServiceManager { readonly manager = "task-scheduler"; constructor(private readonly options: TaskSchedulerServiceManagerOptions) {} + private async run(command: string, args: readonly string[]): Promise { + const result = await this.options.runner.run(command, args, { + timeoutMs: LAUNCHCTL_TIMEOUT_MS, + }); + if (result.code === null) { + throw new ServiceFailedError(`${[command, ...args].join(" ")} did not finish within 10 s`); + } + return result; + } + + private async checked(command: string, args: readonly string[]): Promise { + const result = await this.run(command, args); + if (result.code !== 0) failure(command, args, result); + return result; + } + async state(_definition: ServiceDefinition): Promise { return { state: "not-installed" }; } - async install(_definition: ServiceDefinition): Promise {} + async install(definition: ServiceDefinition): Promise { + const { filesystem } = this.options; + await ensureLog(filesystem, definition.logPath); + const whoamiArgs = ["/user", "/fo", "csv", "/nh"]; + const user = await this.checked("whoami", whoamiArgs); + const sid = /^"[^"]*","([^"]*)"/.exec(user.stdout.trim())?.[1]; + if (sid === undefined) throw new ServiceFailedError("whoami /user printed no SID"); + const xmlPath = join(dirname(definition.logPath), "service-task.xml"); + const xml = taskXml({ + definition, + sid, + installId: randomUUID(), + systemRoot: this.options.systemRoot ?? process.env.SystemRoot ?? "C:\\Windows", + }); + await filesystem.writeFileAtomic(xmlPath, `\uFEFF${xml}`, { encoding: "utf16le" }); + try { + await this.run("schtasks", ["/end", "/tn", definition.name]); + await this.checked("schtasks", ["/create", "/tn", definition.name, "/xml", xmlPath, "/f"]); + } finally { + await filesystem.rm(xmlPath); + } + } async uninstall(_definition: ServiceDefinition): Promise {} async start(_definition: ServiceDefinition): Promise {} } + +export function productionServiceManager( + platform: NodeJS.Platform, + dependencies: { + readonly runner: ProcessRunner; + readonly filesystem: Filesystem; + readonly uid: number; + }, +): ServiceManager | undefined { + if (platform === "linux") return new SystemdServiceManager(dependencies); + if (platform === "win32") return new TaskSchedulerServiceManager(dependencies); + return platform === "darwin" ? new LaunchdServiceManager(dependencies) : undefined; +} From 533413e7fa4e5d6be2cbad61ed82e8f973e74e71 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:11:13 +0100 Subject: [PATCH 03/25] test: an install whose registration fails is SERVICE_FAILED and leaves no task XML (#1698) --- src/cli/index-daemon-service.test.ts | 152 +++++++++++++++++++++------ 1 file changed, 122 insertions(+), 30 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 1b17d07e3..2966e0a0c 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -13,6 +13,7 @@ import { MemoryFilesystem, MemoryIpcTransport, serviceDefinition, + type ProcessResult, type ServiceManager, type ServiceState, TaskSchedulerServiceManager, @@ -766,36 +767,58 @@ describe("CLI: a service manager call fails, or the platform has none (#830)", ( describe("CLI: daemon service on Windows (#1698)", () => { const root = "/Users/me/.simlock"; - const name = "com.callstack.simlock.worker"; const nodePath = "/opt/node/node.exe"; const mainPath = "/opt/simlock/dist/daemon/main.js"; const sid = "S-1-5-21-1-2-3-1001"; - const xmlPath = join(root, "service-task.xml"); const done = { code: 0, stdout: "", stderr: "" }; - it("an operator runs daemon install on Windows: the user's SID goes into a UTF-16 logon task that runs the supervisor hidden with the saved variables, the daemon answers, and install prints the name, Daemon running and the login hint", async () => { + async function installOnWindows(options: { + readonly argv: readonly string[]; + readonly role?: "worker" | "gateway"; + readonly whoami?: ProcessResult; + readonly create?: ProcessResult; + }): Promise<{ + readonly exitCode: number; + readonly output: ReturnType; + readonly runner: ScriptedProcessRunner; + readonly filesystem: MemoryFilesystem; + readonly name: string; + readonly xmlPath: string; + readonly written: { readonly text: string; readonly encoding: string } | undefined; + }> { + const role = options.role ?? "worker"; + const dataDirectory = role === "gateway" ? join(root, "gateway") : root; + const name = `com.callstack.simlock.${role}`; + const xmlPath = join(dataDirectory, "service-task.xml"); const filesystem = new MemoryFilesystem(); const ipcTransport = new MemoryIpcTransport(); let written: { readonly text: string; readonly encoding: string } | undefined; const runner = new ScriptedProcessRunner([ { match: { command: "whoami", args: ["/user", "/fo", "csv", "/nh"] }, - result: { ...done, stdout: `"desktop\\me","${sid}"\r\n` }, - }, - { - match: { command: "schtasks", args: ["/end", "/tn", name] }, - result: { code: 1, stdout: "", stderr: "ERROR: There are no running instances." }, - }, - { - match: { command: "schtasks", args: ["/create", "/tn", name, "/xml", xmlPath, "/f"] }, - result: done, - onSpawn: () => { - const encoding = filesystem.encodingOf(xmlPath); - void filesystem.readFile(xmlPath).then((text) => { - written = { text, encoding }; - }); - }, + result: options.whoami ?? { ...done, stdout: `"desktop\\me","${sid}"\r\n` }, }, + ...(options.whoami === undefined || options.whoami.code === 0 + ? [ + { + match: { command: "schtasks", args: ["/end", "/tn", name] }, + result: { code: 1, stdout: "", stderr: "ERROR: There are no running instances." }, + }, + { + match: { + command: "schtasks", + args: ["/create", "/tn", name, "/xml", xmlPath, "/f"], + }, + result: options.create ?? done, + onSpawn: () => { + const encoding = filesystem.encodingOf(xmlPath); + void filesystem.readFile(xmlPath).then((text) => { + written = { text, encoding }; + }); + }, + }, + ] + : []), ]); const tasks = new TaskSchedulerServiceManager({ runner, @@ -810,10 +833,10 @@ describe("CLI: daemon service on Windows (#1698)", () => { install: async (definition) => { await tasks.install(definition); await startInMemoryDaemon({ - adminTokenPath: join(root, "admin.token"), + adminTokenPath: join(dataDirectory, "admin.token"), filesystem, ipcTransport, - socketPath: join(root, "daemon.sock"), + socketPath: join(dataDirectory, "daemon.sock"), }); }, }; @@ -824,8 +847,8 @@ describe("CLI: daemon service on Windows (#1698)", () => { systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), ipc: ipcTransport, launcher: new FakeDaemonLauncher(), - daemonHome: { role: "worker", dataDirectory: root, gatewayPresent: false }, - homeDirectory: "C:\\Users\\me", + daemonHome: { role, dataDirectory, gatewayPresent: false }, + homeDirectory: "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/Users/me", workingDirectory: "C:\\work", hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), @@ -841,8 +864,21 @@ describe("CLI: daemon service on Windows (#1698)", () => { }, { PATH: "C:\\bin" }, ); + const exitCode = await runCli(options.argv, output.environmentWith()); + return { exitCode, output, runner, filesystem, name, xmlPath, written }; + } - const exitCode = await runCli(["daemon", "install"], output.environmentWith()); + function supervisorArguments(xml: string): RegExpExecArray | null { + const args = /(.*)<\/Arguments>/.exec(xml)?.[1] ?? ""; + return /^--headless "([^"]*)" "([^"]*)"( --gateway)? --task (\S+) --install-id ([0-9a-f-]{36}) --environment (\S+)$/.exec( + args, + ); + } + + it("an operator runs daemon install on Windows: the user's SID goes into a UTF-16 logon task that runs the supervisor hidden with the saved variables, the daemon answers, and install prints the name, Daemon running and the login hint", async () => { + const { exitCode, output, runner, filesystem, name, xmlPath, written } = await installOnWindows( + { argv: ["daemon", "install"] }, + ); expect(output.stderr).toBe(""); expect(exitCode).toBe(0); @@ -875,20 +911,76 @@ describe("CLI: daemon service on Windows (#1698)", () => { ]) { expect(xml, element).toContain(element); } - const args = /(.*)<\/Arguments>/.exec(xml)?.[1] ?? ""; - const parts = - /^--headless "([^"]*)" "([^"]*)" --task (\S+) --install-id ([0-9a-f-]{36}) --environment (\S+)$/.exec( - args, - ); - expect(parts?.slice(1, 4)).toEqual([ + const parts = supervisorArguments(xml); + expect(parts?.slice(1, 5)).toEqual([ nodePath, "/opt/simlock/dist/daemon/service-main.js", + undefined, name, ]); - expect(JSON.parse(Buffer.from(parts?.[5] ?? "", "base64url").toString("utf8"))).toEqual({ + expect(JSON.parse(Buffer.from(parts?.[6] ?? "", "base64url").toString("utf8"))).toEqual({ SIMLOCK_HOME: root, PATH: "C:\\bin", }); expect(await filesystem.exists(xmlPath), "the XML file is deleted after create").toBe(false); }); + + it("daemon install --gateway on Windows names the gateway task and passes --gateway to the supervisor, and --json answers the task-scheduler manager", async () => { + const gateway = await installOnWindows({ + argv: ["--gateway", "daemon", "install"], + role: "gateway", + }); + expect(gateway.output.stderr).toBe(""); + expect(gateway.output.stdout.split("\n")[0]).toBe( + "Service installed: com.callstack.simlock.gateway (task-scheduler)", + ); + const parts = supervisorArguments(gateway.written?.text ?? ""); + expect(parts?.[3], "the supervisor gets --gateway").toBe(" --gateway"); + expect(parts?.[4]).toBe("com.callstack.simlock.gateway"); + + const json = await installOnWindows({ argv: ["daemon", "install", "--json"] }); + expect(JSON.parse(json.output.stdout)).toEqual({ + status: "installed", + service: { + state: "installed", + manager: "task-scheduler", + name: "com.callstack.simlock.worker", + path: "\\com.callstack.simlock.worker", + }, + }); + }); + + it("an install whose registration fails is SERVICE_FAILED with the command's first stderr line, and leaves no task XML", async () => { + const name = "com.callstack.simlock.worker"; + const xmlPath = join(root, "service-task.xml"); + const cases = [ + { + label: "schtasks /create exits 1", + create: { code: 1, stdout: "", stderr: "ERROR: Access is denied.\nsecond line" }, + message: `schtasks /create /tn ${name} /xml ${xmlPath} /f failed: ERROR: Access is denied.`, + }, + { + label: "whoami exits 1", + whoami: { code: 1, stdout: "", stderr: "ERROR: no user" }, + message: "whoami /user /fo csv /nh failed: ERROR: no user", + }, + { + label: "a call past 10 s", + create: { code: null, stdout: "", stderr: "" }, + message: `schtasks /create /tn ${name} /xml ${xmlPath} /f did not finish within 10 s`, + }, + ]; + for (const { label, message, ...results } of cases) { + const failed = await installOnWindows({ argv: ["daemon", "install"], ...results }); + expect(failed.exitCode, label).toBe(1); + expect(JSON.parse(failed.output.stderr.trim()), label).toEqual({ + error: { code: "SERVICE_FAILED", message }, + }); + expect(await failed.filesystem.exists(xmlPath), label).toBe(false); + expect( + failed.runner.calls.every((call) => call.options.timeoutMs === 10_000), + label, + ).toBe(true); + } + }); }); From 525779894507d9b84cc76ff5179a9734f069d5d5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:11:55 +0100 Subject: [PATCH 04/25] test: an operator runs daemon uninstall on Windows (#1698) --- src/cli/index-daemon-service.test.ts | 176 ++++++++++++++++++++------- 1 file changed, 133 insertions(+), 43 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 2966e0a0c..ee1c26d28 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -772,6 +772,72 @@ describe("CLI: daemon service on Windows (#1698)", () => { const sid = "S-1-5-21-1-2-3-1001"; const done = { code: 0, stdout: "", stderr: "" }; + async function runWindowsCli(options: { + readonly argv: readonly string[]; + readonly role: "worker" | "gateway"; + readonly runner: ScriptedProcessRunner; + readonly filesystem: MemoryFilesystem; + readonly startAfterInstall?: boolean; + readonly daemonRunning?: boolean; + readonly state?: ServiceState; + }): Promise<{ readonly exitCode: number; readonly output: ReturnType }> { + const { role, runner, filesystem } = options; + const dataDirectory = role === "gateway" ? join(root, "gateway") : root; + const ipcTransport = new MemoryIpcTransport(); + const startDaemon = async (): Promise => { + await startInMemoryDaemon({ + adminTokenPath: join(dataDirectory, "admin.token"), + filesystem, + ipcTransport, + socketPath: join(dataDirectory, "daemon.sock"), + }); + }; + if (options.daemonRunning === true) await startDaemon(); + const tasks = new TaskSchedulerServiceManager({ + runner, + filesystem, + systemRoot: "C:\\Windows", + }); + const { state } = options; + const serviceManager: ServiceManager = { + manager: "task-scheduler", + state: (definition) => + state === undefined ? tasks.state(definition) : Promise.resolve(state), + uninstall: (definition) => tasks.uninstall(definition), + start: (definition) => tasks.start(definition), + install: async (definition) => { + await tasks.install(definition); + if (options.startAfterInstall === true) await startDaemon(); + }, + }; + const output = outputCapture( + { + filesystem, + clock: new FakeClock(0), + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: ipcTransport, + launcher: new FakeDaemonLauncher(), + daemonHome: { role, dataDirectory, gatewayPresent: false }, + homeDirectory: "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/Users/me", + workingDirectory: "C:\\work", + hostPlatform: "linux", + runTool: async () => ({ outcome: "not-found" }), + service: { + manager: serviceManager, + platform: "win32", + home: "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/Users/me", + user: () => "me", + root, + nodePath, + mainPath, + }, + }, + { PATH: "C:\\bin" }, + ); + const exitCode = await runCli(options.argv, output.environmentWith()); + return { exitCode, output }; + } + async function installOnWindows(options: { readonly argv: readonly string[]; readonly role?: "worker" | "gateway"; @@ -791,7 +857,6 @@ describe("CLI: daemon service on Windows (#1698)", () => { const name = `com.callstack.simlock.${role}`; const xmlPath = join(dataDirectory, "service-task.xml"); const filesystem = new MemoryFilesystem(); - const ipcTransport = new MemoryIpcTransport(); let written: { readonly text: string; readonly encoding: string } | undefined; const runner = new ScriptedProcessRunner([ { @@ -820,51 +885,13 @@ describe("CLI: daemon service on Windows (#1698)", () => { ] : []), ]); - const tasks = new TaskSchedulerServiceManager({ + const { exitCode, output } = await runWindowsCli({ + argv: options.argv, + role, runner, filesystem, - systemRoot: "C:\\Windows", + startAfterInstall: true, }); - const serviceManager: ServiceManager = { - manager: "task-scheduler", - state: (definition) => tasks.state(definition), - uninstall: (definition) => tasks.uninstall(definition), - start: (definition) => tasks.start(definition), - install: async (definition) => { - await tasks.install(definition); - await startInMemoryDaemon({ - adminTokenPath: join(dataDirectory, "admin.token"), - filesystem, - ipcTransport, - socketPath: join(dataDirectory, "daemon.sock"), - }); - }, - }; - const output = outputCapture( - { - filesystem, - clock: new FakeClock(0), - systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), - ipc: ipcTransport, - launcher: new FakeDaemonLauncher(), - daemonHome: { role, dataDirectory, gatewayPresent: false }, - homeDirectory: "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/Users/me", - workingDirectory: "C:\\work", - hostPlatform: "linux", - runTool: async () => ({ outcome: "not-found" }), - service: { - manager: serviceManager, - platform: "win32", - home: "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/Users/me", - user: () => "me", - root, - nodePath, - mainPath, - }, - }, - { PATH: "C:\\bin" }, - ); - const exitCode = await runCli(options.argv, output.environmentWith()); return { exitCode, output, runner, filesystem, name, xmlPath, written }; } @@ -983,4 +1010,67 @@ describe("CLI: daemon service on Windows (#1698)", () => { ).toBe(true); } }); + + it("an operator runs daemon uninstall on Windows: the daemon is stopped, the task is deleted, and no task or a failed delete is reported", async () => { + const name = "com.callstack.simlock.worker"; + const taskState: ServiceState = { state: "installed", path: `\\${name}` }; + const deleteArgs = ["/delete", "/tn", name, "/f"]; + const cases = [ + { + label: "task installed and daemon running", + argv: ["daemon", "uninstall"], + state: taskState, + daemonRunning: true, + script: [{ match: { command: "schtasks", args: deleteArgs }, result: done }], + stdout: `Daemon stopping\nService removed: ${name} (task-scheduler)\n`, + }, + { + label: "task installed, no daemon", + argv: ["daemon", "uninstall"], + state: taskState, + script: [{ match: { command: "schtasks", args: deleteArgs }, result: done }], + stdout: `Service removed: ${name} (task-scheduler)\n`, + }, + { + label: "no task: schtasks /delete is not run", + argv: ["daemon", "uninstall"], + state: { state: "not-installed" } as ServiceState, + script: [], + stdout: `Service not installed: ${name}\n`, + }, + ]; + for (const { label, script, stdout, ...rest } of cases) { + const runner = new ScriptedProcessRunner(script); + const { exitCode, output } = await runWindowsCli({ + ...rest, + role: "worker", + runner, + filesystem: new MemoryFilesystem(), + }); + expect(output.stderr, label).toBe(""); + expect(exitCode, label).toBe(0); + expect(output.stdout, label).toBe(stdout); + expect(runner.calls.length, label).toBe(script.length); + } + + const failed = await runWindowsCli({ + argv: ["daemon", "uninstall"], + role: "worker", + runner: new ScriptedProcessRunner([ + { + match: { command: "schtasks", args: deleteArgs }, + result: { code: 1, stdout: "", stderr: "ERROR: The system cannot find the file." }, + }, + ]), + filesystem: new MemoryFilesystem(), + state: taskState, + }); + expect(failed.exitCode).toBe(1); + expect(JSON.parse(failed.output.stderr.trim())).toEqual({ + error: { + code: "SERVICE_FAILED", + message: `schtasks /delete /tn ${name} /f failed: ERROR: The system cannot find the file.`, + }, + }); + }); }); From 8a11c415ddbaa7ca00d1b093dea207d59f96d729 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:12:04 +0100 Subject: [PATCH 05/25] feat(ports): daemon uninstall on Windows deletes the task (#1698) --- src/ports/service-manager.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index 795015fb0..33eacd7a1 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -500,7 +500,9 @@ export class TaskSchedulerServiceManager implements ServiceManager { } } - async uninstall(_definition: ServiceDefinition): Promise {} + async uninstall(definition: ServiceDefinition): Promise { + await this.checked("schtasks", ["/delete", "/tn", definition.name, "/f"]); + } async start(_definition: ServiceDefinition): Promise {} } From 9646e5aa1844fdfa70baeeeb6b19a3d6307f9c8f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:12:52 +0100 Subject: [PATCH 06/25] test: daemon status on Windows prints one Service line from the task and the desktop session (#1698) --- src/cli/index-daemon-service.test.ts | 151 +++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index ee1c26d28..33788c5ad 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -780,10 +780,15 @@ describe("CLI: daemon service on Windows (#1698)", () => { readonly startAfterInstall?: boolean; readonly daemonRunning?: boolean; readonly state?: ServiceState; + readonly files?: readonly string[]; }): Promise<{ readonly exitCode: number; readonly output: ReturnType }> { const { role, runner, filesystem } = options; const dataDirectory = role === "gateway" ? join(root, "gateway") : root; const ipcTransport = new MemoryIpcTransport(); + for (const file of options.files ?? []) { + await filesystem.mkdirp(dirname(file)); + await filesystem.writeFileAtomic(file, ""); + } const startDaemon = async (): Promise => { await startInMemoryDaemon({ adminTokenPath: join(dataDirectory, "admin.token"), @@ -1073,4 +1078,150 @@ describe("CLI: daemon service on Windows (#1698)", () => { }, }); }); + + it("daemon status on Windows prints one Service: line from the task and the user's desktop session, and --json carries the same state", async () => { + const name = "com.callstack.simlock.worker"; + const supervisor = "/opt/simlock/dist/daemon/service-main.js"; + const query = { + command: "cmd.exe", + args: ["/d", "/c", `chcp 65001 >nul && schtasks /query /tn ${name} /xml`], + }; + const whoami = { command: "whoami", args: ["/user", "/fo", "csv", "/nh"] }; + const tasklist = { + command: "tasklist", + args: ["/fi", "USERNAME eq desktop\\me", "/fi", "SESSION ne 0", "/fo", "csv", "/nh"], + }; + const taskXml = (options: { + readonly node?: string; + readonly supervisor?: string; + readonly arguments?: string; + readonly enabled?: boolean; + }): string => { + const args = + options.arguments ?? + `--headless "${options.node ?? nodePath}" "${options.supervisor ?? supervisor}" --task ${name} --install-id 1 --environment e30`; + return `true${String(options.enabled ?? true)}C:\\Windows\\System32\\conhost.exe${args}`; + }; + const ok = (stdout: string): ProcessResult => ({ code: 0, stdout, stderr: "" }); + const session = [{ match: whoami, result: ok('"desktop\\me","S-1-5-21-1"\r\n') }]; + const present = [nodePath, supervisor]; + const info = "INFO: No tasks are running which match the specified criteria.\r\n"; + const cases = [ + { + label: "no task", + files: [], + script: [{ match: query, result: { code: 1, stdout: "", stderr: "ERROR" } }], + line: "Service: not installed", + }, + { + label: "task, user at the screen", + files: present, + script: [ + { match: query, result: ok(taskXml({})) }, + ...session, + { match: tasklist, result: ok('"sihost.exe","4242","Console","1","20,000 K"\r\n') }, + ], + line: `Service: installed (task-scheduler, ${name})`, + }, + { + label: "no desktop session: tasklist prints only its INFO line", + files: present, + script: [ + { match: query, result: ok(taskXml({})) }, + ...session, + { match: tasklist, result: ok(info) }, + ], + line: `Service: not loaded (task-scheduler, ${name}): commands start the daemon without it`, + }, + { + label: "tasklist fails", + files: present, + script: [ + { match: query, result: ok(taskXml({})) }, + ...session, + { match: tasklist, result: { code: 1, stdout: "", stderr: "ERROR" } }, + ], + line: `Service: not loaded (task-scheduler, ${name}): commands start the daemon without it`, + }, + { + label: "tasklist takes more than 10 s", + files: present, + script: [ + { match: query, result: ok(taskXml({})) }, + ...session, + { match: tasklist, result: { code: null, stdout: "", stderr: "" } }, + ], + line: `Service: not loaded (task-scheduler, ${name}): commands start the daemon without it`, + }, + { + label: "task disabled by hand", + files: present, + script: [{ match: query, result: ok(taskXml({ enabled: false })) }], + line: `Service: not loaded (task-scheduler, ${name}): commands start the daemon without it`, + }, + { + label: "Node path gone", + files: [supervisor], + script: [{ match: query, result: ok(taskXml({})) }], + line: `Service: broken (task-scheduler, ${name}): ${nodePath} is gone; run simlock daemon install`, + }, + { + label: "supervisor path gone", + files: [nodePath], + script: [{ match: query, result: ok(taskXml({})) }], + line: `Service: broken (task-scheduler, ${name}): ${supervisor} is gone; run simlock daemon install`, + }, + { + label: "arguments without two quoted paths after --headless", + files: present, + script: [{ match: query, result: ok(taskXml({ arguments: "--headless node" })) }], + line: `Service: broken (task-scheduler, ${name}): \\${name} is gone; run simlock daemon install`, + }, + { + label: "a path with a non-ASCII character is read whole", + files: [nodePath, "/opt/simlock-ü/dist/daemon/service-main.js"], + script: [ + { + match: query, + result: ok(taskXml({ supervisor: "/opt/simlock-ü/dist/daemon/service-main.js" })), + }, + ...session, + { match: tasklist, result: ok('"sihost.exe","4242","Console","1","20,000 K"\r\n') }, + ], + line: `Service: installed (task-scheduler, ${name})`, + }, + ]; + for (const { label, files, script, line } of cases) { + const runner = new ScriptedProcessRunner(script); + const { exitCode, output } = await runWindowsCli({ + argv: ["daemon", "status"], + role: "worker", + runner, + filesystem: new MemoryFilesystem(), + files, + }); + expect(output.stderr, label).toBe(""); + expect(exitCode, label).toBe(0); + expect(output.stdout, label).toBe(`Daemon stopped\n${line}\n`); + expect(runner.calls.length, label).toBe(script.length); + expect( + runner.calls.every((call) => call.options.timeoutMs === 10_000), + label, + ).toBe(true); + } + + const json = await runWindowsCli({ + argv: ["daemon", "status", "--json"], + role: "worker", + runner: new ScriptedProcessRunner([ + { match: query, result: ok(taskXml({ enabled: false })) }, + ]), + filesystem: new MemoryFilesystem(), + files: present, + }); + expect(JSON.parse(json.output.stdout)).toEqual({ + status: "stopped", + service: { state: "not-loaded", manager: "task-scheduler", name, path: `\\${name}` }, + }); + }); }); From 58eba01cb8c86b7c4ae8a501c217f3617ba640bf Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:13:14 +0100 Subject: [PATCH 07/25] feat(ports): daemon status reads the Windows task and the user's desktop session (#1698) --- src/ports/service-manager.ts | 58 +++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index 33eacd7a1..a5eeac310 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -407,6 +407,17 @@ export interface TaskSchedulerServiceManagerOptions { readonly systemRoot?: string; } +const WHOAMI_ARGS = ["/user", "/fo", "csv", "/nh"]; + +function xmlUnescape(value: string): string { + return value + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll(""", '"') + .replaceAll("'", "'") + .replaceAll("&", "&"); +} + const TASK_NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task"; function quoted(value: string): string { @@ -473,15 +484,54 @@ export class TaskSchedulerServiceManager implements ServiceManager { return result; } - async state(_definition: ServiceDefinition): Promise { - return { state: "not-installed" }; + private async hasDesktopSession(): Promise { + try { + const user = await this.checked("whoami", WHOAMI_ARGS); + const account = /^"([^"]*)"/.exec(user.stdout.trim())?.[1]; + if (account === undefined) return false; + const listed = await this.checked("tasklist", [ + "/fi", + `USERNAME eq ${account}`, + "/fi", + "SESSION ne 0", + "/fo", + "csv", + "/nh", + ]); + return listed.stdout.split(/\r?\n/).some((line) => line.startsWith('"')); + } catch (error: unknown) { + if (error instanceof ServiceFailedError) return false; + throw error; + } + } + + async state(definition: ServiceDefinition): Promise { + const { filesystem } = this.options; + // why: plain schtasks writes the OEM code page, which garbles a non-ASCII path. + const queried = await this.run("cmd.exe", [ + "/d", + "/c", + `chcp 65001 >nul && schtasks /query /tn ${definition.name} /xml`, + ]); + if (queried.code !== 0) return { state: "not-installed" }; + const args = xmlUnescape(/([\s\S]*?)<\/Arguments>/.exec(queried.stdout)?.[1] ?? ""); + const saved = /--headless\s+"([^"]*)"\s+"([^"]*)"/.exec(args); + if (saved === null) + return { state: "broken", path: definition.path, missing: [definition.path] }; + const missing: string[] = []; + for (const path of [saved[1] as string, saved[2] as string]) { + if (!(await filesystem.exists(path))) missing.push(path); + } + if (missing.length > 0) return { state: "broken", path: definition.path, missing }; + const disabled = /[\s\S]*?\s*false\s*<\/Enabled>/i.test(queried.stdout); + const loaded = !disabled && (await this.hasDesktopSession()); + return { state: loaded ? "installed" : "not-loaded", path: definition.path }; } async install(definition: ServiceDefinition): Promise { const { filesystem } = this.options; await ensureLog(filesystem, definition.logPath); - const whoamiArgs = ["/user", "/fo", "csv", "/nh"]; - const user = await this.checked("whoami", whoamiArgs); + const user = await this.checked("whoami", WHOAMI_ARGS); const sid = /^"[^"]*","([^"]*)"/.exec(user.stdout.trim())?.[1]; if (sid === undefined) throw new ServiceFailedError("whoami /user printed no SID"); const xmlPath = join(dirname(definition.logPath), "service-task.xml"); From 27b0eb42d6dcce9fc6493b35fe7398653887744d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:14:03 +0100 Subject: [PATCH 08/25] test: a start runs the Windows task when installed and spawns with a notice otherwise (#1698) --- src/ports/daemon-launcher.test.ts | 124 +++++++++++++++++++++++++++++- 1 file changed, 123 insertions(+), 1 deletion(-) diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 984aebac0..7ffe65f9e 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -7,7 +7,14 @@ import { join } from "node:path"; import { FakeDaemonLauncher, NodeDaemonLauncher, startErrorFrom } from "./daemon-launcher.js"; import { launcherFor } from "./service-launcher.js"; -import { FakeServiceManager, type ServiceState } from "./service-manager.js"; +import { + FakeServiceManager, + MemoryFilesystem, + type ProcessResult, + ScriptedProcessRunner, + type ServiceState, + TaskSchedulerServiceManager, +} from "./index.js"; // why: lets one test refuse a mkdir of one existing folder, as Windows does for a drive root; every // other call goes to the real `mkdir`. @@ -406,3 +413,118 @@ describe("launcherFor with an installed service", () => { } }); }); + +describe("launcherFor with the Windows task (#1698)", () => { + const name = "com.callstack.simlock.worker"; + const nodePath = "/opt/node/node.exe"; + const supervisor = "/opt/simlock/dist/daemon/service-main.js"; + const ok = (stdout: string): ProcessResult => ({ code: 0, stdout, stderr: "" }); + const query = { + command: "cmd.exe", + args: ["/d", "/c", `chcp 65001 >nul && schtasks /query /tn ${name} /xml`], + }; + const run = { command: "schtasks", args: ["/run", "/tn", name] }; + const taskXml = `true--headless "${nodePath}" "${supervisor}" --task ${name}`; + const session = [ + { + match: { command: "whoami", args: ["/user", "/fo", "csv", "/nh"] }, + result: ok('"desktop\\me","S-1-5-21-1"\r\n'), + }, + { + match: { + command: "tasklist", + args: ["/fi", "USERNAME eq desktop\\me", "/fi", "SESSION ne 0", "/fo", "csv", "/nh"], + }, + result: ok('"sihost.exe","4242","Console","1","20,000 K"\r\n'), + }, + ]; + + async function launchWith(options: { + readonly script: ConstructorParameters[0]; + readonly files: readonly string[]; + }): Promise<{ + readonly spawner: FakeDaemonLauncher; + readonly notices: string[]; + readonly runner: ScriptedProcessRunner; + readonly launch: () => Promise; + }> { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/opt/simlock/dist/daemon"); + await filesystem.mkdirp("/opt/node"); + for (const file of options.files) await filesystem.writeFileAtomic(file, ""); + const runner = new ScriptedProcessRunner(options.script); + const spawner = new FakeDaemonLauncher(); + const notices: string[] = []; + const launcher = launcherFor({ + role: "worker", + root: "/Users/me/.simlock", + dataDirectory: "/Users/me/.simlock", + mainPath: "/opt/simlock/dist/daemon/main.js", + nodePath, + home: "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/Users/me", + env: {}, + serviceManager: new TaskSchedulerServiceManager({ runner, filesystem }), + notify: (line) => notices.push(line), + spawner, + }); + return { spawner, notices, runner, launch: () => launcher.launch() }; + } + + it("a start runs the task when the service is installed and spawns the daemon, with the notice, when it is not loaded, broken or not installed", async () => { + const installed = await launchWith({ + script: [{ match: query, result: ok(taskXml) }, ...session, { match: run, result: ok("") }], + files: [nodePath, supervisor], + }); + await installed.launch(); + expect(installed.spawner.launches, "installed: no spawn").toBe(0); + expect(installed.runner.calls.at(-1)?.args, "installed: /run").toEqual(["/run", "/tn", name]); + expect(installed.notices).toEqual([]); + + const notLoaded = await launchWith({ + script: [ + { match: query, result: ok(taskXml) }, + ...session.slice(0, 1), + { + match: session[1]?.match as never, + result: ok("INFO: No tasks are running which match the specified criteria.\r\n"), + }, + ], + files: [nodePath, supervisor], + }); + await notLoaded.launch(); + expect(notLoaded.spawner.launches, "not loaded: spawn").toBe(1); + expect(notLoaded.notices).toEqual([ + `Service ${name} is not loaded; started the daemon without it.`, + ]); + + const broken = await launchWith({ + script: [{ match: query, result: ok(taskXml) }], + files: [supervisor], + }); + await broken.launch(); + expect(broken.spawner.launches, "broken: spawn").toBe(1); + expect(broken.notices).toEqual([ + `Service ${name} is broken (${nodePath} is gone); started the daemon without it. Run simlock daemon install again.`, + ]); + + const none = await launchWith({ + script: [{ match: query, result: { code: 1, stdout: "", stderr: "ERROR" } }], + files: [], + }); + await none.launch(); + expect(none.spawner.launches, "not installed: spawn").toBe(1); + expect(none.notices).toEqual([]); + + const refused = await launchWith({ + script: [ + { match: query, result: ok(taskXml) }, + ...session, + { match: run, result: { code: 1, stdout: "", stderr: "ERROR: The task is disabled." } }, + ], + files: [nodePath, supervisor], + }); + await expect(refused.launch()).rejects.toThrow( + `schtasks /run /tn ${name} failed: ERROR: The task is disabled.`, + ); + }); +}); From a95ce2e2148631e474afd856c397da02d9bd2736 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:14:11 +0100 Subject: [PATCH 09/25] feat(ports): a start runs the Windows task (#1698) --- src/ports/service-manager.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index a5eeac310..355dd7bc2 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -554,7 +554,9 @@ export class TaskSchedulerServiceManager implements ServiceManager { await this.checked("schtasks", ["/delete", "/tn", definition.name, "/f"]); } - async start(_definition: ServiceDefinition): Promise {} + async start(definition: ServiceDefinition): Promise { + await this.checked("schtasks", ["/run", "/tn", definition.name]); + } } export function productionServiceManager( From 288a695d88b6bee848fb159f6fd08621cb97530c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:14:43 +0100 Subject: [PATCH 10/25] test: a worker's doctor reports service-broken for the Windows task (#1698) --- ...perations-round-trips-lease-status.test.ts | 5 +++ src/daemon/main-start-daemon.test.ts | 43 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/contract/operations-round-trips-lease-status.test.ts b/src/contract/operations-round-trips-lease-status.test.ts index e761df7b3..00d7be8c3 100644 --- a/src/contract/operations-round-trips-lease-status.test.ts +++ b/src/contract/operations-round-trips-lease-status.test.ts @@ -154,6 +154,11 @@ describe("operation input/output round trips", () => { findings: [finding], sources: [], }); + const onWindows = { ...finding, manager: "task-scheduler", missing: ["C:\\node\\node.exe"] }; + expect(OPERATIONS["doctor.run"].output.parse({ findings: [onWindows], sources: [] })).toEqual({ + findings: [onWindows], + sources: [], + }); expect(() => OPERATIONS["doctor.run"].output.parse({ findings: [{ ...finding, missing: [] }], diff --git a/src/daemon/main-start-daemon.test.ts b/src/daemon/main-start-daemon.test.ts index e4afb5e99..820572909 100644 --- a/src/daemon/main-start-daemon.test.ts +++ b/src/daemon/main-start-daemon.test.ts @@ -18,6 +18,8 @@ import { type ServiceManager, type ServiceState, MemoryFilesystem, + ScriptedProcessRunner, + TaskSchedulerServiceManager, } from "../ports/index.js"; import { productionServiceCheck } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -374,6 +376,47 @@ describe("startDaemon", () => { } }); + it("productionServiceCheck on Windows reads the task: the path it names that is gone, none when all are there or there is no task, and no check on a gateway", async () => { + const name = "com.callstack.simlock.worker"; + const query = { + command: "cmd.exe", + args: ["/d", "/c", `chcp 65001 >nul && schtasks /query /tn ${name} /xml`], + }; + const xml = `true--headless "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/gone/node.exe" "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/here/service-main.js" --task ${name}`; + const cases = [ + { + label: "path gone", + result: { code: 0, stdout: xml, stderr: "" }, + files: ["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/here/service-main.js"], + missing: ["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/gone/node.exe"], + }, + { + label: "no task", + result: { code: 1, stdout: "", stderr: "ERROR" }, + files: [], + missing: [], + }, + ]; + for (const { label, result, files, missing } of cases) { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/here"); + for (const file of files) await filesystem.writeFileAtomic(file, ""); + const runner = new ScriptedProcessRunner([{ match: query, result }]); + const host = { + manager: new TaskSchedulerServiceManager({ runner, filesystem }), + root: "/Users/me/.simlock", + home: "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/Users/me", + nodePath: "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/gone/node.exe", + mainPath: "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/here/main.js", + env: {}, + }; + const { serviceCheck } = productionServiceCheck("worker", host); + expect(serviceCheck?.manager, label).toBe("task-scheduler"); + expect(await serviceCheck?.check(), label).toEqual(missing); + expect(productionServiceCheck("gateway", host), label).toEqual({}); + } + }); + it("productionServiceCheck builds the service definition from the process facts and reads its state: the missing paths when broken, none otherwise, and no check on a gateway or without a manager", async () => { const seen: ServiceDefinition[] = []; const manager: ServiceManager = { From d78ab67fe97d758a23ad1d0b580efce61eadc448 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:15:02 +0100 Subject: [PATCH 11/25] test: daemon install and uninstall on a platform with no service manager name Windows in the USAGE message (#1698) --- src/cli/index-daemon-service.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 33788c5ad..afab70ce4 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -697,11 +697,11 @@ describe("CLI: a service manager call fails, or the platform has none (#830)", ( it("a failed or stuck launchctl call is SERVICE_FAILED, a failed load removes the plist, and a platform without a service manager is a usage error", async () => { for (const command of ["install", "uninstall"]) { - const result = await run({ argv: ["daemon", command], platform: "win32" }); - expect(result.exitCode, `win32 ${command}`).toBe(2); - expect(errorOf(result.stderr), `win32 ${command}`).toEqual({ + const result = await run({ argv: ["daemon", command], platform: "freebsd" }); + expect(result.exitCode, `freebsd ${command}`).toBe(2); + expect(errorOf(result.stderr), `freebsd ${command}`).toEqual({ code: "USAGE", - message: `daemon ${command} is supported on macOS and Linux only`, + message: `daemon ${command} is supported on macOS, Linux and Windows only`, }); } From 65da7a7627a814c56d9aed7a22f519a30c15a7ea Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:15:05 +0100 Subject: [PATCH 12/25] fix(cli): the daemon install usage error names Windows (#1698) --- src/cli/commands/daemon.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts index b2723c1d2..1b284553b 100644 --- a/src/cli/commands/daemon.ts +++ b/src/cli/commands/daemon.ts @@ -18,7 +18,7 @@ function serviceAccess( } { const { service } = environment; if (service?.manager === undefined) { - throw new UsageError(`daemon ${command} is supported on macOS and Linux only`); + throw new UsageError(`daemon ${command} is supported on macOS, Linux and Windows only`); } return { manager: service.manager, definition: service.definition, user: service.user }; } From 07d000305b927973c393c623c26ee7e8c7ba1c83 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:16:27 +0100 Subject: [PATCH 13/25] test: the supervisor keeps the daemon running and restarts it after a failure while its task is its own (#1698) --- src/daemon/service-main.test.ts | 241 ++++++++++++++++++++++++++++++++ src/daemon/service-main.ts | 15 ++ 2 files changed, 256 insertions(+) create mode 100644 src/daemon/service-main.test.ts create mode 100644 src/daemon/service-main.ts diff --git a/src/daemon/service-main.test.ts b/src/daemon/service-main.test.ts new file mode 100644 index 000000000..620ee7c29 --- /dev/null +++ b/src/daemon/service-main.test.ts @@ -0,0 +1,241 @@ +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + FakeClock, + JsonLinesLogger, + MemoryLogSink, + ProcessSpawnError, + ScriptedProcessRunner, + type ProcessResult, + type ProcessRunner, + type ScriptedProcessExpectation, +} from "../ports/index.js"; +import { runSupervisor } from "./service-main.js"; + +const name = "com.callstack.simlock.worker"; +const installId = "6f1c1b0e-0000-4000-8000-000000000001"; +const home = "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/h/.simlock"; +const nodePath = "/opt/node/node.exe"; +const mainPath = "/opt/simlock/dist/daemon/main.js"; +const encode = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString("base64url"); +const goodArgv = (...gateway: string[]): string[] => [ + ...gateway, + "--task", + name, + "--install-id", + installId, + "--environment", + encode({ SIMLOCK_HOME: home, PATH: "saved" }), +]; + +const settle = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); +const result = (code: number | null, signal?: NodeJS.Signals): ProcessResult => ({ + code, + stdout: "", + stderr: "", + ...(signal === undefined ? {} : { signal }), +}); +const taskXml = (id: string): string => + `--headless "${nodePath}" "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/s/service-main.js" --task ${name} --install-id ${id} --environment e30`; +const query = { command: "schtasks", args: ["/query", "/tn", name, "/xml"] }; + +describe("the Windows supervisor (#1698)", () => { + async function supervise(options: { + readonly argv: readonly string[]; + readonly script: ( + daemon: (outcome: ProcessResult, hangs?: boolean) => ScriptedProcessExpectation, + ) => ScriptedProcessExpectation[]; + readonly failSpawns?: (command: string, attempt: number) => boolean; + readonly steps?: number; + }): Promise<{ + readonly exit: number | undefined; + readonly runner: ScriptedProcessRunner; + readonly startedAt: number[]; + readonly lines: string[]; + readonly logPaths: string[]; + }> { + const clock = new FakeClock(0); + const startedAt: number[] = []; + const daemon = (outcome: ProcessResult, hangs = false): ScriptedProcessExpectation => ({ + match: { + command: nodePath, + args: options.argv[0] === "--gateway" ? [mainPath, "--gateway"] : [mainPath], + }, + result: outcome, + hangs, + onSpawn: () => { + startedAt.push(clock.now()); + }, + }); + const scripted = new ScriptedProcessRunner(options.script(daemon)); + let attempts = 0; + const runner: ProcessRunner = { + run: (command, args, runOptions) => { + if (options.failSpawns?.(command, attempts++) === true) { + throw new ProcessSpawnError(command, args); + } + return scripted.run(command, args, runOptions); + }, + spawn: (command, args, spawnOptions) => { + if (options.failSpawns?.(command, attempts++) === true) { + throw new ProcessSpawnError(command, args); + } + return scripted.spawn(command, args, spawnOptions); + }, + spawnStreaming: (command, args, streamOptions) => + scripted.spawnStreaming(command, args, streamOptions), + }; + const sink = new MemoryLogSink(); + const logPaths: string[] = []; + let exit: number | undefined; + void runSupervisor({ + argv: options.argv, + env: { PATH: "own", KEEP: "1" }, + nodePath, + mainPath, + runner, + clock, + openLog: (path) => { + logPaths.push(path); + return new JsonLinesLogger({ clock, sink, level: "info", module: "supervisor" }); + }, + }).then((code) => { + exit = code; + }); + for (let step = 0; step < (options.steps ?? 12) && exit === undefined; step += 1) { + await settle(); + clock.advance(10_000); + } + await settle(); + const lines = sink.records.map((record) => `${record.level}: ${record.message}`); + return { exit, runner: scripted, startedAt, lines, logPaths }; + } + + it("the supervisor starts the daemon with the saved variables and waits for it, restarts it 10 s after a failure while its task is still the one that started it, and stops when the daemon exits 0, the task is gone or names another install", async () => { + const exited0 = await supervise({ + argv: goodArgv(), + script: (daemon) => [daemon(result(0))], + }); + expect(exited0.exit, "exit 0 ends the supervisor with 0").toBe(0); + expect(exited0.runner.calls, "no restart").toHaveLength(1); + expect(exited0.lines).toEqual([]); + + const failed = await supervise({ + argv: goodArgv(), + script: (daemon) => [ + daemon(result(1)), + { match: query, result: { ...result(0), stdout: taskXml(installId) } }, + daemon(result(null, "SIGKILL")), + { match: query, result: { ...result(0), stdout: taskXml(installId) } }, + daemon(result(1)), + { match: query, result: { ...result(0), stdout: taskXml(installId) } }, + daemon(result(0)), + ], + }); + expect(failed.exit).toBe(0); + expect(failed.startedAt, "each restart 10 s after the failure").toEqual([ + 0, 10_000, 20_000, 30_000, + ]); + expect(failed.lines).toEqual([ + "warn: Daemon exited (code 1); the service starts it again in 10 s", + "warn: Daemon exited (signal SIGKILL); the service starts it again in 10 s", + "warn: Daemon exited (code 1); the service starts it again in 10 s", + ]); + const first = failed.runner.calls[0]; + expect(first?.options.timeoutMs, "the daemon wait has no limit").toBeUndefined(); + expect(first?.options.stdio).toEqual({ file: join(home, "daemon.log") }); + expect(first?.options.env).toMatchObject({ PATH: "saved", KEEP: "1", SIMLOCK_HOME: home }); + expect(failed.logPaths[0]).toBe(join(home, "daemon.log")); + expect( + failed.runner.calls + .filter((call) => call.command === "schtasks") + .map((call) => call.options.timeoutMs), + ).toEqual([10_000, 10_000, 10_000]); + + const gateway = await supervise({ + argv: goodArgv("--gateway"), + script: (daemon) => [daemon(result(0))], + }); + expect(gateway.runner.calls[0]?.args).toEqual([mainPath, "--gateway"]); + expect(gateway.runner.calls[0]?.options.stdio).toEqual({ + file: join(home, "gateway", "daemon.log"), + }); + + const stops = [ + { label: "the task is gone", stdout: undefined, code: 1 }, + { label: "another install id", stdout: taskXml("another-id"), code: 0 }, + ]; + for (const stop of stops) { + const stopped = await supervise({ + argv: goodArgv(), + script: (daemon) => [ + daemon(result(1)), + { match: query, result: { ...result(stop.code), stdout: stop.stdout ?? "" } }, + ], + }); + expect(stopped.exit, stop.label).toBe(0); + expect(stopped.runner.calls, stop.label).toHaveLength(2); + expect(stopped.lines.at(-1), stop.label).toBe( + `warn: The service ${name} is gone; the supervisor stops`, + ); + } + + const unreadable = [ + { label: "the task read passes 10 s", failure: undefined, outcome: result(null) }, + { label: "the task read cannot be spawned", failure: "schtasks", outcome: result(0) }, + ]; + for (const read of unreadable) { + const restarted = await supervise({ + argv: goodArgv(), + failSpawns: (command) => command === read.failure, + script: (daemon) => [ + daemon(result(1)), + ...(read.failure === undefined ? [{ match: query, result: read.outcome }] : []), + daemon(result(0)), + ], + }); + expect(restarted.exit, read.label).toBe(0); + expect(restarted.startedAt, read.label).toEqual([0, 10_000]); + } + + const failedStart = await supervise({ + argv: goodArgv(), + failSpawns: (command, attempt) => command === nodePath && attempt === 0, + script: (daemon) => [ + { match: query, result: { ...result(0), stdout: taskXml(installId) } }, + daemon(result(0)), + ], + }); + expect(failedStart.exit).toBe(0); + expect(failedStart.lines[0]).toBe( + `warn: Daemon failed to start (Failed to spawn ${nodePath} ${mainPath}); the service starts it again in 10 s`, + ); + expect(failedStart.startedAt).toEqual([10_000]); + + const waiting = await supervise({ + argv: goodArgv(), + script: (daemon) => [daemon(result(0), true)], + }); + expect(waiting.exit, "a running daemon keeps the run unsettled").toBeUndefined(); + + for (const argv of [ + [], + goodArgv().slice(2), + ["--task", name, "--install-id", installId], + [...goodArgv(), "extra"], + ["--install-id", installId, "--task", name, "--environment", encode({})], + goodArgv().slice(0, -1).concat("!!!"), + goodArgv() + .slice(0, -1) + .concat(encode(["a"])), + goodArgv() + .slice(0, -1) + .concat(encode({ PATH: 1 })), + ]) { + const refused = await supervise({ argv, script: () => [] }); + expect(refused.exit, argv.join(" ")).toBe(2); + expect(refused.runner.calls, argv.join(" ")).toHaveLength(0); + } + }); +}); diff --git a/src/daemon/service-main.ts b/src/daemon/service-main.ts new file mode 100644 index 000000000..690d6fcd0 --- /dev/null +++ b/src/daemon/service-main.ts @@ -0,0 +1,15 @@ +import type { Clock, Logger, ProcessRunner } from "../ports/index.js"; + +export interface SupervisorDependencies { + readonly argv: readonly string[]; + readonly env: NodeJS.ProcessEnv; + readonly nodePath: string; + readonly mainPath: string; + readonly runner: ProcessRunner; + readonly clock: Clock; + readonly openLog: (path: string) => Logger; +} + +export async function runSupervisor(_dependencies: SupervisorDependencies): Promise { + return 0; +} From 8470e28a1c13ddd88194775d9e33c7e33797f80d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:16:59 +0100 Subject: [PATCH 14/25] feat(daemon): the Windows supervisor keeps the daemon running and ends with its task (#1698) --- .fallowrc.json | 1 + src/daemon/service-main.ts | 140 ++++++++++++++++++++++++++++++++++++- 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/.fallowrc.json b/.fallowrc.json index 24a7c9609..60c0601a5 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -30,6 +30,7 @@ "entry": [ "src/cli/main.ts", "src/daemon/main.ts", + "src/daemon/service-main.ts", "src/updater/main.ts", "src/daemon/openapi.ts", "src/core/usage/read-thread.ts", diff --git a/src/daemon/service-main.ts b/src/daemon/service-main.ts index 690d6fcd0..4d1b7690f 100644 --- a/src/daemon/service-main.ts +++ b/src/daemon/service-main.ts @@ -1,4 +1,18 @@ -import type { Clock, Logger, ProcessRunner } from "../ports/index.js"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { + type Clock, + daemonDataDirectory, + JsonLinesLogger, + type Logger, + NodeFileLogSink, + NodeProcessRunner, + type ProcessResult, + type ProcessRunner, + resolveSimlockHome, + SystemClock, +} from "../ports/index.js"; export interface SupervisorDependencies { readonly argv: readonly string[]; @@ -10,6 +24,126 @@ export interface SupervisorDependencies { readonly openLog: (path: string) => Logger; } -export async function runSupervisor(_dependencies: SupervisorDependencies): Promise { - return 0; +interface SupervisorArguments { + readonly gateway: boolean; + readonly task: string; + readonly installId: string; + readonly environment: Readonly>; +} + +const RESTART_DELAY_MS = 10_000; +const SCHTASKS_TIMEOUT_MS = 10_000; +const WORD = /^[\w.-]+$/; +const BASE64URL = /^[\w-]+$/; + +function decodeEnvironment(text: string): Record | undefined { + if (!BASE64URL.test(text)) return undefined; + let parsed: unknown; + try { + parsed = JSON.parse(Buffer.from(text, "base64url").toString("utf8")); + } catch { + return undefined; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; + const entries = Object.entries(parsed); + if (!entries.every((entry): entry is [string, string] => typeof entry[1] === "string")) { + return undefined; + } + return Object.fromEntries(entries); +} + +/** why: the task's own arguments are the only input, in one fixed order; anything else is a stale or hand-edited task and starts nothing. */ +function parseArguments(argv: readonly string[]): SupervisorArguments | undefined { + const gateway = argv[0] === "--gateway"; + const [taskFlag, task, idFlag, installId, environmentFlag, environmentText, ...extra] = gateway + ? argv.slice(1) + : argv; + if (taskFlag !== "--task" || idFlag !== "--install-id" || environmentFlag !== "--environment") { + return undefined; + } + if (extra.length > 0 || task === undefined || installId === undefined) return undefined; + if (!WORD.test(task) || !WORD.test(installId) || environmentText === undefined) return undefined; + const environment = decodeEnvironment(environmentText); + return environment === undefined ? undefined : { gateway, task, installId, environment }; +} + +function describeExit(result: ProcessResult): string { + return result.signal === undefined ? `code ${String(result.code)}` : `signal ${result.signal}`; +} + +export async function runSupervisor(dependencies: SupervisorDependencies): Promise { + const { clock, runner } = dependencies; + const parsed = parseArguments(dependencies.argv); + if (parsed === undefined) return 2; + const env = { ...dependencies.env, ...parsed.environment }; + const dataDirectory = daemonDataDirectory( + resolveSimlockHome(env), + parsed.gateway ? "gateway" : "worker", + ); + const logPath = join(dataDirectory, "daemon.log"); + const logger = dependencies.openLog(logPath); + const sleep = (): Promise => + new Promise((resolve) => { + clock.setTimer(RESTART_DELAY_MS, resolve); + }); + + // why: a task that cannot be read in time counts as still there, so a slow Task Scheduler never stops a daemon the user wants. + const taskIsOurs = async (): Promise => { + let read: ProcessResult; + try { + read = await runner.run("schtasks", ["/query", "/tn", parsed.task, "/xml"], { + timeoutMs: SCHTASKS_TIMEOUT_MS, + }); + } catch { + return true; + } + if (read.code === null) return true; + if (read.code !== 0) return false; + return new RegExp(`--install-id ${parsed.installId.replaceAll(".", "\\.")}(?![\\w.-])`).test( + read.stdout, + ); + }; + + for (;;) { + let outcome: string; + try { + // why: no timeoutMs: the daemon runs until it exits, the one wait in Simlock with no limit. + const result = await runner + .spawn( + dependencies.nodePath, + [dependencies.mainPath, ...(parsed.gateway ? ["--gateway"] : [])], + { env, stdio: { file: logPath } }, + ) + .wait(); + if (result.code === 0) return 0; + outcome = `Daemon exited (${describeExit(result)})`; + } catch (error: unknown) { + outcome = `Daemon failed to start (${error instanceof Error ? error.message : String(error)})`; + } + logger.warn(`${outcome}; the service starts it again in 10 s`); + await sleep(); + if (!(await taskIsOurs())) { + logger.warn(`The service ${parsed.task} is gone; the supervisor stops`); + return 0; + } + } +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + const clock = new SystemClock(); + process.exitCode = await runSupervisor({ + argv: process.argv.slice(2), + env: process.env, + nodePath: process.execPath, + mainPath: join(dirname(fileURLToPath(import.meta.url)), "main.js"), + runner: new NodeProcessRunner(), + clock, + openLog: (path) => + new JsonLinesLogger({ + clock, + level: "info", + module: "supervisor", + sink: new NodeFileLogSink({ path }), + }), + }); } From 4c3b7c64a1e6af438289bed4022b29c0589c2c3d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:17:42 +0100 Subject: [PATCH 15/25] docs(website): daemon install on Windows (#1698) --- src/daemon/AGENTS.md | 1 + .../content/docs/docs/introduction/requirements.mdx | 2 +- website/src/content/docs/docs/reference/cli.mdx | 6 +++--- website/src/content/docs/docs/reference/errors.mdx | 2 +- .../src/content/docs/docs/using-devices/errors.mdx | 2 +- .../content/docs/docs/worker/running-the-daemon.mdx | 11 ++++++++++- .../src/content/docs/docs/worker/troubleshooting.mdx | 2 +- website/src/content/docs/docs/worker/windows.mdx | 6 +++--- 8 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index c9f9a47f3..504873c5f 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -25,6 +25,7 @@ Start and stop: - `daemon.stop` releases nothing; leases persist with their deadlines. - `dispose` stops the event history after the drivers are disposed, and closes `state.db` last. - A history file that fails costs only history. A start the history refuses (a newer stored projection version, a failed migration) stops the daemon (`history-refused`). +- `service-main.ts` is not the daemon: a Windows logon task runs it (ADR 0086). It starts `main.js` as a child it waits on, restarts it 10 s after a non-zero exit while its task still carries its install id, and imports only `ports/`. - A daemon works in its own role's data directory. Its one look outside is the update's `socketHeld` probe of the other role's socket (`composition-support.ts`). Connections: diff --git a/website/src/content/docs/docs/introduction/requirements.mdx b/website/src/content/docs/docs/introduction/requirements.mdx index bd090196c..9f2150a46 100644 --- a/website/src/content/docs/docs/introduction/requirements.mdx +++ b/website/src/content/docs/docs/introduction/requirements.mdx @@ -17,7 +17,7 @@ Simlock uses the platform tools already on your machine. It never installs Xcode | A gateway | macOS, Linux or Windows | Node.js 22.13 or later. A gateway runs no devices, so it needs no Xcode or Android SDK. | | A physical iPhone or iPad | A Mac | See [Use physical devices](#use-physical-devices) | | A physical Android phone | No system is named. Not checked on Windows yet. | See [Use physical devices](#use-physical-devices) | -| Start at login (`daemon install`) | macOS and Linux. Not on Windows yet. | See [Run the daemon](/simlock/docs/worker/running-the-daemon) | +| Start at login (`daemon install`) | macOS, Linux and Windows. | See [Run the daemon](/simlock/docs/worker/running-the-daemon) | On Windows, follow [Set up a Windows worker](/simlock/docs/worker/windows). diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index a9e45906d..c7a4d2e90 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -451,10 +451,10 @@ simlock daemon uninstall [--json] | --- | --- | | `start` | Start the daemon if it is not running, wait until it has finished starting (up to 90 seconds), and print `Daemon running` with the console address. A start that fails (for example, the HTTP port is taken) exits 1 with `DAEMON_STARTUP_FAILED` and the daemon's own error; a daemon still starting after the wait is left running and reported as such. `simlock --gateway daemon start` creates the gateway on first run. | | `stop` | Ask the daemon to stop, wait until it has exited (up to 300 s, then `SERVICE_FAILED`) and print `Daemon stopping`. With no daemon running it prints `Daemon not running` and exits 0. Before it exits the daemon shuts down every idle device it booted; leased devices keep running. Needs the admin role. Never starts a daemon. | -| `status` | Print the daemon's status, or `Daemon stopped` when none is running, then on macOS and Linux one `Service:` line: `not installed`, `installed (launchd, )`, `not loaded (launchd, ): commands start the daemon without it` or `broken (launchd, ): is gone; run simlock daemon install` (`, are gone` for two). Never starts a daemon. Exits 1 when a daemon answers but refuses the connection, with no `Service:` line. | +| `status` | Print the daemon's status, or `Daemon stopped` when none is running, then one `Service:` line: `not installed`, `installed (launchd, )`, `not loaded (launchd, ): commands start the daemon without it` or `broken (launchd, ): is gone; run simlock daemon install` (`, are gone` for two). The manager is `launchd` on macOS, `systemd` on Linux and `task-scheduler` on Windows, where not loaded means the user has no desktop session or the task is disabled. Never starts a daemon. Exits 1 when a daemon answers but refuses the connection, with no `Service:` line. | | `logs` | Print the last 100 lines of `daemon.log`. | -| `install` | macOS and Linux only. Stop a running daemon (leases are kept), add a LaunchAgent (macOS) or a systemd user unit at `$XDG_CONFIG_HOME/systemd/user/.service`, else `~/.config/systemd/user/.service` (Linux) for this role and start the daemon through it. Prints `Service installed: (launchd)` or `(systemd)`, `Daemon running` and a hint: `To start after a reboot, turn on automatic login for this user.` on macOS, `To start after a reboot without logging in, run: loginctl enable-linger ` on Linux. Without linger the last logout stops the user's systemd, the daemon and its emulators with it. On another platform it is a usage error: `daemon install is supported on macOS and Linux only`. | -| `uninstall` | Stop a running daemon, unload the LaunchAgent or systemd unit and delete its file. Prints `Service removed: (launchd)`, or `Service not installed: ` when there is none (exit 0). | +| `install` | macOS, Linux and Windows only. Stop a running daemon (leases are kept), add a LaunchAgent (macOS), a systemd user unit at `$XDG_CONFIG_HOME/systemd/user/.service`, else `~/.config/systemd/user/.service` (Linux) or a per-user logon task in Task Scheduler (Windows) for this role and start the daemon through it. Prints `Service installed: (launchd)`, `(systemd)` or `(task-scheduler)`, `Daemon running` and a hint: `To start after a reboot, turn on automatic login for this user.` on macOS and Windows, `To start after a reboot without logging in, run: loginctl enable-linger ` on Linux. Without linger the last logout stops the user's systemd, the daemon and its emulators with it. On another platform it is a usage error: `daemon install is supported on macOS, Linux and Windows only`. | +| `uninstall` | Stop a running daemon, unload the LaunchAgent or systemd unit and delete its file, or delete the Windows task. Prints `Service removed: (launchd)`, or `Service not installed: ` when there is none (exit 0). | | Flag | Meaning | Default | | --- | --- | --- | diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index f8816ed03..a407a2872 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -185,7 +185,7 @@ The CLI and the HTTP API each add a few codes of their own: | `USAGE` | CLI | exit 2 | A bad flag, a missing argument or an unknown command. Also a `config.json` the CLI rejects before it starts the daemon, and a `SIMLOCK_HOME` too long for the daemon's socket path. | Run the command with `--help`. | | `SETUP_REFUSED` | CLI | exit 2 | `simlock setup` found a file or a symlink where its `simlock` skill directory goes. Nothing was written. | Move it aside and run `setup` again. | | `SETUP_MCP_FAILED` | CLI | exit 1 | `simlock setup` wrote the skills, but a tool's `mcp add` command failed or ran longer than 30 seconds. The message names each tool and the reason. | Run the tool's `mcp add` command by hand, as the message and [Connect your agent](/simlock/docs/getting-started/connect-your-agent) show. | -| `SERVICE_FAILED` | CLI | exit 1 | `simlock daemon install`, `uninstall` or `daemon stop`, or a start through the service, could not finish: the service manager (launchd or systemd) failed or did not answer in time, or the old daemon did not stop. The message names the command and its first error line. | Fix what the message names and run the command again. | +| `SERVICE_FAILED` | CLI | exit 1 | `simlock daemon install`, `uninstall` or `daemon stop`, or a start through the service, could not finish: the service manager (launchd, systemd or `schtasks` on Windows) failed or did not answer in time, or the old daemon did not stop. The message names the command and its first error line. | Fix what the message names and run the command again. | | `UNSUPPORTED_MEDIA_TYPE` | HTTP | 415 | A request with a JSON body did not send `Content-Type: application/json`. | Send the header `Content-Type: application/json`. | | `UNKNOWN_LEASE_REQUEST` | HTTP | 404 | No lease request has this ID. | Check the ID the create call returned. | | `REQUEST_NOT_CANCELLABLE` | HTTP | 409 | The lease request was already granted, or device work for it is under way. When it was granted, the answer carries the `leaseId`. | Release the lease in place of cancelling the request. | diff --git a/website/src/content/docs/docs/using-devices/errors.mdx b/website/src/content/docs/docs/using-devices/errors.mdx index 660f66279..2269ed218 100644 --- a/website/src/content/docs/docs/using-devices/errors.mdx +++ b/website/src/content/docs/docs/using-devices/errors.mdx @@ -83,7 +83,7 @@ In a script, check the exit code or `code`, never the message: the message is fo | `DAEMON_STARTUP_FAILED` | 1 | The CLI started the daemon and it didn't come up. The message says why. | Fix what the message names, then run the command again. `simlock daemon logs` shows the daemon's own log. | | `DAEMON_CONNECTION_LOST` | 1 | The daemon stopped or crashed while the command was talking to it. A held lease is not released. | Run the command again; the daemon starts on demand. Renew a held lease with `simlock lease renew `. | | `DAEMON_STOPPING` | 1 | The daemon is shutting down. | Wait a moment and run the command again. | -| `SERVICE_FAILED` | 1 | `simlock daemon install`, `uninstall`, `daemon stop` or a start through the service could not finish: `launchctl` failed or took longer than 10 seconds, or the old daemon didn't stop within 300 seconds. The message names the command and its first error line. | Fix what the message names and run the command again. A failed load removes the service file. | +| `SERVICE_FAILED` | 1 | `simlock daemon install`, `uninstall`, `daemon stop` or a start through the service could not finish: `launchctl`, `systemctl` or `schtasks` failed or took longer than 10 seconds, or the old daemon didn't stop within 300 seconds. The message names the command and its first error line. | Fix what the message names and run the command again. A failed load removes the service file. | | `GATEWAY_NOT_PRESENT` | 2 | You passed `--gateway`, but no gateway has run on this machine. | Drop `--gateway`, or start one with `simlock --gateway daemon start`. | | `PROTOCOL_VERSION_UNSUPPORTED` | 1 | The CLI and the running daemon are different versions that can't work together. | After an upgrade, restart the daemon: `simlock daemon stop`, then any command. | diff --git a/website/src/content/docs/docs/worker/running-the-daemon.mdx b/website/src/content/docs/docs/worker/running-the-daemon.mdx index fd0e2c780..88ed14869 100644 --- a/website/src/content/docs/docs/worker/running-the-daemon.mdx +++ b/website/src/content/docs/docs/worker/running-the-daemon.mdx @@ -49,7 +49,7 @@ The command returns once the daemon has exited. That can take a while, because t ## Start it at login -On macOS and Linux, install the daemon as a service: +On macOS, Linux and Windows, install the daemon as a service: ```sh simlock daemon install @@ -71,11 +71,20 @@ Daemon running To start after a reboot without logging in, run: loginctl enable-linger ``` +On Windows: + +```text +Service installed: com.callstack.simlock.worker (task-scheduler) +Daemon running +To start after a reboot, turn on automatic login for this user. +``` + The service starts the daemon when you log in, and starts it again 10 seconds after it crashes. If a daemon was already running, the command first stops it; leases are kept. Before you rely on it, know what it needs: - **macOS:** the service runs only while your user is logged in at the screen. For the machine to come back after a reboot, turn on automatic login for this user. +- **Windows:** the service is a Task Scheduler task that starts when you log in, and it runs only while you are logged in at the screen. For the machine to come back after a reboot, turn on automatic login for this user. If nobody is logged in at the screen, `daemon install` still succeeds and the daemon is started without the service, with a notice; it stops with an SSH session. Ending the task in Task Scheduler does not stop the daemon: use `simlock daemon stop`. The task runs a small Simlock program that starts the daemon again 10 seconds after a failure; it shows no window, and `daemon.log` holds a line for each restart. - **Linux:** without linger, logging out of your last session stops the daemon and its emulators. Run `loginctl enable-linger ` to keep them running. Simlock does not turn linger on for you. - **Environment:** the service remembers `SIMLOCK_HOME`, `PATH`, `JAVA_HOME`, `DEVELOPER_DIR` and the Android SDK variables (such as `ANDROID_HOME`) as they are when you run `daemon install`. diff --git a/website/src/content/docs/docs/worker/troubleshooting.mdx b/website/src/content/docs/docs/worker/troubleshooting.mdx index 8e6aae45d..33da38111 100644 --- a/website/src/content/docs/docs/worker/troubleshooting.mdx +++ b/website/src/content/docs/docs/worker/troubleshooting.mdx @@ -50,7 +50,7 @@ Service broken: com.callstack.simlock.worker (launchd) names missing /Users/dana | Finding | What it means | What `--fix` does | | --- | --- | --- | | `prerequisite-missing` | A tool a platform needs is missing, such as Xcode, its licence, the Android SDK, the emulator, `adb` or a JDK. The message names it and the remedy says how to install it. | Nothing. Install it yourself, then restart the daemon. | -| `service-broken` | The worker's login service names a Node or `main.js` that is gone, so the daemon will not start at login. The finding carries `manager`, `name`, the `missing` paths and the remedy. | Nothing. Run `simlock daemon install` again. | +| `service-broken` | The worker's login service names a Node or `main.js` that is gone (on Windows, the Node or supervisor path of the task), so the daemon will not start at login. The finding carries `manager`, `name`, the `missing` paths and the remedy. | Nothing. Run `simlock daemon install` again. | | `registry-device-missing` | Simlock has a record of a device that no longer exists, for example one you deleted with `simctl delete`. | Marks the device deleted, unless it is leased. | | `foreign-state-change` | A device was booted or shut down outside Simlock. | Updates the record to match, unless the device is leased. | | `expired-live-lease` | A lease ran out but its device is still marked leased. | Ends the lease. | diff --git a/website/src/content/docs/docs/worker/windows.mdx b/website/src/content/docs/docs/worker/windows.mdx index 433bfc9bc..cc6035630 100644 --- a/website/src/content/docs/docs/worker/windows.mdx +++ b/website/src/content/docs/docs/worker/windows.mdx @@ -22,11 +22,11 @@ Every command here is for PowerShell. The page was written for Windows 11 and Wi | Tunnels | `simlock tunnel` with `emulator adb`, `forward` and `reverse`. | | agent-device | Through the worker's local profile. | | `simlock setup` and `simlock mcp` | The skill file and the MCP server. | +| Start at login | `simlock daemon install` registers a Task Scheduler task that starts at login and restarts the daemon after a crash. See [Start it at login](/simlock/docs/worker/running-the-daemon#start-it-at-login). | | Does not work | What you see | | --- | --- | | iOS simulators and iPhones | A lease for iOS fails with `NO_DRIVER` (exit 12). | -| Start at login | `simlock daemon install` is a usage error: `daemon install is supported on macOS and Linux only`. See [Run the daemon](/simlock/docs/worker/running-the-daemon). Start the daemon from a terminal. | | Not checked yet | | | --- | --- | @@ -195,8 +195,8 @@ Read the log with `simlock daemon logs` and run the command it prints. Run Simlo ## How the daemon lives -The first command that needs the daemon starts it, and it keeps running after the terminal that started it closes. A Windows machine has no start at login yet: after a restart, the next `simlock` command starts the daemon again. +The first command that needs the daemon starts it, and it keeps running after the terminal that started it closes. Run `simlock daemon install` to start it at login and again 10 seconds after a crash: see [Start it at login](/simlock/docs/worker/running-the-daemon#start-it-at-login). -A daemon started in an SSH session stops when that session ends. To run a worker on a machine you reach over SSH, start the daemon from a session that stays open, such as a remote desktop session. +Without the service, a daemon started in an SSH session stops when that session ends. With the service installed and the user logged in at the screen, a command over SSH starts the daemon in the desktop session, and it outlives the SSH session. If nobody is logged in at the screen, the command starts the daemon without the service, and it still stops with the SSH session. A machine runs one worker per user. A second one, started from another `SIMLOCK_HOME`, refuses with `another Simlock worker runs for this user`: stop the first one. From 93974d771e12ac2765159d5fd9c433a36eb9e189 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:19:42 +0100 Subject: [PATCH 16/25] refactor(daemon): split the Windows supervisor's argument check and the task's path check (#1698) --- src/daemon/service-main.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/daemon/service-main.ts b/src/daemon/service-main.ts index 4d1b7690f..8e0d23297 100644 --- a/src/daemon/service-main.ts +++ b/src/daemon/service-main.ts @@ -55,16 +55,16 @@ function decodeEnvironment(text: string): Record | undefined { /** why: the task's own arguments are the only input, in one fixed order; anything else is a stale or hand-edited task and starts nothing. */ function parseArguments(argv: readonly string[]): SupervisorArguments | undefined { const gateway = argv[0] === "--gateway"; - const [taskFlag, task, idFlag, installId, environmentFlag, environmentText, ...extra] = gateway - ? argv.slice(1) - : argv; - if (taskFlag !== "--task" || idFlag !== "--install-id" || environmentFlag !== "--environment") { - return undefined; - } - if (extra.length > 0 || task === undefined || installId === undefined) return undefined; - if (!WORD.test(task) || !WORD.test(installId) || environmentText === undefined) return undefined; - const environment = decodeEnvironment(environmentText); - return environment === undefined ? undefined : { gateway, task, installId, environment }; + const rest = gateway ? argv.slice(1) : argv; + const flagged = ["--task", "--install-id", "--environment"].every( + (flag, index) => rest[index * 2] === flag, + ); + const [task, installId, environmentText] = [rest[1], rest[3], rest[5]]; + if (!flagged || rest.length !== 6) return undefined; + if (!WORD.test(task ?? "") || !WORD.test(installId ?? "")) return undefined; + const environment = decodeEnvironment(environmentText ?? ""); + if (environment === undefined) return undefined; + return { gateway, task: task as string, installId: installId as string, environment }; } function describeExit(result: ProcessResult): string { From 6c8788b7608432661da34945c95a98a0b51823b8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:20:03 +0100 Subject: [PATCH 17/25] refactor(ports): split the Windows task's path check from its state (#1698) --- src/ports/service-manager.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index 355dd7bc2..d44ae3278 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -505,8 +505,19 @@ export class TaskSchedulerServiceManager implements ServiceManager { } } + /** why: a task whose arguments do not hold the two paths is as broken as one whose paths are gone; its own path stands for them, as systemd's unit path does. */ + private async missingPaths(xml: string, definition: ServiceDefinition): Promise { + const args = xmlUnescape(/([\s\S]*?)<\/Arguments>/.exec(xml)?.[1] ?? ""); + const saved = /--headless\s+"([^"]*)"\s+"([^"]*)"/.exec(args); + if (saved === null) return [definition.path]; + const missing: string[] = []; + for (const path of saved.slice(1, 3)) { + if (!(await this.options.filesystem.exists(path))) missing.push(path); + } + return missing; + } + async state(definition: ServiceDefinition): Promise { - const { filesystem } = this.options; // why: plain schtasks writes the OEM code page, which garbles a non-ASCII path. const queried = await this.run("cmd.exe", [ "/d", @@ -514,14 +525,7 @@ export class TaskSchedulerServiceManager implements ServiceManager { `chcp 65001 >nul && schtasks /query /tn ${definition.name} /xml`, ]); if (queried.code !== 0) return { state: "not-installed" }; - const args = xmlUnescape(/([\s\S]*?)<\/Arguments>/.exec(queried.stdout)?.[1] ?? ""); - const saved = /--headless\s+"([^"]*)"\s+"([^"]*)"/.exec(args); - if (saved === null) - return { state: "broken", path: definition.path, missing: [definition.path] }; - const missing: string[] = []; - for (const path of [saved[1] as string, saved[2] as string]) { - if (!(await filesystem.exists(path))) missing.push(path); - } + const missing = await this.missingPaths(queried.stdout, definition); if (missing.length > 0) return { state: "broken", path: definition.path, missing }; const disabled = /[\s\S]*?\s*false\s*<\/Enabled>/i.test(queried.stdout); const loaded = !disabled && (await this.hasDesktopSession()); From d11151dbed10e587c6a660a7304ad761c788627b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:20:23 +0100 Subject: [PATCH 18/25] refactor(daemon): fewer branches in the supervisor's argument check (#1698) --- src/daemon/service-main.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/daemon/service-main.ts b/src/daemon/service-main.ts index 8e0d23297..cd4b0f192 100644 --- a/src/daemon/service-main.ts +++ b/src/daemon/service-main.ts @@ -56,15 +56,14 @@ function decodeEnvironment(text: string): Record | undefined { function parseArguments(argv: readonly string[]): SupervisorArguments | undefined { const gateway = argv[0] === "--gateway"; const rest = gateway ? argv.slice(1) : argv; - const flagged = ["--task", "--install-id", "--environment"].every( - (flag, index) => rest[index * 2] === flag, - ); - const [task, installId, environmentText] = [rest[1], rest[3], rest[5]]; - if (!flagged || rest.length !== 6) return undefined; - if (!WORD.test(task ?? "") || !WORD.test(installId ?? "")) return undefined; - const environment = decodeEnvironment(environmentText ?? ""); - if (environment === undefined) return undefined; - return { gateway, task: task as string, installId: installId as string, environment }; + const [, task = "", , installId = "", , environmentText = ""] = rest; + const shaped = + rest.length === 6 && + ["--task", "--install-id", "--environment"].every((flag, index) => rest[index * 2] === flag) && + WORD.test(task) && + WORD.test(installId); + const environment = shaped ? decodeEnvironment(environmentText) : undefined; + return environment === undefined ? undefined : { gateway, task, installId, environment }; } function describeExit(result: ProcessResult): string { From 806bd17f9bc12a936e87123ba781eb7c7d8bb8f1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:20:46 +0100 Subject: [PATCH 19/25] docs(daemon): the manual names the Windows supervisor (#1698) --- src/daemon/AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 504873c5f..dc0c8775e 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -25,7 +25,7 @@ Start and stop: - `daemon.stop` releases nothing; leases persist with their deadlines. - `dispose` stops the event history after the drivers are disposed, and closes `state.db` last. - A history file that fails costs only history. A start the history refuses (a newer stored projection version, a failed migration) stops the daemon (`history-refused`). -- `service-main.ts` is not the daemon: a Windows logon task runs it (ADR 0086). It starts `main.js` as a child it waits on, restarts it 10 s after a non-zero exit while its task still carries its install id, and imports only `ports/`. +- The Windows supervisor (`service-main.ts`, ADR 0086) starts the daemon as a child and imports only `ports/`; it restarts it after a non-zero exit while its task carries its install id. - A daemon works in its own role's data directory. Its one look outside is the update's `socketHeld` probe of the other role's socket (`composition-support.ts`). Connections: From d1646acad895438c6ac93aa4e542e54b5081a9d7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:30:41 +0100 Subject: [PATCH 20/25] test: the Windows supervisor's delay, ids and environment, the task's SID and ampersand paths, and UTF-16 bytes on disk are each pinned (#1698) Protocol-bump: none (tests and a docs sentence only) --- src/cli/index-daemon-service.test.ts | 24 ++++++++++++++++++ src/daemon/service-main.test.ts | 25 ++++++++++++++++--- src/ports/filesystem.test.ts | 16 +++++++++++- .../docs/docs/worker/running-the-daemon.mdx | 2 +- 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index afab70ce4..763e64a41 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -996,6 +996,11 @@ describe("CLI: daemon service on Windows (#1698)", () => { whoami: { code: 1, stdout: "", stderr: "ERROR: no user" }, message: "whoami /user /fo csv /nh failed: ERROR: no user", }, + { + label: "whoami prints no SID", + whoami: { code: 0, stdout: '"desktop\\me"\r\n', stderr: "" }, + message: "whoami /user printed no SID", + }, { label: "a call past 10 s", create: { code: null, stdout: "", stderr: "" }, @@ -1177,6 +1182,25 @@ describe("CLI: daemon service on Windows (#1698)", () => { script: [{ match: query, result: ok(taskXml({ arguments: "--headless node" })) }], line: `Service: broken (task-scheduler, ${name}): \\${name} is gone; run simlock daemon install`, }, + { + label: "whoami prints no account name", + files: present, + script: [ + { match: query, result: ok(taskXml({})) }, + { match: whoami, result: ok("\r\n") }, + ], + line: `Service: not loaded (task-scheduler, ${name}): commands start the daemon without it`, + }, + { + label: "a path with an ampersand is read as the task XML escapes it", + files: [nodePath, supervisor, "/opt/R&D/node.exe"], + script: [ + { match: query, result: ok(taskXml({ node: "/opt/R&D/node.exe" })) }, + ...session, + { match: tasklist, result: ok('"sihost.exe","4242","Console","1","20,000 K"\r\n') }, + ], + line: `Service: installed (task-scheduler, ${name})`, + }, { label: "a path with a non-ASCII character is read whole", files: [nodePath, "/opt/simlock-ü/dist/daemon/service-main.js"], diff --git a/src/daemon/service-main.test.ts b/src/daemon/service-main.test.ts index 620ee7c29..987e09932 100644 --- a/src/daemon/service-main.test.ts +++ b/src/daemon/service-main.test.ts @@ -19,12 +19,13 @@ const home = "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/h/.simlock"; const nodePath = "/opt/node/node.exe"; const mainPath = "/opt/simlock/dist/daemon/main.js"; const encode = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString("base64url"); -const goodArgv = (...gateway: string[]): string[] => [ +const goodArgv = (...gateway: string[]): string[] => argvFor(installId, ...gateway); +const argvFor = (id: string, ...gateway: string[]): string[] => [ ...gateway, "--task", name, "--install-id", - installId, + id, "--environment", encode({ SIMLOCK_HOME: home, PATH: "saved" }), ]; @@ -103,9 +104,10 @@ describe("the Windows supervisor (#1698)", () => { }).then((code) => { exit = code; }); - for (let step = 0; step < (options.steps ?? 12) && exit === undefined; step += 1) { + // why: one second a step, so a restart delay longer or shorter than 10 s lands on another start time. + for (let step = 0; step < (options.steps ?? 120) && exit === undefined; step += 1) { await settle(); - clock.advance(10_000); + clock.advance(1_000); } await settle(); const lines = sink.records.map((record) => `${record.level}: ${record.message}`); @@ -165,6 +167,7 @@ describe("the Windows supervisor (#1698)", () => { const stops = [ { label: "the task is gone", stdout: undefined, code: 1 }, { label: "another install id", stdout: taskXml("another-id"), code: 0 }, + { label: "an install id that starts with ours", stdout: taskXml(`${installId}-2`), code: 0 }, ]; for (const stop of stops) { const stopped = await supervise({ @@ -199,6 +202,16 @@ describe("the Windows supervisor (#1698)", () => { expect(restarted.startedAt, read.label).toEqual([0, 10_000]); } + const dotted = await supervise({ + argv: argvFor("a.b"), + script: (daemon) => [ + daemon(result(1)), + { match: query, result: { ...result(0), stdout: taskXml("axb") } }, + ], + }); + expect(dotted.exit, "a dot in our id is not a wildcard").toBe(0); + expect(dotted.runner.calls).toHaveLength(2); + const failedStart = await supervise({ argv: goodArgv(), failSpawns: (command, attempt) => command === nodePath && attempt === 0, @@ -226,6 +239,10 @@ describe("the Windows supervisor (#1698)", () => { [...goodArgv(), "extra"], ["--install-id", installId, "--task", name, "--environment", encode({})], goodArgv().slice(0, -1).concat("!!!"), + goodArgv().slice(0, -1).concat("e30="), + goodArgv().slice(0, -1).concat(encode(null)), + ["--task", "a b", ...goodArgv().slice(2)], + argvFor("a b"), goodArgv() .slice(0, -1) .concat(encode(["a"])), diff --git a/src/ports/filesystem.test.ts b/src/ports/filesystem.test.ts index 4d2e6e6c9..af916822e 100644 --- a/src/ports/filesystem.test.ts +++ b/src/ports/filesystem.test.ts @@ -1,4 +1,4 @@ -import { lstat, stat, symlink, utimes, writeFile } from "node:fs/promises"; +import { lstat, readFile, stat, symlink, utimes, writeFile } from "node:fs/promises"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -44,6 +44,20 @@ afterEach(async () => { await new NodeFilesystem().rm(temporaryDirectory); }); +describe("NodeFilesystem.writeFileAtomic encoding", () => { + it("writes UTF-16 little-endian bytes when asked and UTF-8 bytes otherwise", async () => { + const filesystem = new NodeFilesystem(); + await filesystem.mkdirp(temporaryDirectory); + const wide = `${temporaryDirectory}/task.xml`; + const narrow = `${temporaryDirectory}/plain.txt`; + await filesystem.writeFileAtomic(wide, "\uFEFFé", { encoding: "utf16le" }); + await filesystem.writeFileAtomic(narrow, "é"); + + expect([...(await readFile(wide))]).toEqual([0xff, 0xfe, 0xe9, 0x00]); + expect([...(await readFile(narrow))]).toEqual([0xc3, 0xa9]); + }); +}); + describe.each(implementations)("Filesystem contract: $name", ({ create, link }) => { it("atomically writes and overwrites a complete file", async () => { const filesystem = create(); diff --git a/website/src/content/docs/docs/worker/running-the-daemon.mdx b/website/src/content/docs/docs/worker/running-the-daemon.mdx index 88ed14869..7d75c7eba 100644 --- a/website/src/content/docs/docs/worker/running-the-daemon.mdx +++ b/website/src/content/docs/docs/worker/running-the-daemon.mdx @@ -98,7 +98,7 @@ To remove the service: simlock daemon uninstall ``` -This stops the daemon and removes the service. On Windows, `daemon install` and `daemon uninstall` are not available. +This stops the daemon and removes the service. ### When the service cannot run From 86a966217eec7a1f7a721c5aac68337ea5c6fb67 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 14:54:00 +0100 Subject: [PATCH 21/25] fix(daemon): the supervisor finds its install id by plain search, not a pattern built from an argument (#1698) --- src/daemon/service-main.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/daemon/service-main.ts b/src/daemon/service-main.ts index cd4b0f192..01fa73d57 100644 --- a/src/daemon/service-main.ts +++ b/src/daemon/service-main.ts @@ -98,9 +98,17 @@ export async function runSupervisor(dependencies: SupervisorDependencies): Promi } if (read.code === null) return true; if (read.code !== 0) return false; - return new RegExp(`--install-id ${parsed.installId.replaceAll(".", "\\.")}(?![\\w.-])`).test( - read.stdout, - ); + // why: a plain search, not a pattern built from the argument; the id must end at a character no id contains. + const needle = `--install-id ${parsed.installId}`; + for ( + let at = read.stdout.indexOf(needle); + at !== -1; + at = read.stdout.indexOf(needle, at + 1) + ) { + const next = read.stdout.charAt(at + needle.length); + if (!/[\w.-]/.test(next)) return true; + } + return false; }; for (;;) { From 6381ef50101bb18f7d59c07d1f2a89b3d689c69a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 15:02:45 +0100 Subject: [PATCH 22/25] fix(daemon): the Windows desktop-session check reads the account as UTF-8; a status line, a comment and the manual say what is true (#1698) --- src/cli/index-daemon-service.test.ts | 39 +++++++++++++++---- src/daemon/AGENTS.md | 2 +- src/daemon/service-main.ts | 2 +- src/ports/daemon-launcher.test.ts | 5 ++- src/ports/service-manager.ts | 7 +++- .../docs/docs/worker/running-the-daemon.mdx | 4 +- 6 files changed, 46 insertions(+), 13 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 763e64a41..7da8009c4 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -907,7 +907,7 @@ describe("CLI: daemon service on Windows (#1698)", () => { ); } - it("an operator runs daemon install on Windows: the user's SID goes into a UTF-16 logon task that runs the supervisor hidden with the saved variables, the daemon answers, and install prints the name, Daemon running and the login hint", async () => { + it("an operator runs daemon install on Windows: the user's SID goes into a UTF-16 logon task that runs the supervisor hidden with the saved variables, the daemon answers, and install prints the name, Daemon running and the login hint; --gateway names the gateway task and passes --gateway to the supervisor, and --json answers the task-scheduler manager", async () => { const { exitCode, output, runner, filesystem, name, xmlPath, written } = await installOnWindows( { argv: ["daemon", "install"] }, ); @@ -955,9 +955,7 @@ describe("CLI: daemon service on Windows (#1698)", () => { PATH: "C:\\bin", }); expect(await filesystem.exists(xmlPath), "the XML file is deleted after create").toBe(false); - }); - it("daemon install --gateway on Windows names the gateway task and passes --gateway to the supervisor, and --json answers the task-scheduler manager", async () => { const gateway = await installOnWindows({ argv: ["--gateway", "daemon", "install"], role: "gateway", @@ -966,9 +964,9 @@ describe("CLI: daemon service on Windows (#1698)", () => { expect(gateway.output.stdout.split("\n")[0]).toBe( "Service installed: com.callstack.simlock.gateway (task-scheduler)", ); - const parts = supervisorArguments(gateway.written?.text ?? ""); - expect(parts?.[3], "the supervisor gets --gateway").toBe(" --gateway"); - expect(parts?.[4]).toBe("com.callstack.simlock.gateway"); + const gatewayParts = supervisorArguments(gateway.written?.text ?? ""); + expect(gatewayParts?.[3], "the supervisor gets --gateway").toBe(" --gateway"); + expect(gatewayParts?.[4]).toBe("com.callstack.simlock.gateway"); const json = await installOnWindows({ argv: ["daemon", "install", "--json"] }); expect(JSON.parse(json.output.stdout)).toEqual({ @@ -1091,7 +1089,10 @@ describe("CLI: daemon service on Windows (#1698)", () => { command: "cmd.exe", args: ["/d", "/c", `chcp 65001 >nul && schtasks /query /tn ${name} /xml`], }; - const whoami = { command: "whoami", args: ["/user", "/fo", "csv", "/nh"] }; + const whoami = { + command: "cmd.exe", + args: ["/d", "/c", "chcp 65001 >nul && whoami /user /fo csv /nh"], + }; const tasklist = { command: "tasklist", args: ["/fi", "USERNAME eq desktop\\me", "/fi", "SESSION ne 0", "/fo", "csv", "/nh"], @@ -1191,6 +1192,30 @@ describe("CLI: daemon service on Windows (#1698)", () => { ], line: `Service: not loaded (task-scheduler, ${name}): commands start the daemon without it`, }, + { + label: "a non-ASCII account name is read as UTF-8 and filtered by whole", + files: present, + script: [ + { match: query, result: ok(taskXml({})) }, + { match: whoami, result: ok('"desktop\\józef","S-1-5-21-1"\r\n') }, + { + match: { + command: "tasklist", + args: [ + "/fi", + "USERNAME eq desktop\\józef", + "/fi", + "SESSION ne 0", + "/fo", + "csv", + "/nh", + ], + }, + result: ok('"sihost.exe","4242","Console","1","20,000 K"\r\n'), + }, + ], + line: `Service: installed (task-scheduler, ${name})`, + }, { label: "a path with an ampersand is read as the task XML escapes it", files: [nodePath, supervisor, "/opt/R&D/node.exe"], diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index dc0c8775e..6bb75feaf 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -25,7 +25,7 @@ Start and stop: - `daemon.stop` releases nothing; leases persist with their deadlines. - `dispose` stops the event history after the drivers are disposed, and closes `state.db` last. - A history file that fails costs only history. A start the history refuses (a newer stored projection version, a failed migration) stops the daemon (`history-refused`). -- The Windows supervisor (`service-main.ts`, ADR 0086) starts the daemon as a child and imports only `ports/`; it restarts it after a non-zero exit while its task carries its install id. +- The Windows supervisor (`service-main.ts`, ADR 0086) imports only `ports/`. - A daemon works in its own role's data directory. Its one look outside is the update's `socketHeld` probe of the other role's socket (`composition-support.ts`). Connections: diff --git a/src/daemon/service-main.ts b/src/daemon/service-main.ts index 01fa73d57..c922b048d 100644 --- a/src/daemon/service-main.ts +++ b/src/daemon/service-main.ts @@ -114,7 +114,7 @@ export async function runSupervisor(dependencies: SupervisorDependencies): Promi for (;;) { let outcome: string; try { - // why: no timeoutMs: the daemon runs until it exits, the one wait in Simlock with no limit. + // why: no timeoutMs: the daemon runs until it exits, so this wait has no limit by design. const result = await runner .spawn( dependencies.nodePath, diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 7ffe65f9e..241584525 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -427,7 +427,10 @@ describe("launcherFor with the Windows task (#1698)", () => { const taskXml = `true--headless "${nodePath}" "${supervisor}" --task ${name}`; const session = [ { - match: { command: "whoami", args: ["/user", "/fo", "csv", "/nh"] }, + match: { + command: "cmd.exe", + args: ["/d", "/c", "chcp 65001 >nul && whoami /user /fo csv /nh"], + }, result: ok('"desktop\\me","S-1-5-21-1"\r\n'), }, { diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index d44ae3278..5b5c354ad 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -486,7 +486,12 @@ export class TaskSchedulerServiceManager implements ServiceManager { private async hasDesktopSession(): Promise { try { - const user = await this.checked("whoami", WHOAMI_ARGS); + // why: plain whoami writes the OEM code page, which garbles a non-ASCII account name and makes the tasklist filter match nothing. + const user = await this.checked("cmd.exe", [ + "/d", + "/c", + `chcp 65001 >nul && whoami ${WHOAMI_ARGS.join(" ")}`, + ]); const account = /^"([^"]*)"/.exec(user.stdout.trim())?.[1]; if (account === undefined) return false; const listed = await this.checked("tasklist", [ diff --git a/website/src/content/docs/docs/worker/running-the-daemon.mdx b/website/src/content/docs/docs/worker/running-the-daemon.mdx index 7d75c7eba..da11671d5 100644 --- a/website/src/content/docs/docs/worker/running-the-daemon.mdx +++ b/website/src/content/docs/docs/worker/running-the-daemon.mdx @@ -126,13 +126,13 @@ Daemon: running (worker) `starting` means the daemon is still reading the machine's devices. Devices, leases and capacity appear once it finishes. [Monitoring](/simlock/docs/worker/monitoring) explains the rest of the report. -On macOS and Linux the last line shows the service: +The last line shows the service: | Line | What it means | | --- | --- | | `Service: not installed` | You have not run `simlock daemon install`. | | `Service: installed (launchd, com.callstack.simlock.worker)` | The service is set up and working. | -| `Service: not loaded (...)` | Nobody is logged in at the screen, or there is no Linux user session. Commands start the daemon without the service. | +| `Service: not loaded (...)` | Nobody is logged in at the screen, there is no Linux user session, or on Windows the task is disabled. Commands start the daemon without the service. | | `Service: broken (...): is gone; run simlock daemon install` | The Node or Simlock the service starts has moved, for example after an nvm or Homebrew upgrade. Run `simlock daemon install` again. | Add `--json` for a machine-readable answer, such as `{"status":"stopped"}`. From 5856c95eed5b1dabd0eb09b1d96deb7b5471f85e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 15:03:20 +0100 Subject: [PATCH 23/25] test: the Windows install test's gateway and --json checks sit in a helper (#1698) --- src/cli/index-daemon-service.test.ts | 49 +++++++++++++++------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/cli/index-daemon-service.test.ts b/src/cli/index-daemon-service.test.ts index 7da8009c4..68d33c1f5 100644 --- a/src/cli/index-daemon-service.test.ts +++ b/src/cli/index-daemon-service.test.ts @@ -907,6 +907,31 @@ describe("CLI: daemon service on Windows (#1698)", () => { ); } + async function expectGatewayAndJsonInstalls(): Promise { + const gateway = await installOnWindows({ + argv: ["--gateway", "daemon", "install"], + role: "gateway", + }); + expect(gateway.output.stderr).toBe(""); + expect(gateway.output.stdout.split("\n")[0]).toBe( + "Service installed: com.callstack.simlock.gateway (task-scheduler)", + ); + const gatewayParts = supervisorArguments(gateway.written?.text ?? ""); + expect(gatewayParts?.[3], "the supervisor gets --gateway").toBe(" --gateway"); + expect(gatewayParts?.[4]).toBe("com.callstack.simlock.gateway"); + + const json = await installOnWindows({ argv: ["daemon", "install", "--json"] }); + expect(JSON.parse(json.output.stdout)).toEqual({ + status: "installed", + service: { + state: "installed", + manager: "task-scheduler", + name: "com.callstack.simlock.worker", + path: "\\com.callstack.simlock.worker", + }, + }); + } + it("an operator runs daemon install on Windows: the user's SID goes into a UTF-16 logon task that runs the supervisor hidden with the saved variables, the daemon answers, and install prints the name, Daemon running and the login hint; --gateway names the gateway task and passes --gateway to the supervisor, and --json answers the task-scheduler manager", async () => { const { exitCode, output, runner, filesystem, name, xmlPath, written } = await installOnWindows( { argv: ["daemon", "install"] }, @@ -955,29 +980,7 @@ describe("CLI: daemon service on Windows (#1698)", () => { PATH: "C:\\bin", }); expect(await filesystem.exists(xmlPath), "the XML file is deleted after create").toBe(false); - - const gateway = await installOnWindows({ - argv: ["--gateway", "daemon", "install"], - role: "gateway", - }); - expect(gateway.output.stderr).toBe(""); - expect(gateway.output.stdout.split("\n")[0]).toBe( - "Service installed: com.callstack.simlock.gateway (task-scheduler)", - ); - const gatewayParts = supervisorArguments(gateway.written?.text ?? ""); - expect(gatewayParts?.[3], "the supervisor gets --gateway").toBe(" --gateway"); - expect(gatewayParts?.[4]).toBe("com.callstack.simlock.gateway"); - - const json = await installOnWindows({ argv: ["daemon", "install", "--json"] }); - expect(JSON.parse(json.output.stdout)).toEqual({ - status: "installed", - service: { - state: "installed", - manager: "task-scheduler", - name: "com.callstack.simlock.worker", - path: "\\com.callstack.simlock.worker", - }, - }); + await expectGatewayAndJsonInstalls(); }); it("an install whose registration fails is SERVICE_FAILED with the command's first stderr line, and leaves no task XML", async () => { From 0707899207165608bf377080b1ec0f92ae5c17d0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 11:36:13 +0100 Subject: [PATCH 24/25] docs(adr): 0086 is Accepted (#1698) --- ...on-service-is-a-logon-task-that-runs-a-simlock-supervisor.md | 2 +- docs/internal/adr/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/internal/adr/0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md b/docs/internal/adr/0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md index 74c4142a4..9a0400926 100644 --- a/docs/internal/adr/0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md +++ b/docs/internal/adr/0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md @@ -1,6 +1,6 @@ # 0086. On Windows the daemon service is a logon task that runs a Simlock supervisor -- **Status:** Accepted — not yet implemented +- **Status:** Accepted - **Date:** 2026-11-18 - **Issue:** [#1691](https://github.com/callstackincubator/simlock/issues/1691) (request [#1069](https://github.com/callstackincubator/simlock/issues/1069)) - **Narrows:** [ADR 0041](0041-the-daemon-can-run-under-the-users-service-manager.md) diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index 4b4c4e90d..8871d2214 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -120,4 +120,4 @@ the status is stale. | [0083](0083-a-worker-may-turn-single-slim-services-on-or-off-beside-its-categories.md) | A worker may turn single slim services on or off beside its categories | Accepted; narrows 0060 §1, §2 and 0066 §2 | | [0084](0084-a-worker-may-serve-a-platforms-enrolled-phones-only.md) | A worker may serve a platform's enrolled phones only | Accepted; narrows 0022 and 0009 §4 | | [0085](0085-an-ios-simulator-takes-keys-on-every-runtime-and-the-app-switcher-and-lock.md) | An iOS simulator takes keys on every runtime, and the app switcher and Lock | Accepted; narrows 0049 §4 | -| [0086](0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md) | On Windows the daemon service is a logon task that runs a Simlock supervisor | Accepted — not yet implemented; narrows 0041 §1, §3, §4, §5 and §8 | +| [0086](0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md) | On Windows the daemon service is a logon task that runs a Simlock supervisor | Accepted; narrows 0041 §1, §3, §4, §5 and §8 | From 39c53ba055abfd80080f4c420fad7baa232da5af Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 11:38:08 +0100 Subject: [PATCH 25/25] docs(adr): keep one Accepted 0086 row (#1698) --- docs/internal/adr/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index 4664c7049..fbf934c88 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -121,5 +121,4 @@ the status is stale. | [0084](0084-a-worker-may-serve-a-platforms-enrolled-phones-only.md) | A worker may serve a platform's enrolled phones only | Accepted; narrows 0022 and 0009 §4 | | [0085](0085-an-ios-simulator-takes-keys-on-every-runtime-and-the-app-switcher-and-lock.md) | An iOS simulator takes keys on every runtime, and the app switcher and Lock | Accepted; narrows 0049 §4 | | [0086](0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md) | On Windows the daemon service is a logon task that runs a Simlock supervisor | Accepted; narrows 0041 §1, §3, §4, §5 and §8 | -| [0086](0086-on-windows-the-daemon-service-is-a-logon-task-that-runs-a-simlock-supervisor.md) | On Windows the daemon service is a logon task that runs a Simlock supervisor | Accepted — not yet implemented; narrows 0041 §1, §3, §4, §5 and §8 | | [0088](0088-a-macos-worker-checks-fseventsd-when-doctor-runs.md) | A macOS worker checks fseventsd's memory when doctor runs, and an optional module may be on by default on a macOS worker | Accepted; narrows 0030 §2, §3 and §7, and 0046 §1 |