44 DeviceOperationError ,
55 type DevicePlatform ,
66} from "@t3tools/contracts" ;
7+ import * as Cause from "effect/Cause" ;
8+ import * as Clock from "effect/Clock" ;
79import * as Duration from "effect/Duration" ;
810import * as Effect from "effect/Effect" ;
911import * as Option from "effect/Option" ;
@@ -13,6 +15,20 @@ import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } fr
1315import type { DeviceHostReady , DeviceOperations , HostDevice } from "./DeviceHost.ts" ;
1416
1517const BOOT_TIMEOUT = Duration . minutes ( 3 ) ;
18+ const ANDROID_BOOT_COMPLETED_TIMEOUT = Duration . minutes ( 2 ) ;
19+ // Poll every 1.5 s once adb is online so boot completion is noticed quickly without hammering SSH hosts.
20+ const ANDROID_BOOT_POLL_INTERVAL = Duration . millis ( 1_500 ) ;
21+ // Cold serve-emu startup (ffmpeg probe + scrcpy-server + capture start) can outlast the client's 15 s frame timer.
22+ const ANDROID_BOOT_WARMUP_TIMEOUT = Duration . seconds ( 60 ) ;
23+ const ANDROID_STREAM_POLL_INTERVAL = Duration . seconds ( 2 ) ;
24+ const ANDROID_MAX_WARMUP_FAILURES = 2 ;
25+ const ANDROID_EXIT_PROBE_TIMEOUT = Duration . seconds ( 2 ) ;
26+ // Reserve two exit-confirmation probes plus their gap inside each deadline so exit checks never overshoot it.
27+ const ANDROID_EXIT_CONFIRM_RESERVE_MS =
28+ Duration . toMillis ( ANDROID_EXIT_PROBE_TIMEOUT ) * 2 + Duration . toMillis ( ANDROID_BOOT_POLL_INTERVAL ) ;
29+ // expo-device-hub 0.26.1 serve-emu middleware.js returns 503 with this message during its 5 s SPAWN_RETRY_COOLDOWN_MS.
30+ const SERVE_EMU_COOLING_DOWN = / c o o l i n g d o w n a f t e r a f a i l u r e / i;
31+ const EMULATOR_SERIAL = / ^ e m u l a t o r - \d + $ / ;
1632const SCREENSHOT_TIMEOUT = Duration . seconds ( 20 ) ;
1733// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill.
1834const ANDROID_SHUTDOWN_TIMEOUT = Duration . seconds ( 45 ) ;
@@ -55,10 +71,15 @@ const HubActionResult = Schema.Struct({
5571 Schema . Array ( Schema . Struct ( { message : Schema . String , error : Schema . optional ( Schema . String ) } ) ) ,
5672 ) ,
5773} ) ;
74+ const ServeEmuHealth = Schema . Struct ( {
75+ ok : Schema . Boolean ,
76+ status : Schema . optional ( Schema . String ) ,
77+ error : Schema . optional ( Schema . String ) ,
78+ } ) ;
5879
5980// Hub diagnostics can carry a whole stderr dump.
6081const boundDiagnostics = ( text : string ) =>
61- text . length > 2_000 ? `${ text . slice ( 0 , 1_999 ) } …` : text ;
82+ text . length > 2_000 ? `${ text . slice ( 0 , 1_999 ) . replace ( / [ \uD800 - \uDBFF ] $ / u , "" ) } …` : text ;
6283
6384// The hub's `error` is a util.inspect of Node's exec error; the stack and the
6485// inspected fields follow the first frame, so keep the lines before it.
@@ -269,6 +290,190 @@ export const makeDeviceHubOperations = (options: {
269290 } ;
270291 } ) . pipe ( Effect . withSpan ( "DeviceHubOperations.list" ) ) ;
271292
293+ // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an
294+ // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer
295+ // lists its serial in any state.
296+ const emulatorExited = ( serial : string , timeoutMs = Duration . toMillis ( ADB_DEVICES_TIMEOUT ) ) =>
297+ EMULATOR_SERIAL . test ( serial ) && timeoutMs > 0
298+ ? run ( "adb" , [ "devices" ] , { timeoutMs } ) . pipe (
299+ Effect . map (
300+ ( { code, stdout } ) =>
301+ code === 0 &&
302+ ! stdout . split ( / \r ? \n / ) . some ( ( line ) => line . trim ( ) . split ( / \s + / ) [ 0 ] === serial ) ,
303+ ) ,
304+ Effect . orElseSucceed ( ( ) => false ) ,
305+ )
306+ : Effect . succeed ( false ) ;
307+
308+ const emulatorExitedDuringBoot = (
309+ device : HostDevice ,
310+ serial : string ,
311+ stage : string ,
312+ cause : unknown ,
313+ ) =>
314+ new DeviceBootError ( {
315+ hostId,
316+ deviceId : device . id ,
317+ reason : "launch_failed" ,
318+ diagnostics : boundDiagnostics (
319+ `The emulator process for "${ device . name } " (${ serial } ) exited ${ stage } .` ,
320+ ) ,
321+ cause,
322+ } ) ;
323+
324+ // Require two omissions separated by a poll interval so a brief adb transport blip is not misread
325+ // as a process exit (an external adb server restart can still briefly return empty lists).
326+ // Callers reserve ANDROID_EXIT_CONFIRM_RESERVE_MS inside deadlineMs so exit checks stay within budget.
327+ const confirmEmulatorExited = Effect . fn ( "DeviceHubOperations.confirmEmulatorExited" ) ( function * (
328+ serial : string ,
329+ deadlineMs : number ,
330+ ) {
331+ const probeTimeoutMs = Duration . toMillis ( ANDROID_EXIT_PROBE_TIMEOUT ) ;
332+ const firstBudgetMs = Math . min ( probeTimeoutMs , deadlineMs - ( yield * Clock . currentTimeMillis ) ) ;
333+ if ( ! ( yield * emulatorExited ( serial , firstBudgetMs ) ) ) return false ;
334+ if (
335+ deadlineMs - ( yield * Clock . currentTimeMillis ) <=
336+ Duration . toMillis ( ANDROID_BOOT_POLL_INTERVAL )
337+ ) {
338+ return false ;
339+ }
340+ yield * Effect . sleep ( ANDROID_BOOT_POLL_INTERVAL ) ;
341+ const secondBudgetMs = Math . min ( probeTimeoutMs , deadlineMs - ( yield * Clock . currentTimeMillis ) ) ;
342+ return yield * emulatorExited ( serial , secondBudgetMs ) ;
343+ } ) ;
344+
345+ // Returns true once sys.boot_completed=1, false if a slow boot outlasts the deadline (so boot
346+ // degrades to opening), and fails with DeviceBootError only when the emulator is confirmed gone.
347+ const waitForAndroidBootCompleted = Effect . fn ( "DeviceHubOperations.waitForAndroidBootCompleted" ) (
348+ function * ( device : HostDevice , serial : string , deadlineMs : number ) {
349+ const probeDeadlineMs = deadlineMs - ANDROID_EXIT_CONFIRM_RESERVE_MS ;
350+ while ( true ) {
351+ const remainingMs = probeDeadlineMs - ( yield * Clock . currentTimeMillis ) ;
352+ if ( remainingMs <= 0 ) {
353+ yield * Effect . logWarning ( "Timed out waiting for Android boot completion" , {
354+ hostId,
355+ serial,
356+ } ) ;
357+ return false ;
358+ }
359+ const probe = yield * run ( "adb" , [ "-s" , serial , "shell" , "getprop" , "sys.boot_completed" ] , {
360+ timeoutMs : Math . min ( Duration . toMillis ( ADB_DEVICES_TIMEOUT ) , remainingMs ) ,
361+ } ) ;
362+ if ( probe . code === 0 && probe . stdout . trim ( ) === "1" ) return true ;
363+ if ( probe . code !== 0 && ( yield * confirmEmulatorExited ( serial , deadlineMs ) ) ) {
364+ return yield * emulatorExitedDuringBoot ( device , serial , "before finishing boot" , probe ) ;
365+ }
366+ if (
367+ probeDeadlineMs - ( yield * Clock . currentTimeMillis ) <=
368+ Duration . toMillis ( ANDROID_BOOT_POLL_INTERVAL )
369+ ) {
370+ yield * Effect . logWarning ( "Timed out waiting for Android boot completion" , {
371+ hostId,
372+ serial,
373+ } ) ;
374+ return false ;
375+ }
376+ yield * Effect . sleep ( ANDROID_BOOT_POLL_INTERVAL ) ;
377+ }
378+ } ,
379+ ) ;
380+
381+ // serve-emu starts its capture session lazily on /health and returns 200 once streaming.
382+ // Video/HTTP failures degrade so agent-only flows and Reconnect still work; a confirmed
383+ // emulator exit fails so boot does not return a gone serial.
384+ const warmAndroidStream = Effect . fn ( "DeviceHubOperations.warmAndroidStream" ) ( function * (
385+ device : HostDevice ,
386+ serial : string ,
387+ deadlineMs : number ,
388+ ) {
389+ const probeDeadlineMs = deadlineMs - ANDROID_EXIT_CONFIRM_RESERVE_MS ;
390+ let startupFailures = 0 ;
391+ while ( true ) {
392+ const remainingMs = probeDeadlineMs - ( yield * Clock . currentTimeMillis ) ;
393+ if ( remainingMs <= 0 ) {
394+ yield * Effect . logWarning ( "Android stream warm-up timed out" , { hostId, serial } ) ;
395+ return ;
396+ }
397+ const attempt = yield * httpClient
398+ . execute (
399+ HttpClientRequest . get (
400+ `${ origin } ${ vendorPrefix ( "android" ) } /health?device=${ encodeURIComponent ( serial ) } ` ,
401+ ) ,
402+ )
403+ . pipe (
404+ Effect . flatMap ( ( res ) =>
405+ HttpClientResponse . schemaBodyJson ( ServeEmuHealth ) ( res ) . pipe (
406+ Effect . option ,
407+ Effect . map ( ( body ) => ( { status : res . status , body } ) ) ,
408+ ) ,
409+ ) ,
410+ Effect . scoped ,
411+ Effect . timeout ( Duration . millis ( remainingMs ) ) ,
412+ Effect . result ,
413+ ) ;
414+ if ( attempt . _tag === "Failure" ) {
415+ if ( yield * confirmEmulatorExited ( serial , deadlineMs ) ) {
416+ return yield * emulatorExitedDuringBoot (
417+ device ,
418+ serial ,
419+ "during stream warm-up" ,
420+ attempt . failure ,
421+ ) ;
422+ }
423+ yield * Effect . logWarning ( "Android stream warm-up request failed" , {
424+ hostId,
425+ serial,
426+ reason : Cause . isTimeoutError ( attempt . failure ) ? "timeout" : "request_failed" ,
427+ } ) ;
428+ return ;
429+ }
430+ const response = attempt . success ;
431+ const body = Option . getOrUndefined ( response . body ) ;
432+ if (
433+ response . status >= 200 &&
434+ response . status < 300 &&
435+ body !== undefined &&
436+ body . ok &&
437+ ( body . status === undefined || body . status === "streaming" )
438+ ) {
439+ return ;
440+ }
441+ if ( response . status !== 503 ) {
442+ yield * Effect . logWarning ( "Android stream warm-up returned an unexpected response" , {
443+ hostId,
444+ serial,
445+ status : response . status ,
446+ } ) ;
447+ return ;
448+ }
449+ if ( yield * confirmEmulatorExited ( serial , deadlineMs ) ) {
450+ return yield * emulatorExitedDuringBoot (
451+ device ,
452+ serial ,
453+ "during stream warm-up" ,
454+ body ?? { status : response . status } ,
455+ ) ;
456+ }
457+ const coolingDown = SERVE_EMU_COOLING_DOWN . test ( body ?. error ?? "" ) ;
458+ if ( ! coolingDown && ++ startupFailures >= ANDROID_MAX_WARMUP_FAILURES ) {
459+ yield * Effect . logWarning ( "Android stream warm-up did not become ready" , {
460+ hostId,
461+ serial,
462+ status : response . status ,
463+ } ) ;
464+ return ;
465+ }
466+ if (
467+ probeDeadlineMs - ( yield * Clock . currentTimeMillis ) <=
468+ Duration . toMillis ( ANDROID_STREAM_POLL_INTERVAL )
469+ ) {
470+ yield * Effect . logWarning ( "Android stream warm-up timed out" , { hostId, serial } ) ;
471+ return ;
472+ }
473+ yield * Effect . sleep ( ANDROID_STREAM_POLL_INTERVAL ) ;
474+ }
475+ } ) ;
476+
272477 const boot : DeviceOperations [ "boot" ] = Effect . fn ( "DeviceHubOperations.boot" ) ( function * ( device ) {
273478 const result = yield * postJson (
274479 "/api/devices/boot" ,
@@ -297,30 +502,31 @@ export const makeDeviceHubOperations = (options: {
297502 cause : result ,
298503 } ) ;
299504 }
300- if ( device . platform === "ios" ) yield * attachIosStream ( device . id , "boot" ) ;
301- return result . serial ?? result . id ?? device . id ;
505+ const bootedId = result . serial ?? result . id ?? device . id ;
506+ if ( device . platform === "ios" ) {
507+ yield * attachIosStream ( device . id , "boot" ) ;
508+ } else if (
509+ device . platform === "android" &&
510+ ! device . physical &&
511+ EMULATOR_SERIAL . test ( bootedId )
512+ ) {
513+ const bootDeadlineMs =
514+ ( yield * Clock . currentTimeMillis ) + Duration . toMillis ( ANDROID_BOOT_COMPLETED_TIMEOUT ) ;
515+ const bootCompleted = yield * waitForAndroidBootCompleted ( device , bootedId , bootDeadlineMs ) ;
516+ if ( bootCompleted ) {
517+ const warmupDeadlineMs =
518+ ( yield * Clock . currentTimeMillis ) + Duration . toMillis ( ANDROID_BOOT_WARMUP_TIMEOUT ) ;
519+ yield * warmAndroidStream ( device , bootedId , warmupDeadlineMs ) ;
520+ }
521+ }
522+ return bootedId ;
302523 } ) ;
303524
304525 const attach : DeviceOperations [ "attach" ] = ( device ) =>
305526 device . platform === "ios"
306527 ? attachIosStream ( device . id , "open" ) . pipe ( Effect . asVoid )
307528 : Effect . void ;
308529
309- // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an
310- // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer
311- // lists its serial in any state.
312- const emulatorExited = ( serial : string ) =>
313- / ^ e m u l a t o r - \d + $ / . test ( serial )
314- ? run ( "adb" , [ "devices" ] , { timeoutMs : Duration . toMillis ( ADB_DEVICES_TIMEOUT ) } ) . pipe (
315- Effect . map (
316- ( { code, stdout } ) =>
317- code === 0 &&
318- ! stdout . split ( / \r ? \n / ) . some ( ( line ) => line . trim ( ) . split ( / \s + / ) [ 0 ] === serial ) ,
319- ) ,
320- Effect . orElseSucceed ( ( ) => false ) ,
321- )
322- : Effect . succeed ( false ) ;
323-
324530 const shutdown : DeviceOperations [ "shutdown" ] = Effect . fn ( "DeviceHubOperations.shutdown" ) (
325531 function * ( device ) {
326532 const postShutdown = ( path : string , body : Record < string , string > , timeout ?: Duration . Input ) =>
0 commit comments