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(hopper): preserve caller abort reasons on cancellation (#5780)
morluto4a7a4b5744ab
diff --git a/src/domain/hopperErrors.test.ts b/src/domain/hopperErrors.test.tsnew file mode 100644index 000000000..a95584302--- /dev/null+++ b/src/domain/hopperErrors.test.ts@@ -0,0 +1,28 @@+import { expect, it } from "vitest";++import { HopperCancelledError } from "./hopperErrors.js";++it("omits a cause when the caller does not supply one", () => {+ const error = new HopperCancelledError();++ expect(error._tag).toBe("HopperCancelledError");+ expect(error.cause).toBeUndefined();+ expect(Object.hasOwn(error, "cause")).toBe(false);+});++it("retains an explicitly undefined cause separately from omission", () => {+ const error = new HopperCancelledError(undefined, {+ diagnostics: { stage: "queue" },+ });++ expect(error.cause).toBeUndefined();+ expect(Object.hasOwn(error, "cause")).toBe(true);+ expect(error.diagnostics).toEqual({ stage: "queue" });+});++it("retains an opaque caller reason by identity", () => {+ const reason = { source: "caller", opaque: 7 };+ const error = new HopperCancelledError(reason);++ expect(error.cause).toBe(reason);+});diff --git a/src/domain/hopperErrors.ts b/src/domain/hopperErrors.tsindex 935dd1b48..ddc67a152 100644--- a/src/domain/hopperErrors.ts+++ b/src/domain/hopperErrors.ts@@ -61,16 +61,37 @@ export class HopperCancelledError extends HopperError {readonly _tag = "HopperCancelledError";constructor(- cause?: unknown,- options: Omit<AnalysisErrorOptions, "cause"> = {},+ ...parameters:+ | readonly []+ | readonly [cause: unknown]+ | readonly [cause: unknown, options: Omit<AnalysisErrorOptions, "cause">]) {- super(- "Hopper operation was cancelled",- cause === undefined ? options : { ...options, cause },- );+ const errorOptions: AnalysisErrorOptions = { ...parameters[1] };+ // Argument presence matters: an explicit undefined is the caller's reason.+ if (parameters.length > 0)+ Object.defineProperty(errorOptions, "cause", {+ configurable: true,+ enumerable: true,+ value: parameters[0],+ writable: true,+ });+ super("Hopper operation was cancelled", errorOptions);}}+/**+ * Classify caller cancellation from a signal.+ *+ * An aborted signal keeps its exact reason, including undefined. A signal that+ * has not aborted does not invent a reason.+ */+export const hopperCancelledBySignal = (+ signal: AbortSignal | undefined,+): HopperCancelledError =>+ signal?.aborted === true+ ? new HopperCancelledError(signal.reason)+ : new HopperCancelledError();+/** Hopper returned bytes or JSON that do not satisfy the NDJSON RPC contract. */export class HopperProtocolError extends HopperError {readonly _tag = "HopperProtocolError";diff --git a/src/hopper/BridgeLauncher.ts b/src/hopper/BridgeLauncher.tsindex 99431606f..76c477677 100644--- a/src/hopper/BridgeLauncher.ts+++ b/src/hopper/BridgeLauncher.ts@@ -4,6 +4,7 @@ import { basename, dirname, extname, join } from "node:path";import { promisify } from "node:util";import {+ hopperCancelledBySignal,HopperCancelledError,HopperProcessError,HopperStartError,@@ -331,7 +332,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {];let launched = false;try {- if (signal?.aborted === true) return err(new HopperCancelledError());+ if (signal?.aborted === true) return err(hopperCancelledBySignal(signal));let expectedLinuxSha256: string | undefined;if (usesLinuxDemo(this.options)) {const inspected = await (@@ -339,7 +340,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {)(this.options.launcherPath, this.options.environment, signal);if (!inspected.ok)return inspected.error.reason === "cancelled"- ? err(new HopperCancelledError())+ ? err(cancelledLauncherVerification(signal, inspected.error)): err(new HopperStartError({userMessage: inspected.error.message,@@ -366,7 +367,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {this.options.environment,signal,);- if (!prepared) return err(new HopperCancelledError());+ if (!prepared) return err(hopperCancelledBySignal(signal));const linuxDemo = linuxDemoLaunch(this.options,session,@@ -383,7 +384,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {linuxDemo,signal,});- if (started === null) return err(new HopperCancelledError());+ if (started === null) return err(hopperCancelledBySignal(signal));launched = true;const cleanup = () => cleanupOwnedProcessGroup(started.ownership);const ownedLauncher = {@@ -518,7 +519,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {...(signal === undefined ? {} : { signal }),});if (signal?.aborted === true)- return { ok: false, error: new HopperCancelledError() };+ return { ok: false, error: hopperCancelledBySignal(signal) };return selection.ok? { ok: true, strategy: selection.strategy }: {@@ -637,12 +638,22 @@ export const linuxDemoLaunch = (};};+const cancelledLauncherVerification = (+ signal: AbortSignal | undefined,+ error: Error,+): HopperCancelledError => {+ if (signal?.aborted === true) return new HopperCancelledError(signal.reason);+ return Object.hasOwn(error, "cause")+ ? new HopperCancelledError(error.cause)+ : new HopperCancelledError();+};+const hopperLaunchFailure = (cause: unknown,signal: AbortSignal | undefined,): HopperCancelledError | HopperStartError =>signal?.aborted === true- ? new HopperCancelledError()+ ? new HopperCancelledError(signal.reason): new HopperStartError({ cause });/** Select the publisher-verified demo adapter from the caller's explicit launch mode. */diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.tsindex 6a0dd077d..cbd99cf9b 100644--- a/src/hopper/HopperClient.ts+++ b/src/hopper/HopperClient.ts@@ -9,7 +9,8 @@ import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.import { analysisClientFailureContext } from "../providers/AnalysisClientFailure.js";import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";import {- HopperCancelledError,+ hopperCancelledBySignal,+ type HopperCancelledError,type HopperError,type HopperLauncherOutcome,HopperProcessError,@@ -313,11 +314,11 @@ export class HopperClient {/** Launch the bridge once while each caller retains its own cancellation. */start(signal?: AbortSignal): Promise<HopperStartupResult> {if (isAborted(signal))- return Promise.resolve(err(new HopperCancelledError()));+ return Promise.resolve(err(hopperCancelledBySignal(signal)));if (this.#closePromise !== undefined)return waitForAbortable(this.#closePromise, signal).then((closed) =>closed === ABORTED- ? err(new HopperCancelledError())+ ? err(hopperCancelledBySignal(signal)): closed.ok? this.start(signal): closed,@@ -355,7 +356,7 @@ export class HopperClient {const waited = await attempt.wait(signal);if (waited.status === "completed") return waited.value;if (waited.status === "stopped" && !waited.value.ok) return waited.value;- return err(new HopperCancelledError());+ return err(hopperCancelledBySignal(signal));}/** Cleanup belongs to the abandoned attempt, never to a prospective retry. */@@ -365,7 +366,7 @@ export class HopperClient {): Promise<HopperStartupResult> {const waited = await waitForAbortable(attempt.promise, signal);if (waited === ABORTED || (waited.ok && isAborted(signal)))- return err(new HopperCancelledError());+ return err(hopperCancelledBySignal(signal));if (waited.ok || waited.error.cleanupIncomplete) return waited;return this.start(signal);}@@ -373,7 +374,7 @@ export class HopperClient {async #start(signal?: AbortSignal,): Promise<Result<HopperServerInfo, AnalysisError>> {- if (isAborted(signal)) return err(new HopperCancelledError());+ if (isAborted(signal)) return err(hopperCancelledBySignal(signal));if (this.#socket !== undefined ||this.#resources.launch !== undefined ||@@ -835,7 +836,7 @@ export class HopperClient {if (deadline.signal.reason === STARTUP_OWNER_CLOSED)return new HopperProtocolError("Hopper session closed during startup");if (deadline.interruption === "cancelled")- return new HopperCancelledError();+ return hopperCancelledBySignal(deadline.signal);return new HopperTimeoutError(deadline.timeoutMs,undefined,@@ -969,7 +970,7 @@ export class HopperClient {);}if (options.signal?.aborted === true)- return err(new HopperCancelledError());+ return err(hopperCancelledBySignal(options.signal));const startedAt = performance.now();const result = await this.#requests.run(id, method, params, {...(options.signal === undefined ? {} : { signal: options.signal }),diff --git a/src/hopper/HopperRequestQueue.test.ts b/src/hopper/HopperRequestQueue.test.tsindex 183d67bae..2cc32e978 100644--- a/src/hopper/HopperRequestQueue.test.ts+++ b/src/hopper/HopperRequestQueue.test.ts@@ -103,9 +103,9 @@ describe("HopperRequestQueue deadlines", () => {{ timeoutMs: 25, signal: controller.signal },);controller.abort();- await expect(pending).resolves.toEqual({+ await expect(pending).resolves.toMatchObject({ok: false,- error: new HopperCancelledError(),+ error: { cause: controller.signal.reason },});expect(vi.getTimerCount()).toBe(0);queue.accept(1, ok(null));@@ -118,6 +118,7 @@ describe("HopperRequestQueue deadlines", () => {const send = vi.fn();const queue = new HopperRequestQueue(send);const controller = new AbortController();+ const reason = { source: "progress" };const pending = queue.run(1,"echo",@@ -127,7 +128,7 @@ describe("HopperRequestQueue deadlines", () => {signal: controller.signal,progress: {report: () => {- controller.abort();+ controller.abort(reason);return Promise.resolve();},},@@ -135,7 +136,7 @@ describe("HopperRequestQueue deadlines", () => {);await expect(pending).resolves.toMatchObject({ok: false,- error: { _tag: "HopperCancelledError" },+ error: { cause: reason },});expect(vi.getTimerCount()).toBe(0);expect(send).not.toHaveBeenCalled();@@ -298,3 +299,56 @@ describe("Hopper deadlines before timer dispatch", () => {expect(vi.getTimerCount()).toBe(0);});});++describe("HopperRequestQueue caller abort reasons", () => {+ const reason = { source: "caller", opaque: 7 };++ it("retains an opaque reason for a signal aborted before admission", async () => {+ const queue = new HopperRequestQueue(() => {});+ const controller = new AbortController();+ controller.abort(reason);+ const result = await queue.run(+ 1,+ "echo",+ {},+ { signal: controller.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected cancellation");+ expect(result.error).toBeInstanceOf(HopperCancelledError);+ expect(result.error.cause).toBe(reason);+ });++ it("retains an opaque reason when the active caller aborts", async () => {+ const sent: number[] = [];+ const queue = new HopperRequestQueue(({ id }) => sent.push(id));+ const controller = new AbortController();+ const pending = queue.run(1, "echo", {}, { signal: controller.signal });+ controller.abort(reason);+ const result = await pending;+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected cancellation");+ expect(result.error.cause).toBe(reason);+ expect(sent).toEqual([1]);+ expect(queue.accept(1, ok(null))).toBe(true);+ expect(result.error.cause).toBe(reason);+ expect(queue.activity()).toBeNull();+ });++ it("retains an opaque reason for a queued caller without transmitting it", async () => {+ const sent: number[] = [];+ const queue = new HopperRequestQueue(({ id }) => sent.push(id));+ const active = queue.run(1, "active", {}, {});+ const controller = new AbortController();+ const queued = queue.run(2, "queued", {}, { signal: controller.signal });+ controller.abort(reason);+ const result = await queued;+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected cancellation");+ expect(result.error.cause).toBe(reason);+ expect(queue.hasQueued(2)).toBe(false);+ queue.accept(1, ok(null));+ await active;+ expect(sent).toEqual([1]);+ });+});diff --git a/src/hopper/HopperRequestQueue.ts b/src/hopper/HopperRequestQueue.tsindex 43f4f2821..9dc9fb500 100644--- a/src/hopper/HopperRequestQueue.ts+++ b/src/hopper/HopperRequestQueue.ts@@ -5,7 +5,7 @@ import type {import { hopperOperationStage } from "./HopperOperationStage.js";import type { HopperBridgeEvent } from "./protocol.js";import {- HopperCancelledError,+ hopperCancelledBySignal,type HopperError,HopperProcessError,HopperProtocolError,@@ -77,7 +77,7 @@ export class HopperRequestQueue {options: HopperRequestQueueOptions,): Promise<HopperRequestResult> {if (options.signal?.aborted === true)- return Promise.resolve(err(new HopperCancelledError()));+ return Promise.resolve(err(hopperCancelledBySignal(options.signal)));const timeoutMs = options.timeoutMs;if (timeoutMs !== undefined &&@@ -239,7 +239,11 @@ export class HopperRequestQueue {return;}if (entry.signal?.aborted === true) {- this.#settleCaller(entry, err(new HopperCancelledError()), "cancelled");+ this.#settleCaller(+ entry,+ err(hopperCancelledBySignal(entry.signal)),+ "cancelled",+ );this.#drain();return;}@@ -316,7 +320,7 @@ export class HopperRequestQueue {#cancel(entry: QueuedRequest,- error: HopperError = new HopperCancelledError(),+ error: HopperError = hopperCancelledBySignal(entry.signal),): void {if (entry.callerSettled) return;if (this.#active === entry) {diff --git a/src/hopper/HopperSocketConnection.test.ts b/src/hopper/HopperSocketConnection.test.tsnew file mode 100644index 000000000..0d67984da--- /dev/null+++ b/src/hopper/HopperSocketConnection.test.ts@@ -0,0 +1,22 @@+import { tmpdir } from "node:os";+import { join } from "node:path";++import { expect, it } from "vitest";++import { HopperCancelledError } from "../domain/hopperErrors.js";+import { connectHopperSocketOnce } from "./HopperSocketConnection.js";++it("retains the caller abort reason when the socket signal is already aborted", async () => {+ const reason = { source: "caller", opaque: 7 };+ const controller = new AbortController();+ controller.abort(reason);+ const result = await connectHopperSocketOnce(+ join(tmpdir(), "rea-hopper-cancelled.sock"),+ controller.signal,+ );++ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected cancellation");+ expect(result.error).toBeInstanceOf(HopperCancelledError);+ expect(result.error.cause).toBe(reason);+});diff --git a/src/hopper/HopperSocketConnection.ts b/src/hopper/HopperSocketConnection.tsindex 8333bb164..77fe8ef30 100644--- a/src/hopper/HopperSocketConnection.ts+++ b/src/hopper/HopperSocketConnection.ts@@ -1,7 +1,8 @@import { createConnection, type Socket } from "node:net";import {- HopperCancelledError,+ hopperCancelledBySignal,+ type HopperCancelledError,HopperStartError,} from "../domain/hopperErrors.js";import { err, ok, type Result } from "../domain/result.js";@@ -30,7 +31,7 @@ export const connectHopperSocketOnce = (const onAbort = (): void => {detach();socket.destroy();- resolve(err(new HopperCancelledError()));+ resolve(err(hopperCancelledBySignal(signal)));};socket.once("connect", onConnect);socket.once("error", onError);diff --git a/tests/boundary/providers/hopper/bridgeBootstrapCleanup.test.ts b/tests/boundary/providers/hopper/bridgeBootstrapCleanup.test.tsindex 81a8ffc5e..b45e68233 100644--- a/tests/boundary/providers/hopper/bridgeBootstrapCleanup.test.ts+++ b/tests/boundary/providers/hopper/bridgeBootstrapCleanup.test.ts@@ -3,6 +3,7 @@ import { join } from "node:path";import { expect, it } from "vitest";+import { HopperCancelledError } from "../../../../src/domain/hopperErrors.js";import { HopperApplicationLauncher } from "../../../../src/hopper/BridgeLauncher.js";import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";@@ -11,7 +12,8 @@ it.each(["failed", "cancelled"] as const)(async (outcome) => {const directory = await createTestTempDirectory("rea-bootstrap-cleanup-");const controller = new AbortController();- if (outcome === "cancelled") controller.abort();+ const reason = { source: "caller", opaque: 7 };+ if (outcome === "cancelled") controller.abort(reason);let releases = 0;const launcher = new HopperApplicationLauncher({@@ -45,11 +47,12 @@ it.each(["failed", "cancelled"] as const)({ signal: controller.signal },);expect(result.ok).toBe(false);- if (outcome === "cancelled")- expect(result).toMatchObject({- ok: false,- error: { _tag: "HopperCancelledError" },- });+ if (outcome === "cancelled") {+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected cancellation");+ expect(result.error).toBeInstanceOf(HopperCancelledError);+ expect(result.error.cause).toBe(reason);+ }await expect(lstat(join(directory, "bootstrap.py"))).rejects.toMatchObject({code: "ENOENT",});diff --git a/tests/boundary/providers/hopper/hopperClient.startupWaiters.test.ts b/tests/boundary/providers/hopper/hopperClient.startupWaiters.test.tsindex 6c2fdb7c2..fd25fc14d 100644--- a/tests/boundary/providers/hopper/hopperClient.startupWaiters.test.ts+++ b/tests/boundary/providers/hopper/hopperClient.startupWaiters.test.ts@@ -2,6 +2,7 @@ import { access } from "node:fs/promises";import { expect, it, vi } from "vitest";+import { HopperCancelledError } from "../../../../src/domain/hopperErrors.js";import { HopperClient } from "../../../../src/hopper/HopperClient.js";import { ok } from "../../../../src/domain/result.js";import { ProviderRunLineage } from "../../../../src/process/ProviderRunLineage.js";@@ -16,11 +17,13 @@ it("preserves a warm provider when an already cancelled caller joins", async ()const client = trackHopperClient(new HopperClient({ launcher }));await expect(client.start()).resolves.toMatchObject({ ok: true });const controller = new AbortController();- controller.abort();- await expect(client.start(controller.signal)).resolves.toMatchObject({- ok: false,- error: { _tag: "HopperCancelledError" },- });+ const reason = { source: "caller", opaque: 7 };+ controller.abort(reason);+ const joined = await client.start(controller.signal);+ expect(joined.ok).toBe(false);+ if (joined.ok) throw new Error("Expected cancellation");+ expect(joined.error).toBeInstanceOf(HopperCancelledError);+ expect(joined.error.cause).toBe(reason);expect(client.isReady()).toBe(true);expect(client.operationHealth()).toMatchObject({ state: "idle" });await expect(@@ -137,13 +140,18 @@ it.each([0, 1])(void waits[cancelledIndex]?.then((result) => {cancelled = result;});- controllers[cancelledIndex]?.abort();+ const reason = { source: "caller", opaque: cancelledIndex };+ controllers[cancelledIndex]?.abort(reason);await vi.waitFor(() =>expect(cancelled).toMatchObject({ok: false,error: { _tag: "HopperCancelledError" },}),);+ if (cancelled === undefined || cancelled.ok)+ throw new Error("Expected cancellation");+ expect(cancelled.error).toBeInstanceOf(HopperCancelledError);+ expect(cancelled.error.cause).toBe(reason);expect(launcher.processes).toHaveLength(0);release?.();await expect(waits[1 - cancelledIndex]).resolves.toMatchObject({