diff --git a/examples/test-app/README.md b/examples/test-app/README.md index c616b4000f..7edda45d3e 100644 --- a/examples/test-app/README.md +++ b/examples/test-app/README.md @@ -18,6 +18,7 @@ It is intentionally small, but each surface is dense with durable accessibility - `Settings`: switch rows, accordion content, loading and error states, retry flow, destructive-confirm modal - `Automation lab`: long-press, alert-result, app-event, app-state, appearance, orientation, permission-recovery, log canaries, a flattened (`accessible={true}`) text input, and an Apple Pay sheet hosted in `com.apple.PassbookUIService` - `WebView accessibility`: a deterministic semantic fixture plus live websites with varied HTML for native accessibility snapshot verification +- `Sign-in sheet lab`: a real `ASWebAuthenticationSession` sheet hosted out of process in `com.apple.SafariViewService`, opened against a loopback fixture identity provider (see [Sign-in sheet lab](#sign-in-sheet-lab)) - `Perf lab`: seeded JavaScript render problems for `react-devtools profile`, one per scenario (see [Perf lab](#perf-lab)) - `Settle lab`: timed effects with known final screens for `--settle` regression runs (an in-place counter; results 500 and 800 ms after an immediate `Run N` acknowledgement; a 750 ms fading overlay; two-stage transitions with and without a spinner; a toast that precedes navigation), reached by the `agent-device-test-app://settle-lab` deep link - `Heavy feed`: a Bluesky-shaped home feed whose accessibility tree is deeper than 65 levels (see [Heavy feed](#heavy-feed)) @@ -334,6 +335,55 @@ The stable ids are `heavy-feed-title`, `heavy-feed-liked-count`, `heavy-feed-las post `heavy-post-`, `heavy-post--like`, `-reply`, `-repost`, and `-more`. A like press updates `Liked posts: `, and a long press on a post sets `Last action: held post `. +## Sign-in sheet lab + +**Settings → Open sign-in sheet lab** (`open-auth-session-lab`, route `auth-session-lab`) presents a +real `ASWebAuthenticationSession` sheet. iOS hosts that sheet out of the app's process in +`com.apple.SafariViewService`, over this screen and with the app still the accessibility primaryApp, +so it is the committed fixture for reading and driving a hosted web sign-in sheet in place (#2438, +#2449). The native module is `modules/auth-session-lab`; nothing about the flow activates or +relaunches anything, which is what keeps the sheet alive. + +The sheet opens a page served over loopback by the fixture identity provider, so the flow involves +no real identity provider and no credential: `src/auth-idp-fixture.ts` owns the page and `Email`, +`Password`, and `LOGIN` are the vocabulary a lane asserts on. Submitting the fixture form navigates +to the app's own callback scheme, which ends the sheet and returns the app; `auth-session-status` +then reports `completed` and `auth-session-message` carries the callback URL. + +Run the lane with the sheet's page served by the same script that owns its lifecycle: + +```bash +pnpm test-app:maestro:auth:ios -- --udid "" +``` + +The launcher starts the provider at `127.0.0.1:4593` and runs +`examples/test-app/maestro-ios/auth-session-sheet.yaml` through `agent-device test --maestro`. When +the flow ends or you cancel it, the launcher closes the provider. + +To drive the sheet by hand and see its loading state, start the provider from the repo root: + +```bash +node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs --delay-ms 6000 +``` + +Omit `--delay-ms` to show the form immediately. + +The committed flow reads the sheet and stops at its form controls. Driving past that point is not +committed, because on iOS 27.0 the same steps alternate between passing and refusing the capture, +which is the intermittency #4593 reports. Fill the sheet's fields and submit it when you want that +state, and expect to see one of three capture refusals on the step that follows the first `inputText` +or the submit: `regular iOS snapshot presentation requires a valid viewport`, `regular iOS snapshot +node escaped its cumulative clip`, or `main thread execution timed out`. The first two come from +`packages/capture-kit/src/ios-snapshot-engine/invariants.ts`. The XCTest runner reports the third, which +`packages/apple-runner/src/runner-failure-diagnostics.ts` classifies. The viewport refusal carries no +`retriable` flag, so the step aborts during stability re-capture. + +The app needs a build that includes the module: a development client (`pnpm test-app:ios`) or a +Release build (`pnpm --dir examples/test-app exec expo run:ios --configuration Release --device +generic --no-bundler`). It is a native change, so it produces one new fingerprinted build that +consumers then share. A build without it shows `unavailable` in `auth-session-status` instead of +opening a sheet. + ## Local Agent Device suites The repo includes two local suites for iterating on the fixture app: diff --git a/examples/test-app/app/(tabs)/settings.tsx b/examples/test-app/app/(tabs)/settings.tsx index e8e39b4796..a696104a95 100644 --- a/examples/test-app/app/(tabs)/settings.tsx +++ b/examples/test-app/app/(tabs)/settings.tsx @@ -18,6 +18,7 @@ export default function SettingsRoute() { onConfirmReset={state.resetLabState} onLoadDiagnostics={state.loadDiagnostics} onOpenAccessorySetup={() => router.push('/accessory-setup')} + onOpenAuthSessionLab={() => router.push('/auth-session-lab')} onOpenAutomationLab={() => router.push('/automation')} onOpenHeavyFeed={() => router.push('/heavy-feed')} onOpenInertSurface={() => router.push('/inert')} diff --git a/examples/test-app/app/_layout.tsx b/examples/test-app/app/_layout.tsx index 38ca0c0e9f..21589a906c 100644 --- a/examples/test-app/app/_layout.tsx +++ b/examples/test-app/app/_layout.tsx @@ -24,6 +24,7 @@ function RootLayoutContent() { > + diff --git a/examples/test-app/app/auth-session-lab.tsx b/examples/test-app/app/auth-session-lab.tsx new file mode 100644 index 0000000000..1f15e5143f --- /dev/null +++ b/examples/test-app/app/auth-session-lab.tsx @@ -0,0 +1,14 @@ +import { useRouter } from 'expo-router'; + +import { AppFrame } from '../src/components'; +import { AuthSessionLabScreen } from '../src/screens/AuthSessionLabScreen'; + +export default function AuthSessionLabRoute() { + const router = useRouter(); + + return ( + + router.back()} /> + + ); +} diff --git a/examples/test-app/maestro-ios/auth-session-sheet.yaml b/examples/test-app/maestro-ios/auth-session-sheet.yaml new file mode 100644 index 0000000000..9539eed2fa --- /dev/null +++ b/examples/test-app/maestro-ios/auth-session-sheet.yaml @@ -0,0 +1,32 @@ +appId: com.callstack.agentdevicelab +name: Sign-in sheet +# Read SafariViewService in place while the app remains the accessibility primaryApp (#2438). +# Stop before typing or submitting, which can encounter the capture refusals in #4593. +env: + AUTH_SHEET_TIMEOUT: '20000' +onFlowStart: + - launchApp: + clearState: true + - assertVisible: Agent Device Tester +--- +- tapOn: + text: Settings +- scrollUntilVisible: + element: + id: open-auth-session-lab +- tapOn: + id: open-auth-session-lab +- assertVisible: Sign-in sheet lab +- assertVisible: + id: auth-session-open +- tapOn: + id: auth-session-open +- extendedWaitUntil: + visible: Fixture sign-in + timeout: ${AUTH_SHEET_TIMEOUT} +- assertVisible: + text: Email +- assertVisible: + text: Password +- assertVisible: + text: LOGIN diff --git a/examples/test-app/modules/auth-session-lab/expo-module.config.json b/examples/test-app/modules/auth-session-lab/expo-module.config.json new file mode 100644 index 0000000000..5187edc63e --- /dev/null +++ b/examples/test-app/modules/auth-session-lab/expo-module.config.json @@ -0,0 +1,6 @@ +{ + "platforms": ["ios"], + "apple": { + "modules": ["AuthSessionLabModule"] + } +} diff --git a/examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec new file mode 100644 index 0000000000..91d7ee9225 --- /dev/null +++ b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec @@ -0,0 +1,16 @@ +Pod::Spec.new do |s| + s.name = 'AuthSessionLab' + s.version = '1.0.0' + s.summary = 'ASWebAuthenticationSession fixture for Agent Device Tester' + s.description = s.summary + s.license = { :type => 'MIT' } + s.author = { 'Callstack' => 'opensource@callstack.com' } + s.homepage = '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/callstack/agent-device' + s.platforms = { :ios => '15.1' } + s.source = { :git => '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/callstack/agent-device.git' } + s.static_framework = true + + s.dependency 'ExpoModulesCore' + s.frameworks = 'AuthenticationServices', 'Foundation', 'UIKit' + s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' +end diff --git a/examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift new file mode 100644 index 0000000000..669cf0bcee --- /dev/null +++ b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift @@ -0,0 +1,86 @@ +import AuthenticationServices +import ExpoModulesCore +import UIKit + +// Presents a real sign-in sheet through ASWebAuthenticationSession. iOS hosts that sheet out of +// process in com.apple.SafariViewService, which makes this the #2449 fixture: the sheet is read and +// driven in place (#2438), the app stays the accessibility primaryApp while the sheet is up, and no +// step may activate or relaunch anything. +// +// The page itself is served by the fixture identity provider, not by the app: see +// `src/auth-idp-fixture.ts` for its content and `scripts/serve-auth-idp.mjs`, in this app's folder, +// for the server a lane starts. It holds fixture values only, so this flow needs no credentials. +// `startSignInAsync` resolves with the callback URL the sheet ended on, which is the observable end +// of the flow. +public final class AuthSessionLabModule: Module { + public func definition() -> ModuleDefinition { + Name("AuthSessionLab") + + AsyncFunction("startSignInAsync") { (url: String, callbackScheme: String, promise: Promise) in + AuthSessionLabController.shared.start(url: url, callbackScheme: callbackScheme, promise: promise) + }.runOnQueue(.main) + } +} + +private final class AuthSessionLabController: NSObject { + static let shared = AuthSessionLabController() + + private struct Session { + let controller: ASWebAuthenticationSession + let promise: Promise + } + + // One sheet at a time: two concurrent sessions would make which sheet answered ambiguous. + private var session: Session? + + func start(url: String, callbackScheme: String, promise: Promise) { + guard session == nil else { + promise.reject( + Exception( + name: "AuthSessionAlreadyPresented", + description: "A sign-in sheet is already presented." + ) + ) + return + } + + guard let url = URL(string: url), url.scheme != nil else { + promise.reject( + Exception(name: "InvalidAuthURL", description: "The sign-in URL is not a valid URL.") + ) + return + } + + let controller = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) { + callbackURL, error in + guard let session = self.session else { return } + self.session = nil + if let callbackURL { + session.promise.resolve(callbackURL.absoluteString) + return + } + let sessionError = error as? ASWebAuthenticationSessionError + session.promise.reject( + Exception( + name: sessionError?.code == .canceledLogin ? "AuthSessionCanceled" : "AuthSessionFailed", + description: error?.localizedDescription ?? "The sign-in session failed." + ) + ) + } + + // Ephemeral so the sheet shares no cookies or website data with anything else on the device. + controller.prefersEphemeralWebBrowserSession = true + controller.presentationContextProvider = self + session = Session(controller: controller, promise: promise) + controller.start() + } +} + +extension AuthSessionLabController: ASWebAuthenticationPresentationContextProviding { + public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + let windows = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .flatMap(\.windows) + return windows.first(where: \.isKeyWindow) ?? ASPresentationAnchor() + } +} diff --git a/examples/test-app/scripts/serve-auth-idp.mjs b/examples/test-app/scripts/serve-auth-idp.mjs new file mode 100644 index 0000000000..7aeff817e6 --- /dev/null +++ b/examples/test-app/scripts/serve-auth-idp.mjs @@ -0,0 +1,24 @@ +#!/usr/bin/env node +import { AUTH_IDP_DEFAULT_URL } from '../src/auth-idp-fixture.ts'; +import { startAuthIdpServer } from '../src/auth-idp-server.mjs'; + +const [flag, value, ...rest] = process.argv.slice(2); +const delayMs = Number(value ?? 0); +if ( + flag !== undefined && + (flag !== '--delay-ms' || + !value?.trim() || + !Number.isFinite(delayMs) || + delayMs < 0 || + rest.length) +) { + console.error( + 'Usage: node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs [--delay-ms ]', + ); + process.exitCode = 1; +} else { + const provider = await startAuthIdpServer({ delayMs }); + console.log(`[auth-idp] ${AUTH_IDP_DEFAULT_URL} delayMs=${delayMs}`); + process.once('SIGINT', () => provider.close()); + process.once('SIGTERM', () => provider.close()); +} diff --git a/examples/test-app/src/auth-idp-fixture.ts b/examples/test-app/src/auth-idp-fixture.ts new file mode 100644 index 0000000000..c70727e649 --- /dev/null +++ b/examples/test-app/src/auth-idp-fixture.ts @@ -0,0 +1,69 @@ +export const AUTH_IDP_DEFAULT_PORT = 4593; + +export const AUTH_IDP_PATH = '/auth-idp'; + +export const AUTH_IDP_DEFAULT_URL = `http://127.0.0.1:${AUTH_IDP_DEFAULT_PORT}${AUTH_IDP_PATH}`; + +export const AUTH_IDP_FIXTURE_REDIRECT = + 'agent-device-test-app://auth-callback?code=fixture-code&state=fixture-state'; +// The words a lane asserts on. Keep the Maestro flow and this page changed together. +export const AUTH_IDP_TEXT = { + loading: 'Loading sign-in', + title: 'Fixture sign-in', + email: 'Email', + password: 'Password', + submit: 'LOGIN', +} as const; + +// On iOS 27.0 the sheet intercepts native form submission to the callback scheme. +// Redirecting from page script with `location.assign` leaves the sheet open. +export function renderAuthIdpPage(options: { delayMs?: number } = {}): string { + const delayMs = options.delayMs ?? 0; + if (delayMs > 0) { + return ` + + + + ${AUTH_IDP_TEXT.loading} + + + +

${AUTH_IDP_TEXT.loading}

+ + +`; + } + + return ` + + + + ${AUTH_IDP_TEXT.title} + + + +

${AUTH_IDP_TEXT.title}

+
+ + + +
+ + +`; +} diff --git a/examples/test-app/src/auth-idp-server.mjs b/examples/test-app/src/auth-idp-server.mjs new file mode 100644 index 0000000000..33d0605a1a --- /dev/null +++ b/examples/test-app/src/auth-idp-server.mjs @@ -0,0 +1,46 @@ +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { AUTH_IDP_DEFAULT_URL, AUTH_IDP_PATH, renderAuthIdpPage } from './auth-idp-fixture.ts'; + +export async function startAuthIdpServer({ delayMs = 0 } = {}) { + let nextDelayMs = delayMs; + const server = createServer((request, response) => { + if (request.url?.split('?', 1)[0] !== AUTH_IDP_PATH) { + response.writeHead(404, { 'content-type': 'text/plain' }); + response.end('not found\n'); + return; + } + + const html = renderAuthIdpPage({ delayMs: nextDelayMs }); + nextDelayMs = 0; + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'content-length': Buffer.byteLength(html), + 'cache-control': 'no-store', + }); + response.end(html); + }); + + const url = new URL(AUTH_IDP_DEFAULT_URL); + const startup = new AbortController(); + const timeout = setTimeout( + () => startup.abort(new Error('provider was not ready within 15s')), + 15_000, + ); + try { + server.listen({ host: url.hostname, port: Number(url.port), signal: startup.signal }); + await once(server, 'listening', { signal: startup.signal }); + } finally { + clearTimeout(timeout); + } + + let closed; + return { + close() { + return (closed ??= new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + server.closeAllConnections(); + })); + }, + }; +} diff --git a/examples/test-app/src/auth-session.ts b/examples/test-app/src/auth-session.ts new file mode 100644 index 0000000000..71bfcc14f3 --- /dev/null +++ b/examples/test-app/src/auth-session.ts @@ -0,0 +1,31 @@ +import { Platform } from 'react-native'; +import { requireOptionalNativeModule } from 'expo-modules-core'; + +// The callback scheme the fixture registers in app.config.js. A real IdP redirect lands here, so +// the sheet closing with a callback to this scheme is the observable end of the flow. +export const AUTH_SESSION_CALLBACK_SCHEME = 'agent-device-test-app'; + +type AuthSessionLabModule = { + startSignInAsync(url: string, callbackScheme: string): Promise; +}; + +const authSessionLab = + Platform.OS === 'ios' + ? requireOptionalNativeModule('AuthSessionLab') + : null; + +export function isAuthSessionLabAvailable(): boolean { + return authSessionLab !== null; +} + +/** + * Opens the system sign-in sheet for `url` and resolves with the callback URL the fixture IdP + * redirected to. Rejects when the sheet is canceled or fails. + */ +export async function startFixtureSignInSession(url: string): Promise { + if (!authSessionLab) { + throw new Error('Rebuild the iOS development client to include AuthSessionLab.'); + } + + return authSessionLab.startSignInAsync(url, AUTH_SESSION_CALLBACK_SCHEME); +} diff --git a/examples/test-app/src/screens/AuthSessionLabScreen.tsx b/examples/test-app/src/screens/AuthSessionLabScreen.tsx new file mode 100644 index 0000000000..617d312596 --- /dev/null +++ b/examples/test-app/src/screens/AuthSessionLabScreen.tsx @@ -0,0 +1,103 @@ +import { useState } from 'react'; +import { ScrollView, StyleSheet, Text } from 'react-native'; + +import { AUTH_IDP_DEFAULT_URL } from '../auth-idp-fixture'; +import { isAuthSessionLabAvailable, startFixtureSignInSession } from '../auth-session'; +import { ActionButton, InlineBadge, ScreenTitle, SectionCard } from '../components'; +import { useAppColors, type AppColors } from '../theme'; + +type SheetStatus = 'idle' | 'presenting' | 'completed' | 'canceled' | 'error' | 'unavailable'; + +function initialStatus(): SheetStatus { + return isAuthSessionLabAvailable() ? 'idle' : 'unavailable'; +} + +export function AuthSessionLabScreen(props: { onBack: () => void }) { + const colors = useAppColors(); + const styles = createStyles(colors); + const [status, setStatus] = useState(initialStatus); + const [message, setMessage] = useState('Ready to open the system sign-in sheet.'); + + async function openSheet() { + setStatus('presenting'); + setMessage('Sign-in sheet requested.'); + + try { + const callbackUrl = await startFixtureSignInSession(AUTH_IDP_DEFAULT_URL); + setStatus('completed'); + setMessage(`Signed in: ${callbackUrl}`); + } catch (error) { + const canceled = error instanceof Error && error.name === 'AuthSessionCanceled'; + setStatus(canceled ? 'canceled' : 'error'); + setMessage(error instanceof Error ? error.message : String(error)); + } + } + + return ( + + + + + + {AUTH_IDP_DEFAULT_URL} + + + iOS hosts the sheet in com.apple.SafariViewService, over this screen and outside the + app's process. + + + + + void openSheet()} testID="auth-session-open" /> + + {status} + + {status === 'presenting' ? : null} + + {message} + + + + + + ); +} + +function createStyles(colors: AppColors) { + return StyleSheet.create({ + content: { + gap: 16, + padding: 20, + }, + url: { + color: colors.text, + fontFamily: 'Menlo', + fontSize: 13, + }, + body: { + color: colors.textSoft, + fontSize: 14, + }, + status: { + color: colors.text, + fontSize: 16, + fontWeight: '600', + }, + }); +} diff --git a/examples/test-app/src/screens/SettingsScreen.tsx b/examples/test-app/src/screens/SettingsScreen.tsx index bd5be5dbb4..6f9658bc5d 100644 --- a/examples/test-app/src/screens/SettingsScreen.tsx +++ b/examples/test-app/src/screens/SettingsScreen.tsx @@ -19,6 +19,7 @@ export interface SettingsScreenProps { onConfirmReset: () => void; onLoadDiagnostics: () => void; onOpenAccessorySetup: () => void; + onOpenAuthSessionLab: () => void; onOpenAutomationLab: () => void; onOpenHeavyFeed: () => void; onOpenInertSurface: () => void; @@ -110,6 +111,17 @@ export function SettingsScreen(props: SettingsScreenProps) { /> + + + + { + stderr += chunk; + }); + const exit = once(child, 'close'); + onTestFinished(async () => { + if (child.kill('SIGKILL')) await exit; + }); + return { + root, + child, + exit, + stderr: () => stderr, + marker: (name: string) => fs.existsSync(path.join(root, name)), + }; +} + +test('the lane runs only the sign-in sheet flow and closes its fixture server', async () => { + const lane = fixture("fs.writeFileSync('argv', JSON.stringify(process.argv.slice(2)));"); + assert.deepEqual(await lane.exit, [0, null], lane.stderr()); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(lane.root, 'argv'), 'utf8')), [ + '--session', + 'test-app-maestro', + 'test', + path.join(lane.root, 'examples/test-app/maestro-ios/auth-session-sheet.yaml'), + '--maestro', + '--platform', + 'ios', + '--udid', + 'fixture', + ]); +}); + +test.skipIf(process.platform === 'win32')( + 'cancellation closes the fixture server and stops the suite CLI', + async () => { + const lane = fixture( + ` + process.on('SIGTERM', () => { + fs.writeFileSync('cli-stopped', ''); + process.exit(0); + }); + fs.writeFileSync('cli-started', ''); + setTimeout(() => process.exit(8), 5000); + `, + ); + try { + await expect.poll(() => lane.marker('cli-started')).toBe(true); + } finally { + lane.child.kill('SIGTERM'); + } + assert.deepEqual(await lane.exit, [1, null], lane.stderr()); + assert.equal(lane.marker('cli-stopped'), true); + }, + 8000, +); diff --git a/scripts/run-test-app-auth-session-lane.mjs b/scripts/run-test-app-auth-session-lane.mjs new file mode 100644 index 0000000000..4313cffb16 --- /dev/null +++ b/scripts/run-test-app-auth-session-lane.mjs @@ -0,0 +1,86 @@ +#!/usr/bin/env node +// Run the read-only ASWebAuthenticationSession flow against the loopback fixture provider (#2449). +// Pass extra agent-device arguments after `--`. +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import path from 'node:path'; +import process from 'node:process'; +import { setTimeout as delay } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; +import { startAuthIdpServer } from '../examples/test-app/src/auth-idp-server.mjs'; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const flow = path.join(repoRoot, 'examples', 'test-app', 'maestro-ios', 'auth-session-sheet.yaml'); +const suiteScript = path.join(repoRoot, 'scripts', 'run-test-app-maestro-suite.mjs'); +const passthroughIndex = process.argv.indexOf('--'); +const passthrough = passthroughIndex === -1 ? [] : process.argv.slice(passthroughIndex + 1); +const cleanupTimeoutMs = 5_000; + +function signalSuite(child, signal) { + if (!child.pid) return false; + if (process.platform === 'win32') { + return child.exitCode === null && child.signalCode === null && child.kill(signal); + } + try { + process.kill(-child.pid, signal); + return true; + } catch (error) { + if (error.code === 'ESRCH') return false; + throw error; + } +} + +async function stopSuite(child, exit, signal) { + if (!signalSuite(child, signal)) return; + const deadline = Date.now() + cleanupTimeoutMs; + // The suite runner can exit before its agent-device child on cancellation. + while (signalSuite(child, 0)) { + if (Date.now() >= deadline) { + signalSuite(child, 'SIGKILL'); + break; + } + await delay(25); + } + await exit.catch(() => {}); +} + +async function runLane() { + let provider; + let suite; + let suiteExit; + let signal; + const { promise: cancellation, resolve: finishCancellation } = Promise.withResolvers(); + function cancel(received) { + signal ??= received; + finishCancellation(); + } + process.on('SIGINT', cancel); + process.on('SIGTERM', cancel); + try { + provider = await startAuthIdpServer(); + if (signal) return 1; + suite = spawn( + process.execPath, + [suiteScript, '--platform', 'ios', '--flow', flow, '--', ...passthrough], + { cwd: repoRoot, stdio: 'inherit', detached: process.platform !== 'win32' }, + ); + suiteExit = once(suite, 'exit'); + const result = await Promise.race([suiteExit, cancellation]); + return result?.[0] ?? 1; + } catch (error) { + console.error(`[auth-session-lane] ${error.message}`); + return 1; + } finally { + try { + await Promise.all([ + provider?.close(), + suite && stopSuite(suite, suiteExit, signal ?? 'SIGTERM'), + ]); + } finally { + process.off('SIGINT', cancel); + process.off('SIGTERM', cancel); + } + } +} + +process.exitCode = await runLane(); diff --git a/scripts/run-test-app-maestro-suite.mjs b/scripts/run-test-app-maestro-suite.mjs index e2b4796070..68b486b68c 100644 --- a/scripts/run-test-app-maestro-suite.mjs +++ b/scripts/run-test-app-maestro-suite.mjs @@ -11,6 +11,7 @@ const options = { platform: 'ios', session: 'test-app-maestro', flowDir: path.join(repoRoot, 'examples', 'test-app', 'maestro'), + flow: undefined, close: false, passthrough: [], }; @@ -36,6 +37,11 @@ for (let index = 2; index < process.argv.length; index += 1) { index += 1; continue; } + if (arg === '--flow' && process.argv[index + 1]) { + options.flow = path.resolve(process.argv[index + 1]); + index += 1; + continue; + } if (arg === '--close') { options.close = true; continue; @@ -43,11 +49,13 @@ for (let index = 2; index < process.argv.length; index += 1) { options.passthrough.push(arg); } -const flows = fs - .readdirSync(options.flowDir) - .filter((entry) => entry.endsWith('.yaml') || entry.endsWith('.yml')) - .sort() - .map((entry) => path.join(options.flowDir, entry)); +const flows = options.flow + ? [options.flow] + : fs + .readdirSync(options.flowDir) + .filter((entry) => entry.endsWith('.yaml') || entry.endsWith('.yml')) + .sort() + .map((entry) => path.join(options.flowDir, entry)); if (flows.length === 0) { console.error(`No Maestro flows found in ${options.flowDir}`); diff --git a/vitest.config.ts b/vitest.config.ts index 0335d9caac..77dacc6226 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -151,6 +151,7 @@ export default defineConfig({ // The tooling send over real loopback daemons: in-process, no device. 'scripts/lib/recorded-daemon.test.ts', 'scripts/__tests__/vitest-slow-test-reporter.test.ts', + 'scripts/__tests__/auth-session-lane.test.ts', // Artifact guards assert on Swift sources, package.json, workflows, docs and examples rather // than on a module under src. 'test/repo-guards/*.test.ts',