feat: complete REA remediation program
This commit is contained in:
+102
-16
@@ -3,7 +3,11 @@ import { chmod, writeFile } from "node:fs/promises";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { HopperCancelledError, HopperStartError } from "../domain/errors.js";
|
||||
import {
|
||||
HopperCancelledError,
|
||||
HopperProcessError,
|
||||
HopperStartError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
||||
import {
|
||||
@@ -11,6 +15,11 @@ import {
|
||||
spawnOwnedProviderProcess,
|
||||
} from "../process/ProviderProcess.js";
|
||||
import { waitForAbortableDelay } from "../process/ProviderDeadline.js";
|
||||
import {
|
||||
selectLinuxPrivateDisplayStrategy,
|
||||
type LinuxPrivateDisplayRunnableStrategy,
|
||||
type LinuxPrivateDisplaySelection,
|
||||
} from "./LinuxPrivateDisplayProbe.js";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -35,7 +44,12 @@ export interface BridgeLauncher {
|
||||
launch(
|
||||
session: BridgeSession,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
): Promise<Result<BridgeLaunch, HopperStartError | HopperCancelledError>>;
|
||||
): Promise<
|
||||
Result<
|
||||
BridgeLaunch,
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
>
|
||||
>;
|
||||
}
|
||||
|
||||
interface SharedHopperApplicationLauncherOptions {
|
||||
@@ -57,6 +71,13 @@ export type HopperApplicationLauncherOptions =
|
||||
readonly demoHelperPath: string;
|
||||
});
|
||||
|
||||
export interface HopperApplicationLauncherDependencies {
|
||||
readonly selectPrivateDisplay?: (options: {
|
||||
readonly helperPath: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}) => Promise<LinuxPrivateDisplaySelection>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Launches Hopper through its documented CLI and injects only REA's owned bridge.
|
||||
*
|
||||
@@ -72,12 +93,20 @@ export type HopperApplicationLauncherOptions =
|
||||
* macOS LaunchServices may create or reuse.
|
||||
*/
|
||||
export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
constructor(readonly options: HopperApplicationLauncherOptions) {}
|
||||
constructor(
|
||||
readonly options: HopperApplicationLauncherOptions,
|
||||
readonly dependencies: HopperApplicationLauncherDependencies = {},
|
||||
) {}
|
||||
|
||||
async launch(
|
||||
session: BridgeSession,
|
||||
options: { readonly signal?: AbortSignal } = {},
|
||||
): Promise<Result<BridgeLaunch, HopperStartError | HopperCancelledError>> {
|
||||
): Promise<
|
||||
Result<
|
||||
BridgeLaunch,
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
>
|
||||
> {
|
||||
const bootstrapPath = `${session.directory}/bootstrap.py`;
|
||||
const ownsProcessLifetime = usesLinuxDemo(this.options);
|
||||
const source = [
|
||||
@@ -109,12 +138,19 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
try {
|
||||
if (options.signal?.aborted === true)
|
||||
return err(new HopperCancelledError());
|
||||
const display = await this.#privateDisplay(options.signal);
|
||||
if (!display.ok) return err(display.error);
|
||||
const prepared = await prepareHopperApplication(
|
||||
this.options.launcherPath,
|
||||
options.signal,
|
||||
);
|
||||
if (!prepared) return err(new HopperCancelledError());
|
||||
const linuxDemo = linuxDemoLaunch(this.options, session, args);
|
||||
const linuxDemo = linuxDemoLaunch(
|
||||
this.options,
|
||||
session,
|
||||
args,
|
||||
display.strategy,
|
||||
);
|
||||
const ownershipCommand =
|
||||
linuxDemo?.ownershipCommand ?? this.options.launcherPath;
|
||||
const started = await spawnOwnedProviderProcess({
|
||||
@@ -154,12 +190,44 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
return err(hopperLaunchFailure(cause, options.signal));
|
||||
}
|
||||
}
|
||||
|
||||
async #privateDisplay(signal: AbortSignal | undefined): Promise<
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly strategy: LinuxPrivateDisplayRunnableStrategy | undefined;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly error: HopperProcessError | HopperCancelledError;
|
||||
}
|
||||
> {
|
||||
if (!usesLinuxDemo(this.options)) return { ok: true, strategy: undefined };
|
||||
const selection = await (
|
||||
this.dependencies.selectPrivateDisplay ??
|
||||
selectLinuxPrivateDisplayStrategy
|
||||
)({
|
||||
helperPath: this.options.demoHelperPath,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
if (signal?.aborted === true)
|
||||
return { ok: false, error: new HopperCancelledError() };
|
||||
return selection.ok
|
||||
? { ok: true, strategy: selection.strategy }
|
||||
: {
|
||||
ok: false,
|
||||
error: new HopperProcessError(
|
||||
selection.exitCode,
|
||||
selection.diagnostic,
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const linuxDemoLaunch = (
|
||||
export const linuxDemoLaunch = (
|
||||
options: HopperApplicationLauncherOptions,
|
||||
session: BridgeSession,
|
||||
hopperArgs: readonly string[],
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy | undefined,
|
||||
):
|
||||
| {
|
||||
readonly command: string;
|
||||
@@ -169,19 +237,37 @@ const linuxDemoLaunch = (
|
||||
| undefined => {
|
||||
if (!usesLinuxDemo(options) || options.demoHelperPath === undefined)
|
||||
return undefined;
|
||||
const helperArguments = [
|
||||
options.demoHelperPath,
|
||||
"--strategy",
|
||||
strategy ?? "direct",
|
||||
...(strategy === "user-mount-namespace" ? ["--mount-private-x11"] : []),
|
||||
"--hopper",
|
||||
options.launcherPath,
|
||||
"--socket",
|
||||
session.socketPath,
|
||||
"--",
|
||||
options.launcherPath,
|
||||
...hopperArgs,
|
||||
];
|
||||
if (strategy === "user-mount-namespace")
|
||||
return {
|
||||
command: "/usr/bin/unshare",
|
||||
ownershipCommand: "/usr/bin/python3",
|
||||
args: [
|
||||
"--user",
|
||||
"--map-root-user",
|
||||
"--mount",
|
||||
"--propagation",
|
||||
"private",
|
||||
"/usr/bin/python3",
|
||||
...helperArguments,
|
||||
],
|
||||
};
|
||||
return {
|
||||
command: "/usr/bin/python3",
|
||||
ownershipCommand: "/usr/bin/python3",
|
||||
args: [
|
||||
options.demoHelperPath,
|
||||
"--hopper",
|
||||
options.launcherPath,
|
||||
"--socket",
|
||||
session.socketPath,
|
||||
"--",
|
||||
options.launcherPath,
|
||||
...hopperArgs,
|
||||
],
|
||||
args: helperArguments,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
HopperStartError,
|
||||
hopperStartupFailure,
|
||||
HopperTimeoutError,
|
||||
type HopperStartupDiagnostic,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
@@ -32,6 +33,7 @@ import {
|
||||
type HopperServerInfo,
|
||||
} from "./HopperSessionValues.js";
|
||||
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
|
||||
import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js";
|
||||
import { parseResponseLine, responseResult } from "./protocol.js";
|
||||
|
||||
export type { HopperServerInfo } from "./HopperSessionValues.js";
|
||||
@@ -81,6 +83,7 @@ export class HopperClient {
|
||||
#buffer = "";
|
||||
#closing = false;
|
||||
#launcherExitCode: number | null | undefined;
|
||||
#launcherFailureDiagnostic: HopperStartupDiagnostic | undefined;
|
||||
#startupController: AbortController | undefined;
|
||||
#startPromise: Promise<Result<HopperServerInfo, HopperError>> | undefined;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
@@ -177,10 +180,11 @@ export class HopperClient {
|
||||
const socketPath = join(this.#runtimeRoot.path, "bridge.sock");
|
||||
this.#token = randomBytes(32).toString("hex");
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
const runId = randomUUID();
|
||||
const launched: Result<
|
||||
BridgeLaunch,
|
||||
HopperStartError | HopperCancelledError
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
> = await this.#options.launcher
|
||||
.launch(
|
||||
{
|
||||
@@ -327,6 +331,7 @@ export class HopperClient {
|
||||
this.#token = undefined;
|
||||
this.#buffer = "";
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
} finally {
|
||||
this.#closing = false;
|
||||
}
|
||||
@@ -356,7 +361,12 @@ export class HopperClient {
|
||||
this.#launcherExitCode !== undefined &&
|
||||
hopperStartupFailure(this.#launcherExitCode) !== undefined
|
||||
)
|
||||
return err(new HopperProcessError(this.#launcherExitCode));
|
||||
return err(
|
||||
new HopperProcessError(
|
||||
this.#launcherExitCode,
|
||||
this.#launcherFailureDiagnostic,
|
||||
),
|
||||
);
|
||||
try {
|
||||
await access(socketPath);
|
||||
} catch {
|
||||
@@ -459,12 +469,15 @@ export class HopperClient {
|
||||
}
|
||||
if (event.type !== "exit") return;
|
||||
this.#launcherExitCode = event.code;
|
||||
this.#launcherFailureDiagnostic = hopperLauncherFailureDiagnostic(event);
|
||||
this.#options.onDiagnostic?.({
|
||||
type: "launcher-exit",
|
||||
code: event.code,
|
||||
});
|
||||
if (launch.ownsProcessLifetime && !this.#closing)
|
||||
this.#failAll(new HopperProcessError(event.code));
|
||||
this.#failAll(
|
||||
new HopperProcessError(event.code, this.#launcherFailureDiagnostic),
|
||||
);
|
||||
}
|
||||
|
||||
#onData(chunk: string): void {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import {
|
||||
hopperStartupFailure,
|
||||
type HopperStartupDiagnostic,
|
||||
} from "../domain/errors.js";
|
||||
import type { ProviderProcessDiagnostic } from "../process/ProviderProcess.js";
|
||||
import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js";
|
||||
|
||||
/** Extract only a matching, versioned Linux adapter failure record. */
|
||||
export const hopperLauncherFailureDiagnostic = (
|
||||
event: Extract<ProviderProcessDiagnostic, { readonly type: "exit" }>,
|
||||
): HopperStartupDiagnostic | undefined => {
|
||||
const parsed = parseLinuxPrivateDisplayDiagnostic(
|
||||
event.snapshot.stderr.text,
|
||||
event.snapshot.stderr.truncated,
|
||||
);
|
||||
if (!parsed.ok) return undefined;
|
||||
const expected = hopperStartupFailure(event.code)?.code;
|
||||
return parsed.value.operation === "launch" &&
|
||||
parsed.value.status === "error" &&
|
||||
parsed.value.failure_code === expected
|
||||
? parsed.value
|
||||
: undefined;
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
isHopperStartupFailureCode,
|
||||
type HopperStartupDiagnostic,
|
||||
} from "../domain/hopperStartupFailure.js";
|
||||
|
||||
export const LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX = "REA_X11_DIAGNOSTIC_V1=";
|
||||
|
||||
const diagnosticSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
component: z.literal("hopper_private_display"),
|
||||
operation: z.enum(["probe", "launch"]),
|
||||
status: z.enum(["ready", "error"]),
|
||||
failure_code: z.string().max(64).nullable(),
|
||||
reason: z
|
||||
.string()
|
||||
.regex(/^[a-z0-9_]+$/u)
|
||||
.max(64),
|
||||
socket_directory: z.literal("/tmp/.X11-unix"),
|
||||
socket_directory_mode: z
|
||||
.string()
|
||||
.regex(/^[0-7]{4}$/u)
|
||||
.nullable(),
|
||||
mount_read_only: z.boolean().nullable(),
|
||||
effective_socket_directory_mode: z
|
||||
.string()
|
||||
.regex(/^[0-7]{4}$/u)
|
||||
.nullable(),
|
||||
effective_mount_read_only: z.boolean().nullable(),
|
||||
wsl: z.boolean(),
|
||||
strategy: z.enum(["direct", "user-mount-namespace", "unavailable"]),
|
||||
fallback_reason: z
|
||||
.string()
|
||||
.regex(/^[a-z0-9_]+$/u)
|
||||
.max(64)
|
||||
.nullable(),
|
||||
xvfb_stderr_bytes: z.number().int().nonnegative().safe(),
|
||||
xvfb_stderr_truncated: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type LinuxPrivateDisplayDiagnosticParse =
|
||||
| { readonly ok: true; readonly value: HopperStartupDiagnostic }
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason:
|
||||
| "diagnostic_missing"
|
||||
| "diagnostic_multiple"
|
||||
| "diagnostic_malformed"
|
||||
| "diagnostic_truncated";
|
||||
};
|
||||
|
||||
/** Parse exactly one bounded, versioned helper diagnostic from stderr. */
|
||||
export const parseLinuxPrivateDisplayDiagnostic = (
|
||||
stderr: string,
|
||||
truncated: boolean,
|
||||
): LinuxPrivateDisplayDiagnosticParse => {
|
||||
if (truncated) return { ok: false, reason: "diagnostic_truncated" };
|
||||
const records = stderr
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX));
|
||||
if (records.length === 0) return { ok: false, reason: "diagnostic_missing" };
|
||||
if (records.length !== 1) return { ok: false, reason: "diagnostic_multiple" };
|
||||
const record = records[0];
|
||||
if (record === undefined) return { ok: false, reason: "diagnostic_missing" };
|
||||
try {
|
||||
const parsed = diagnosticSchema.safeParse(
|
||||
JSON.parse(record.slice(LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX.length)),
|
||||
);
|
||||
if (!parsed.success) return { ok: false, reason: "diagnostic_malformed" };
|
||||
const code = parsed.data.failure_code;
|
||||
if (code !== null && !isHopperStartupFailureCode(code))
|
||||
return { ok: false, reason: "diagnostic_malformed" };
|
||||
if (
|
||||
(parsed.data.status === "ready" && code !== null) ||
|
||||
(parsed.data.status === "error" && code === null)
|
||||
)
|
||||
return { ok: false, reason: "diagnostic_malformed" };
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
...parsed.data,
|
||||
failure_code: code,
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return { ok: false, reason: "diagnostic_malformed" };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,326 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
hopperStartupExitCode,
|
||||
type HopperPrivateDisplayStrategy,
|
||||
type HopperStartupDiagnostic,
|
||||
type HopperStartupFailureCode,
|
||||
} from "../domain/hopperStartupFailure.js";
|
||||
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
spawnOwnedProviderProcess,
|
||||
} from "../process/ProviderProcess.js";
|
||||
import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js";
|
||||
|
||||
const PYTHON_PATH = "/usr/bin/python3";
|
||||
const UNSHARE_PATH = "/usr/bin/unshare";
|
||||
const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
|
||||
const PROBE_OUTPUT_LIMIT_BYTES = 64 * 1024;
|
||||
|
||||
export type LinuxPrivateDisplayRunnableStrategy = Exclude<
|
||||
HopperPrivateDisplayStrategy,
|
||||
"unavailable"
|
||||
>;
|
||||
|
||||
export interface LinuxPrivateDisplayProbeProcessResult {
|
||||
readonly exitCode: number | null | undefined;
|
||||
readonly stderr: string;
|
||||
readonly stderrBytes: number;
|
||||
readonly stderrTruncated: boolean;
|
||||
readonly timedOut: boolean;
|
||||
readonly cancelled: boolean;
|
||||
readonly cleanupIncomplete: boolean;
|
||||
}
|
||||
|
||||
export type LinuxPrivateDisplayProbeRunner = (
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy,
|
||||
options: {
|
||||
readonly helperPath: string;
|
||||
readonly timeoutMs: number;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
) => Promise<LinuxPrivateDisplayProbeProcessResult>;
|
||||
|
||||
export type LinuxPrivateDisplaySelection =
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly strategy: LinuxPrivateDisplayRunnableStrategy;
|
||||
readonly diagnostic: HopperStartupDiagnostic;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly strategy: "unavailable";
|
||||
readonly exitCode: number;
|
||||
readonly diagnostic: HopperStartupDiagnostic;
|
||||
};
|
||||
|
||||
/** Probe the exact Xvfb boundary and select the least-privileged viable strategy. */
|
||||
export const selectLinuxPrivateDisplayStrategy = async (options: {
|
||||
readonly helperPath: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly runProbe?: LinuxPrivateDisplayProbeRunner;
|
||||
}): Promise<LinuxPrivateDisplaySelection> => {
|
||||
const timeoutMs = options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
||||
const runner = options.runProbe ?? runLinuxPrivateDisplayProbe;
|
||||
const direct = await evaluatedProbe("direct", options, timeoutMs, runner);
|
||||
if (direct.ok) return direct;
|
||||
if (direct.diagnostic.failure_code !== "x11_socket_directory_unusable")
|
||||
return unavailable(direct.diagnostic);
|
||||
|
||||
const isolated = await evaluatedProbe(
|
||||
"user-mount-namespace",
|
||||
options,
|
||||
timeoutMs,
|
||||
runner,
|
||||
);
|
||||
if (!isolated.ok)
|
||||
return unavailable({
|
||||
...direct.diagnostic,
|
||||
strategy: "unavailable",
|
||||
reason: "namespace_unavailable",
|
||||
fallback_reason: isolated.diagnostic.reason,
|
||||
effective_socket_directory_mode:
|
||||
isolated.diagnostic.effective_socket_directory_mode,
|
||||
effective_mount_read_only: isolated.diagnostic.effective_mount_read_only,
|
||||
xvfb_stderr_bytes: isolated.diagnostic.xvfb_stderr_bytes,
|
||||
xvfb_stderr_truncated: isolated.diagnostic.xvfb_stderr_truncated,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
strategy: "user-mount-namespace",
|
||||
diagnostic: {
|
||||
...isolated.diagnostic,
|
||||
socket_directory_mode: direct.diagnostic.socket_directory_mode,
|
||||
mount_read_only: direct.diagnostic.mount_read_only,
|
||||
fallback_reason: null,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Run one helper probe in an owned process group with a hard output bound. */
|
||||
export const runLinuxPrivateDisplayProbe: LinuxPrivateDisplayProbeRunner =
|
||||
async (strategy, options) => {
|
||||
if (options.signal?.aborted === true)
|
||||
return emptyProcessResult({ cancelled: true });
|
||||
const command = privateDisplayProbeCommand(options.helperPath, strategy);
|
||||
let started: Awaited<ReturnType<typeof spawnOwnedProviderProcess>>;
|
||||
try {
|
||||
started = await spawnOwnedProviderProcess({
|
||||
command: command.command,
|
||||
arguments: command.arguments,
|
||||
runId: randomUUID(),
|
||||
expectedCommand: null,
|
||||
});
|
||||
} catch {
|
||||
return emptyProcessResult();
|
||||
}
|
||||
const launch = {
|
||||
process: started.process,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
|
||||
};
|
||||
const supervisor = new ProviderProcessSupervisor(launch, {
|
||||
maxOutputBytesPerStream: PROBE_OUTPUT_LIMIT_BYTES,
|
||||
});
|
||||
const outcome = await waitForProbeExit(
|
||||
supervisor,
|
||||
options.timeoutMs,
|
||||
options.signal,
|
||||
);
|
||||
let cleanupIncomplete = false;
|
||||
if (outcome !== "exit") {
|
||||
const stopped = await supervisor.stop();
|
||||
cleanupIncomplete = stopped.status === "incomplete";
|
||||
} else supervisor.dispose();
|
||||
const snapshot = supervisor.snapshot();
|
||||
return {
|
||||
exitCode: snapshot.exitCode,
|
||||
stderr: snapshot.stderr.text,
|
||||
stderrBytes: snapshot.stderr.bytes,
|
||||
stderrTruncated: snapshot.stderr.truncated,
|
||||
timedOut: outcome === "timeout",
|
||||
cancelled: outcome === "cancelled",
|
||||
cleanupIncomplete,
|
||||
};
|
||||
};
|
||||
|
||||
const privateDisplayProbeCommand = (
|
||||
helperPath: string,
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy,
|
||||
): { readonly command: string; readonly arguments: readonly string[] } =>
|
||||
strategy === "direct"
|
||||
? {
|
||||
command: PYTHON_PATH,
|
||||
arguments: [helperPath, "--probe", "--strategy", "direct"],
|
||||
}
|
||||
: {
|
||||
command: UNSHARE_PATH,
|
||||
arguments: [
|
||||
"--user",
|
||||
"--map-root-user",
|
||||
"--mount",
|
||||
"--propagation",
|
||||
"private",
|
||||
PYTHON_PATH,
|
||||
helperPath,
|
||||
"--probe",
|
||||
"--strategy",
|
||||
"user-mount-namespace",
|
||||
"--mount-private-x11",
|
||||
],
|
||||
};
|
||||
|
||||
const evaluatedProbe = async (
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy,
|
||||
options: {
|
||||
readonly helperPath: string;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
timeoutMs: number,
|
||||
runner: LinuxPrivateDisplayProbeRunner,
|
||||
): Promise<
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly strategy: LinuxPrivateDisplayRunnableStrategy;
|
||||
readonly diagnostic: HopperStartupDiagnostic;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly diagnostic: HopperStartupDiagnostic;
|
||||
}
|
||||
> => {
|
||||
let processResult: LinuxPrivateDisplayProbeProcessResult;
|
||||
try {
|
||||
processResult = await runner(strategy, {
|
||||
helperPath: options.helperPath,
|
||||
timeoutMs,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
ok: false,
|
||||
diagnostic: syntheticDiagnostic(strategy, "probe_failed"),
|
||||
};
|
||||
}
|
||||
if (processResult.cancelled)
|
||||
return {
|
||||
ok: false,
|
||||
diagnostic: syntheticDiagnostic(strategy, "cancelled"),
|
||||
};
|
||||
if (processResult.timedOut)
|
||||
return {
|
||||
ok: false,
|
||||
diagnostic: syntheticDiagnostic(strategy, "probe_timeout"),
|
||||
};
|
||||
if (processResult.cleanupIncomplete)
|
||||
return {
|
||||
ok: false,
|
||||
diagnostic: syntheticDiagnostic(strategy, "cleanup_incomplete"),
|
||||
};
|
||||
const parsed = parseLinuxPrivateDisplayDiagnostic(
|
||||
processResult.stderr,
|
||||
processResult.stderrTruncated,
|
||||
);
|
||||
if (!parsed.ok)
|
||||
return {
|
||||
ok: false,
|
||||
diagnostic: syntheticDiagnostic(strategy, parsed.reason),
|
||||
};
|
||||
const diagnostic = parsed.value;
|
||||
if (
|
||||
diagnostic.strategy !== strategy ||
|
||||
diagnostic.operation !== "probe" ||
|
||||
!exitMatchesDiagnostic(processResult.exitCode, diagnostic)
|
||||
)
|
||||
return {
|
||||
ok: false,
|
||||
diagnostic: syntheticDiagnostic(strategy, "diagnostic_malformed"),
|
||||
};
|
||||
return diagnostic.status === "ready"
|
||||
? { ok: true, strategy, diagnostic }
|
||||
: { ok: false, diagnostic };
|
||||
};
|
||||
|
||||
const exitMatchesDiagnostic = (
|
||||
exitCode: number | null | undefined,
|
||||
diagnostic: HopperStartupDiagnostic,
|
||||
): boolean =>
|
||||
diagnostic.status === "ready"
|
||||
? exitCode === 0
|
||||
: diagnostic.failure_code !== null &&
|
||||
hopperStartupExitCode(diagnostic.failure_code) === exitCode;
|
||||
|
||||
const syntheticDiagnostic = (
|
||||
strategy: LinuxPrivateDisplayRunnableStrategy,
|
||||
reason: string,
|
||||
failureCode: HopperStartupFailureCode = "private_display_unavailable",
|
||||
): HopperStartupDiagnostic => ({
|
||||
schema_version: 1,
|
||||
component: "hopper_private_display",
|
||||
operation: "probe",
|
||||
status: "error",
|
||||
failure_code: failureCode,
|
||||
reason,
|
||||
socket_directory: "/tmp/.X11-unix",
|
||||
socket_directory_mode: null,
|
||||
mount_read_only: null,
|
||||
effective_socket_directory_mode: null,
|
||||
effective_mount_read_only: null,
|
||||
wsl: false,
|
||||
strategy,
|
||||
fallback_reason: null,
|
||||
xvfb_stderr_bytes: 0,
|
||||
xvfb_stderr_truncated: false,
|
||||
});
|
||||
|
||||
const unavailable = (
|
||||
diagnostic: HopperStartupDiagnostic,
|
||||
): LinuxPrivateDisplaySelection => ({
|
||||
ok: false,
|
||||
strategy: "unavailable",
|
||||
exitCode:
|
||||
diagnostic.failure_code === null
|
||||
? 70
|
||||
: (hopperStartupExitCode(diagnostic.failure_code) ?? 70),
|
||||
diagnostic: { ...diagnostic, strategy: "unavailable" },
|
||||
});
|
||||
|
||||
const emptyProcessResult = (
|
||||
overrides: Partial<LinuxPrivateDisplayProbeProcessResult> = {},
|
||||
): LinuxPrivateDisplayProbeProcessResult => ({
|
||||
exitCode: undefined,
|
||||
stderr: "",
|
||||
stderrBytes: 0,
|
||||
stderrTruncated: false,
|
||||
timedOut: false,
|
||||
cancelled: false,
|
||||
cleanupIncomplete: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const waitForProbeExit = async (
|
||||
supervisor: ProviderProcessSupervisor,
|
||||
timeoutMs: number,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<"exit" | "timeout" | "cancelled"> => {
|
||||
if (signal?.aborted === true) return "cancelled";
|
||||
let releaseAbort: (() => void) | undefined;
|
||||
const aborted = new Promise<"cancelled">((resolve) => {
|
||||
if (signal === undefined) return;
|
||||
const listener = (): void => resolve("cancelled");
|
||||
signal.addEventListener("abort", listener, { once: true });
|
||||
releaseAbort = () => signal.removeEventListener("abort", listener);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([
|
||||
supervisor
|
||||
.waitForExit(Math.max(1, timeoutMs))
|
||||
.then((exited): "exit" | "timeout" => (exited ? "exit" : "timeout")),
|
||||
aborted,
|
||||
]);
|
||||
} finally {
|
||||
releaseAbort?.();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user