Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(electron): retain process and transport cleanup owners
morlutoe7df00e80777
diff --git a/docs/testing.md b/docs/testing.mdindex d17d479f9..133a39234 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -232,6 +232,14 @@ after reader finalization, plus active-provider shutdown during preflight.They preserve real filesystem cleanup where possible; mocked launch boundariesdo not establish real Electron teardown or naturally occurring OS failures.+Active Electron cleanup controls retain independent transport and process-family+owners, block replacement captures until recovery, and retry only unresolved+owners. Cover late close acknowledgement and rejection after a wait deadline,+opaque rejection reasons, cancellation during failed finalization, and missing+lineage followed by a confirmed passive family census. Windows controls require+a fresh lineage observation and do not signal cached descendant PIDs after root+termination. Simulated Windows controls do not establish native Windows behavior.+For atomic writes, exercise cancellation on both sides of the documented commitpoint and preserve any publication receipt. A late interruption does not provethat no output was published.diff --git a/src/browser/ElectronCaptureCleanup.boundary.test.ts b/src/browser/ElectronCaptureCleanup.boundary.test.tsnew file mode 100644index 000000000..1fdf98b12--- /dev/null+++ b/src/browser/ElectronCaptureCleanup.boundary.test.ts@@ -0,0 +1,75 @@+import { randomUUID } from "node:crypto";+import { once } from "node:events";+import { expect, it, vi } from "vitest";+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import {+ spawnOwnedProviderProcess,+ ProviderProcessSupervisor,+} from "../process/ProviderProcess.js";+import { observeOwnedProcessLineage } from "../process/ProcessOwnershipObservation.js";+import { ElectronCaptureCleanup } from "./ElectronCaptureCleanup.js";++// An authored idle Node fixture exercises POSIX ownership; it is not Electron.+it.skipIf(process.platform === "win32")(+ "retains transport recovery after real owned process-family cleanup",+ async () => {+ const spawned = await spawnOwnedProviderProcess({+ command: process.execPath,+ arguments: [+ "-e",+ "process.stdout.write('ready'); setInterval(() => {}, 1000)",+ ],+ expectedCommand: null,+ runId: randomUUID(),+ sweepTokenOwnedProcesses: true,+ });+ const supervisor = new ProviderProcessSupervisor({+ ...spawned,+ ownsProcessLifetime: true,+ });+ const scope = new ArtifactResourceScope();+ let denied = true;+ const close = vi.fn(async () => {+ if (denied) throw new Error("authored transport close denial");+ });+ try {+ await once(spawned.process.stdout!, "data");+ const lineage = await observeOwnedProcessLineage(spawned.ownership);+ expect(lineage.status).toBe("verified");+ const owner = new ElectronCaptureCleanup(+ { close },+ spawned.ownership,+ lineage,+ );+ expect(await owner.release(scope)).toMatchObject({+ transport: { kind: "failed" },+ processes: { kind: "released" },+ });+ expect(await supervisor.waitForExit(1000)).toBe(true);+ const error = new ProviderCleanupError(+ "rea-playwright-electron-active",+ owner.pendingResources,+ {},+ );+ owner.bind(error);+ expect(error.cleanupResources).toEqual(["browser_transport"]);+ denied = false;+ await scope.close();+ expect(error.cleanupIncomplete).toBe(false);+ expect(close).toHaveBeenCalledTimes(2);+ } finally {+ denied = false;+ try {+ await scope.close();+ } finally {+ try {+ const stopped = await supervisor.stop();+ expect(stopped.status).not.toBe("incomplete");+ } finally {+ supervisor.dispose();+ }+ }+ }+ },+);diff --git a/src/browser/ElectronCaptureCleanup.test.ts b/src/browser/ElectronCaptureCleanup.test.tsnew file mode 100644index 000000000..7e128152f--- /dev/null+++ b/src/browser/ElectronCaptureCleanup.test.ts@@ -0,0 +1,330 @@+import { afterEach, expect, it, vi } from "vitest";+import { createDeferred } from "../../tests/fixtures/binarySession.js";+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import * as ownershipObservation from "../process/ProcessOwnershipObservation.js";+import * as processCleanup from "./ElectronProcessCleanup.js";+import * as processOwnership from "../process/ProcessOwnership.js";+import type {+ OwnedProcessGroup,+ ProcessLineageObservation,+} from "../process/ProcessOwnership.js";+import { ElectronCaptureCleanup } from "./ElectronCaptureCleanup.js";++const ownership: OwnedProcessGroup = {+ runId: "authored-run-token",+ leaderPid: 424242,+ processGroupId: 424242,+};+const verified: ProcessLineageObservation = {+ status: "verified",+ observedAt: "2026-10-17T00:00:00Z",+ lineage: {+ runId: ownership.runId,+ launcherPid: ownership.leaderPid,+ launcherParentPid: 1,+ processGroupId: ownership.processGroupId,+ descendants: [],+ },+};+const unavailable: ProcessLineageObservation = {+ status: "unavailable",+ observedAt: "2026-10-17T00:00:01Z",+ runId: ownership.runId,+ launcherPid: ownership.leaderPid,+ processGroupId: ownership.processGroupId,+ reason: "authored identity unavailable",+};+afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+});++const bindFailure = (owner: ElectronCaptureCleanup) => {+ const error = new ProviderCleanupError(+ "rea-playwright-electron-active",+ owner.pendingResources,+ {},+ );+ owner.bind(error);+ return error;+};++it("retries only the failed transport while preserving confirmed process release", async () => {+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(verified);+ const processes = vi+ .spyOn(processCleanup, "cleanupElectronProcesses")+ .mockResolvedValue({ cleaned: true, signaled: false });+ let denied = true;+ const close = vi.fn(async () => {+ if (denied) throw new Error("transport denied");+ });+ const owner = new ElectronCaptureCleanup({ close }, ownership, verified);+ const scope = new ArtifactResourceScope();+ await owner.release(scope);+ const original = bindFailure(owner);+ expect(original.cleanupResources).toEqual(["browser_transport"]);+ denied = false;+ await scope.close();+ expect(close).toHaveBeenCalledTimes(2);+ expect(processes).toHaveBeenCalledOnce();+ expect(original.cleanupIncomplete).toBe(false);+});++it("shrinks mixed cleanup and aggregate errors without repeating a released peer", async () => {+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(verified);+ let processDenied = true,+ transportDenied = true;+ const processes = vi+ .spyOn(processCleanup, "cleanupElectronProcesses")+ .mockImplementation(async () =>+ processDenied+ ? { cleaned: false, reason: "process denied" }+ : { cleaned: true, signaled: false },+ );+ const close = vi.fn(async () => {+ if (transportDenied) throw new Error("transport denied");+ });+ const owner = new ElectronCaptureCleanup({ close }, ownership, verified);+ const scope = new ArtifactResourceScope();+ await owner.release(scope);+ const original = bindFailure(owner);+ processDenied = false;+ let aggregate: ProviderCleanupError | undefined;+ try {+ await scope.close();+ } catch (cause) {+ aggregate = new ProviderCleanupError(+ "rea-playwright-electron-active",+ [],+ {},+ );+ bindArtifactFileCleanup(cause, aggregate);+ }+ expect(original.cleanupResources).toEqual(["browser_transport"]);+ expect(aggregate?.cleanupResources).toEqual(["browser_transport"]);+ transportDenied = false;+ await scope.close();+ expect(original.cleanupIncomplete).toBe(false);+ expect(aggregate?.cleanupIncomplete).toBe(false);+ expect(processes).toHaveBeenCalledTimes(2);+ expect(close).toHaveBeenCalledTimes(3);+});++it("joins a timed-out close's late acknowledgement instead of calling close twice", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(verified);+ const processes = vi+ .spyOn(processCleanup, "cleanupElectronProcesses")+ .mockResolvedValue({ cleaned: true, signaled: false });+ const completion = createDeferred<void>();+ const close = vi.fn(() => completion.promise);+ const owner = new ElectronCaptureCleanup({ close }, ownership, verified);+ const scope = new ArtifactResourceScope();+ const pending = owner.release(scope);+ await vi.advanceTimersByTimeAsync(5_001);+ expect(await pending).toMatchObject({+ transport: { kind: "failed" },+ processes: { kind: "released" },+ });+ const original = bindFailure(owner);+ completion.resolve();+ await scope.close();+ expect(close).toHaveBeenCalledOnce();+ expect(processes).toHaveBeenCalledOnce();+ expect(original.cleanupIncomplete).toBe(false);+});++it.each([null, undefined])(+ "retains a physical transport rejection of %j without treating it as success",+ async (reason) => {+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(verified);+ vi.spyOn(processCleanup, "cleanupElectronProcesses").mockResolvedValue({+ cleaned: true,+ signaled: false,+ });+ const close = vi+ .fn()+ .mockRejectedValueOnce(reason)+ .mockResolvedValue(undefined);+ const owner = new ElectronCaptureCleanup({ close }, ownership, verified);+ const scope = new ArtifactResourceScope();+ expect(await owner.release(scope)).toMatchObject({+ transport: { kind: "failed", cause: reason },+ });+ const error = bindFailure(owner);+ await scope.close();+ expect(close).toHaveBeenCalledTimes(2);+ expect(error.cleanupIncomplete).toBe(false);+ },+);++it("retains unknown process identity even after its exact transport closes", async () => {+ const observe = vi.spyOn(ownershipObservation, "observeOwnedProcessLineage");+ const cleanup = vi.spyOn(processCleanup, "cleanupElectronProcesses");+ const owner = new ElectronCaptureCleanup(+ { close: async () => undefined },+ undefined,+ undefined,+ );+ const scope = new ArtifactResourceScope();+ await owner.release(scope);+ const original = bindFailure(owner);+ await expect(scope.close()).rejects.toMatchObject({+ cleanup: { reason: "owned Electron process identity was unavailable" },+ });+ expect(original.cleanupResources).toEqual(["owned_process_group"]);+ expect(original.cleanupIncomplete).toBe(true);+ expect(observe).not.toHaveBeenCalled();+ expect(cleanup).not.toHaveBeenCalled();+});++it("refreshes Windows lineage and never authorizes retry from a cached verified snapshot", async () => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform")!;+ Object.defineProperty(process, "platform", { value: "win32" });+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(unavailable);+ const terminate = vi+ .spyOn(processOwnership, "cleanupWindowsProcessTree")+ .mockResolvedValue({ cleaned: true, signaled: true });+ const absence = vi+ .spyOn(processOwnership, "verifyNoTokenOwnedProcesses")+ .mockResolvedValue({+ cleaned: false,+ reason: "authored census unavailable",+ });+ const owner = new ElectronCaptureCleanup(+ { close: async () => undefined },+ ownership,+ verified,+ );+ const scope = new ArtifactResourceScope();+ try {+ await owner.release(scope);+ const error = bindFailure(owner);+ expect(error.cleanupIncomplete).toBe(true);+ absence.mockResolvedValue({ cleaned: true, signaled: false });+ await scope.close();+ expect(error.cleanupIncomplete).toBe(false);+ expect(terminate).not.toHaveBeenCalled();+ } finally {+ Object.defineProperty(process, "platform", platform);+ }+});++it.skipIf(process.platform === "win32")(+ "discharges absent POSIX families after unavailable lineage, without inventing ownership",+ async () => {+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(unavailable);+ vi.spyOn(processOwnership, "cleanupOwnedProcessGroup").mockResolvedValue({+ cleaned: true,+ signaled: false,+ });+ const absence = vi+ .spyOn(processOwnership, "verifyNoTokenOwnedProcesses")+ .mockResolvedValue({+ cleaned: false,+ reason: "authored census unavailable",+ });+ const owner = new ElectronCaptureCleanup(+ { close: async () => undefined },+ ownership,+ undefined,+ );+ const scope = new ArtifactResourceScope();+ await owner.release(scope);+ const error = bindFailure(owner);+ expect(error.cleanupIncomplete).toBe(true);+ absence.mockResolvedValue({ cleaned: true, signaled: false });+ await scope.close();+ expect(error.cleanupIncomplete).toBe(false);+ },+);++it("waits for a timed-out close to reject before starting a replacement", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });+ vi.spyOn(+ ownershipObservation,+ "observeOwnedProcessLineage",+ ).mockResolvedValue(verified);+ vi.spyOn(processCleanup, "cleanupElectronProcesses").mockResolvedValue({+ cleaned: true,+ signaled: false,+ });+ const completion = createDeferred<void>();+ const failedClose: Promise<void> = completion.promise.then(() => {+ throw undefined;+ });+ const close = vi.fn(() => failedClose);+ const owner = new ElectronCaptureCleanup({ close }, ownership, verified);+ const scope = new ArtifactResourceScope();+ const first = owner.release(scope);+ await vi.advanceTimersByTimeAsync(5_001);+ await first;+ const error = bindFailure(owner);+ const retry = scope.retryCleanup();+ const failedRetry = expect(retry).rejects.toMatchObject({+ cleanup: { resources: ["browser_transport"] },+ });+ await vi.advanceTimersByTimeAsync(5_001);+ await failedRetry;+ expect(close).toHaveBeenCalledOnce();+ completion.resolve();+ await expect(failedClose).rejects.toBeUndefined();+ close.mockResolvedValue(undefined);+ await scope.close();+ expect(close).toHaveBeenCalledTimes(2);+ expect(error.cleanupIncomplete).toBe(false);+});++it("retains a Windows family left after root termination without signaling cached child PIDs", async () => {+ const terminateTree = vi.fn(async () => ({+ cleaned: true as const,+ signaled: true,+ }));+ const absence = vi+ .spyOn(processOwnership, "verifyNoTokenOwnedProcesses")+ .mockResolvedValue({ cleaned: false, reason: "owned helper remains" });+ const lineage = {+ ...verified,+ lineage: {+ ...verified.lineage,+ descendants: [+ {+ pid: 424243,+ parentPid: ownership.leaderPid,+ processGroupId: ownership.processGroupId,+ },+ ],+ },+ };+ const result = await processCleanup.cleanupElectronProcesses(+ ownership,+ lineage,+ { platform: "win32", terminateTree },+ );+ expect(result).toMatchObject({+ cleaned: false,+ reason: "owned helper remains",+ });+ expect(terminateTree).toHaveBeenCalledExactlyOnceWith(ownership.leaderPid);+ expect(absence).toHaveBeenCalledOnce();+});diff --git a/src/browser/ElectronCaptureCleanup.ts b/src/browser/ElectronCaptureCleanup.tsnew file mode 100644index 000000000..d7e0e567a--- /dev/null+++ b/src/browser/ElectronCaptureCleanup.ts@@ -0,0 +1,117 @@+import type { _electron as electron } from "playwright-core";+import {+ AnalysisCleanupLease,+ AnalysisCleanupLeaseGroup,+} from "../artifacts/AnalysisCleanupLease.js";+import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";+import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import type { AnalysisError } from "../domain/analysisErrorBase.js";+import { observeOwnedProcessLineage } from "../process/ProcessOwnershipObservation.js";+import type {+ OwnedProcessGroup,+ ProcessCleanupResult,+ ProcessLineageObservation,+} from "../process/ProcessOwnership.js";+import { runWithExecutionLimits } from "./PlaywrightElectronActiveActions.js";+import { cleanupElectronProcesses } from "./ElectronProcessCleanup.js";++type ElectronApplication = Awaited<ReturnType<typeof electron.launch>>;++/** Transport acknowledgement and process-family release are independent facts. */+export class ElectronCaptureCleanup {+ readonly #transport: AnalysisCleanupLease;+ readonly #processes: AnalysisCleanupLease;+ #closeOperation: Promise<void> | undefined;+ #lineage: ProcessLineageObservation | undefined;+ #processResult: ProcessCleanupResult | undefined;++ constructor(+ application: Pick<ElectronApplication, "close">,+ ownership: OwnedProcessGroup | undefined,+ lineage: ProcessLineageObservation | undefined,+ ) {+ this.#lineage = lineage;+ this.#transport = new AnalysisCleanupLease(async () => {+ // A deadline stops this wait, not the underlying Playwright close. Reuse+ // a still-running/fulfilled close; only a physical rejection permits retry.+ if (this.#closeOperation === undefined) {+ const closing = Promise.resolve().then(() => application.close());+ this.#closeOperation = closing;+ void closing.catch(() => {+ if (this.#closeOperation === closing)+ this.#closeOperation = undefined;+ });+ }+ await runWithExecutionLimits(+ this.#closeOperation,+ undefined,+ performance.now() + 5_000,+ );+ }, ["browser_transport"]);+ const resources =+ ownership === undefined+ ? ["owned_process_group"]+ : [+ "owned_process_group",+ `run:${ownership.runId}`,+ `process-group:${String(ownership.processGroupId)}`,+ ];+ this.#processes = new AnalysisCleanupLease(async () => {+ const cleanup =+ ownership === undefined+ ? {+ cleaned: false as const,+ reason: "owned Electron process identity was unavailable",+ }+ : await this.#cleanupProcesses(ownership);+ this.#processResult = cleanup;+ if (!cleanup.cleaned)+ throw new ArtifactReaderFailure("unavailable", cleanup.reason, {+ cleanup: { reason: cleanup.reason, resources },+ });+ }, resources);+ }++ get processResult(): ProcessCleanupResult | undefined {+ return this.#processResult;+ }+ get pendingResources(): readonly string[] {+ return this.#pending.flatMap((lease) => lease.cleanupResources ?? []);+ }+ get #pending(): AnalysisCleanupLease[] {+ return [this.#transport, this.#processes].filter(+ (lease) => !lease.released,+ );+ }++ async release(scope: ArtifactResourceScope) {+ const transport = await scope.release({+ kind: "lease",+ resource: "browser_transport",+ lease: this.#transport,+ });+ const processes = await scope.release({+ kind: "lease",+ resource: "owned_process_group",+ lease: this.#processes,+ });+ return { transport, processes };+ }++ bind(error: AnalysisError): void {+ new AnalysisCleanupLeaseGroup(error, this.#pending);+ }++ async #cleanupProcesses(+ ownership: OwnedProcessGroup,+ ): Promise<ProcessCleanupResult> {+ const current = await observeOwnedProcessLineage(ownership);+ if (current.status === "verified") this.#lineage = current;+ // Cached POSIX group IDs are candidates only; the shared primitive checks+ // current tokens/start identities. Windows requires this attempt's lineage.+ return cleanupElectronProcesses(+ ownership,+ process.platform === "win32" ? current : (this.#lineage ?? current),+ );+ }+}diff --git a/src/browser/ElectronProcessCleanup.ts b/src/browser/ElectronProcessCleanup.tsnew file mode 100644index 000000000..df13ed20e--- /dev/null+++ b/src/browser/ElectronProcessCleanup.ts@@ -0,0 +1,123 @@+import {+ cleanupOwnedProcessGroup,+ cleanupWindowsProcessTree,+ verifyNoTokenOwnedProcesses,+ type OwnedProcessGroup,+ type ProcessCleanupResult,+ type ProcessLineageObservation,+ type OwnershipSweepUnverifiedProcess,+} from "../process/ProcessOwnership.js";+import { selectCapturedProcessGroupIds } from "../process/ProcessOwnershipProcessTree.js";++/** Clean up an Electron launch. Windows signals a process only after lineage is verified. */+export const cleanupElectronProcesses = async (+ ownership: OwnedProcessGroup,+ lineage: ProcessLineageObservation | undefined,+ host: {+ readonly platform: NodeJS.Platform;+ readonly terminateTree: typeof cleanupWindowsProcessTree;+ } = {+ platform: process.platform,+ terminateTree: cleanupWindowsProcessTree,+ },+): Promise<ProcessCleanupResult> => {+ if (+ lineage?.status === "verified" &&+ (lineage.lineage.runId !== ownership.runId ||+ lineage.lineage.launcherPid !== ownership.leaderPid ||+ lineage.lineage.processGroupId !== ownership.processGroupId)+ ) {+ return {+ cleaned: false,+ reason: "Electron lineage does not match the retained process owner",+ };+ }+ if (lineage?.status !== "verified") {+ const root =+ host.platform === "win32"+ ? { cleaned: true as const, signaled: false }+ : await cleanupOwnedProcessGroup(ownership);+ if (!root.cleaned) return root;+ const released = await verifyFamilyRelease(ownership, root);+ return released.cleaned+ ? released+ : {+ ...released,+ reason: `${lineage?.reason ?? "owned Electron lineage was not observed"}; helper cleanup was not proven: ${released.reason}`,+ };+ }+ if (host.platform === "win32") {+ // /t already includes descendants. Do not signal cached child PIDs again+ // after awaiting root termination: they may have exited or been reused.+ const root = await host.terminateTree(ownership.leaderPid);+ return root.cleaned ? verifyFamilyRelease(ownership, root) : root;+ }+ const groupIds = selectCapturedProcessGroupIds(+ ownership.leaderPid,+ lineage.lineage.descendants.map(({ pid, processGroupId }) => ({+ pid,+ process_group_id: processGroupId,+ })),+ );+ let signaled = false;+ const unverified: OwnershipSweepUnverifiedProcess[] = [];+ for (const processGroupId of groupIds) {+ const cleanupOwnership: OwnedProcessGroup =+ processGroupId === ownership.processGroupId+ ? { ...ownership, leaderPid: processGroupId, processGroupId }+ : {+ runId: ownership.runId,+ leaderPid: processGroupId,+ processGroupId,+ };+ const result = await cleanupOwnedProcessGroup(cleanupOwnership);+ if (!result.cleaned) return result;+ signaled ||= result.signaled;+ unverified.push(...(result.unverified ?? []));+ }+ return verifyFamilyRelease(ownership, {+ cleaned: true,+ signaled,+ ...(unverified.length === 0 ? {} : { unverified }),+ });+};++const verifyFamilyRelease = async (+ ownership: OwnedProcessGroup,+ root: Extract<ProcessCleanupResult, { readonly cleaned: true }>,+): Promise<ProcessCleanupResult> => {+ const remaining = await verifyNoTokenOwnedProcesses(+ ownership.runId,+ undefined,+ ownership.captureBaseline,+ {+ leaderPid: ownership.leaderPid,+ processGroupId: ownership.processGroupId,+ ...(ownership.sampledProcessGroupIds === undefined+ ? {}+ : { sampledProcessGroupIds: ownership.sampledProcessGroupIds }),+ },+ );+ const unverified = [+ ...(root.unverified ?? []),+ ...(remaining.unverified ?? []),+ ];+ if (!remaining.cleaned)+ return { ...remaining, ...(unverified.length === 0 ? {} : { unverified }) };+ return {+ cleaned: true,+ signaled: root.signaled || remaining.signaled,+ ...(unverified.length === 0+ ? {}+ : {+ unverified: [+ ...new Map(+ unverified.map((item) => [+ `${String(item.pid)}:${item.diagnostic}`,+ item,+ ]),+ ).values(),+ ],+ }),+ };+};diff --git a/src/browser/PlaywrightElectronActiveProvider.test.ts b/src/browser/PlaywrightElectronActiveProvider.test.tsindex 9efcf0754..17c34e985 100644--- a/src/browser/PlaywrightElectronActiveProvider.test.ts+++ b/src/browser/PlaywrightElectronActiveProvider.test.ts@@ -1,3 +1,5 @@+import { projectAnalysisError } from "../domain/analysisErrorProjection.js";+import { cleanupElectronProcesses } from "./ElectronProcessCleanup.js";import { afterEach, expect, it, vi } from "vitest";import { writeFile } from "node:fs/promises";import { dirname, join } from "node:path";@@ -14,7 +16,6 @@ import * as electronActions from "./PlaywrightElectronActiveActions.js";import { electronActiveObservationInputSchema } from "../domain/javascript/electronActiveObservation.js";import type { OwnedProcessGroup } from "../process/ProcessOwnership.js";import {- cleanupElectronProcesses,PlaywrightElectronActiveProvider,safeElectronEnvironment,} from "./PlaywrightElectronActiveProvider.js";@@ -105,6 +106,9 @@ it.each([])("does not signal a Windows Electron PID when lineage is unavailable: %s",async (reason) => {+ vi.spyOn(processOwnership, "verifyNoTokenOwnedProcesses").mockResolvedValue(+ { cleaned: false, reason: "authored census unavailable" },+ );const terminateTree = vi.fn(async () => ({cleaned: true as const,signaled: true,@@ -125,12 +129,18 @@ it.each([expect(terminateTree).not.toHaveBeenCalled();expect(result).toEqual({cleaned: false,- reason: `${reason}; helper cleanup was not proven`,+ reason: expect.stringContaining(+ `${reason}; helper cleanup was not proven`,+ ),});},);it("does not signal an unobserved Windows Electron lineage", async () => {+ vi.spyOn(processOwnership, "verifyNoTokenOwnedProcesses").mockResolvedValue({+ cleaned: false,+ reason: "authored census unavailable",+ });const terminateTree = vi.fn();expect(await cleanupElectronProcesses(ownership, undefined, {@@ -139,50 +149,49 @@ it("does not signal an unobserved Windows Electron lineage", async () => {}),).toEqual({cleaned: false,- reason:+ reason: expect.stringContaining("owned Electron lineage was not observed; helper cleanup was not proven",+ ),});expect(terminateTree).not.toHaveBeenCalled();});-it.each([0, 1])(- "preserves a Windows termination failure at tree index %i",- async (failedIndex) => {- const failure = { cleaned: false as const, reason: "termination denied" };- const terminateTree = vi- .fn<typeof processOwnership.cleanupWindowsProcessTree>()- .mockResolvedValue({ cleaned: true, signaled: true });- terminateTree.mockImplementationOnce(async () =>- failedIndex === 0 ? failure : { cleaned: true, signaled: true },- );- if (failedIndex === 1) terminateTree.mockResolvedValueOnce(failure);- const result = await cleanupElectronProcesses(- ownership,- {- status: "verified",- observedAt: "2026-10-10T00:00:00.000Z",- lineage: {- runId: ownership.runId,- launcherPid: ownership.leaderPid,- launcherParentPid: 1,- processGroupId: ownership.processGroupId,- descendants: [- {- pid: 4343,- parentPid: ownership.leaderPid,- processGroupId: ownership.processGroupId,- },- ],- },+it("preserves a Windows root termination failure without signaling cached descendants", async () => {+ const failure = { cleaned: false as const, reason: "termination denied" };+ const terminateTree = vi+ .fn<typeof processOwnership.cleanupWindowsProcessTree>()+ .mockResolvedValue({ cleaned: true, signaled: true });+ terminateTree.mockResolvedValueOnce(failure);+ const result = await cleanupElectronProcesses(+ ownership,+ {+ status: "verified",+ observedAt: "2026-10-10T00:00:00.000Z",+ lineage: {+ runId: ownership.runId,+ launcherPid: ownership.leaderPid,+ launcherParentPid: 1,+ processGroupId: ownership.processGroupId,+ descendants: [+ {+ pid: 4343,+ parentPid: ownership.leaderPid,+ processGroupId: ownership.processGroupId,+ },+ ],},- { platform: "win32", terminateTree },- );- expect(result).toBe(failure);- expect(terminateTree).toHaveBeenCalledTimes(failedIndex + 1);- },-);+ },+ { platform: "win32", terminateTree },+ );+ expect(result).toBe(failure);+ expect(terminateTree).toHaveBeenCalledOnce();+});it("signals a Windows Electron tree only after lineage is verified", async () => {+ vi.spyOn(processOwnership, "verifyNoTokenOwnedProcesses").mockResolvedValue({+ cleaned: true,+ signaled: false,+ });const terminateTree = vi.fn(async () => ({cleaned: true as const,signaled: true,@@ -210,7 +219,7 @@ it("signals a Windows Electron tree only after lineage is verified", async () =>);expect(terminateTree).toHaveBeenNthCalledWith(1, 4242);- expect(terminateTree).toHaveBeenNthCalledWith(2, 4343);+ expect(terminateTree).toHaveBeenCalledOnce();expect(result).toEqual({ cleaned: true, signaled: true });});@@ -228,6 +237,10 @@ it("retains the partial capture without taskkill when Windows lineage is unavailprocessGroupId: 424242,reason: "process table permission denied",});+ vi.spyOn(processOwnership, "verifyNoTokenOwnedProcesses").mockResolvedValue({+ cleaned: false,+ reason: "authored census unavailable",+ });const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");Object.defineProperty(process, "platform", { value: "win32" });const terminateTree = vi@@ -272,8 +285,9 @@ it("retains the partial capture without taskkill when Windows lineage is unavail_tag: "BrowserObservationError",reason: "cleanup_failed",cleanup: {- reason:+ reason: expect.stringContaining("process table permission denied; helper cleanup was not proven",+ ),},partialObservation: {kind: "electron-active-observation",@@ -743,14 +757,16 @@ it("keeps cleanup failure precedence over cancellation observed during cleanup",expect(result.ok).toBe(false);if (result.ok) throw new Error("Expected cleanup to fail");expect(result.error).toMatchObject({- _tag: "BrowserObservationError",- reason: "cleanup_failed",- cleanup: { reason: "process group still alive" },+ cleanupIncomplete: true,partialObservation: {kind: "electron-active-observation",capture: { application: { cleanup: "unverified" } },},});+ expect(result.error.cleanupPrimary).toMatchObject({+ _tag: "BrowserObservationError",+ reason: "cancelled",+ });});it.each(["process", "transport"] as const)(@@ -793,10 +809,8 @@ it.each(["process", "transport"] as const)(expect(result.ok).toBe(false);if (result.ok) throw new Error("Expected incomplete cleanup");expect(result.error).toMatchObject({- _tag: "BrowserObservationError",- reason: "cleanup_failed",- userCategory: "cancelled",- cause: {+ cleanupIncomplete: true,+ cleanupPrimary: {_tag: "BrowserObservationError",reason: "cancelled",cause: reason,@@ -805,7 +819,7 @@ it.each(["process", "transport"] as const)(kind: "electron-active-observation",},});- expect(result.error.userMessage).toContain(+ expect(JSON.stringify(result.error.diagnostics)).toContain(failure === "process"? "process group still alive": "transport still connected",@@ -813,3 +827,145 @@ it.each(["process", "transport"] as const)(expect(application.close).toHaveBeenCalledOnce();},);++it.each(["process", "transport", "both"] as const)(+ "retains %s cleanup and blocks replacement capture until recovery",+ async (failure) => {+ stubVerifiedElectronCleanup();+ stubCompletedCapture();+ let denyProcess = failure !== "transport";+ let denyTransport = failure !== "process";+ const processCleanup = vi.fn(async () =>+ denyProcess+ ? { cleaned: false as const, reason: "authored process cleanup denial" }+ : { cleaned: true as const, signaled: false },+ );+ vi.spyOn(processOwnership, "cleanupOwnedProcessGroup").mockImplementation(+ processCleanup,+ );+ vi.spyOn(processOwnership, "cleanupWindowsProcessTree").mockImplementation(+ processCleanup,+ );+ const application = {+ process: () => ({ pid: 424242 }),+ close: vi.fn(async () => {+ if (denyTransport) throw new Error("authored transport cleanup denial");+ }),+ windows: () => [],+ };+ const launch = vi.fn(+ async () =>+ application as unknown as Awaited<+ ReturnType<typeof import("playwright-core")._electron.launch>+ >,+ );+ const provider = new PlaywrightElectronActiveProvider({}, launch);+ const input = {+ ...electronActiveObservationInputSchema.parse({+ executable_path: process.execPath,+ application_path: process.execPath,+ }),+ application_root: dirname(process.execPath),+ };+ try {+ const first = await provider.capture(input);+ expect(first).toMatchObject({+ ok: false,+ error: { cleanupIncomplete: true },+ });+ const blocked = await provider.capture(input);+ expect(blocked).toMatchObject({+ ok: false,+ error: { cleanupIncomplete: true },+ });+ expect(launch).toHaveBeenCalledOnce();+ denyProcess = false;+ denyTransport = false;+ expect((await provider.capture(input)).ok).toBe(true);+ expect(first).toMatchObject({+ error: { cleanupIncomplete: false, cleanupResources: [] },+ });+ expect(blocked).toMatchObject({+ error: { cleanupIncomplete: false, cleanupResources: [] },+ });+ expect(launch).toHaveBeenCalledTimes(2);+ } finally {+ denyProcess = false;+ denyTransport = false;+ await provider.close();+ }+ },+);++it.each(["process", "transport"] as const)(+ "retains cancellation first observed during failed %s cleanup through retry",+ async (phase) => {+ stubVerifiedElectronCleanup();+ stubCompletedCapture();+ const controller = new AbortController();+ const reason = { caller: "during final cleanup", phase };+ let denied = true;+ const processCleanup = async () => {+ if (phase === "process" && denied) {+ controller.abort(reason);+ return {+ cleaned: false as const,+ reason: "authored late process failure",+ };+ }+ return { cleaned: true as const, signaled: false };+ };+ vi.spyOn(processOwnership, "cleanupOwnedProcessGroup").mockImplementation(+ processCleanup,+ );+ vi.spyOn(processOwnership, "cleanupWindowsProcessTree").mockImplementation(+ processCleanup,+ );+ const application = {+ process: () => ({ pid: 424242 }),+ windows: () => [],+ close: vi.fn(async () => {+ if (phase === "transport" && denied) {+ controller.abort(reason);+ throw new Error("authored late transport failure");+ }+ }),+ };+ const provider = new PlaywrightElectronActiveProvider(+ {},+ async () =>+ application as unknown as Awaited<+ ReturnType<typeof import("playwright-core")._electron.launch>+ >,+ );+ try {+ const result = await provider.capture(+ {+ ...electronActiveObservationInputSchema.parse({+ executable_path: process.execPath,+ application_path: process.execPath,+ }),+ application_root: dirname(process.execPath),+ },+ { signal: controller.signal },+ );+ if (result.ok)+ throw new Error("Expected cleanup failure over cancellation");+ expect(projectAnalysisError(result.error).code).toBe(+ "cleanup_incomplete",+ );+ expect(result.error.cleanupPrimary?.cause).toBe(reason);+ expect(result.error.partialObservation).toMatchObject({+ kind: "electron-active-observation",+ });+ denied = false;+ await provider.close();+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(projectAnalysisError(result.error).code).toBe("cancelled");+ expect(result.error.cleanupPrimary?.cause).toBe(reason);+ } finally {+ denied = false;+ await provider.close();+ }+ },+);diff --git a/src/browser/PlaywrightElectronActiveProvider.ts b/src/browser/PlaywrightElectronActiveProvider.tsindex b53520353..819501130 100644--- a/src/browser/PlaywrightElectronActiveProvider.ts+++ b/src/browser/PlaywrightElectronActiveProvider.ts@@ -1,3 +1,8 @@+import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";+import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import { ElectronCaptureCleanup } from "./ElectronCaptureCleanup.js";+import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";import { electronFuseFailure } from "../electron/ElectronFuseFailures.js";import { randomUUID } from "node:crypto";@@ -19,21 +24,15 @@ import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";import { BrowserObservationError } from "../domain/browserObservationError.js";import { ProviderAdapterError } from "../domain/providerAdapterError.js";import { err, ok, type Result } from "../domain/result.js";-import {- cleanupOwnedProcessGroup,- cleanupWindowsProcessTree,- verifyNoTokenOwnedProcesses,- type OwnedProcessGroup,- type ProcessCleanupResult,- type ProcessLineageObservation,- type OwnershipSweepUnverifiedProcess,+import type {+ OwnedProcessGroup,+ ProcessLineageObservation,} from "../process/ProcessOwnership.js";import {observeOwnedProcessLineage,prepareProcessOwnershipInspection,systemProcessOwnershipHost,} from "../process/ProcessOwnershipObservation.js";-import { selectCapturedProcessGroupIds } from "../process/ProcessOwnershipProcessTree.js";import {runElectronActions,readApplicationState,@@ -65,13 +64,13 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservatireadonly #resources = new ArtifactResourceScope();readonly #shutdown = new AbortController();- /** Stop admitting work, cancel and join captures, then retry exact fuse owners. */+ /** Stop admitting work, cancel and join captures, then retry exact retained resource owners. */async close(): Promise<void> {this.#shutdown.abort(new Error("Electron active provider is closing"));try {await this.#resources.close();} catch (cause: unknown) {- throw electronFuseFailure(cause, "fuse-preflight", OPERATION);+ throw providerError(cause);}}@@ -100,7 +99,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservatithis.#capture(input, { ...options, signal }),);} catch (cause: unknown) {- return err(electronFuseFailure(cause, input.executable_path, OPERATION));+ return err(providerError(cause));}}@@ -244,76 +243,68 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati}}if (application !== undefined) {- if (ownership !== undefined) {- const currentLineage = await observeOwnedProcessLineage(ownership);- if (currentLineage.status === "verified" || lineage === undefined)- lineage = currentLineage;- }- let closeError: unknown;- try {- await runWithExecutionLimits(- application.close(),- undefined,- performance.now() + 5_000,- );- } catch (cause: unknown) {- closeError = cause;- }- const cleanup =- ownership === undefined- ? ({- cleaned: false,- reason: "owned Electron process identity was unavailable",- } satisfies ProcessCleanupResult)- : await cleanupElectronProcesses(ownership, lineage);- if (!cleanup.cleaned)- return err(- new BrowserObservationError(OPERATION, "cleanup_failed", {- cause: outcome.ok ? new Error(cleanup.reason) : outcome.error,- detail: `Electron cleanup could not be verified: ${cleanup.reason}.${capture !== undefined ? " Collected observations are retained in partial_observation." : ""}${outcome.ok ? "" : ` Capture also failed: ${outcome.error.message}.`} Inspect the reported process resources before launching another capture.`,- cleanup: {- reason: cleanup.reason,- resources:- ownership === undefined- ? ["owned_process_group"]- : [- "owned_process_group",- `run:${ownership.runId}`,- `process-group:${String(ownership.processGroupId)}`,- ],- },- ...(capture !== undefined- ? {- partialObservation: {- kind: "electron-active-observation" as const,- capture: {- ...capture,- application: {- ...capture.application,- cleanup: "unverified" as const,- },- },- },- }- : {}),- }),+ const owner = new ElectronCaptureCleanup(application, ownership, lineage);+ const released = await owner.release(this.#resources);+ const cleanup = owner.processResult;+ if (outcome.ok && options.signal?.aborted === true)+ outcome = err(cancelledCapture(outcome.value, options.signal.reason));+ if (+ released.processes.kind === "failed" ||+ released.transport.kind === "failed"+ ) {+ const processFailure = released.processes.kind === "failed";+ const failures = [released.processes, released.transport].flatMap(+ (attempt) => (attempt.kind === "failed" ? [attempt.cause] : []),);- if (closeError !== undefined)- return err(- new BrowserObservationError(OPERATION, "cleanup_failed", {- cause: outcome.ok ? closeError : outcome.error,- detail: `Electron transport teardown failed after process cleanup: ${closeError instanceof Error ? closeError.message : String(closeError)}.${capture !== undefined ? " Collected observations are retained in partial_observation." : ""}${outcome.ok ? "" : ` Capture also failed: ${outcome.error.message}.`}`,- ...(capture !== undefined- ? {+ const cause =+ failures.length === 1+ ? failures[0]+ : new AggregateError(+ failures,+ "Electron process and transport cleanup failed",+ );+ const reason = failures+ .map((failure) =>+ failure instanceof Error ? failure.message : String(failure),+ )+ .join("; ");+ const failure = new BrowserObservationError(+ OPERATION,+ "cleanup_failed",+ {+ cause,+ detail: `${processFailure ? "Electron process cleanup could not be verified" : "Electron transport teardown failed after process cleanup"}: ${reason}. Collected observations are retained when available.`,+ cleanup: { reason, resources: owner.pendingResources },+ ...(capture === undefined+ ? {}+ : {partialObservation: {kind: "electron-active-observation" as const,- capture,+ capture: processFailure+ ? {+ ...capture,+ application: {+ ...capture.application,+ cleanup: "unverified" as const,+ },+ }+ : capture,},- }- : {}),- }),+ }),+ },);- if (outcome.ok && cleanup.unverified !== undefined)+ owner.bind(failure);+ if (outcome.ok) return err(failure);+ const composed = analysisErrorWithCleanupFailure(+ outcome.error,+ failure,+ OPERATION,+ ).bindCleanupDependencies([outcome.error, failure]);+ if (failure.partialObservation !== undefined)+ composed.partialObservation = failure.partialObservation;+ return err(composed);+ }+ if (outcome.ok && cleanup?.cleaned && cleanup.unverified !== undefined)outcome = ok({...outcome.value,limitations: [@@ -364,92 +355,6 @@ const cancellationCause = (}: { cause };-/** Clean up an Electron launch. Windows signals a process only after lineage is verified. */-export const cleanupElectronProcesses = async (- ownership: OwnedProcessGroup,- lineage: ProcessLineageObservation | undefined,- host: {- readonly platform: NodeJS.Platform;- readonly terminateTree: typeof cleanupWindowsProcessTree;- } = {- platform: process.platform,- terminateTree: cleanupWindowsProcessTree,- },-): Promise<ProcessCleanupResult> => {- if (lineage?.status !== "verified") {- if (host.platform !== "win32") {- const root = await cleanupOwnedProcessGroup(ownership);- if (!root.cleaned) return root;- }- return {- cleaned: false,- reason: `${lineage?.reason ?? "owned Electron lineage was not observed"}; helper cleanup was not proven`,- };- }- if (host.platform === "win32") {- const root = await host.terminateTree(ownership.leaderPid);- if (!root.cleaned) return root;- for (const descendant of lineage.lineage.descendants) {- const result = await host.terminateTree(descendant.pid);- if (!result.cleaned) return result;- }- return root;- }- const groupIds = selectCapturedProcessGroupIds(- ownership.leaderPid,- lineage.lineage.descendants.map(({ pid, processGroupId }) => ({- pid,- process_group_id: processGroupId,- })),- );- let signaled = false;- const unverified: OwnershipSweepUnverifiedProcess[] = [];- for (const processGroupId of groupIds) {- const cleanupOwnership: OwnedProcessGroup =- processGroupId === ownership.processGroupId- ? { ...ownership, leaderPid: processGroupId, processGroupId }- : {- runId: ownership.runId,- leaderPid: processGroupId,- processGroupId,- };- const result = await cleanupOwnedProcessGroup(cleanupOwnership);- if (!result.cleaned) return result;- signaled ||= result.signaled;- unverified.push(...(result.unverified ?? []));- }- const remaining = await verifyNoTokenOwnedProcesses(- ownership.runId,- undefined,- ownership.captureBaseline,- {- leaderPid: ownership.leaderPid,- processGroupId: ownership.processGroupId,- ...(ownership.sampledProcessGroupIds === undefined- ? {}- : { sampledProcessGroupIds: ownership.sampledProcessGroupIds }),- },- );- if (!remaining.cleaned) return remaining;- unverified.push(...(remaining.unverified ?? []));- return {- cleaned: true,- signaled,- ...(unverified.length === 0- ? {}- : {- unverified: [- ...new Map(- unverified.map((item) => [- `${String(item.pid)}:${item.diagnostic}`,- item,- ]),- ).values(),- ],- }),- };-};-export const safeElectronEnvironment = (environment: Readonly<Record<string, string | undefined>>,runId: string,@@ -572,16 +477,26 @@ const containLaunchRejections = async <T>(}};-const providerError = (cause: unknown): AnalysisError =>- cause instanceof AnalysisError- ? cause- : new ProviderAdapterError(- PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY.id,- OPERATION,- {- cause,- diagnostics: {- message: cause instanceof Error ? cause.message : String(cause),- },- },- );+const providerError = (cause: unknown): AnalysisError => {+ if (cause instanceof AnalysisError) return cause;+ if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) {+ const failure = new ProviderCleanupError(+ PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY.id,+ cause.cleanup.resources,+ { reason: cause.cleanup.reason },+ { operation: OPERATION, cause },+ );+ bindArtifactFileCleanup(cause, failure);+ return failure;+ }+ return new ProviderAdapterError(+ PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY.id,+ OPERATION,+ {+ cause,+ diagnostics: {+ message: cause instanceof Error ? cause.message : String(cause),+ },+ },+ );+};