Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ios-simulator): await WDA process-group shutdown
JiangJiahaoeca7308e3c5a
diff --git a/packages/ios-simulator-runtime/src/wda/errors.ts b/packages/ios-simulator-runtime/src/wda/errors.tsindex 5095f5ec83..73528d4085 100644--- a/packages/ios-simulator-runtime/src/wda/errors.ts+++ b/packages/ios-simulator-runtime/src/wda/errors.ts@@ -12,6 +12,7 @@ export const WDA_ERROR_CODES = ["BUILD_FAILED","LAUNCH_FAILED","START_TIMEOUT",+ "TERMINATION_FAILED",] as const;export type WdaErrorCode = (typeof WDA_ERROR_CODES)[number];diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.tsindex 2101b70303..cef2aa264b 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts@@ -24,6 +24,12 @@ import {const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";const roots: string[] = [];+interface HarnessOptions {+ startTimeoutMs?: number;+ leaderExitsOn?: readonly NodeJS.Signals[];+ groupExitsOn?: readonly NodeJS.Signals[];+}+afterEach(async () => {await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),@@ -32,6 +38,7 @@ afterEach(async () => {async function createHarness(nativeCapabilityProvider?: WdaProcessManagerOptions["nativeCapabilityProvider"],+ harnessOptions: HarnessOptions = {},) {const root = await mkdtemp(path.join(os.tmpdir(), "cindy-wda-manager-test-"));roots.push(root);@@ -61,15 +68,35 @@ async function createHarness(let exitProcess:| ((value: { code: number | null; signal: NodeJS.Signals | null }) => void)| null = null;+ let leaderExited = false;+ let groupAlive = true;const killed: NodeJS.Signals[] = [];+ const settleLeader = (signal: NodeJS.Signals | null) => {+ if (leaderExited) return;+ leaderExited = true;+ exitProcess?.({ code: signal ? null : 0, signal });+ };+ const exitGroup = (signal: NodeJS.Signals | null = null) => {+ groupAlive = false;+ settleLeader(signal);+ };const process: WdaManagedProcess = {pid: 42,exited: new Promise((resolve) => {exitProcess = resolve;}),+ isAlive: vi.fn(() => groupAlive),kill: vi.fn((signal) => {killed.push(signal);- exitProcess?.({ code: 0, signal });+ if (harnessOptions.leaderExitsOn?.includes(signal)) {+ settleLeader(signal);+ }+ if (+ harnessOptions.groupExitsOn === undefined ||+ harnessOptions.groupExitsOn.includes(signal)+ ) {+ exitGroup(signal);+ }}),onOutput: vi.fn(() => () => undefined),};@@ -97,13 +124,14 @@ async function createHarness(deleteSession: vi.fn(async () => undefined),};let now = 1_000;- const ports = [18_100, 19_100];+ const ports = [18_100, 19_100, 18_101, 19_101];+ const launch = vi.fn(() => process);const manager = new WdaProcessManager({archivePath,cacheRoot: path.join(root, "cache"),sourceManifest: manifest,commandRunner: { run },- processLauncher: { launch: vi.fn(() => process) },+ processLauncher: { launch },allocatePort: vi.fn(async () => ports.shift()!),createDriver: vi.fn(() => driver as unknown as IOSSimulatorAutomationDriver,@@ -115,8 +143,18 @@ async function createHarness(},},nativeCapabilityProvider,+ startTimeoutMs: harnessOptions.startTimeoutMs,});- return { manager, run, driver, process, killed };+ return {+ manager,+ run,+ driver,+ process,+ killed,+ launch,+ exitGroup,+ exitLeader: settleLeader,+ };}describe("WdaProcessManager", () => {@@ -241,6 +279,176 @@ describe("WdaProcessManager", () => {expect(harness.killed).toEqual(["SIGINT"]);});+ it("awaits full process-group termination before returning a readiness timeout", async () => {+ const harness = await createHarness(undefined, {+ startTimeoutMs: 500,+ leaderExitsOn: ["SIGINT"],+ groupExitsOn: ["SIGKILL"],+ });+ harness.driver.probe.mockRejectedValue(new Error("connection refused"));++ await expect(+ harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ }),+ ).rejects.toMatchObject({ code: "START_TIMEOUT" });++ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(harness.process.isAlive()).toBe(false);+ });++ it("terminates the whole process group when WDA session setup fails", async () => {+ const harness = await createHarness(undefined, {+ leaderExitsOn: ["SIGINT"],+ groupExitsOn: ["SIGKILL"],+ });+ harness.driver.createSession.mockRejectedValue(new Error("session failed"));++ await expect(+ harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ }),+ ).rejects.toMatchObject({ code: "LAUNCH_FAILED" });++ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(harness.process.isAlive()).toBe(false);+ });++ it("waits through stop escalation when the leader exits before its process group", async () => {+ const harness = await createHarness(undefined, {+ leaderExitsOn: ["SIGINT"],+ groupExitsOn: ["SIGKILL"],+ });+ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });++ await harness.manager.stop("instance-a");++ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(harness.process.isAlive()).toBe(false);+ expect(harness.manager.get("instance-a")).toBeNull();+ });++ it("routes an unexpected leader exit through the process-group termination barrier", async () => {+ const harness = await createHarness(undefined, {+ groupExitsOn: ["SIGKILL"],+ });+ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });++ harness.exitLeader("SIGTERM");++ await vi.waitFor(() => {+ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(harness.manager.get("instance-a")).toBeNull();+ });+ expect(harness.process.isAlive()).toBe(false);+ });++ it("quarantines an unkillable process group and blocks replacement starts", async () => {+ const harness = await createHarness(undefined, {+ leaderExitsOn: ["SIGINT"],+ groupExitsOn: [],+ });+ const input = {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64" as const,+ };+ await harness.manager.start(input);++ await expect(harness.manager.stop("instance-a")).rejects.toMatchObject({+ code: "TERMINATION_FAILED",+ });+ await expect(harness.manager.start(input)).rejects.toMatchObject({+ code: "TERMINATION_FAILED",+ });++ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(harness.process.isAlive()).toBe(true);+ expect(harness.launch).toHaveBeenCalledTimes(1);+ });++ it("quarantines an unkillable readiness-timeout group before retrying start", async () => {+ const harness = await createHarness(undefined, {+ startTimeoutMs: 500,+ leaderExitsOn: ["SIGINT"],+ groupExitsOn: [],+ });+ harness.driver.probe.mockRejectedValue(new Error("connection refused"));+ const input = {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64" as const,+ };++ await expect(harness.manager.start(input)).rejects.toMatchObject({+ code: "TERMINATION_FAILED",+ });+ await expect(harness.manager.start(input)).rejects.toMatchObject({+ code: "TERMINATION_FAILED",+ });++ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(harness.process.isAlive()).toBe(true);+ expect(harness.launch).toHaveBeenCalledTimes(1);+ });++ it("cleans a retired process group before allowing a replacement start", async () => {+ const harness = await createHarness(undefined, {+ leaderExitsOn: ["SIGINT"],+ groupExitsOn: [],+ });+ const input = {+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64" as const,+ };+ await harness.manager.start(input);+ await expect(harness.manager.stop("instance-a")).rejects.toMatchObject({+ code: "TERMINATION_FAILED",+ });++ const replacement: WdaManagedProcess = {+ pid: 43,+ exited: new Promise(() => undefined),+ isAlive: vi.fn(() => true),+ kill: vi.fn(),+ onOutput: vi.fn(() => () => undefined),+ };+ harness.launch.mockReturnValue(replacement);+ harness.exitGroup();++ const running = await harness.manager.start(input);++ expect(running.pid).toBe(43);+ expect(harness.launch).toHaveBeenCalledTimes(2);+ });+it("attaches the optional native adapter by exact generation and stops it with WDA", async () => {const nativeDriver = {kind: "native-sidecar",diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.ts b/packages/ios-simulator-runtime/src/wda/process-manager.tsindex 7990e13671..4c9f840dfa 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.ts@@ -26,6 +26,10 @@ import {} from "./source-provider.js";const MAX_LOG_BYTES = 256 * 1024;+const WDA_INTERRUPT_GRACE_MS = 5_000;+const WDA_TERMINATE_GRACE_MS = 1_000;+const WDA_KILL_GRACE_MS = 500;+const WDA_EXIT_POLL_MS = 25;export interface WdaManagedProcess {readonly pid: number;@@ -33,6 +37,7 @@ export interface WdaManagedProcess {code: number | null;signal: NodeJS.Signals | null;}>;+ isAlive(): boolean;kill(signal: NodeJS.Signals): void;onOutput(listener: (chunk: string) => void): () => void;}@@ -104,6 +109,12 @@ interface PendingWdaOperation {promise?: Promise<WdaRunningInstance>;}+interface RetiringWdaProcess {+ process: WdaManagedProcess;+ simulatorUdid: string;+ finalizing?: Promise<void>;+}+class BoundedLog {#value = "";@@ -191,6 +202,7 @@ export function createNodeWdaProcessLauncher(): WdaProcessLauncher {});if (!child.pid)throw new WdaError("LAUNCH_FAILED", "WDA process did not start");+ const pid = child.pid;const listeners = new Set<(chunk: string) => void>();const publish = (chunk: Buffer) => {const text = chunk.toString("utf8");@@ -198,16 +210,36 @@ export function createNodeWdaProcessLauncher(): WdaProcessLauncher {};child.stdout?.on("data", publish);child.stderr?.on("data", publish);+ let leaderExited = false;+ const exited = new Promise<{+ code: number | null;+ signal: NodeJS.Signals | null;+ }>((resolve) => {+ child.once("exit", (code, signal) => {+ leaderExited = true;+ resolve({ code, signal });+ });+ child.once("error", () => {+ leaderExited = true;+ resolve({ code: null, signal: null });+ });+ });return {- pid: child.pid,- exited: new Promise((resolve) => {- child.once("exit", (code, signal) => resolve({ code, signal }));- child.once("error", () => resolve({ code: null, signal: null }));- }),+ pid,+ exited,+ isAlive() {+ if (process.platform === "win32") return !leaderExited;+ try {+ process.kill(-pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException | null)?.code === "EPERM";+ }+ },kill(signal) {- if (process.platform !== "win32" && child.pid) {+ if (process.platform !== "win32") {try {- process.kill(-child.pid, signal);+ process.kill(-pid, signal);return;} catch {// The group may have already exited; fall back to the direct@@ -254,6 +286,7 @@ export class WdaProcessManager {readonly #running = new Map<string, InternalRunningInstance>();readonly #starting = new Map<string, PendingWdaOperation>();readonly #stopping = new Map<string, Promise<void>>();+ readonly #retiring = new Map<string, RetiringWdaProcess>();constructor(options: WdaProcessManagerOptions) {this.#options = options;@@ -324,6 +357,8 @@ export class WdaProcessManager {start(options: WdaStartOptions): Promise<WdaRunningInstance> {const stopping = this.#stopping.get(options.instanceId);if (stopping) return stopping.then(() => this.start(options));+ const retiring = this.#retiring.get(options.instanceId);+ if (retiring) return this.#resumeAfterRetiringProcess(options, retiring);const running = this.get(options.instanceId);if (running) return Promise.resolve(running);const pending = this.#starting.get(options.instanceId);@@ -464,11 +499,16 @@ export class WdaProcessManager {}if (!health) {unsubscribeOutput();- process.kill("SIGINT");- throw new WdaError(+ const failure = new WdaError("START_TIMEOUT","WebDriverAgent did not become ready in time",);+ await this.#terminateProcessGroup(+ options.instanceId,+ options.simulatorUdid,+ process,+ );+ throw failure;}let driverSessionId: string;try {@@ -481,11 +521,16 @@ export class WdaProcessManager {});} catch (error) {unsubscribeOutput();- process.kill("SIGINT");- throw new WdaError(+ const failure = new WdaError("LAUNCH_FAILED",`WebDriverAgent session setup failed: ${error instanceof Error ? error.message : String(error)}`,);+ await this.#terminateProcessGroup(+ options.instanceId,+ options.simulatorUdid,+ process,+ );+ throw failure;}let nativeSidecar: IOSSimulatorNativeSidecarDriver | undefined;let nativeUnavailableReason: string | null = null;@@ -551,9 +596,7 @@ export class WdaProcessManager {this.#running.set(options.instanceId, running);void process.exited.then(() => {if (this.#running.get(options.instanceId)?.pid === process.pid) {- unsubscribeOutput();- void nativeManager?.stop(options.instanceId).catch(() => undefined);- this.#running.delete(options.instanceId);+ void this.stop(options.instanceId).catch(() => undefined);}});return this.get(options.instanceId)!;@@ -581,6 +624,120 @@ export class WdaProcessManager {});}+ #isProcessGroupAlive(process: WdaManagedProcess): boolean {+ try {+ return process.isAlive();+ } catch {+ // A failed liveness probe cannot prove that the process group is gone.+ return true;+ }+ }++ async #waitForProcessGroupExit(+ process: WdaManagedProcess,+ timeoutMs: number,+ ): Promise<boolean> {+ const deadline = this.#clock.now() + timeoutMs;+ while (this.#isProcessGroupAlive(process)) {+ const remaining = deadline - this.#clock.now();+ if (remaining <= 0) return false;+ await this.#clock.sleep(Math.min(WDA_EXIT_POLL_MS, remaining));+ }+ return true;+ }++ #rememberRetiringProcess(+ instanceId: string,+ simulatorUdid: string,+ process: WdaManagedProcess,+ ): void {+ const retiring = { process, simulatorUdid };+ this.#retiring.set(instanceId, retiring);+ void process.exited+ .then(() => this.#finalizeRetiringProcess(instanceId, retiring))+ .catch(() => undefined);+ }++ async #finalizeRetiringProcess(+ instanceId: string,+ retiring: RetiringWdaProcess,+ ): Promise<void> {+ if (+ this.#retiring.get(instanceId) !== retiring ||+ this.#isProcessGroupAlive(retiring.process)+ ) {+ return;+ }+ retiring.finalizing ??= cleanupDetachedDiagnostics(+ this.#options.cacheRoot,+ retiring.simulatorUdid,+ );+ await retiring.finalizing;+ if (+ this.#retiring.get(instanceId) === retiring &&+ !this.#isProcessGroupAlive(retiring.process)+ ) {+ this.#retiring.delete(instanceId);+ }+ }++ async #terminateProcessGroup(+ instanceId: string,+ simulatorUdid: string,+ process: WdaManagedProcess,+ ): Promise<void> {+ const stages: ReadonlyArray<{+ signal: NodeJS.Signals;+ graceMs: number;+ }> = [+ { signal: "SIGINT", graceMs: WDA_INTERRUPT_GRACE_MS },+ { signal: "SIGTERM", graceMs: WDA_TERMINATE_GRACE_MS },+ { signal: "SIGKILL", graceMs: WDA_KILL_GRACE_MS },+ ];+ for (const stage of stages) {+ if (!this.#isProcessGroupAlive(process)) break;+ try {+ process.kill(stage.signal);+ } catch {+ // Exit observation remains authoritative; continue the bounded wait.+ }+ if (await this.#waitForProcessGroupExit(process, stage.graceMs)) break;+ }+ if (this.#isProcessGroupAlive(process)) {+ this.#rememberRetiringProcess(instanceId, simulatorUdid, process);+ throw new WdaError(+ "TERMINATION_FAILED",+ "WebDriverAgent process group did not terminate after SIGKILL",+ );+ }+ const retiring = this.#retiring.get(instanceId);+ if (retiring?.process === process) {+ await this.#finalizeRetiringProcess(instanceId, retiring);+ } else {+ await cleanupDetachedDiagnostics(this.#options.cacheRoot, simulatorUdid);+ }+ }++ async #resumeAfterRetiringProcess(+ options: WdaStartOptions,+ retiring: RetiringWdaProcess,+ ): Promise<WdaRunningInstance> {+ if (this.#isProcessGroupAlive(retiring.process)) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "A previous WebDriverAgent process group is still terminating",+ );+ }+ await this.#finalizeRetiringProcess(options.instanceId, retiring);+ if (this.#retiring.get(options.instanceId) === retiring) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "A previous WebDriverAgent process group cleanup is still pending",+ );+ }+ return this.start(options);+ }+async stop(instanceId: string): Promise<void> {const existing = this.#stopping.get(instanceId);if (existing) return existing;@@ -601,6 +758,14 @@ export class WdaProcessManager {.catch(() => undefined);await pending.promise?.catch(() => undefined);}+ const retiring = this.#retiring.get(instanceId);+ if (retiring) {+ await this.#terminateProcessGroup(+ instanceId,+ retiring.simulatorUdid,+ retiring.process,+ );+ }const running = this.#running.get(instanceId);if (!running) return;this.#running.delete(instanceId);@@ -613,15 +778,10 @@ export class WdaProcessManager {} catch {// The XCTest process may already be gone; process shutdown remains authoritative.}- running.process.kill("SIGINT");- const exited = await Promise.race([- running.process.exited.then(() => true),- this.#clock.sleep(5_000).then(() => false),- ]);- if (!exited) running.process.kill("SIGTERM");- await cleanupDetachedDiagnostics(- this.#options.cacheRoot,+ await this.#terminateProcessGroup(+ instanceId,running.simulatorUdid,+ running.process,);}}