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(native): bind UI runtime cleanup to exact owners
morluto04221e5f0145
diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.tsindex 16d0ee5ae..19f2fed84 100644--- a/src/native/NativeMacOSProvider.ts+++ b/src/native/NativeMacOSProvider.ts@@ -12,6 +12,7 @@ import {} from "./NativeMacOSProviderMetadata.js";import { inspectAppleDispatchMetadata } from "./AppleDispatchMetadata.js";import { observeNativeUi } from "./NativeUiObservation.js";+import { NativeUiCleanupError } from "./NativeUiCleanupError.js";import { LldbCallTracer, type NativeCallTracer } from "./LldbCallTracer.js";import { observeNativeCalls } from "./NativeCallObservation.js";import { basename, dirname, isAbsolute, resolve } from "node:path";@@ -385,7 +386,11 @@ class NativeMacOSClient implements AnalysisClient {return err(result.ok? cleanup- : analysisErrorWithCleanupFailure(result.error, cleanup, operation),+ : analysisErrorWithCleanupFailure(+ result.error,+ cleanup,+ operation,+ ).bindCleanupDependencies([result.error, cleanup]),);}return result.ok@@ -455,26 +460,7 @@ class NativeMacOSClient implements AnalysisClient {operation: string,partialObservation?: NativeUiObservationResult,): ProviderCleanupError {- const resources = failures.flatMap(({ runtime }) => runtime.resources());- return new ProviderCleanupError(- IDENTITY.id,- resources.length === 0 ? ["native-ui-runtime"] : resources,- {- reason: "Native UI runtime cleanup remains incomplete",- failures: failures.map(({ runtime, cause }) => ({- resources: [...runtime.resources()],- reason: cause instanceof Error ? cause.message : String(cause),- })),- },- {- operation,- cause: new AggregateError(- failures.map(({ cause }) => cause),- "Native UI runtime cleanup failed",- ),- ...(partialObservation === undefined ? {} : { partialObservation }),- },- );+ return new NativeUiCleanupError(failures, operation, partialObservation);}#dispatch(diff --git a/src/native/NativeUiCleanupError.ts b/src/native/NativeUiCleanupError.tsnew file mode 100644index 000000000..d3e8685e1--- /dev/null+++ b/src/native/NativeUiCleanupError.ts@@ -0,0 +1,53 @@+import { AnalysisCleanupLeaseGroup } from "../artifacts/AnalysisCleanupLease.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";+import type { NativeUiObservationResult } from "../domain/native/nativeUiObservation.js";+import type { NativeUiHelperRuntime } from "./NativeUiHelperRuntime.js";++/** Exact runtime owners remain reachable for standalone callers' cleanup retry. */+export class NativeUiCleanupError extends ProviderCleanupError {+ readonly runtimes: readonly NativeUiHelperRuntime[];++ constructor(+ failures: readonly {+ readonly runtime: NativeUiHelperRuntime;+ readonly cause: unknown;+ }[],+ operation: string,+ partialObservation?: NativeUiObservationResult,+ ) {+ const runtimes = failures.map(({ runtime }) => runtime);+ const resources = () =>+ runtimes+ .filter((runtime) => !runtime.cleanupLease.released)+ .flatMap((runtime) => runtime.resources());+ super(+ "native-macos",+ resources(),+ {+ reason: "Native UI runtime cleanup remains incomplete",+ failures: failures.map(({ runtime, cause }) => ({+ resources: [...runtime.resources()],+ reason: cause instanceof Error ? cause.message : String(cause),+ })),+ },+ {+ operation,+ cause: new AggregateError(+ failures.map(({ cause }) => cause),+ "Native UI runtime cleanup failed",+ ),+ partialObservation,+ },+ );+ this.runtimes = runtimes;+ new AnalysisCleanupLeaseGroup(+ this,+ runtimes.map((runtime) => runtime.cleanupLease),+ );+ this.bindCleanupResourceOwner({+ get cleanupResources() {+ return resources();+ },+ });+ }+}diff --git a/src/native/NativeUiHelperRuntime.ts b/src/native/NativeUiHelperRuntime.tsindex dfeae245d..4df72b8c5 100644--- a/src/native/NativeUiHelperRuntime.ts+++ b/src/native/NativeUiHelperRuntime.ts@@ -1,3 +1,5 @@+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";import { snapshotEnvironment } from "../process/snapshotEnvironment.js";import { mkdir, mkdtemp, rm, symlink } from "node:fs/promises";import { tmpdir } from "node:os";@@ -11,6 +13,8 @@ import { NATIVE_UI_HELPER_MAX_BUFFER } from "./NativeUiOutputBudget.js";export interface NativeUiHelperRuntime {readonly invoke: NativeUiHelper;+ readonly cleanupLease: AnalysisCleanupLease;+ readonly signal: AbortSignal;close(): Promise<void>;resources(): readonly string[];}@@ -20,75 +24,91 @@ export const createNativeUiHelperRuntime = (environment: Readonly<NodeJS.ProcessEnv>,): NativeUiHelperRuntime => {const selectedEnvironment = snapshotEnvironment(environment);+ const deadlineSignal = AbortSignal.timeout(180_000);+ const operations = new ArtifactResourceScope();let root: string | undefined;- let executable: string | undefined;- const invoke: NativeUiHelper = async (parameters, signal) => {- if (executable === undefined) {- root = await mkdtemp(join(tmpdir(), "rea-native-ui-"));- const output = join(root, "observer");- const main = join(root, "main.swift");- await symlink(+ let preparation: Promise<string> | undefined;+ const cleanupLease = new AnalysisCleanupLease(async () => {+ await operations.close();+ if (root !== undefined) {+ await rm(root, { recursive: true, force: true });+ root = undefined;+ preparation = undefined;+ }+ });+ const prepare = async (signal: AbortSignal): Promise<string> => {+ root = await mkdtemp(join(tmpdir(), "rea-native-ui-"));+ const output = join(root, "observer");+ const main = join(root, "main.swift");+ await symlink(+ fileURLToPath(+ new URL("../../bridge/native/ReaNativeUI.swift", import.meta.url),+ ),+ main,+ );+ // Keep swiftc's intermediate objects inside the removable root.+ const compilerTemporary = join(root, "tmp");+ await mkdir(compilerTemporary);+ await execFileOutput(+ "/usr/bin/xcrun",+ [+ "swiftc",+ "-module-cache-path",+ join(root, "modules"),fileURLToPath(- new URL("../../bridge/native/ReaNativeUI.swift", import.meta.url),+ new URL(+ "../../bridge/native/NativeUIChildren.swift",+ import.meta.url,+ ),),main,- );- // Keep swiftc's intermediate objects inside the removable root.- const compilerTemporary = join(root, "tmp");- await mkdir(compilerTemporary);- await execFileOutput(- "/usr/bin/xcrun",- [- "swiftc",- "-module-cache-path",- join(root, "modules"),- fileURLToPath(- new URL(- "../../bridge/native/NativeUIChildren.swift",- import.meta.url,- ),- ),- main,- "-o",- output,- ],- {- timeout: 60_000,- maxBuffer: 1024 * 1024,- stopSignal: SWIFTC_INTERRUPT,- env: { ...selectedEnvironment, TMPDIR: compilerTemporary },- ...(signal === undefined ? {} : { signal }),- },- );- executable = output;- }- const output = await execFileOutput(- executable,- [JSON.stringify(parameters)],+ "-o",+ output,+ ],{- timeout: 30_000,- maxBuffer: NATIVE_UI_HELPER_MAX_BUFFER,- stopSignal: "SIGTERM",- env: selectedEnvironment,- ...(signal === undefined ? {} : { signal }),+ timeout: 60_000,+ maxBuffer: 1024 * 1024,+ stopSignal: SWIFTC_INTERRUPT,+ env: { ...selectedEnvironment, TMPDIR: compilerTemporary },+ signal,},);- const parsed = safeParseJson(output.stdout);- if (!parsed.ok)- throw new Error(`Native helper returned invalid JSON: ${parsed.error}`, {- cause: parsed.cause,- });- return parsed.value;+ return output;};+ const invoke: NativeUiHelper = (parameters, callerSignal) =>+ operations.run(async () => {+ const signal =+ callerSignal === undefined+ ? deadlineSignal+ : AbortSignal.any([callerSignal, deadlineSignal]);+ preparation ??= prepare(signal);+ const executable = await preparation;+ const output = await execFileOutput(+ executable,+ [JSON.stringify(parameters)],+ {+ timeout: 30_000,+ maxBuffer: NATIVE_UI_HELPER_MAX_BUFFER,+ stopSignal: "SIGTERM",+ env: selectedEnvironment,+ signal,+ },+ );+ const parsed = safeParseJson(output.stdout);+ if (!parsed.ok)+ throw new Error(+ `Native helper returned invalid JSON: ${parsed.error}`,+ {+ cause: parsed.cause,+ },+ );+ return parsed.value;+ });return {invoke,- close: async () => {- if (root !== undefined) {- await rm(root, { recursive: true, force: true });- root = undefined;- executable = undefined;- }- },+ cleanupLease,+ signal: deadlineSignal,+ close: () => cleanupLease.release(),resources: () => (root === undefined ? [] : [root]),};};diff --git a/tests/boundary/providers/native/nativeUiRuntimeOwnership.test.ts b/tests/boundary/providers/native/nativeUiRuntimeOwnership.test.tsnew file mode 100644index 000000000..1fea60105--- /dev/null+++ b/tests/boundary/providers/native/nativeUiRuntimeOwnership.test.ts@@ -0,0 +1,160 @@+import { access } from "node:fs/promises";+import * as filesystem from "node:fs/promises";+import { expect, it, vi, onTestFinished } from "vitest";+import * as commands from "../../../../src/process/ExecFileOutput.js";+import { createNativeUiHelperRuntime } from "../../../../src/native/NativeUiHelperRuntime.js";+import { NativeUiCleanupError } from "../../../../src/native/NativeUiCleanupError.js";++vi.mock("node:fs/promises", async (importOriginal) => {+ const original = await importOriginal<typeof import("node:fs/promises")>();+ return { ...original, rm: vi.fn(original.rm) };+});++it("retains the actual helper root after failed removal and releases its exact lease on retry", async () => {+ const command = vi.spyOn(commands, "execFileOutput").mockResolvedValue({+ stdout: "{}",+ stderr: "",+ stdoutBytes: 2,+ stderrBytes: 0,+ });+ const runtime = createNativeUiHelperRuntime({});+ let restoreRemoval: (() => void) | undefined;+ onTestFinished(async () => {+ restoreRemoval?.();+ await runtime.close();+ command.mockRestore();+ });+ await runtime.invoke({});+ const root = runtime.resources()[0];+ if (root === undefined) throw new Error("Expected actual owned helper root");+ await expect(access(root)).resolves.toBeUndefined();+ const physicalFailure = new Error("controlled helper root removal failure");+ const original =+ await vi.importActual<typeof import("node:fs/promises")>(+ "node:fs/promises",+ );+ const remove = vi+ .mocked(filesystem.rm)+ .mockRejectedValueOnce(physicalFailure);+ restoreRemoval = () => {+ remove.mockReset();+ remove.mockImplementation(original.rm);+ };+ await expect(runtime.close()).rejects.toBe(physicalFailure);+ const failure = new NativeUiCleanupError(+ [{ runtime, cause: physicalFailure }],+ "observe_native_ui",+ );+ expect(runtime.cleanupLease.released).toBe(false);+ expect(failure.cleanupIncomplete).toBe(true);+ expect(failure.cleanupResources).toEqual([root]);+ restoreRemoval();+ await runtime.close();+ expect(runtime.cleanupLease.released).toBe(true);+ expect(failure.cleanupIncomplete).toBe(false);+ expect(failure.cleanupResources).toEqual([]);+ await expect(access(root)).rejects.toMatchObject({ code: "ENOENT" });+ await expect(runtime.invoke({})).rejects.toThrow("scope is closed");+ expect(command).toHaveBeenCalledTimes(2);+});++it("keeps a mixed runtime aggregate incomplete until both exact owners release", async () => {+ const command = vi.spyOn(commands, "execFileOutput").mockResolvedValue({+ stdout: "{}",+ stderr: "",+ stdoutBytes: 2,+ stderrBytes: 0,+ });+ const first = createNativeUiHelperRuntime({});+ const second = createNativeUiHelperRuntime({});+ onTestFinished(async () => {+ await first.close();+ await second.close();+ command.mockRestore();+ });+ await first.invoke({});+ await second.invoke({});+ const firstRoot = first.resources()[0];+ const secondRoot = second.resources()[0];+ if (firstRoot === undefined || secondRoot === undefined)+ throw new Error("Missing owned roots");+ const failure = new NativeUiCleanupError(+ [+ { runtime: first, cause: new Error("first removal failed") },+ { runtime: second, cause: new Error("second removal failed") },+ ],+ "close_binary",+ );+ await first.close();+ expect(failure.cleanupIncomplete).toBe(true);+ expect(failure.cleanupResources).toEqual([secondRoot]);+ await expect(access(firstRoot)).rejects.toMatchObject({ code: "ENOENT" });+ await expect(access(secondRoot)).resolves.toBeUndefined();+ await second.close();+ expect(failure.cleanupIncomplete).toBe(false);+ expect(failure.cleanupResources).toEqual([]);+ // Repeated close remains a confirmed release.+ await first.close();+ expect(command).toHaveBeenCalledTimes(4);+});++it("joins admitted compilation and helper completion before removing the runtime", async () => {+ let entered!: () => void, resume!: () => void;+ const compiling = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ resume = resolve;+ });+ let calls = 0;+ const command = vi+ .spyOn(commands, "execFileOutput")+ .mockImplementation(async () => {+ if (++calls === 1) {+ entered();+ await gate;+ }+ return { stdout: "{}", stderr: "", stdoutBytes: 2, stderrBytes: 0 };+ });+ const runtime = createNativeUiHelperRuntime({});+ onTestFinished(async () => {+ resume();+ await runtime.close();+ command.mockRestore();+ });+ const running = runtime.invoke({});+ await compiling;+ const root = runtime.resources()[0];+ if (root === undefined) throw new Error("Missing active root");+ const closing = runtime.close();+ expect(runtime.cleanupLease.released).toBe(false);+ await expect(access(root)).resolves.toBeUndefined();+ await expect(runtime.invoke({})).rejects.toThrow("scope is closed");+ resume();+ await expect(running).resolves.toEqual({});+ await closing;+ expect(runtime.cleanupLease.released).toBe(true);+ expect(calls).toBe(2);+ await expect(access(root)).rejects.toMatchObject({ code: "ENOENT" });+});++it("retains one failed compilation and its root instead of overwriting ownership on retry", async () => {+ const physical = new Error("controlled compiler failure");+ const command = vi+ .spyOn(commands, "execFileOutput")+ .mockRejectedValue(physical);+ const runtime = createNativeUiHelperRuntime({});+ onTestFinished(async () => {+ await runtime.close();+ command.mockRestore();+ });+ await expect(runtime.invoke({})).rejects.toBe(physical);+ const roots = runtime.resources();+ expect(roots).toHaveLength(1);+ await expect(runtime.invoke({})).rejects.toBe(physical);+ expect(runtime.resources()).toEqual(roots);+ expect(command).toHaveBeenCalledTimes(1);+ await runtime.close();+ for (const root of roots)+ await expect(access(root)).rejects.toMatchObject({ code: "ENOENT" });+});