Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(daemon): start the daemon behind the Windows app channel

Marcelito6ef8faed6eac
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index b7fdcd1..d19e74b 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -94,7 +94,7 @@ jobs:
pnpm --filter @gentle-dot/daemon run build:windows-stop -- --compiler "$compiler" --headers "$inputs/node-$version/include/node" --node-lib "$inputs/node.lib"
if ($LASTEXITCODE -ne 0) { throw 'Native addon build failed' }
- # The portable adapter tests, the real-addon refusal tests, the agent shutdown tests, the engine environment tests, and the private memory lookup tests.
+ # The portable adapter tests, the real-addon refusal tests, the agent shutdown tests, the engine environment tests, the private memory lookup tests, and the daemon lifecycle and CLI tests.
- name: Daemon tests
- run: pnpm exec vitest run packages/daemon/test/windows-stop.test.ts packages/daemon/test/windows-app-channel.test.ts packages/daemon/test/app-channel-platform.test.ts packages/daemon/test/app-channel.test.ts packages/daemon/test/app-channel-fd.test.ts packages/daemon/test/windows-app-channel-addon.test.ts packages/daemon/test/process-tree.test.ts packages/daemon/test/supervisor.test.ts packages/daemon/test/runtime.test.ts packages/daemon/test/config.test.ts packages/daemon/test/isolation.test.ts packages/daemon/test/private-memory.test.ts
+ run: pnpm exec vitest run packages/daemon/test/windows-stop.test.ts packages/daemon/test/windows-app-channel.test.ts packages/daemon/test/app-channel-platform.test.ts packages/daemon/test/app-channel.test.ts packages/daemon/test/app-channel-fd.test.ts packages/daemon/test/windows-app-channel-addon.test.ts packages/daemon/test/process-tree.test.ts packages/daemon/test/supervisor.test.ts packages/daemon/test/runtime.test.ts packages/daemon/test/config.test.ts packages/daemon/test/isolation.test.ts packages/daemon/test/private-memory.test.ts packages/daemon/test/lifecycle.test.ts packages/daemon/test/cli.test.ts
diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.ts
index f06901b..4cfbecb 100644
--- a/packages/daemon/src/cli.ts
+++ b/packages/daemon/src/cli.ts
@@ -1,5 +1,7 @@
#!/usr/bin/env node
import { existsSync } from "node:fs";
+import { join } from "node:path";
+import type { Duplex } from "node:stream";
import { fileURLToPath } from "node:url";
import { inheritedAppSocket } from "./app-channel.ts";
import { serveAuthHelper } from "./auth-helper.ts";
@@ -10,6 +12,8 @@ import { resolveEngramBin, runtimeDir } from "./runtime.ts";
import { SECRETS_KEY_VAR } from "./secret-file.ts";
import { loadVpsOptions } from "./vps.ts";
import { IDENTITY_SOURCE } from "./white-label.ts";
+import type { WindowsAppChannel } from "./windows-app-channel.ts";
+import { finishWindowsShutdown, startWithWindowsAppChannel } from "./windows-stop.ts";
/** This file (or the bundled `cli.mjs`), which the sign-in helper runs again. */
const ENTRY = fileURLToPath(import.meta.url);
@@ -41,31 +45,56 @@ async function main(): Promise<void> {
const config = loadConfig();
// The desktop app that launched the daemon hands over its private channel on fd 3 (S25.1); it is
// opened before anything is spawned, and refused if children would inherit it.
- const appChannel = inheritedAppSocket({ log });
+ const appChannel = process.platform === "win32" ? undefined : inheritedAppSocket({ log });
// Server mode only when GENTLE_DOT_VPS says so (S25.8). The secrets key is read once and removed
// from the process environment, so no child the daemon starts can inherit it.
const vps = loadVpsOptions(process.env, { uid: process.getuid?.() ?? -1 });
delete process.env[SECRETS_KEY_VAR];
- const daemon = await startDaemon({
- port: config.port,
- host: config.host,
- dataDir: config.dataDir,
- workspace: config.workspace,
- ...(config.preferredFolder ? { preferredFolder: config.preferredFolder } : {}),
- uiDir: config.uiDir,
- agentCommand: config.agentCommand,
- agentArgs: config.agentArgs,
- ...(config.agentHome ? { agentHome: config.agentHome } : {}),
- allowedOrigins: config.allowedOrigins,
- ...(appChannel ? { appChannel } : {}),
- // Sign-in runs in this same entry point as the engine's user (`--auth-helper`, B1).
- ...(vps
- ? { vps: { ...vps, authHelper: { command: process.execPath, args: [ENTRY, "--auth-helper"] } } }
- : {}),
- log,
- });
+ const start = (channel: Duplex | undefined = appChannel) =>
+ startDaemon({
+ port: config.port,
+ host: config.host,
+ dataDir: config.dataDir,
+ workspace: config.workspace,
+ ...(config.preferredFolder ? { preferredFolder: config.preferredFolder } : {}),
+ uiDir: config.uiDir,
+ agentCommand: config.agentCommand,
+ agentArgs: config.agentArgs,
+ ...(config.agentHome ? { agentHome: config.agentHome } : {}),
+ allowedOrigins: config.allowedOrigins,
+ ...(channel ? { appChannel: channel } : {}),
+ // Sign-in runs in this same entry point as the engine's user (`--auth-helper`, B1).
+ ...(vps
+ ? { vps: { ...vps, authHelper: { command: process.execPath, args: [ENTRY, "--auth-helper"] } } }
+ : {}),
+ log,
+ });
+ // Windows requires the L98 private exact-launch record. No implicit unmanaged bypass.
+ // Construction precedes startDaemon and therefore all descendant startup.
+ const windows =
+ process.platform === "win32"
+ ? await startWithWindowsAppChannel<Awaited<ReturnType<typeof start>>, WindowsAppChannel>(
+ join(config.dataDir, "daemon.pid"),
+ start,
+ )
+ : undefined;
+ const daemon = windows?.daemon ?? (await start());
process.stdout.write(`${startupMessage(daemon.url, config.dataDir, process.stdout.isTTY === true)}\n`);
+ if (windows) {
+ const shutdown = () => {
+ void windows.close();
+ };
+ process.on("SIGINT", shutdown);
+ process.on("SIGTERM", shutdown);
+ // Only successful daemon.close AND native drain may report success. Never use
+ // daemon.closed directly here: it also settles when daemon.close rejects.
+ // On failure, retain the owner and set exitCode without abandoning native
+ // ownership through process.exit. No descendant completion is claimed.
+ void finishWindowsShutdown(windows, process, log);
+ return;
+ }
+
let closing = false;
const shutdown = (signal: string) => {
if (closing) return;
@@ -87,6 +116,8 @@ else {
if (process.argv.includes("--self-check")) selfCheck();
main().catch((error: Error) => {
log(`failed to start: ${error.message}`);
- process.exit(1);
+ // Windows lets native ownership drain instead of exiting at once (`finishWindowsShutdown`).
+ if (process.platform === "win32") process.exitCode = 1;
+ else process.exit(1);
});
}
diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.ts
index b740379..3595220 100644
--- a/packages/daemon/src/daemon.ts
+++ b/packages/daemon/src/daemon.ts
@@ -45,6 +45,7 @@ import { VoiceService } from "./voice.ts";
import { CONNECTOR_HOME, chownHandOver, prepareVpsLayout, type VpsOptions } from "./vps.ts";
import { PIN_FILE, PinGate } from "./web-pin.ts";
import { identityArgs } from "./white-label.ts";
+import { isProductionWindowsAppChannel } from "./windows-app-channel.ts";
export interface DaemonOptions {
port: number;
@@ -152,7 +153,26 @@ export function startupMessage(url: string, dataDir: string, interactive: boolea
}
export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
+ // A generic Duplex or fd number is not Windows descendant-exclusion admission.
+ // Only actual main-thread/native ownership transfer on the production startup
+ // path admits a requested channel, before privateMemory can spawn PowerShell.
+ if (
+ process.platform === "win32" &&
+ options.appChannel &&
+ !isProductionWindowsAppChannel(options.appChannel)
+ )
+ throw new Error("Windows app channel requires validated production ownership before startup");
const log = options.log ?? (() => {});
+ const openApp = () =>
+ options.appChannel
+ ? new AppChannel(options.appChannel, {
+ log,
+ ...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),
+ })
+ : undefined;
+ // Observe Windows transport errors during asynchronous memory bootstrap.
+ // Unix retains its original channel-construction timing below.
+ const earlyWindowsApp = process.platform === "win32" ? openApp() : undefined;
const token = ensureToken(options.dataDir);
const vps = options.vps;
// Server mode (S25.8): the daemon's files stay its own, the engine's folders become the engine's,
@@ -183,12 +203,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
agentEnv.GENTLE_PI_CONFIG_HOME = join(options.dataDir, "gentle-ai");
}
const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);
- const app = options.appChannel
- ? new AppChannel(options.appChannel, {
- log,
- ...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),
- })
- : undefined;
+ const app = earlyWindowsApp ?? openApp();
// The approved connectors are read once, here; the engine cannot change them (docs/design.md).
// Their secrets come from the app's secure store over its channel, and only into memory (S25.5).
const connectorStore = new ConnectorStore({
@@ -339,6 +354,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
// Nothing the app asks changes connectors before connectors.json was checked (S25.6).
app.handler = async (method, params) => {
await integrity;
+ if (!app.connected) throw new Error("The Gentle Dot app closed its channel.");
return appRequest(method, params, bridge, connectors, app);
};
// The computer helper belongs to the app that registered it (S24.7).
@@ -394,21 +410,46 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
const shutdown = async () => {
// Not listening any more first, so an app relaunched meanwhile starts a daemon of its own.
const serverClosed = new Promise<void>((done) => server.close(() => done()));
- app?.close();
- for (const client of wss.clients) client.terminate();
- wss.close();
- // Stops waiting approvals and the connectors' servers (stdio ones are processes of the daemon).
- await proxy.close();
- await serverClosed;
- await supervisor.stop();
- connectorStore.close();
- authHelper?.close();
- await memory?.stop();
+ let failed = false;
+ let firstError: unknown;
+ const attempt = async (cleanup: () => unknown) => {
+ try {
+ await cleanup();
+ } catch (error) {
+ if (!failed) {
+ failed = true;
+ firstError = error;
+ }
+ }
+ };
+ // Logical refusal and secret invalidation happen NOW, not after native drain.
+ // Start drain independently so a pending/failed channel cannot skip cleanup.
+ const channelClosed = attempt(() => app?.close());
+ await attempt(() => {
+ for (const client of wss.clients) client.terminate();
+ wss.close();
+ });
+ await attempt(() => proxy.close());
+ await attempt(() => serverClosed);
+ await attempt(() => supervisor.stop());
+ await attempt(() => connectorStore.close());
+ await attempt(() => authHelper?.close());
+ await attempt(() => memory?.stop());
+ await channelClosed;
+ if (failed) throw firstError;
};
let stopping: Promise<void> | undefined;
const close = (): Promise<void> => {
if (!stopping) {
- stopping = shutdown();
+ // Publish before synchronous logical close notifies app.onClose; do not
+ // defer refusal, and do not recursively start another shutdown.
+ let resolveClose!: () => void;
+ let rejectClose!: (error: unknown) => void;
+ stopping = new Promise<void>((resolve, reject) => {
+ resolveClose = resolve;
+ rejectClose = reject;
+ });
+ void shutdown().then(resolveClose, rejectClose);
stopping.then(stopped, (error: Error) => {
log(`the assistant did not stop cleanly: ${error.message}`);
stopped();
diff --git a/packages/daemon/test/cli.test.ts b/packages/daemon/test/cli.test.ts
index be0e465..5348e08 100644
--- a/packages/daemon/test/cli.test.ts
+++ b/packages/daemon/test/cli.test.ts
@@ -5,11 +5,12 @@ import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
+import { itWithInheritedAppChannel, itWithUnmanagedCli } from "./support/windows.ts";
const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));
describe("gentle-dot command", () => {
- it("keeps the access key out of redirected output, such as a log file", async () => {
+ itWithUnmanagedCli("keeps the access key out of redirected output, such as a log file", async () => {
const dataDir = join(tempDir(), "data");
const child = spawn(process.execPath, [CLI], {
env: {
@@ -69,38 +70,41 @@ describe("gentle-dot command", () => {
},
);
- it("a daemon launched with the app's channel exits when the app goes (S35.2, #22)", async () => {
- const dataDir = join(tempDir(), "data");
- const { app, daemon } = await socketPair();
- const child = spawn(process.execPath, [CLI], {
- env: {
- ...process.env,
- GENTLE_DOT_DATA_DIR: dataDir,
- GENTLE_DOT_PORT: "0",
- GENTLE_DOT_AGENT_BIN: process.execPath,
- GENTLE_DOT_AGENT_ARGS: JSON.stringify([FAKE_AGENT]),
- },
- stdio: ["ignore", "pipe", "pipe", daemon],
- });
- daemon.destroy();
- let output = "";
- const collect = (chunk: Buffer) => {
- output += chunk.toString();
- };
- child.stdout?.on("data", collect);
- child.stderr?.on("data", collect);
- const exited = new Promise<number | null>((resolve) => child.on("close", (code) => resolve(code)));
- try {
- // The daemon is up once it asks the app for something (the connectors' integrity key).
- await new Promise((resolve) => app.once("data", resolve));
- // The app quits, crashes, or is killed: the kernel closes its end of the pair.
- app.destroy();
- expect(await exited).toBe(0);
- } finally {
- child.kill("SIGKILL");
- }
- expect(output).toContain("the desktop app's channel closed; stopping the assistant");
- });
+ itWithInheritedAppChannel(
+ "a daemon launched with the app's channel exits when the app goes (S35.2, #22)",
+ async () => {
+ const dataDir = join(tempDir(), "data");
+ const { app, daemon } = await socketPair();
+ const child = spawn(process.execPath, [CLI], {
+ env: {
+ ...process.env,
+ GENTLE_DOT_DATA_DIR: dataDir,
+ GENTLE_DOT_PORT: "0",
+ GENTLE_DOT_AGENT_BIN: process.execPath,
+ GENTLE_DOT_AGENT_ARGS: JSON.stringify([FAKE_AGENT]),
+ },
+ stdio: ["ignore", "pipe", "pipe", daemon],
+ });
+ daemon.destroy();
+ let output = "";
+ const collect = (chunk: Buffer) => {
+ output += chunk.toString();
+ };
+ child.stdout?.on("data", collect);
+ child.stderr?.on("data", collect);
+ const exited = new Promise<number | null>((resolve) => child.on("close", (code) => resolve(code)));
+ try {
+ // The daemon is up once it asks the app for something (the connectors' integrity key).
+ await new Promise((resolve) => app.once("data", resolve));
+ // The app quits, crashes, or is killed: the kernel closes its end of the pair.
+ app.destroy();
+ expect(await exited).toBe(0);
+ } finally {
+ child.kill("SIGKILL");
+ }
+ expect(output).toContain("the desktop app's channel closed; stopping the assistant");
+ },
+ );
});
/** A connected pair of Unix sockets (Node has no socketpair): the app's end and the daemon's. */
diff --git a/packages/daemon/test/lifecycle.test.ts b/packages/daemon/test/lifecycle.test.ts
index 58224ef..989e154 100644
--- a/packages/daemon/test/lifecycle.test.ts
+++ b/packages/daemon/test/lifecycle.test.ts
@@ -3,12 +3,13 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { AppChannel } from "../src/app-channel.ts";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
import { fakeApp } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
+import { itWithAppChannel } from "./support/windows.ts";
const MARKER = ".gentle-shell-home";
@@ -60,7 +61,7 @@ const alive = (pid: number) => {
};
describe("the daemon's lifetime (S35.2)", () => {
- it("a daemon started by the app stops when its app channel closes", async () => {
+ itWithAppChannel("a daemon started by the app stops when its app channel closes", async () => {
const app = fakeApp();
const { d, logs } = await start({ appChannel: app });
const engine = d.supervisor.pid;
@@ -91,7 +92,64 @@ describe("the daemon's lifetime (S35.2)", () => {
expect(await health(d.port)).toBe(true);
});
- it("closing twice, or closing while the app quits, stops once", async () => {
+ itWithAppChannel(
+ "daemon close and closed settlement wait for channel drain without a close-event cycle",
+ async () => {
+ const app = fakeApp();
+ const { d } = await start({ appChannel: app });
+ const original = AppChannel.prototype.close;
+ let drain!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ drain = resolve;
+ });
+ const spy = vi.spyOn(AppChannel.prototype, "close").mockImplementation(function (this: AppChannel) {
+ void original.call(this); // real logical refusal and onClose reentry
+ return pending;
+ });
+ let settled = false;
+ void d.closed.then(() => {
+ settled = true;
+ });
+ try {
+ const closing = d.close();
+ expect(d.close()).toBe(closing);
+ await waitFor(() => d.supervisor.state === "stopped");
+ expect(settled).toBe(false);
+ expect(spy).toHaveBeenCalled();
+ drain();
+ await closing;
+ await d.closed;
+ expect(settled).toBe(true);
+ } finally {
+ drain();
+ spy.mockRestore();
+ }
+ },
+ );
+
+ itWithAppChannel("channel drain failure propagates after other daemon cleanup completes", async () => {
+ const app = fakeApp();
+ const { d } = await start({ appChannel: app });
+ const original = AppChannel.prototype.close;
+ const failure = new Error("channel drain failed");
+ const spy = vi.spyOn(AppChannel.prototype, "close").mockImplementation(function (this: AppChannel) {
+ void original.call(this);
+ const rejected = Promise.reject(failure);
+ void rejected.catch(() => {});
+ return rejected;
+ });
+ try {
+ await expect(d.close()).rejects.toBe(failure);
+ await d.closed;
+ expect(d.supervisor.state).toBe("stopped");
+ expect(await health(d.port)).toBe(false);
+ } finally {
+ spy.mockRestore();
+ daemons.splice(daemons.indexOf(d), 1);
+ }
+ });
+
+ itWithAppChannel("closing twice, or closing while the app quits, stops once", async () => {
const app = fakeApp();
const { d } = await start({ appChannel: app });
const first = d.close();
@@ -101,6 +159,26 @@ describe("the daemon's lifetime (S35.2)", () => {
});
});
+describe.runIf(process.platform === "win32")("Windows app channel admission", () => {
+ it("refuses a generic Duplex as the app channel before anything starts", async () => {
+ const dataDir = tempDir();
+ await expect(
+ startDaemon({
+ port: 0,
+ host: "127.0.0.1",
+ dataDir,
+ workspace: join(dataDir, "workspace"),
+ uiDir: dataDir,
+ agentCommand: process.execPath,
+ agentArgs: [FAKE_AGENT],
+ appChannel: fakeApp().daemonEnd,
+ }),
+ ).rejects.toThrow("Windows app channel requires validated production ownership before startup");
+ // Refused before the token, the engine or any descendant.
+ expect(existsSync(join(dataDir, "token"))).toBe(false);
+ });
+});
+
describe("frames the app would refuse are never sent (S35.2: a refused frame would close the channel)", () => {
it("an approval too large for one frame is refused here and the channel stays open", async () => {
const app = fakeApp(["allow"]);
diff --git a/packages/daemon/test/support/windows.ts b/packages/daemon/test/support/windows.ts
index a52e895..e6efa98 100644
--- a/packages/daemon/test/support/windows.ts
+++ b/packages/daemon/test/support/windows.ts
@@ -12,6 +12,9 @@ export const SERVER_MODE =
export const POSIX_FILE_MODE =
"Windows has no POSIX permission bits; private files rely on the user profile's ACL. Linux and macOS cover these mode assertions";
+export const UNMANAGED_CLI =
+ "Windows CLI startup requires a native exact-launch owner record; Linux and macOS cover unmanaged CLI startup";
+
export const POSIX_LOGIN_SHELL =
"Windows intentionally ignores POSIX login shells; Linux and macOS cover login-shell Engram discovery";
@@ -24,6 +27,7 @@ export function expectPosixMode(actualMode: number, expectedMode: number): void
/** Only daemon tests requiring a generic Duplex app channel lack Windows coverage. */
export const describeWithAppChannel: ReturnType<typeof describe.skipIf> = describe.skipIf(windows);
+export const itWithAppChannel: ReturnType<typeof it.skipIf> = it.skipIf(windows);
/** Server-mode tests are absent on Windows; desktop and generic file behavior remain active. */
export const itServerMode: ReturnType<typeof it.skipIf> = it.skipIf(windows);
@@ -31,10 +35,13 @@ export const itServerMode: ReturnType<typeof it.skipIf> = it.skipIf(windows);
export const itWithPosixShell: ReturnType<typeof it.skipIf> = it.skipIf(windows);
export const describeWithInheritedAppChannel: ReturnType<typeof describe.skipIf> = describe.skipIf(windows);
+export const itWithInheritedAppChannel: ReturnType<typeof it.skipIf> = it.skipIf(windows);
+export const itWithUnmanagedCli: ReturnType<typeof it.skipIf> = it.skipIf(windows);
if (windows) {
console.info(`Windows-only test skip: ${WINDOWS_APP_CHANNEL}`);
console.info(`Windows-only test skip: ${SERVER_MODE}`);
console.info(`Windows-only test skip: ${INHERITED_APP_CHANNEL}`);
+ console.info(`Windows-only test skip: ${UNMANAGED_CLI}`);
console.info(`Windows-only test skip: ${POSIX_LOGIN_SHELL}`);
}