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 stop listener
Marcelitoea482d60633f
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex ce18c3f..fd80c24 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -96,5 +96,5 @@ jobs:# These portable adapter tests and real-addon refusal tests stay together.- name: App-channel tests- run: pnpm exec vitest run 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+ 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.tsdiff --git a/packages/daemon/native/windows-stop.cc b/packages/daemon/native/windows-stop.ccindex 79e7414..0690518 100644--- a/packages/daemon/native/windows-stop.cc+++ b/packages/daemon/native/windows-stop.cc@@ -382,8 +382,10 @@ DWORD WINAPI Listen(void* data) {s.Stop();// Every issued operation has completed before these resources are released.s.operation.reset();- if (!CloseHandle(s.pipe.value)) s.Fail(GetLastError());- else s.pipe.value = INVALID_HANDLE_VALUE;+ // A failed CloseHandle leaves ownership uncertain; never close the value a second time.+ HANDLE pipe = s.pipe.value;+ s.pipe.value = INVALID_HANDLE_VALUE;+ if (!CloseHandle(pipe)) s.Fail(GetLastError());s.nativeComplete.store(true);ReleaseParticipant(s, napi_tsfn_release);return 0;diff --git a/packages/daemon/src/windows-stop.ts b/packages/daemon/src/windows-stop.tsindex 0af528e..00194c2 100644--- a/packages/daemon/src/windows-stop.ts+++ b/packages/daemon/src/windows-stop.ts@@ -1,3 +1,59 @@+import { timingSafeEqual } from "node:crypto";+import { createRequire } from "node:module";+import { fileURLToPath } from "node:url";++interface StopListener {+ capability: Buffer;+ // Closing drops queued authenticated frames; close() is only reached during shutdown already in progress.+ close(): Promise<void>;+}+interface Stoppable {+ close(): Promise<void>;+ closed: Promise<void>;+}+interface RequestHandler {+ onRequest(frame: Buffer): void;+}+interface HandlerReference {+ deref(): RequestHandler | undefined;+}+interface StopOptions {+ platform?: NodeJS.Platform;+ /** Injection seams for deterministic portable tests. */+ loadNative?: () => unknown;+ handlerReference?: (handler: RequestHandler) => HandlerReference;+}++const FRAME_VERSION = Buffer.from("GDS1");+const HANDLER_LIFETIME = Symbol("Windows stop handler lifetime");+// Failed owners are deliberately retained, not forgotten because their Promise settled.+// No retries, record removal, or descendant-completion claims are implied by this set.+const failedWindowsOwners = new Set<object>();++/** A separate lexical scope ensures the native-rooted callback captures ONLY the weak reference. */+// Native delivers via a thread-safe function: an onRequest exception reaches napi_fatal_exception,+// terminating the process by design.+function weakRequestCallback(reference: HandlerReference): (frame: Buffer) => void {+ return (frame) => reference.deref()?.onRequest(frame);+}++async function closeDaemonAndListener(daemon: Stoppable, listener: StopListener): Promise<void> {+ let daemonFailed = false;+ let originalError: unknown;+ try {+ await daemon.close(); // daemon.closed is settlement, NOT successful cleanup.+ } catch (error) {+ daemonFailed = true;+ originalError = error;+ }+ try {+ await listener.close(); // Attempt drain independently, including after daemon failure.+ } catch (error) {+ if (!daemonFailed) throw error;+ }+ if (daemonFailed) throw originalError;+}+/** Source lives in src/, while the bundle lives directly in daemon/. */export function windowsStopArtifact(entry = new URL(import.meta.url)): URL {return new URL(@@ -5,3 +61,125 @@ export function windowsStopArtifact(entry = new URL(import.meta.url)): URL {entry,);}++/**+ * Install the authenticated listener before start() can create descendants. Windows startup+ * always requires the private, exact-current-process record validated by the native module.+ * Neither its capability nor native exception details are sent to argv, env, or logs.+ */+export async function startWithWindowsStop<T extends Stoppable>(+ recordPath: string,+ start: () => Promise<T>,+ options: StopOptions = {},+): Promise<{ daemon: T; close(): Promise<void>; closed: Promise<void> }> {+ if ((options.platform ?? process.platform) !== "win32") {+ const daemon = await start();+ return { daemon, close: () => daemon.close(), closed: daemon.closed };+ }++ let ready!: (daemon: T) => void;+ let startupFailed!: (error: unknown) => void;+ const startup = new Promise<T>((resolve, reject) => {+ ready = resolve;+ startupFailed = reject;+ });+ let capability: Buffer | undefined;+ let listener: StopListener | undefined;+ let stopping: Promise<void> | undefined;+ let stopped!: () => void;+ let failed!: (error: unknown) => void;+ const closed = new Promise<void>((resolve, reject) => {+ stopped = resolve;+ failed = reject;+ });+ // Consumers attach after asynchronous startup; retain rejection without an unhandled window.+ void closed.catch(() => {});+ void startup.catch(() => {});+ const close = (): Promise<void> => {+ if (!stopping) {+ stopping = startup.then((daemon) => closeDaemonAndListener(daemon, listener as StopListener));+ void stopping.then(stopped, (error) => {+ failedWindowsOwners.add(lifetimeOwner);+ failed(error);+ });+ }+ return stopping;+ };++ // Native TSFN delivery is asynchronous. The injected synchronous factory seam may+ // deliver before it returns the capability: retain at most four correctly shaped+ // frames (144 bytes), then fail initialization rather than silently drop a stop.+ const preinitFrames: Buffer[] = [];+ let preinitOverflow = false;+ // Buffer.isBuffer, length/tag checks and timingSafeEqual on equal 32-byte lengths cannot throw+ // for any input; void close() only schedules asynchronous shutdown.+ const handler: RequestHandler = {+ onRequest(frame) {+ if (!Buffer.isBuffer(frame) || frame.length !== 36 || !frame.subarray(0, 4).equals(FRAME_VERSION))+ return;+ if (!capability) {+ if (preinitFrames.length < 4) preinitFrames.push(Buffer.from(frame));+ else preinitOverflow = true;+ return;+ }+ if (timingSafeEqual(frame.subarray(4), capability)) void close();+ },+ };+ // Explicit returned ownership keeps the handler alive; native owns only a weak association.+ const lifetimeOwner = { close, closed, [HANDLER_LIFETIME]: handler };+ const reference = options.handlerReference?.(handler) ?? new WeakRef(handler);+ const callback = weakRequestCallback(reference);+ try {+ const native = (+ options.loadNative ?? (() => createRequire(import.meta.url)(fileURLToPath(windowsStopArtifact())))+ )() as { createStopListener?: (path: string, callback: (frame: Buffer) => void) => StopListener };+ if (typeof native?.createStopListener !== "function") throw new Error("invalid addon");+ listener = native.createStopListener(recordPath, callback);+ if (+ !listener ||+ typeof listener.close !== "function" ||+ !Buffer.isBuffer(listener.capability) ||+ listener.capability.length !== 32 ||+ preinitOverflow+ ) {+ throw new Error("invalid listener");+ }+ capability = Buffer.from(listener.capability);+ } catch {+ if (typeof listener?.close === "function") {+ try {+ await listener.close();+ } catch {+ failedWindowsOwners.add(lifetimeOwner);+ }+ }+ throw new Error("Windows stop listener initialization failed");+ }+ for (const frame of preinitFrames) handler.onRequest(frame);+ preinitFrames.length = 0;++ let daemon: T;+ try {+ daemon = await start();+ } catch (error) {+ startupFailed(error);+ // A partially started daemon is uncertain. Retain the owner and attempt drain.+ failedWindowsOwners.add(lifetimeOwner);+ try {+ await listener.close();+ } catch {+ /* Retained owner above; cleanup must not replace the startup failure. */+ }+ throw error;+ }+ ready(daemon);+ void daemon.closed.then(+ () => {+ void close();+ },+ () => {+ void close();+ },+ );+ return { daemon, ...lifetimeOwner };+}diff --git a/packages/daemon/test/windows-stop.test.ts b/packages/daemon/test/windows-stop.test.tsnew file mode 100644index 0000000..e7543c9--- /dev/null+++ b/packages/daemon/test/windows-stop.test.ts@@ -0,0 +1,286 @@+import { describe, expect, it, vi } from "vitest";+import { startWithWindowsStop, windowsStopArtifact } from "../src/windows-stop.ts";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+function fixture() {+ const capability = Buffer.alloc(32, 17);+ let deliver!: (frame: Buffer) => void;+ const listenerClose = vi.fn(async () => {});+ const nativeFactory = vi.fn((_path: string, callback: (frame: Buffer) => void) => {+ deliver = callback;+ return { capability, close: listenerClose };+ });+ const loadNative = vi.fn(() => ({ createStopListener: nativeFactory }));+ const done = deferred<void>();+ const close = vi.fn(async () => {+ done.resolve();+ });+ const daemon = { close, closed: done.promise };+ const frame = Buffer.concat([Buffer.from("GDS1"), capability]);+ return {+ loadNative,+ nativeFactory,+ listenerClose,+ daemon,+ done,+ frame,+ deliver: (frame: Buffer) => deliver(frame),+ };+}++describe("Windows production stop bootstrap (S8, S10, S11)", () => {+ it("does not load native code on Unix", async () => {+ const f = fixture();+ const started = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "linux",+ loadNative: f.loadNative,+ });+ expect(f.loadNative).not.toHaveBeenCalled();+ expect(started.daemon).toBe(f.daemon);+ });+ it("creates the listener before startup and latches a stop during asynchronous startup", async () => {+ const f = fixture();+ const ready = deferred<typeof f.daemon>();+ const started = startWithWindowsStop(+ "data/daemon.pid",+ () => {+ expect(f.nativeFactory).toHaveBeenCalledWith("data/daemon.pid", expect.any(Function));+ f.deliver(f.frame);+ return ready.promise;+ },+ { platform: "win32", loadNative: f.loadNative },+ );+ expect(f.daemon.close).not.toHaveBeenCalled();+ ready.resolve(f.daemon);+ const owner = await started;+ await owner.closed;+ expect(f.daemon.close).toHaveBeenCalledTimes(1);+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it("rejects wrong capability, version, short and extra frames without shutdown", async () => {+ const f = fixture();+ const owner = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "win32",+ loadNative: f.loadNative,+ });+ for (const frame of [+ Buffer.concat([Buffer.from("GDS1"), Buffer.alloc(32)]),+ Buffer.concat([Buffer.from("GDS2"), f.frame.subarray(4)]),+ Buffer.concat([Buffer.from([0xc7, 0x44, 0x53, 0x31]), f.frame.subarray(4)]),+ f.frame.subarray(0, 35),+ Buffer.concat([f.frame, Buffer.alloc(1)]),+ ])+ f.deliver(frame);+ await Promise.resolve();+ expect(f.daemon.close).not.toHaveBeenCalled();+ const first = owner.close();+ expect(owner.close()).toBe(first);+ f.deliver(f.frame);+ await first;+ expect(f.daemon.close).toHaveBeenCalledTimes(1);+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it("never throws from onRequest for hostile inputs", async () => {+ const f = fixture();+ const owner = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "win32",+ loadNative: f.loadNative,+ });+ const callback = f.nativeFactory.mock.calls[0]?.[1] as (frame: unknown) => void;+ for (const input of [+ undefined,+ null,+ "GDS1",+ {},+ new Uint8Array(36),+ Buffer.alloc(0),+ f.frame.subarray(0, 35),+ Buffer.concat([f.frame, Buffer.alloc(1)]),+ Buffer.concat([Buffer.from("GDS2"), f.frame.subarray(4)]),+ Buffer.concat([Buffer.from("GDS1"), Buffer.alloc(32)]),+ ])+ expect(() => callback(input)).not.toThrow();+ await Promise.resolve();+ expect(f.daemon.close).not.toHaveBeenCalled();+ expect(() => callback(f.frame)).not.toThrow();+ await owner.closed;+ expect(f.daemon.close).toHaveBeenCalledTimes(1);+ });+ it("observes the real close rejection even when daemon.closed reports settlement", async () => {+ const f = fixture();+ f.daemon.close.mockImplementation(async () => {+ f.done.resolve();+ throw new Error("close failed");+ });+ const owner = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "win32",+ loadNative: f.loadNative,+ });+ f.done.resolve();+ await expect(owner.closed).rejects.toThrow("close failed");+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it("attempts drain after daemon failure and preserves the original error when both fail", async () => {+ const f = fixture();+ const original = new Error("daemon failure");+ f.daemon.close.mockRejectedValue(original);+ f.listenerClose.mockRejectedValue(new Error("secondary drain failure"));+ const owner = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "win32",+ loadNative: f.loadNative,+ });+ await expect(owner.close()).rejects.toBe(original);+ await expect(owner.closed).rejects.toBe(original);+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it("validates a synchronous factory frame after capability assignment and before startup completes", async () => {+ const f = fixture();+ const ready = deferred<typeof f.daemon>();+ const started = startWithWindowsStop("data/daemon.pid", () => ready.promise, {+ platform: "win32",+ loadNative: () => ({+ createStopListener: (_path: string, callback: (frame: Buffer) => void) => {+ callback(f.frame);+ return { capability: Buffer.from(f.frame.subarray(4)), close: f.listenerClose };+ },+ }),+ });+ expect(f.daemon.close).not.toHaveBeenCalled();+ ready.resolve(f.daemon);+ const owner = await started;+ await Promise.resolve();+ await Promise.resolve();+ expect(f.daemon.close).toHaveBeenCalledTimes(1);+ await owner.closed;+ });+ it("rejects unauthenticated synchronous frames without early shutdown but retains a later valid frame", async () => {+ const f = fixture();+ const owner = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "win32",+ loadNative: () => ({+ createStopListener: (_path: string, callback: (frame: Buffer) => void) => {+ callback(f.frame.subarray(0, 35));+ callback(Buffer.concat([Buffer.from("GDS2"), f.frame.subarray(4)]));+ callback(Buffer.concat([Buffer.from("GDS1"), Buffer.alloc(32)]));+ expect(f.daemon.close).not.toHaveBeenCalled();+ callback(f.frame);+ return { capability: f.frame.subarray(4), close: f.listenerClose };+ },+ }),+ });+ await owner.closed;+ expect(f.daemon.close).toHaveBeenCalledTimes(1);+ });+ it("bounds synchronous preinitialization retention and fails closed on overflow", async () => {+ const f = fixture();+ const start = vi.fn(async () => f.daemon);+ await expect(+ startWithWindowsStop("data/daemon.pid", start, {+ platform: "win32",+ loadNative: () => ({+ createStopListener: (_path: string, callback: (frame: Buffer) => void) => {+ for (let count = 0; count < 5; count++) callback(f.frame);+ return { capability: f.frame.subarray(4), close: f.listenerClose };+ },+ }),+ }),+ ).rejects.toThrow("Windows stop listener initialization failed");+ expect(start).not.toHaveBeenCalled();+ expect(f.daemon.close).not.toHaveBeenCalled();+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it("dispatches only through the weak handler association while the owner retains its handler", async () => {+ const f = fixture();+ const deref = vi.fn();+ const associate = vi.fn((handler: { onRequest(frame: Buffer): void }) => {+ deref.mockReturnValue(handler);+ return { deref };+ });+ const owner = await startWithWindowsStop("data/daemon.pid", async () => f.daemon, {+ platform: "win32",+ loadNative: f.loadNative,+ handlerReference: associate,+ });+ expect(associate).toHaveBeenCalledTimes(1);+ // Simulate a collected weak target without depending on GC scheduling.+ deref.mockReturnValue(undefined);+ f.deliver(f.frame);+ await Promise.resolve();+ expect(deref).toHaveBeenCalled();+ expect(f.daemon.close).not.toHaveBeenCalled();+ // The explicit owner still controls shutdown, independently of the native callback.+ await owner.close();+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it.each(["missing module", "unsafe record"])("fails closed before startup: %s", async (reason) => {+ const start = vi.fn();+ await expect(+ startWithWindowsStop("data/daemon.pid", start, {+ platform: "win32",+ loadNative: () => {+ if (reason === "missing module") throw new Error(reason);+ return {+ createStopListener: () => {+ throw new Error(reason);+ },+ };+ },+ }),+ ).rejects.toThrow("Windows stop listener initialization failed");+ expect(start).not.toHaveBeenCalled();+ });+ it("refuses a malformed native export or capability before startup", async () => {+ for (const native of [+ {},+ { createStopListener: () => ({ capability: Buffer.alloc(31), close: async () => {} }) },+ ]) {+ const start = vi.fn();+ await expect(+ startWithWindowsStop("data/daemon.pid", start, { platform: "win32", loadNative: () => native }),+ ).rejects.toThrow("Windows stop listener initialization failed");+ expect(start).not.toHaveBeenCalled();+ }+ });+ it("drains the listener on startup failure without leaking native error details", async () => {+ const f = fixture();+ await expect(+ startWithWindowsStop(+ "data/daemon.pid",+ async () => {+ throw new Error("startup failed");+ },+ { platform: "win32", loadNative: f.loadNative },+ ),+ ).rejects.toThrow("startup failed");+ expect(f.listenerClose).toHaveBeenCalledTimes(1);+ });+ it("preserves startup failure even when listener cleanup also fails", async () => {+ const f = fixture();+ f.listenerClose.mockRejectedValue(new Error("native private details"));+ await expect(+ startWithWindowsStop(+ "data/daemon.pid",+ async () => {+ throw new Error("startup failed");+ },+ { platform: "win32", loadNative: f.loadNative },+ ),+ ).rejects.toThrow("startup failed");+ });+ it("uses the same native artifact relative to source and staged daemon entry", () => {+ expect(windowsStopArtifact(new URL("file:///repo/packages/daemon/src/windows-stop.ts")).pathname).toBe(+ "/repo/packages/daemon/native/windows-stop.node",+ );+ expect(windowsStopArtifact(new URL("file:///runtime/daemon/cli.mjs")).pathname).toBe(+ "/runtime/daemon/native/windows-stop.node",+ );+ });+});