A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(daemon): add the Windows app channel's TypeScript adapter
Marcelito64ff1bf91299
diff --git a/packages/daemon/native/windows-app-channel-napi.cc b/packages/daemon/native/windows-app-channel-napi.ccindex 75341b0..5f16f6d 100644--- a/packages/daemon/native/windows-app-channel-napi.cc+++ b/packages/daemon/native/windows-app-channel-napi.cc@@ -147,6 +147,10 @@ napi_value Read(napi_env e, napi_callback_info i) {// native read cursor. No external Buffer aliases the backend's OVERLAPPED bytes.void* destination = nullptr; napi_value buffer;if (!Check(e, napi_create_buffer(e, count, &destination, &buffer))) return nullptr;+ // InspectStream and TakeStreamRead run back to back on the one loop thread with no+ // Poll/Stop/Release call between them, so the phase stays as inspected and+ // readable_bytes cannot shrink: TakeStreamRead copies exactly `count` bytes. Its result is+ // not checked because the cursor has already advanced; there is nothing to undo.if (count) TakeStreamRead(b->stream, destination, count);return buffer;}diff --git a/packages/daemon/src/app-channel.ts b/packages/daemon/src/app-channel.tsindex d2842dd..fbaeecf 100644--- a/packages/daemon/src/app-channel.ts+++ b/packages/daemon/src/app-channel.ts@@ -16,6 +16,7 @@ import { type StdioOptions, spawnSync } from "node:child_process";import { closeSync, fstatSync } from "node:fs";import { Socket } from "node:net";import type { Duplex } from "node:stream";+import { isWindowsAppChannel } from "./windows-app-channel.ts";/** Where the app puts its end of the channel. */export const APP_FD = 3;@@ -78,6 +79,7 @@ export class AppChannel implements AppLink {private buffer = "";private nextId = 0;private open = true;+ private closing?: Promise<void>;constructor(stream: Duplex, options: AppChannelOptions = {}) {this.stream = stream;@@ -136,10 +138,23 @@ export class AppChannel implements AppLink {return Promise.race([answer, aborted]);}- close(): void {- if (!this.open) return;+ /** Logical refusal/notification precedes transport drain. Memoize before notifying+ * listeners: daemon shutdown may reenter close, but must never await itself. */+ close(): Promise<void> {+ if (this.closing) return this.closing;this.open = false;- this.stream.destroy();+ this.buffer = "";+ const stream = this.stream;+ const windows = isWindowsAppChannel(stream);+ this.closing = windows+ ? Promise.resolve().then(async () => {+ const result = await stream.close("drain");+ if (result.mode !== "drain" || result.drained !== true)+ throw new Error("Windows app channel was not drained.");+ })+ : Promise.resolve();+ void this.closing.catch(() => {}); // EOF/error initiators have no awaiter+ if (!windows) this.stream.destroy();for (const [id, waiting] of this.pending) {clearTimeout(waiting.timer);waiting.reject(new Error("The Gentle Dot app closed its channel."));@@ -147,9 +162,11 @@ export class AppChannel implements AppLink {}for (const listener of [...this.closeListeners]) listener();this.closeListeners.clear();+ return this.closing;}private receive(chunk: string): void {+ if (!this.open) return;this.buffer += chunk;for (let end = this.buffer.indexOf("\n"); end >= 0; end = this.buffer.indexOf("\n")) {const line = this.buffer.slice(0, end);@@ -184,7 +201,10 @@ export class AppChannel implements AppLink {if (frame.kind !== "request" || typeof frame.method !== "string") return;const { id, method } = frame;Promise.resolve()- .then(() => this.handler(method, frame.params))+ .then(() => {+ if (!this.open) throw new Error("The Gentle Dot app closed its channel.");+ return this.handler(method, frame.params);+ }).then((result) => this.write({ kind: "response", id, result: result ?? {} }),(error: Error) => this.write({ kind: "response", id, error: error.message }),@@ -220,6 +240,8 @@ export function childInherits(identity: string,stdio: StdioOptions = ["ignore", "pipe", "ignore"],) {+ // Unix dev:ino equality cannot prove Windows handle exclusion; fail closed without probing.+ if (process.platform === "win32") return true;const script = `try{const s=require("fs").fstatSync(${fd},{bigint:true});process.stdout.write(s.dev+":"+s.ino)}catch{}`;const probe = spawnSync(process.execPath, ["-e", script], { stdio, encoding: "utf8", timeout: 10_000 });// A probe that could not run proves nothing: treat it as a leak.@@ -239,6 +261,9 @@ export interface InheritedChannelOptions extends AppChannelOptions {* holding it could act as the app.*/export function inheritedAppSocket(options: InheritedChannelOptions = {}): Socket | undefined {+ // No equivalent Windows transport/exclusion is established yet. Do not inspect or wrap a+ // Windows handle as a Unix socket; acquisition stays unavailable, independently of the protocol.+ if (process.platform === "win32") return undefined;const fd = options.fd ?? APP_FD;if (process.env.NODE_CHANNEL_FD === String(fd)) return undefined;let identity: string;diff --git a/packages/daemon/src/windows-app-channel.ts b/packages/daemon/src/windows-app-channel.tsnew file mode 100644index 0000000..89a699c--- /dev/null+++ b/packages/daemon/src/windows-app-channel.ts@@ -0,0 +1,358 @@+import { createRequire } from "node:module";+import { Duplex } from "node:stream";+import { fileURLToPath } from "node:url";+import { isMainThread } from "node:worker_threads";+import { windowsStopArtifact } from "./windows-stop.ts";++export interface NativeAppChannelSnapshot {+ phase: "open" | "stopping" | "closed" | "retained_failure";+ error: number;+ eof: boolean;+ pendingIo: boolean;+ readableBytes: number;+ queuedBytes: number;+ queuedItems: number;+ acceptedWrite: bigint;+ completedWrite: bigint;+}+export interface NativeAppChannelOwner {+ poll(): NativeAppChannelSnapshot;+ status(): NativeAppChannelSnapshot;+ read(maxBytes: number): Buffer;+ write(bytes: Buffer): {+ admission: "accepted" | "backpressure" | "stopped" | "invalid" | "allocation_failed";+ ticket: bigint;+ };+ stop(mode: "drain" | "abort"): NativeAppChannelSnapshot;+ /** Returns PRE-disposal status. No method is legal after successful release. */+ release(): NativeAppChannelSnapshot;+}+export interface NativeAppChannelAPI {+ adoptAppChannelFd3(exclusiveStartupReservation: true): NativeAppChannelOwner;+}+export interface WindowsAppChannelOptions {+ /** Caller MUST reserve fd3 exclusively, on the main startup loop, before ANY spawn.+ * This assertion and absence of visible IPC do not prove absence of aliases. */+ exclusiveFd3Startup: true;+ closeTimeoutMs?: number;+}+export interface WindowsAppChannelCloseResult {+ mode: "drain" | "abort";+ /** Delivery means ordered native completion, NOT a peer protocol acknowledgement. */+ drained: boolean;+}+// If release throws before disposal (e.g. snapshot OOM), retain the exact owner.+// Successful emergency release delegates uncertain I/O lifetime to native quarantine.+const retainedOwners = new Set<NativeAppChannelOwner>();+type WriteCallback = (error?: Error | null) => void;+const productionChannels = new WeakSet<object>();++/** Only production construction with actual startup facts and successful native+ * ownership transfer admits Windows descendants. Not a child-inspection proof. */+export function isProductionWindowsAppChannel(stream: object): stream is WindowsAppChannel {+ return (+ productionChannels.has(stream) &&+ stream instanceof WindowsAppChannel &&+ !stream.destroyed &&+ !stream.writableEnded+ );+}++/** Includes the portable adapter test seam; used only to await transport cleanup. */+export function isWindowsAppChannel(stream: object): stream is WindowsAppChannel {+ return stream instanceof WindowsAppChannelDuplex;+}++/** Explicit Windows-only Duplex. Importing this module neither loads nor adopts fd3.+ * All native methods run synchronously on this JS loop with their original receiver.+ * close(drain) ends/flushed Node's writable queue before requesting native drain;+ * close(abort) may discard undelivered writes and NEVER certifies drain.+ * First close wins. Deadline/error rejects, disposes into native quarantine, and+ * never forces process exit. Native env cleanup handles environment destruction. */+interface StartupFacts {+ mainThread: boolean;+ ipcChannel: boolean;+ ipcConnected: boolean;+ channelFdPresent: boolean;+ platform: NodeJS.Platform;+}++/** Orchestration-only seam: always requires an injected fake addon and startup+ * facts. Production construction above never accepts injected startup facts. */+export function createWindowsAppChannelForTesting(+ options: WindowsAppChannelOptions & { loadNative: () => NativeAppChannelAPI },+ facts: StartupFacts,+): WindowsAppChannel {+ if (typeof options?.loadNative !== "function")+ throw new TypeError("App channel test loader must be a function");+ return new WindowsAppChannelDuplex(options, facts, options.loadNative);+}++class WindowsAppChannelDuplex extends Duplex {+ #owner: NativeAppChannelOwner;+ #snapshot: NativeAppChannelSnapshot;+ #timeoutMs: number;+ #pollTimer?: NodeJS.Timeout;+ #deadline?: NodeJS.Timeout;+ #reading = false;+ #driving = false;+ #disposed = false;+ #stopping = false;+ #failure?: Error;+ #abortError?: Error;+ #write?: { bytes: Buffer; callback: WriteCallback; ticket?: bigint; capacity?: [number, number] };+ #final?: WriteCallback;+ #close?: Promise<WindowsAppChannelCloseResult>;+ #resolve?: (result: WindowsAppChannelCloseResult) => void;+ #reject?: (error: Error) => void;+ #mode: "drain" | "abort" = "abort";++ constructor(options: WindowsAppChannelOptions, facts: StartupFacts, loadNative: () => NativeAppChannelAPI) {+ super({ readableHighWaterMark: 65536, writableHighWaterMark: 65536, autoDestroy: true });+ if (options.exclusiveFd3Startup !== true || !facts.mainThread)+ throw new Error("Exclusive main-thread fd3 startup required");+ if (facts.ipcChannel || facts.ipcConnected || facts.channelFdPresent)+ throw new Error("App channel startup IPC collision");+ if (facts.platform !== "win32") throw new Error("Windows app channel requires Windows");+ this.#timeoutMs = options.closeTimeoutMs ?? 5000;+ if (!Number.isSafeInteger(this.#timeoutMs) || this.#timeoutMs < 1)+ throw new Error("Invalid app channel close deadline");+ const native = loadNative();+ if (typeof native?.adoptAppChannelFd3 !== "function")+ throw new Error("Windows app channel addon unavailable");+ this.#owner = native.adoptAppChannelFd3(true);+ try {+ this.#snapshot = this.#owner.status();+ if (this.#snapshot.phase !== "open" || this.#snapshot.error || this.#snapshot.eof)+ throw new Error("Windows app channel ownership initialization failed");+ } catch (error) {+ try {+ this.#owner.stop("abort");+ } catch {+ /* release retains uncertain native ownership */+ }+ this.dispose();+ throw error;+ }+ this.schedule();+ }++ close(mode: "drain" | "abort" = "drain"): Promise<WindowsAppChannelCloseResult> {+ if (this.#close) return this.#close;+ this.#mode = mode;+ this.#close = new Promise((resolve, reject) => {+ this.#resolve = resolve;+ this.#reject = reject;+ });+ void this.#close.catch(() => {}); // observed even when destroy initiated close+ if (this.#disposed) {+ this.#reject?.(this.#failure ?? new Error("App channel already disposed"));+ return this.#close;+ }+ this.#deadline = setTimeout(() => {+ this.#failure ??= new Error("App channel close deadline exceeded");+ this.finish(false);+ }, this.#timeoutMs);+ if (mode === "drain" && !this.#failure) this.end();+ else {+ this.#abortError ??= new Error("App channel aborted");+ this.rejectWrite(this.#failure ?? this.#abortError);+ this.stop("abort");+ }+ this.drive();+ return this.#close;+ }++ override _read(): void {+ this.#reading = true;+ this.drive();+ }+ override _write(chunk: Buffer, _encoding: BufferEncoding, callback: WriteCallback): void {+ if (this.#disposed || this.#stopping || this.#failure) {+ callback(this.#failure ?? new Error("App channel stopped"));+ return;+ }+ if (!chunk.length) {+ callback();+ return;+ }+ if (chunk.length > 2 * 1024 * 1024) {+ callback(new Error("App channel write exceeds 2 MiB"));+ return;+ }+ this.#write = { bytes: chunk, callback };+ this.drive();+ }+ override _final(callback: WriteCallback): void {+ this.#final = callback;+ if (!this.#close) void this.close("drain");+ this.stop("drain");+ this.drive();+ }+ override _destroy(error: Error | null, callback: WriteCallback): void {+ if (error !== this.#abortError) this.#failure ??= error ?? undefined;+ if (!this.#disposed) {+ // Aborting an existing drain can discard Node-buffered writes whose+ // bytes have no native ticket. Ticket equality cannot certify that drain.+ if (this.#close && this.#mode === "drain")+ this.#failure ??= new Error("App channel drain interrupted by destruction");+ if (!this.#close) void this.close("abort");+ else {+ this.rejectWrite(this.#failure ?? new Error("App channel aborted"));+ this.stop("abort");+ this.schedule();+ }+ }+ callback(this.#failure ?? error);+ }++ private observe(status: NativeAppChannelSnapshot): void {+ this.#snapshot = status;+ if (status.error) this.#failure ??= new Error(`Windows app channel native error ${status.error}`);+ else if (status.eof) this.#failure ??= new Error("App channel EOF");+ else if (status.phase === "retained_failure")+ this.#failure ??= new Error("App channel native ownership retained");+ }+ private stop(mode: "drain" | "abort"): void {+ if (this.#disposed || (this.#stopping && mode === "drain")) return;+ this.#stopping = true;+ try {+ this.observe(this.#owner.stop(mode));+ } catch {+ this.#failure ??= new Error("App channel stop failed");+ }+ }+ private drive(): void {+ if (this.#disposed || this.#driving) return;+ this.#driving = true;+ try {+ this.observe(this.#owner.poll());+ if (this.#failure) {+ // observe() has already bound the first failure, so callback reentry+ // cannot admit new writes. Completion still certifies an earlier ticket.+ const delivered = this.#write;+ if (delivered?.ticket !== undefined && delivered.ticket <= this.#snapshot.completedWrite) {+ this.#write = undefined;+ delivered.callback();+ }+ this.rejectWrite(this.#failure);+ if (!this.#close) void this.close("abort");+ this.stop("abort");+ this.destroy(this.#failure);+ }+ const pending = this.#write;+ if (pending && !this.#failure && !this.#stopping) {+ if (+ pending.ticket === undefined &&+ (!pending.capacity ||+ this.#snapshot.queuedBytes < pending.capacity[0] ||+ this.#snapshot.queuedItems < pending.capacity[1])+ ) {+ const admission = this.#owner.write(pending.bytes);+ if (admission.admission === "accepted") pending.ticket = admission.ticket;+ else if (admission.admission === "backpressure")+ pending.capacity = [this.#snapshot.queuedBytes, this.#snapshot.queuedItems];+ else throw new Error("App channel write admission failed");+ }+ if (pending.ticket !== undefined && pending.ticket <= this.#snapshot.completedWrite) {+ this.#write = undefined;+ pending.callback();+ }+ }+ if (this.#reading && !this.#stopping && !this.#failure && this.#snapshot.readableBytes) {+ const bytes = this.#owner.read(65536);+ if (bytes.length) this.#reading = this.push(bytes);+ }+ if (this.#snapshot.phase === "closed" || this.#snapshot.phase === "retained_failure") {+ if (!this.#close) {+ this.#failure ??= new Error("App channel closed unexpectedly");+ void this.close("abort");+ }+ const drained =+ this.#mode === "drain" &&+ !this.#failure &&+ this.#snapshot.phase === "closed" &&+ this.#snapshot.acceptedWrite === this.#snapshot.completedWrite;+ if (this.#mode === "drain" && !drained)+ this.#failure ??= new Error("App channel writes were not drained");+ this.finish(drained);+ }+ } catch {+ // write() may have accepted before an envelope/BigInt allocation throws.+ // Inspect for the first native error, but NEVER retry the uncertain bytes.+ try {+ this.observe(this.#owner.status());+ } catch {+ /* retain prior evidence */+ }+ this.#failure ??= new Error("App channel native operation failed");+ this.rejectWrite(this.#failure);+ if (!this.#close) void this.close("abort");+ this.stop("abort");+ this.destroy(this.#failure);+ } finally {+ this.#driving = false;+ this.schedule();+ }+ }+ private schedule(): void {+ if (this.#disposed || this.#pollTimer) return;+ // A pending read is active I/O, not idle spinning. When the native read+ // buffer is full and JS is paused, leave it bounded until _read resumes.+ if (!this.#stopping && !this.#write && !this.#snapshot.pendingIo && !this.#reading) return;+ this.#pollTimer = setTimeout(() => {+ this.#pollTimer = undefined;+ this.drive();+ }, 10);+ }+ private rejectWrite(error: Error): void {+ const pending = this.#write;+ this.#write = undefined;+ pending?.callback(error);+ }+ private dispose(): void {+ this.#disposed = true;+ clearTimeout(this.#pollTimer);+ clearTimeout(this.#deadline);+ this.#pollTimer = this.#deadline = undefined;+ try {+ this.#owner.release();+ } catch {+ retainedOwners.add(this.#owner);+ this.#failure ??= new Error("App channel disposal failed");+ }+ }+ private finish(drained: boolean): void {+ if (this.#disposed) return;+ this.dispose(); // release is NEVER the evidence for drain+ this.rejectWrite(this.#failure ?? new Error("App channel closed"));+ const final = this.#final;+ this.#final = undefined;+ final?.(this.#failure);+ if (this.#failure) this.#reject?.(this.#failure);+ else this.#resolve?.({ mode: this.#mode, drained });+ this.destroy(this.#failure);+ }+}++/** Production entry: actual process facts and the default artifact loader are+ * mandatory. Injected participants belong only to the unbranded test factory. */+export class WindowsAppChannel extends WindowsAppChannelDuplex {+ constructor(options: WindowsAppChannelOptions) {+ // Refuse injection even from untyped JS or a structurally compatible object.+ // No caller-provided loader/boolean can mint production ownership admission.+ if ("loadNative" in options) throw new Error("Production app channel does not accept an injected loader");+ super(+ options,+ {+ mainThread: isMainThread,+ ipcChannel: Boolean(process.channel),+ ipcConnected: Boolean(process.connected),+ channelFdPresent: process.env.NODE_CHANNEL_FD !== undefined,+ platform: process.platform,+ },+ () => createRequire(import.meta.url)(fileURLToPath(windowsStopArtifact())) as NativeAppChannelAPI,+ );+ productionChannels.add(this);+ }+}diff --git a/packages/daemon/src/windows-stop.ts b/packages/daemon/src/windows-stop.tsnew file mode 100644index 0000000..0af528e--- /dev/null+++ b/packages/daemon/src/windows-stop.ts@@ -0,0 +1,7 @@+/** Source lives in src/, while the bundle lives directly in daemon/. */+export function windowsStopArtifact(entry = new URL(import.meta.url)): URL {+ return new URL(+ entry.pathname.endsWith(".ts") ? "../native/windows-stop.node" : "./native/windows-stop.node",+ entry,+ );+}diff --git a/packages/daemon/test/app-channel-fd.test.ts b/packages/daemon/test/app-channel-fd.test.tsindex fe61fa5..cdc993e 100644--- a/packages/daemon/test/app-channel-fd.test.ts+++ b/packages/daemon/test/app-channel-fd.test.ts@@ -5,8 +5,9 @@ import { spawn } from "node:child_process";import { createServer, type Socket, connect as unixConnect } from "node:net";import { join } from "node:path";import { fileURLToPath } from "node:url";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, expect, it } from "vitest";import { tempDir } from "./helpers.ts";+import { describeWithInheritedAppChannel } from "./support/windows.ts";const CHILD = fileURLToPath(new URL("./fixtures/app-channel-child.ts", import.meta.url));@@ -59,7 +60,7 @@ async function runChild(mode: "normal" | "leak") {return { code, stdout, stderr, lines };}-describe("the app channel on fd 3 (S25.1)", () => {+describeWithInheritedAppChannel("the app channel on fd 3 (S25.1)", () => {it("is opened by the daemon and never reaches the children it spawns", async () => {const { code, stderr, lines } = await runChild("normal");expect(code, stderr).toBe(0);diff --git a/packages/daemon/test/app-channel-platform.test.ts b/packages/daemon/test/app-channel-platform.test.tsnew file mode 100644index 0000000..09ab945--- /dev/null+++ b/packages/daemon/test/app-channel-platform.test.ts@@ -0,0 +1,47 @@+import { spawnSync } from "node:child_process";+import { fstatSync } from "node:fs";+import { Socket } from "node:net";+import { afterEach, describe, expect, it, vi } from "vitest";+import { childInherits, inheritedAppSocket, openInheritedChannel } from "../src/app-channel.ts";++vi.mock("node:child_process", () => ({ spawnSync: vi.fn() }));+vi.mock("node:fs", () => ({+ closeSync: vi.fn(),+ fstatSync: vi.fn(() => {+ throw new Error("Unix descriptor inspection must not run on Windows");+ }),+}));+vi.mock("node:net", () => ({ Socket: vi.fn() }));++const descriptor = Object.getOwnPropertyDescriptor(process, "platform");+if (!descriptor) throw new Error("process.platform has no own property descriptor");+const platformDescriptor: PropertyDescriptor = descriptor;+afterEach(() => {+ Object.defineProperty(process, "platform", platformDescriptor);+ vi.clearAllMocks();+});++// Dispatch tests only: changing this property does not emulate native Windows handles.+describe("app channel acquisition on Windows", () => {+ it("refuses socket acquisition before any Unix descriptor inspection or wrapping", () => {+ Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });+ const probe = vi.fn();+ expect(inheritedAppSocket({ probe })).toBeUndefined();+ expect(fstatSync).not.toHaveBeenCalled();+ expect(probe).not.toHaveBeenCalled();+ expect(Socket).not.toHaveBeenCalled();+ });++ it("leaves the public channel opener disconnected without a Windows transport", () => {+ Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });+ expect(openInheritedChannel()).toBeUndefined();+ expect(fstatSync).not.toHaveBeenCalled();+ expect(Socket).not.toHaveBeenCalled();+ });++ it("treats the Unix inheritance probe as unproven without spawning on Windows", () => {+ Object.defineProperty(process, "platform", { ...platformDescriptor, value: "win32" });+ expect(childInherits(3, "0:0")).toBe(true);+ expect(spawnSync).not.toHaveBeenCalled();+ });+});diff --git a/packages/daemon/test/app-channel.test.ts b/packages/daemon/test/app-channel.test.tsindex f823d2c..ee9e16a 100644--- a/packages/daemon/test/app-channel.test.ts+++ b/packages/daemon/test/app-channel.test.ts@@ -11,6 +11,7 @@ import { fakeApp } from "./fake-app.ts";import { fakeAuthRuntime } from "./fake-auth-runtime.ts";import { oauthOptions } from "./fake-oauth.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";+import { describeWithAppChannel } from "./support/windows.ts";const HELPER = "http://127.0.0.1:51234/mcp";const KEY = "s3cr3t-Computer-Key-0123456789abcdef";@@ -133,7 +134,7 @@ async function draftAndScan(window: Awaited<ReturnType<typeof connect>>) {return { draftId: draft.draftId, importId };}-describe("a window with the access key (S25.2)", () => {+describeWithAppChannel("a window with the access key (S25.2)", () => {it("cannot change connectors, approve a draft, import, or register the computer: each is refused and nothing changes", async () => {const window = await setup();const { draftId, importId } = await draftAndScan(window);@@ -178,7 +179,7 @@ describe("a window with the access key (S25.2)", () => {});});-describe("the desktop app's channel (S25.2, S25.3)", () => {+describeWithAppChannel("the desktop app's channel (S25.2, S25.3)", () => {it("changes a connector's mode; widening it is confirmed natively, narrowing it is not", async () => {const { app, clientId, saved, find, d } = await setup();app.answer("allow");diff --git a/packages/daemon/test/support/windows.ts b/packages/daemon/test/support/windows.tsnew file mode 100644index 0000000..7e46c11--- /dev/null+++ b/packages/daemon/test/support/windows.ts@@ -0,0 +1,19 @@+import { describe } from "vitest";++export const WINDOWS_APP_CHANNEL =+ "Windows admits only the native production app channel (daemon.ts startDaemon); the protocol is covered on Linux and macOS";++export const INHERITED_APP_CHANNEL =+ "Windows uses the native production channel, not inherited Unix fd 3; Linux and macOS cover fd 3";++const windows = process.platform === "win32";++/** Only daemon tests requiring a generic Duplex app channel lack Windows coverage. */+export const describeWithAppChannel: ReturnType<typeof describe.skipIf> = describe.skipIf(windows);++export const describeWithInheritedAppChannel: ReturnType<typeof describe.skipIf> = describe.skipIf(windows);++if (windows) {+ console.info(`Windows-only test skip: ${WINDOWS_APP_CHANNEL}`);+ console.info(`Windows-only test skip: ${INHERITED_APP_CHANNEL}`);+}diff --git a/packages/daemon/test/windows-app-channel.test.ts b/packages/daemon/test/windows-app-channel.test.tsnew file mode 100644index 0000000..4707132--- /dev/null+++ b/packages/daemon/test/windows-app-channel.test.ts@@ -0,0 +1,499 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { AppChannel } from "../src/app-channel.ts";+import {+ createWindowsAppChannelForTesting,+ isProductionWindowsAppChannel,+ type NativeAppChannelOwner,+ type NativeAppChannelSnapshot,+ WindowsAppChannel,+} from "../src/windows-app-channel.ts";++// These fakes verify JS orchestration only, not Windows adoption or native I/O.+const startupFacts = {+ mainThread: true,+ ipcChannel: false,+ ipcConnected: false,+ channelFdPresent: false,+ platform: "win32" as const,+};+function fixture() {+ const status: NativeAppChannelSnapshot = {+ phase: "open",+ error: 0,+ eof: false,+ pendingIo: true,+ readableBytes: 0,+ queuedBytes: 0,+ queuedItems: 0,+ acceptedWrite: 0n,+ completedWrite: 0n,+ };+ let bytes: Buffer = Buffer.alloc(0);+ let pressure = false;+ let uncertain = false;+ let released: NativeAppChannelSnapshot | undefined;+ const calls: string[] = [];+ const owner: NativeAppChannelOwner = {+ status() {+ expect(this).toBe(owner);+ return { ...status };+ },+ poll() {+ expect(this).toBe(owner);+ calls.push("poll");+ return { ...status };+ },+ read(max) {+ expect(this).toBe(owner);+ calls.push("read");+ const result = bytes.subarray(0, max);+ bytes = bytes.subarray(result.length);+ status.readableBytes = bytes.length;+ return result;+ },+ write(chunk) {+ expect(this).toBe(owner);+ calls.push(`write:${chunk.toString()}`);+ if (pressure) return { admission: "backpressure", ticket: 0n };+ status.acceptedWrite++;+ status.queuedBytes += chunk.length;+ status.queuedItems++;+ if (uncertain) throw new Error("allocation after acceptance");+ return { admission: "accepted", ticket: status.acceptedWrite };+ },+ stop(mode) {+ expect(this).toBe(owner);+ calls.push(`stop:${mode}`);+ if (status.phase === "open") status.phase = "stopping";+ return { ...status };+ },+ release() {+ expect(this).toBe(owner);+ calls.push("release");+ return released ?? { ...status };+ },+ };+ const factory = vi.fn(() => ({+ adoptAppChannelFd3: (reservation: true) => {+ expect(reservation).toBe(true);+ return owner;+ },+ }));+ const stream = () => {+ const result = createWindowsAppChannelForTesting(+ { exclusiveFd3Startup: true, loadNative: factory, closeTimeoutMs: 100 },+ startupFacts,+ );+ result.on("error", () => {});+ return result;+ };+ return {+ status,+ calls,+ factory,+ stream,+ data(value: Buffer) {+ bytes = value;+ status.readableBytes = bytes.length;+ },+ pressure(value: boolean) {+ pressure = value;+ },+ uncertain() {+ uncertain = true;+ },+ releaseReturns(snapshot: NativeAppChannelSnapshot) {+ released = snapshot;+ },+ };+}+async function tick() {+ await vi.advanceTimersByTimeAsync(10);+}+async function terminate(f: ReturnType<typeof fixture>, stream: WindowsAppChannel) {+ const closing = stream.close("abort");+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await closing;+}+beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++describe("Windows app channel lifecycle integration", () => {+ it("a first abort makes later AppChannel drain reject instead of certifying closure", async () => {+ const f = fixture();+ const s = f.stream();+ const app = new AppChannel(s);+ const aborted = s.close("abort");+ const closing = app.close();+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await expect(aborted).resolves.toEqual({ mode: "abort", drained: false });+ await expect(closing).rejects.toThrow("not drained");+ expect(app.close()).toBe(closing);+ expect(app.connected).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });+ it("logically refuses approvals before awaited native drain without recursive close", async () => {+ const f = fixture();+ const s = f.stream();+ const app = new AppChannel(s);+ const approval = app.approve({ connector: "test", action: "send", preview: [] });+ let notifications = 0;+ app.onClose(() => {+ notifications++;+ void app.close();+ });+ const closing = app.close();+ expect(app.connected).toBe(false);+ expect(notifications).toBe(1);+ await expect(approval).resolves.toBe(false);+ await expect(app.approve({ connector: "test", action: "send", preview: [] })).rejects.toThrow(+ "not connected",+ );+ let finished = false;+ void Promise.resolve(closing).then(() => {+ finished = true;+ });+ await Promise.resolve();+ expect(finished).toBe(false);+ f.status.completedWrite = f.status.acceptedWrite;+ await tick();+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await closing;+ expect(notifications).toBe(1);+ expect(vi.getTimerCount()).toBe(0);+ });+ it.each(["eof", "error"])(+ "unexpected native %s logically closes while disposal is still pending",+ async (cause) => {+ const f = fixture();+ const s = f.stream();+ const app = new AppChannel(s);+ const notify = vi.fn();+ app.onClose(notify);+ const approval = app.approve({ connector: "test", action: "send", preview: [] });+ if (cause === "eof") f.status.eof = true;+ else f.status.error = 123;+ await tick();+ expect(app.connected).toBe(false);+ expect(notify).toHaveBeenCalledTimes(1);+ expect(f.calls).not.toContain("release");+ await expect(approval).resolves.toBe(false);+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await expect(app.close()).rejects.toThrow();+ expect(vi.getTimerCount()).toBe(0);+ },+ );+});++describe("Windows app channel orchestration", () => {+ it("reads normally and leaves native bytes buffered under readable backpressure", async () => {+ const f = fixture();+ const s = f.stream();+ f.data(Buffer.alloc(65536, 65));+ s.read(0);+ await tick();+ expect(f.calls.filter((x) => x === "read")).toHaveLength(1);+ f.data(Buffer.from("later"));+ await tick();+ expect(f.calls.filter((x) => x === "read")).toHaveLength(1);+ expect(s.read(65536).length).toBe(65536);+ await tick();+ expect(s.read().toString()).toBe("later");+ await terminate(f, s);+ expect(vi.getTimerCount()).toBe(0);+ });+ it("settles ordered writes only at completed BigInt tickets, not partial progress", async () => {+ const f = fixture();+ const s = f.stream();+ const callbacks: string[] = [];+ f.status.acceptedWrite = 9007199254740992n;+ f.status.completedWrite = f.status.acceptedWrite;+ s.write("one", () => callbacks.push("one"));+ s.write("two", () => callbacks.push("two"));+ await tick();+ expect(callbacks).toEqual([]);+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one"]);+ f.status.completedWrite++;+ await tick();+ expect(callbacks).toEqual(["one"]);+ f.status.completedWrite++;+ await tick();+ expect(callbacks).toEqual(["one", "two"]);+ await terminate(f, s);+ });+ it("retries queue-full only after capacity drops without discarding or reordering", async () => {+ const f = fixture();+ f.pressure(true);+ f.status.queuedBytes = 100;+ f.status.queuedItems = 64;+ const s = f.stream();+ s.write("one");+ s.write("two");+ await tick();+ await tick();+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one"]);+ f.pressure(false);+ f.status.queuedBytes = 0;+ f.status.queuedItems = 0;+ await tick();+ f.status.completedWrite = 1n;+ await tick();+ // Completing the first callback queues Node's next write without reentering+ // the active native poll. Admission occurs on the next scheduled poll.+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one", "write:one"]);+ await tick();+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one", "write:one", "write:two"]);+ await terminate(f, s);+ });+ it("preserves first native error and rejects undelivered callbacks", async () => {+ const f = fixture();+ const s = f.stream();+ const errors: Array<Error | null | undefined> = [];+ s.write("one", (e) => errors.push(e));+ s.write("two", (e) => errors.push(e));+ f.status.error = 123;+ await tick();+ f.status.error = 456;+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ expect(errors).toHaveLength(2);+ expect(errors.every((e) => e?.message.includes("123"))).toBe(true);+ await expect(s.close()).rejects.toThrow("123");+ expect(f.calls.filter((x) => x === "release")).toHaveLength(1);+ });+ it("never retries a write whose thrown result could follow acceptance", async () => {+ const f = fixture();+ f.uncertain();+ const s = f.stream();+ s.write("one", () => {});+ await tick();+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one"]);+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await expect(s.close()).rejects.toThrow();+ });+ it("drain waits for Node queued writes and terminal delivery before release; close is idempotent", async () => {+ const f = fixture();+ const s = f.stream();+ s.write("one");+ s.write("two");+ const close = s.close();+ expect(s.close()).toBe(close);+ await tick();+ expect(f.calls).not.toContain("stop:drain");+ f.status.completedWrite = 1n;+ await tick();+ f.status.completedWrite = 2n;+ await tick();+ expect(f.calls).toContain("stop:drain");+ expect(f.calls).not.toContain("release");+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await expect(close).resolves.toEqual({ mode: "drain", drained: true });+ expect(vi.getTimerCount()).toBe(0);+ });+ it("rejects an interrupted drain even when admitted tickets were all completed", async () => {+ const f = fixture();+ const s = f.stream();+ const callbacks: Array<{ name: string; error: Error | null | undefined }> = [];+ s.write("one", (error) => callbacks.push({ name: "one", error }));+ s.write("two", (error) => callbacks.push({ name: "two", error }));+ f.status.completedWrite = 1n;+ const close = s.close("drain"); // settles one, but two is still only Node-buffered+ s.destroy();+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ expect(f.status.acceptedWrite).toBe(f.status.completedWrite);+ await expect(close).rejects.toThrow("drain interrupted");+ expect(s.close("abort")).toBe(close);+ expect(callbacks.map((x) => x.name)).toEqual(["one", "two"]);+ expect(callbacks[0]?.error == null).toBe(true);+ expect(callbacks[1]?.error?.message).toContain("drain interrupted");+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one"]);+ expect(f.calls.filter((x) => x === "release")).toHaveLength(1);+ expect(vi.getTimerCount()).toBe(0);+ await tick();+ expect(callbacks).toHaveLength(2);+ });+ it.each(["EOF", "native error"])(+ "settles delivered ticket before rejecting remaining work on terminal %s",+ async (cause) => {+ const f = fixture();+ const s = f.stream();+ const callbacks: Array<{ name: string; error: Error | null | undefined }> = [];+ s.write("one", (error) => callbacks.push({ name: "one", error }));+ s.write("two", (error) => callbacks.push({ name: "two", error }));+ f.status.completedWrite = 1n;+ if (cause === "EOF") f.status.eof = true;+ else f.status.error = 123;+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ const firstCause = cause === "EOF" ? "EOF" : "123";+ expect(callbacks.map((x) => x.name)).toEqual(["one", "two"]);+ expect(callbacks[0]?.error == null).toBe(true);+ expect(callbacks[1]?.error?.message).toContain(firstCause);+ expect(f.calls.filter((x) => x.startsWith("write:"))).toEqual(["write:one"]);+ f.status.error = 456;+ await tick();+ await expect(s.close()).rejects.toThrow(firstCause);+ expect(f.calls.filter((x) => x === "release")).toHaveLength(1);+ expect(callbacks).toHaveLength(2);+ expect(vi.getTimerCount()).toBe(0);+ },+ );+ it("abort is disposal, not successful drain", async () => {+ const f = fixture();+ const s = f.stream();+ s.write("one", () => {});+ const close = s.close("abort");+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await expect(close).resolves.toEqual({ mode: "abort", drained: false });+ expect(f.calls).toContain("release");+ });+ it("waits through the native stopping phase and certifies drain only at closed", async () => {+ const f = fixture();+ const s = f.stream();+ let settled = false;+ const close = s.close("drain");+ void close.then(+ () => (settled = true),+ () => (settled = true),+ );+ await tick();+ expect(f.calls).toContain("stop:drain");+ expect(f.status.phase).toBe("stopping");+ await tick();+ await tick();+ expect(settled).toBe(false);+ expect(f.calls).not.toContain("release");+ f.status.phase = "closed";+ f.status.pendingIo = false;+ await tick();+ await expect(close).resolves.toEqual({ mode: "drain", drained: true });+ expect(f.calls.filter((x) => x === "release")).toHaveLength(1);+ });+ it("rejects drain at retained_failure even with every admitted ticket completed", async () => {+ const f = fixture();+ const s = f.stream();+ const close = s.close("drain");+ await tick();+ f.status.phase = "retained_failure";+ f.status.pendingIo = false;+ await tick();+ expect(f.status.acceptedWrite).toBe(f.status.completedWrite);+ await expect(close).rejects.toThrow("native ownership retained");+ expect(f.calls.filter((x) => x === "release")).toHaveLength(1);+ expect(vi.getTimerCount()).toBe(0);+ });+ it("never takes release()'s pre-release snapshot as drain evidence", async () => {+ const drainedLooking: NativeAppChannelSnapshot = {+ phase: "closed",+ error: 0,+ eof: false,+ pendingIo: false,+ readableBytes: 0,+ queuedBytes: 0,+ queuedItems: 0,+ acceptedWrite: 0n,+ completedWrite: 0n,+ };+ const failed = fixture();+ failed.releaseReturns(drainedLooking);+ const failing = failed.stream().close("drain");+ await tick();+ failed.status.phase = "retained_failure";+ failed.status.pendingIo = false;+ await tick();+ await expect(failing).rejects.toThrow("native ownership retained");++ const drained = fixture();+ drained.releaseReturns({ ...drainedLooking, phase: "open", pendingIo: true, acceptedWrite: 5n });+ const draining = drained.stream().close("drain");+ await tick();+ drained.status.phase = "closed";+ drained.status.pendingIo = false;+ await tick();+ await expect(draining).resolves.toEqual({ mode: "drain", drained: true });+ expect(drained.calls.filter((x) => x === "release")).toHaveLength(1);+ });+ it("rejects false drain, EOF and deadline while safely disposing uncertain ownership", async () => {+ for (const cause of ["mismatch", "eof", "deadline"]) {+ const f = fixture();+ const s = f.stream();+ const close = s.close();+ if (cause === "mismatch") {+ f.status.phase = "closed";+ f.status.acceptedWrite = 1n;+ }+ if (cause === "eof") f.status.eof = true;+ await vi.advanceTimersByTimeAsync(100);+ await expect(close).rejects.toThrow();+ expect(f.calls.filter((x) => x === "release")).toHaveLength(1);+ expect(vi.getTimerCount()).toBe(0);+ }+ });+ it("rejects each injected visible IPC collision before loading or adoption", () => {+ for (const key of ["ipcChannel", "ipcConnected", "channelFdPresent"] as const) {+ const f = fixture();+ expect(() =>+ createWindowsAppChannelForTesting(+ { exclusiveFd3Startup: true, loadNative: f.factory },+ { ...startupFacts, [key]: true },+ ),+ ).toThrow("IPC");+ expect(f.factory).not.toHaveBeenCalled();+ }+ });+ it.each([undefined, null, 17])("rejects invalid JS test loader %s before construction", (loader) => {+ const f = fixture();+ // An independently invalid deadline makes RED safe: the old implementation+ // fails there before it could fall back to loading the real addon.+ const options = {+ exclusiveFd3Startup: true,+ closeTimeoutMs: 0,+ ...(loader === undefined ? {} : { loadNative: loader }),+ };+ expect(() =>+ createWindowsAppChannelForTesting(+ options as unknown as Parameters<typeof createWindowsAppChannelForTesting>[0],+ startupFacts,+ ),+ ).toThrow("test loader");+ expect(f.factory).not.toHaveBeenCalled();+ expect(f.calls).toEqual([]);+ expect(vi.getTimerCount()).toBe(0);+ });+ it("production entry rejects injected loaders; a successful fake owner remains unbranded", async () => {+ const f = fixture();+ const injected = { exclusiveFd3Startup: true as const, loadNative: f.factory };+ // Injection is refused independently of host platform/IPC. No real loader+ // is invoked and no process facts are altered to simulate native proof.+ expect(() => new WindowsAppChannel(injected)).toThrow("does not accept an injected loader");+ expect(f.factory).not.toHaveBeenCalled();+ const s = f.stream();+ expect(f.factory).toHaveBeenCalledTimes(1);+ expect(isProductionWindowsAppChannel(s)).toBe(false);+ await terminate(f, s);+ });+ it("the real production loading route retains actual Vitest IPC refusal before artifact loading", () => {+ expect(+ Boolean(process.channel) || Boolean(process.connected) || process.env.NODE_CHANNEL_FD !== undefined,+ ).toBe(true);+ expect(() => new WindowsAppChannel({ exclusiveFd3Startup: true })).toThrow("IPC");+ });+});