fix(hopper): preserve startup failures and recover denied launches

Preserve the primary Hopper startup failure and launcher diagnostics while retaining resources when cleanup cannot be confirmed. Reauthenticate matching external application sessions before document cleanup, keep the Python bridge available for bounded reconnects, and expose the provider-owned Hopper startup deadline.

Real headless Linux Hopper semantic analysis and 65 focused configuration, handshake, cleanup, and bridge tests passed. macOS authorization/crash causes and saved-HOP behavior require their own real-provider verification.

Refs #1808

Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
morluto
2026-10-11 22:35:01 +08:00
committed by GitHub
co-authored by N0zoM1z0 Kaoru0822
parent ee5275cd9f
commit 069308bbe6
25 changed files with 1074 additions and 166 deletions
+104 -35
View File
@@ -50,10 +50,15 @@ import {
} from "./HopperCleanup.js";
import {
parseHopperServerInfo,
HOPPER_SHUTDOWN_TIMEOUT_MS,
type HopperServerInfo,
} from "./HopperSessionValues.js";
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js";
import {
hopperLauncherFailureDiagnostic,
nativeHopperLaunchWasDenied,
} from "./HopperProcessDiagnostic.js";
import { DEFAULT_HOPPER_STARTUP_TIMEOUT_MS } from "../config/providerStartupTimeout.js";
import {
HopperRequestQueue,
type HopperRequestActivity,
@@ -68,7 +73,6 @@ import {
/** Aggregate in-memory retention budget for this provider's launcher output. */
export const HOPPER_PROCESS_DIAGNOSTIC_BYTES = 8 * 1024 * 1024;
const SHUTDOWN_TIMEOUT_MS = 30_000;
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
/** Dependencies, deadlines, and redacted diagnostics for one bridge client. */
@@ -114,6 +118,8 @@ export class HopperClient {
#launcherFailureDiagnostic: HopperStartupFailureDiagnostic | undefined;
#operationFailure: OperationFailureRecord | undefined;
#startupController: AbortController | undefined;
#startupFailureResult: AnalysisError | undefined;
#runId: string | undefined;
#startPromise: Promise<Result<HopperServerInfo, AnalysisError>> | undefined;
#closePromise: Promise<Result<null, AnalysisError>> | undefined;
readonly #onSocketData = (chunk: string): void => {
@@ -169,7 +175,8 @@ export class HopperClient {
this.#logger = options.logger ?? silentLogger;
this.#options = {
...options,
startupTimeoutMs: options.startupTimeoutMs ?? 120_000,
startupTimeoutMs:
options.startupTimeoutMs ?? DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
};
this.#requests = new HopperRequestQueue(
({ id, method, params }, failed) => {
@@ -311,14 +318,18 @@ export class HopperClient {
signal?: AbortSignal,
): Promise<Result<HopperServerInfo, AnalysisError>> {
if (isAborted(signal)) return err(new HopperCancelledError());
this.#operationFailure = undefined;
if (
this.#socket !== undefined ||
this.#resources.launch !== undefined ||
this.#resources.runtimeRoot !== undefined
) {
return err(new HopperProtocolError("Hopper client is already started"));
return err(
this.#startupFailureResult ??
new HopperProtocolError("Hopper client is already started"),
);
}
this.#operationFailure = undefined;
this.#startupFailureResult = undefined;
this.#resources.shutdownConfirmed = false;
const deadline = new ProviderStartupDeadline(
this.#options.startupTimeoutMs,
@@ -343,7 +354,7 @@ export class HopperClient {
return err(new HopperStartError({ cause }));
}
if (deadline.signal.aborted) {
return this.#startupFailure(startupInterruption(deadline));
return this.#startupFailure(await this.#startupInterruption(deadline));
}
const socketPath = join(this.#resources.runtimeRoot.path, "bridge.sock");
this.#token = randomBytes(32).toString("hex");
@@ -351,6 +362,7 @@ export class HopperClient {
this.#launcherExitCode = undefined;
this.#launcherFailureDiagnostic = undefined;
const runId = this.#options.runId ?? randomUUID();
this.#runId = runId;
const launched: Result<
BridgeLaunch,
HopperStartError | HopperCancelledError | HopperProcessError
@@ -368,7 +380,7 @@ export class HopperClient {
if (!launched.ok) {
return this.#startupFailure(
deadline.signal.aborted
? startupInterruption(deadline)
? await this.#startupInterruption(deadline)
: launched.error,
);
}
@@ -399,9 +411,7 @@ export class HopperClient {
}
const remainingMs = deadline.remainingMs();
if (remainingMs <= 0) {
return this.#startupFailure(
new HopperTimeoutError(this.#options.startupTimeoutMs),
);
return this.#startupFailure(await this.#startupInterruption(deadline));
}
const health = await this.#request(
"health",
@@ -413,7 +423,9 @@ export class HopperClient {
);
if (!health.ok) {
return this.#startupFailure(
deadline.signal.aborted ? startupInterruption(deadline) : health.error,
deadline.signal.aborted
? await this.#startupInterruption(deadline)
: health.error,
);
}
const parsed = parseHopperServerInfo(health.value, runId);
@@ -426,22 +438,20 @@ export class HopperClient {
primary: AnalysisError,
): Promise<Result<never, AnalysisError>> {
this.#rememberStartupFailure(primary);
// Failed readiness never authorized this connection to mutate a document.
this.#releaseTransport();
const closed = await this.#cleanup();
return err(
closed.ok
? primary
: analysisErrorWithCleanupFailure(primary, closed.error, "open_binary"),
);
const failure = closed.ok
? primary
: analysisErrorWithCleanupFailure(primary, closed.error, "open_binary");
this.#startupFailureResult = failure;
return err(failure);
}
#rememberStartupFailure(failure: AnalysisError): void {
if (failure instanceof HopperProcessError)
this.#rememberProcessFailure(failure, []);
else if (
this.#operationFailure === undefined &&
(failure instanceof HopperTimeoutError ||
failure instanceof HopperStartError)
)
else if (this.#operationFailure === undefined)
this.#operationFailure = {
state:
failure instanceof HopperTimeoutError ? "not_started" : "unknown",
@@ -500,6 +510,7 @@ export class HopperClient {
// best-effort cleanup: a rejected startup must not mask close/cleanup;
// #cleanup reports the authoritative close result.
await starting?.catch(() => undefined);
await this.#reconnectForCleanup();
return await this.#cleanup(options);
} finally {
if (this.#startPromise === starting) this.#startPromise = undefined;
@@ -510,6 +521,51 @@ export class HopperClient {
}
}
/** Reauthenticate this run after late readiness or a lost transport. */
async #reconnectForCleanup(): Promise<void> {
if (this.#socket?.destroyed === true) this.#releaseTransport();
const root = this.#resources.runtimeRoot;
const runId = this.#runId;
if (
this.#socket !== undefined ||
root === undefined ||
runId === undefined ||
this.#token === undefined ||
this.#resources.shutdownConfirmed ||
this.#resources.launch?.providerLifetime !== "external-application"
)
return;
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(),
HOPPER_SHUTDOWN_TIMEOUT_MS,
);
this.#closing = true;
try {
const connected = await connectHopperSocketOnce(
join(root.path, "bridge.sock"),
controller.signal,
);
if (!connected.ok) return;
const socket = connected.value;
this.#socket = socket;
this.#attachSocket(socket);
const health = await this.#request(
"health",
{},
{
signal: controller.signal,
timeoutMs: HOPPER_SHUTDOWN_TIMEOUT_MS,
},
);
if (health.ok && parseHopperServerInfo(health.value, runId).ok) return;
this.#releaseTransport();
} finally {
this.#closing = false;
clearTimeout(timer);
}
}
async #cleanup(
options: HopperClientCloseOptions = {},
): Promise<Result<null, AnalysisError>> {
@@ -523,18 +579,18 @@ export class HopperClient {
logger: this.#logger,
onDiagnostic: this.#options.onDiagnostic,
request: (method) =>
this.#request(method, {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS }),
this.#request(method, {}, { timeoutMs: HOPPER_SHUTDOWN_TIMEOUT_MS }),
retainDocument: options.retainDocument === true,
releaseTransport: (socket) => {
this.#failAll(new HopperProcessError(null));
if (socket !== undefined) this.#detachSocket(socket);
socket?.destroy();
},
releaseTransport: () => this.#releaseTransport(),
});
} finally {
if (this.#socket?.destroyed === true) this.#socket = undefined;
if (this.#socket === undefined) this.#token = undefined;
// Retained external launches may publish their authenticated socket later.
if (this.#resources.runtimeRoot === undefined) {
this.#token = undefined;
this.#runId = undefined;
}
if (this.#socket === undefined) this.#responses.reset();
if (this.#resources.processSupervisor === undefined) {
this.#launcherExitCode = undefined;
@@ -662,6 +718,17 @@ export class HopperClient {
"launch",
launcherFailure,
);
if (
this.#resources.launch?.authorizationDenialBeforeHandoff === true &&
nativeHopperLaunchWasDenied(launcherFailure)
) {
this.#resources.shutdownConfirmed = true;
return new HopperStartError({
userMessage:
"macOS denied permission to send Apple Events to Hopper. Allow the application that starts REA under System Settings > Privacy & Security > Automation, then retry opening the target.",
launcherFailure,
});
}
return new HopperStartError({
userMessage:
"Hopper's launcher helper failed before bridge readiness. Review details.launcher and complete Hopper setup before retrying.",
@@ -757,6 +824,15 @@ export class HopperClient {
socket.off("close", this.#onSocketClose);
}
#releaseTransport(): void {
const socket = this.#socket;
this.#socket = undefined;
this.#failAll(new HopperProcessError(null));
if (socket !== undefined) this.#detachSocket(socket);
socket?.destroy();
this.#responses.reset();
}
#attachLauncher(launch: BridgeLaunch): void {
this.#resources.processSupervisor = new ProviderProcessSupervisor(launch, {
maxDiagnosticBytes: HOPPER_PROCESS_DIAGNOSTIC_BYTES,
@@ -927,10 +1003,3 @@ const mergeFailedRequests = (
};
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
const startupInterruption = (
deadline: ProviderStartupDeadline,
): HopperCancelledError | HopperTimeoutError =>
deadline.interruption === "cancelled"
? new HopperCancelledError()
: new HopperTimeoutError(deadline.timeoutMs);