Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(ios-simulator): improve native streaming and input

JiangJiahao5c7af874cdd1
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
index 7edb6c38a2..5c3b8e29dc 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
@@ -195,12 +195,14 @@ describe('iOS Simulator IPC handlers', () => {
};
await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
- profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ nativeProfile: { framesPerSecond: 60, scalingPercent: 70 },
});
expect(setViewerStreamProfile).toHaveBeenCalledWith(
'session-a',
{ instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },
- { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ { framesPerSecond: 60, scalingPercent: 70 },
);
await expect(
harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
@@ -208,6 +210,13 @@ describe('iOS Simulator IPC handlers', () => {
profile: { framesPerSecond: '10', jpegQuality: 45, scalingPercent: 70 },
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
+ ...route,
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ nativeProfile: { framesPerSecond: '60', scalingPercent: 70 },
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
});
it('validates and routes host-owned live touch samples', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
index d47a531804..07f803dd19 100644
--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
@@ -1,4 +1,5 @@
import type {
+ IOSSimulatorNativeH264StreamProfileRequest,
IOSSimulatorSessionStatus,
IOSSimulatorToolResponse,
} from '../../shared/iosSimulatorIpc.js';
@@ -45,6 +46,7 @@ export interface IOSSimulatorHandlerDeps {
sessionId: string,
route: { instanceId: string; generation: number; leaseId: string },
profile: { framesPerSecond: number; jpegQuality: number; scalingPercent: number },
+ nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,
): Promise<IOSSimulatorToolResponse>;
getLatestFrame(
sessionId: string,
@@ -256,11 +258,38 @@ export function registerIOSSimulatorHandlers(
) {
throwIpcError('INVALID_PARAMS', 'profile values must be integers');
}
- return resolved.setViewerStreamProfile(sessionId, readViewerRoute(record), {
- framesPerSecond: Number(candidate.framesPerSecond),
- jpegQuality: Number(candidate.jpegQuality),
- scalingPercent: Number(candidate.scalingPercent),
- });
+ const rawNativeProfile = record.nativeProfile;
+ let nativeProfile: IOSSimulatorNativeH264StreamProfileRequest | undefined;
+ if (rawNativeProfile !== undefined) {
+ if (
+ !rawNativeProfile ||
+ typeof rawNativeProfile !== 'object' ||
+ Array.isArray(rawNativeProfile)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'nativeProfile must be an object');
+ }
+ const nativeCandidate = rawNativeProfile as Record<string, unknown>;
+ if (
+ !Number.isSafeInteger(nativeCandidate.framesPerSecond) ||
+ !Number.isSafeInteger(nativeCandidate.scalingPercent)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'nativeProfile values must be integers');
+ }
+ nativeProfile = {
+ framesPerSecond: Number(nativeCandidate.framesPerSecond),
+ scalingPercent: Number(nativeCandidate.scalingPercent),
+ };
+ }
+ return resolved.setViewerStreamProfile(
+ sessionId,
+ readViewerRoute(record),
+ {
+ framesPerSecond: Number(candidate.framesPerSecond),
+ jpegQuality: Number(candidate.jpegQuality),
+ scalingPercent: Number(candidate.scalingPercent),
+ },
+ nativeProfile,
+ );
});
registry.handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (_event, payload) => {
const record = readRecord(payload);
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index e43d976d94..324e14fe71 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -1279,6 +1279,12 @@ describe('iOS Simulator host', () => {
const wdaDriver = {
getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),
getOrientation: vi.fn(async () => 'PORTRAIT' as const),
+ configureStream: vi.fn(
+ async (
+ _sessionId: string,
+ profile: { framesPerSecond: number; jpegQuality: number; scalingPercent: number },
+ ) => profile,
+ ),
setOrientation: vi.fn(async () => undefined),
tap: vi.fn(async () => undefined),
swipe: vi.fn(
@@ -1355,7 +1361,7 @@ describe('iOS Simulator host', () => {
};
let h264Snapshot = {
...jpegSnapshot,
- state: 'connecting' as 'connecting' | 'disconnected',
+ state: 'connecting' as 'connecting' | 'streaming' | 'disconnected',
};
const framePump = {
setVisible: vi.fn((request: { instanceId: string; generation: number }) => {
@@ -1441,6 +1447,58 @@ describe('iOS Simulator host', () => {
},
});
+ const fallbackHighProfile = {
+ framesPerSecond: 20,
+ jpegQuality: 70,
+ scalingPercent: 100,
+ };
+ const experimentalNativeProfile = {
+ framesPerSecond: 60,
+ scalingPercent: 70,
+ };
+ await expect(
+ host.setViewerStreamProfile(
+ 'session-a',
+ route,
+ fallbackHighProfile,
+ experimentalNativeProfile,
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });
+ expect(wdaDriver.configureStream).not.toHaveBeenCalled();
+
+ h264Snapshot = { ...h264Snapshot, state: 'streaming' };
+ await expect(
+ host.setViewerStreamProfile(
+ 'session-a',
+ route,
+ fallbackHighProfile,
+ experimentalNativeProfile,
+ ),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: {
+ profile: fallbackHighProfile,
+ nativeProfile: experimentalNativeProfile,
+ },
+ });
+ expect(wdaDriver.configureStream).toHaveBeenLastCalledWith('wda-session', fallbackHighProfile);
+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ profile: expect.objectContaining({
+ encoding: 'h264',
+ framesPerSecond: 60,
+ scalingPercent: 70,
+ }),
+ }),
+ );
+ await expect(
+ host.setViewerStreamProfile('session-a', route, {
+ framesPerSecond: 60,
+ jpegQuality: 70,
+ scalingPercent: 70,
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });
+
wdaDriver.setOrientation.mockRejectedValueOnce(
new WdaError(
'ORIENTATION_UNSUPPORTED',
@@ -1516,6 +1574,15 @@ describe('iOS Simulator host', () => {
viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
},
});
+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ profile: expect.objectContaining({
+ framesPerSecond: 60,
+ scalingPercent: 70,
+ orientation: 'PORTRAIT',
+ }),
+ }),
+ );
h264Snapshot = { ...h264Snapshot, state: 'disconnected' };
nativeAvailable = false;
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 3575d0eb6b..899ff4565f 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -67,6 +67,7 @@ import type {
} from '@cindy/mcps';
import type {
+ IOSSimulatorNativeH264StreamProfileRequest,
IOSSimulatorPublicEnvironmentReport,
IOSSimulatorPublicInstance,
IOSSimulatorPublicViewport,
@@ -90,6 +91,8 @@ const BUILD_DIAGNOSTICS_TTL_MS = 30 * 60_000;
const MAX_BUILD_DIAGNOSTICS = 32;
const MANAGED_BUILD_RESULT_BUNDLE_PATTERN = /^CindyBuild(?:-[0-9a-f-]+)?\.xcresult$/i;
const DEFAULT_DEVICE_LIVENESS_INTERVAL_MS = 1_000;
+const MAX_WDA_VIEWER_FRAMES_PER_SECOND = 20;
+const MAX_NATIVE_H264_VIEWER_FRAMES_PER_SECOND = 60;
interface IOSSimulatorSessionSnapshot {
id: string;
@@ -203,6 +206,7 @@ export interface IOSSimulatorHost {
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
profile: IOSSimulatorStreamProfile,
+ nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,
): Promise<IOSSimulatorHostResult>;
updateViewerTouch(
sessionId: string,
@@ -655,6 +659,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const driverViewports = new Map<string, IOSSimulatorPublicViewport>();
const viewerOrientationOverrides = new Map<string, 'PORTRAIT' | 'LANDSCAPE'>();
const streamProfiles = new Map<string, IOSSimulatorStreamProfile>();
+ const nativeStreamProfiles = new Map<string, IOSSimulatorNativeH264StreamProfileRequest>();
const viewerEncodings = new Map<string, 'jpeg' | 'h264'>();
const viewerPreferredEncodings = new Map<string, 'jpeg' | 'h264'>();
const viewerFallbackReasons = new Map<string, IOSSimulatorPublicRouteReasonCode>();
@@ -1227,6 +1232,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerFallbackReasons.delete(instance.instanceId);
viewerSessions.delete(instance.instanceId);
streamProfiles.delete(instance.instanceId);
+ nativeStreamProfiles.delete(instance.instanceId);
clearViewportState(instance.instanceId);
screenMaps.clear(instance.instanceId);
clearVisualBaselines(instance.instanceId);
@@ -1401,6 +1407,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerSessions.delete(instance.instanceId);
clearViewportState(instance.instanceId);
streamProfiles.delete(instance.instanceId);
+ nativeStreamProfiles.delete(instance.instanceId);
let cleanupSucceeded = await discardInstanceMedia(instance);
let driverCleanupSucceeded = true;
if (driverManager) {
@@ -2286,6 +2293,27 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return route.source;
}
+ function nativeViewerProfile(
+ instanceId: string,
+ fallback: IOSSimulatorStreamProfile,
+ ): IOSSimulatorNativeH264StreamProfileRequest {
+ return (
+ nativeStreamProfiles.get(instanceId) ?? {
+ framesPerSecond: fallback.framesPerSecond,
+ scalingPercent: fallback.scalingPercent,
+ }
+ );
+ }
+
+ function activeNativeH264Driver(
+ instanceId: string,
+ running: WdaRunningInstance,
+ ): IOSSimulatorNativeSidecarDriver | null {
+ if (viewerEncodings.get(instanceId) !== 'h264') return null;
+ if (h264FramePump.snapshot(instanceId)?.state !== 'streaming') return null;
+ return nativeH264Driver(running);
+ }
+
function startViewerStream(
instance: IOSSimulatorInstance,
running: WdaRunningInstance,
@@ -2308,19 +2336,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
driver: running.driver,
visible: false,
});
- const profile = streamProfiles.get(instance.instanceId) ?? {
+ const fallbackProfile = streamProfiles.get(instance.instanceId) ?? {
framesPerSecond: 5,
jpegQuality: 25,
scalingPercent: 50,
};
+ const nativeProfile = nativeViewerProfile(instance.instanceId, fallbackProfile);
const snapshot = h264FramePump.setVisible({
instanceId: instance.instanceId,
generation: instance.generation,
driver: nativeDriver,
profile: {
encoding: 'h264',
- framesPerSecond: profile.framesPerSecond,
- scalingPercent: profile.scalingPercent,
+ framesPerSecond: nativeProfile.framesPerSecond,
+ scalingPercent: nativeProfile.scalingPercent,
orientation,
},
visible: true,
@@ -2675,7 +2704,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return safeHostError(error, sessionId, `viewer_touch_${touch.phase}`);
}
},
- async setViewerStreamProfile(sessionId, route, profile) {
+ async setViewerStreamProfile(sessionId, route, profile, nativeProfile) {
try {
assertHostActive();
const resolved = await resolveSession(sessionId);
@@ -2684,7 +2713,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (
!Number.isSafeInteger(profile.framesPerSecond) ||
profile.framesPerSecond < 1 ||
- profile.framesPerSecond > 60 ||
+ profile.framesPerSecond > MAX_WDA_VIEWER_FRAMES_PER_SECOND ||
!Number.isSafeInteger(profile.jpegQuality) ||
profile.jpegQuality < 1 ||
profile.jpegQuality > 100 ||
@@ -2694,39 +2723,73 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
) {
throw new IOSSimulatorInstanceError(
'INVALID_ARGUMENT',
- 'Stream profile values are outside the supported range.',
+ 'WDA fallback profile values are outside the supported range.',
+ );
+ }
+ if (
+ nativeProfile &&
+ (!Number.isSafeInteger(nativeProfile.framesPerSecond) ||
+ nativeProfile.framesPerSecond < 1 ||
+ nativeProfile.framesPerSecond > MAX_NATIVE_H264_VIEWER_FRAMES_PER_SECOND ||
+ !Number.isSafeInteger(nativeProfile.scalingPercent) ||
+ nativeProfile.scalingPercent < 1 ||
+ nativeProfile.scalingPercent > 100)
+ ) {
+ throw new IOSSimulatorInstanceError(
+ 'INVALID_ARGUMENT',
+ 'Native H.264 profile values are outside the supported range.',
);
}
const instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });
const running = getDriverManager().get(instance.instanceId);
+ const activeNativeDriver =
+ nativeProfile && running ? activeNativeH264Driver(instance.instanceId, running) : null;
+ if (nativeProfile && !activeNativeDriver) {
+ throw new IOSSimulatorInstanceError(
+ 'INVALID_ARGUMENT',
+ 'Native H.264 profile changes require an active Native H.264 viewer.',
+ );
+ }
if (!running) {
- // The viewer may request its profile while WDA is still being rebuilt.
- // Keep the desired profile so ensureDriver applies it after the session
- // becomes available instead of dropping the request as a disconnect.
+ // The viewer may request its fallback profile while WDA is being rebuilt.
+ // Native-only intent is rejected above because no active route can prove it.
streamProfiles.set(instance.instanceId, profile);
+ nativeStreamProfiles.delete(instance.instanceId);
return { ok: true, data: { profile } };
}
const applied = await running.driver.configureStream(running.driverSessionId, profile);
assertHostActive();
streamProfiles.set(instance.instanceId, applied);
+ if (nativeProfile) nativeStreamProfiles.set(instance.instanceId, nativeProfile);
+ else nativeStreamProfiles.delete(instance.instanceId);
if (viewerEncodings.get(instance.instanceId) === 'h264') {
- const nativeDriver = nativeH264Driver(running);
+ const nativeDriver = activeNativeDriver ?? nativeH264Driver(running);
if (nativeDriver) {
+ const appliedNativeProfile = nativeProfile ?? {
+ framesPerSecond: applied.framesPerSecond,
+ scalingPercent: applied.scalingPercent,
+ };
h264FramePump.setVisible({
instanceId: instance.instanceId,
generation: instance.generation,
driver: nativeDriver,
profile: {
encoding: 'h264',
- framesPerSecond: applied.framesPerSecond,
- scalingPercent: applied.scalingPercent,
+ framesPerSecond: appliedNativeProfile.framesPerSecond,
+ scalingPercent: appliedNativeProfile.scalingPercent,
orientation: viewports.get(instance.instanceId)?.orientation ?? 'PORTRAIT',
},
visible: true,
});
}
}
- return { ok: true, data: { profile: applied } };
+ return {
+ ok: true,
+ data: {
+ profile: applied,
+ ...(nativeProfile ? { nativeProfile: { ...nativeProfile } } : {}),
+ },
+ };
} catch (error) {
return safeHostError(error, sessionId, 'set_viewer_stream_profile');
}
@@ -3360,19 +3423,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
const driverViewport =
driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
- const profile = streamProfiles.get(instance.instanceId) ?? {
+ const fallbackProfile = streamProfiles.get(instance.instanceId) ?? {
framesPerSecond: 5,
jpegQuality: 25,
scalingPercent: 50,
};
+ const nativeProfile = nativeViewerProfile(instance.instanceId, fallbackProfile);
h264FramePump.setVisible({
instanceId: instance.instanceId,
generation: instance.generation,
driver: nativeDriver,
profile: {
encoding: 'h264',
- framesPerSecond: profile.framesPerSecond,
- scalingPercent: profile.scalingPercent,
+ framesPerSecond: nativeProfile.framesPerSecond,
+ scalingPercent: nativeProfile.scalingPercent,
orientation,
},
visible: true,
@@ -3392,19 +3456,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (mode === 'device' && viewerEncodings.get(instance.instanceId) === 'h264') {
const nativeDriver = nativeH264Driver(running);
if (nativeDriver) {
- const profile = streamProfiles.get(instance.instanceId) ?? {
+ const fallbackProfile = streamProfiles.get(instance.instanceId) ?? {
framesPerSecond: 5,
jpegQuality: 25,
scalingPercent: 50,
};
+ const nativeProfile = nativeViewerProfile(instance.instanceId, fallbackProfile);
h264FramePump.setVisible({
instanceId: instance.instanceId,
generation: instance.generation,
driver: nativeDriver,
profile: {
encoding: 'h264',
- framesPerSecond: profile.framesPerSecond,
- scalingPercent: profile.scalingPercent,
+ framesPerSecond: nativeProfile.framesPerSecond,
+ scalingPercent: nativeProfile.scalingPercent,
orientation,
},
visible: true,
@@ -4290,6 +4355,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerSessions.delete(instance.instanceId);
clearViewportState(instance.instanceId);
streamProfiles.delete(instance.instanceId);
+ nativeStreamProfiles.delete(instance.instanceId);
}),
);
routeStatusCache.clear();
@@ -4363,8 +4429,14 @@ export function setIOSSimulatorViewerStreamProfile(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
profile: IOSSimulatorStreamProfile,
+ nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,
): Promise<IOSSimulatorHostResult> {
- return defaultIOSSimulatorHost.setViewerStreamProfile(sessionId, route, profile);
+ return defaultIOSSimulatorHost.setViewerStreamProfile(
+ sessionId,
+ route,
+ profile,
+ nativeProfile,
+ );
}
export function updateIOSSimulatorViewerTouch(
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
index 2fe67145ed..42f0c0de79 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
@@ -55,18 +55,69 @@ interface IOSSimulatorTabBodyProps {
}
type Operation = 'attach' | 'start' | 'stop' | 'detach' | 'grant' | 'control' | null;
-type StreamProfileName = 'low' | 'balanced' | 'high';
+type StandardStreamProfileName = 'low' | 'balanced' | 'high';
+type StreamProfileName = StandardStreamProfileName | 'experimental60';
+type StreamProfile = { framesPerSecond: number; jpegQuality: number; scalingPercent: number };
+type NativeStreamProfile = { framesPerSecond: number; scalingPercent: number };
-const STREAM_PROFILES: Record<
- StreamProfileName,
- { framesPerSecond: number; jpegQuality: number; scalingPercent: number }
-> = {
+const WDA_STREAM_PROFILES: Record<StandardStreamProfileName, StreamProfile> = {
low: { framesPerSecond: 5, jpegQuality: 25, scalingPercent: 50 },
balanced: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
high: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
};
+const NATIVE_STREAM_PROFILES: Record<StreamProfileName, NativeStreamProfile> = {
+ low: { framesPerSecond: 5, scalingPercent: 50 },
+ balanced: { framesPerSecond: 20, scalingPercent: 70 },
+ high: { framesPerSecond: 30, scalingPercent: 100 },
+ experimental60: { framesPerSecond: 60, scalingPercent: 70 },
+};
+
+function viewerStreamProfile(
+ name: StreamProfileName,
+ nativeActive: boolean,
+): { profile: StreamProfile; nativeProfile?: NativeStreamProfile } {
+ const fallbackName = name === 'experimental60' ? 'high' : name;
+ return {
+ profile: WDA_STREAM_PROFILES[fallbackName],
+ ...(nativeActive ? { nativeProfile: NATIVE_STREAM_PROFILES[name] } : {}),
+ };
+}
+
const FRAME_FRESHNESS_TIMEOUT_MS = 3_000;
+const POINTER_GESTURE_IDLE_TIMEOUT_MS = 5_000;
+const NATIVE_RECOVERY_BACKOFF_BASE_MS = 5_000;
+const NATIVE_RECOVERY_BACKOFF_MAX_MS = 60_000;
+
+interface NativeRecoveryGate {
+ routeKey: string | null;
+ attemptCount: number;
+ retryAfter: number;
+ inFlight: boolean;
+}
+
+function resetNativeRecoveryGate(gate: NativeRecoveryGate, routeKey: string | null): void {
+ gate.routeKey = routeKey;
+ gate.attemptCount = 0;
+ gate.retryAfter = 0;
+ gate.inFlight = false;
+}
+
+function nativeRecoveryBackoff(attemptCount: number): number {
+ return Math.min(
+ NATIVE_RECOVERY_BACKOFF_MAX_MS,
+ NATIVE_RECOVERY_BACKOFF_BASE_MS * 2 ** Math.max(0, attemptCount - 1),
+ );
+}
+
+function isRecoverableNativeFallback(status: IOSSimulatorPublicRouteStatus | null): boolean {
+ if (!status) return false;
+ return (
+ status.stream.reasonCode === 'native-stream-disconnected' ||
+ status.stream.reasonCode === 'native-sidecar-unavailable' ||
+ status.input.reasonCode === 'native-sidecar-unavailable'
+ );
+}
/** Translate stable discovery codes instead of leaking host-side English guidance into the UI. */
export function setupStepKeys(issue: IOSSimulatorRuntimeErrorCode | null): string[] {
@@ -159,6 +210,7 @@ interface PointerGesture {
pointerId: number;
gestureId: string;
route: ReturnType<typeof routeFor>;
+ captureTarget: HTMLImageElement | HTMLCanvasElement;
startedAt: number;
startClientX: number;
startClientY: number;
@@ -168,9 +220,29 @@ interface PointerGesture {
lastYRatio: number;
pendingMove: { xRatio: number; yRatio: number } | null;
moveDrainQueued: boolean;
+ beginAcknowledged: boolean;
+ failed: boolean;
+ terminalQueued: boolean;
+ idleTimer: number | null;
tail: Promise<void>;
}
+function clearPointerGestureIdleTimer(gesture: PointerGesture): void {
+ if (gesture.idleTimer === null) return;
+ window.clearTimeout(gesture.idleTimer);
+ gesture.idleTimer = null;
+}
+
+function releaseGesturePointerCapture(gesture: PointerGesture): void {
+ try {
+ if (gesture.captureTarget.hasPointerCapture(gesture.pointerId)) {
+ gesture.captureTarget.releasePointerCapture(gesture.pointerId);
+ }
+ } catch {
+ // The element or pointer may already have lost capture during teardown.
+ }
+}
+
export function IOSSimulatorTabBody({
state,
ctx,
@@ -202,12 +274,28 @@ export function IOSSimulatorTabBody({
const pointerGestureRef = useRef<PointerGesture | null>(null);
const gestureSequenceRef = useRef(0);
const streamProfileRef = useRef<StreamProfileName>('balanced');
+ const profileRouteRef = useRef<{
+ routeKey: string | null;
+ nativeSelected: boolean;
+ nativeActive: boolean;
+ } | null>(null);
+ const nativeProfileAppliedRef = useRef<{
+ routeKey: string;
+ profile: StreamProfileName;
+ } | null>(null);
const interactiveProfileActiveRef = useRef(false);
const profileRestoreTimerRef = useRef<number | null>(null);
const h264CanvasRef = useRef<HTMLCanvasElement | null>(null);
const frameUrlRef = useRef<string | null>(null);
const presentationEpochRef = useRef(0);
const frameFreshnessTimerRef = useRef<number | null>(null);
+ const currentRouteStatusRef = useRef<IOSSimulatorPublicRouteStatus | null>(null);
+ const nativeRecoveryGateRef = useRef<NativeRecoveryGate>({
+ routeKey: null,
+ attemptCount: 0,
+ retryAfter: 0,
+ inFlight: false,
+ });
const replaceFrameUrl = useCallback((next: string | null) => {
const previous = frameUrlRef.current;
@@ -242,6 +330,14 @@ export function IOSSimulatorTabBody({
const markFramePresented = useCallback(
(routeKey: string, presentation: 'jpeg' | 'h264') => {
+ const now = performance.now();
+ if (fpsWindowRef.current.startedAt === 0) fpsWindowRef.current.startedAt = now;
+ fpsWindowRef.current.frames += 1;
+ const elapsed = now - fpsWindowRef.current.startedAt;
+ if (elapsed >= 1_000) {
+ setStreamFps((fpsWindowRef.current.frames * 1_000) / elapsed);
+ fpsWindowRef.current = { startedAt: now, frames: 0 };
+ }
if (frameFreshnessTimerRef.current !== null) {
window.clearTimeout(frameFreshnessTimerRef.current);
}
@@ -310,6 +406,13 @@ export function IOSSimulatorTabBody({
? `${attachedInstance.instanceId}:${attachedInstance.generation}`
: null;
const routeStatus = viewerRouteKey ? routeStatuses[viewerRouteKey] ?? null : null;
+ currentRouteStatusRef.current = routeStatus;
+ const nativeH264Selected = Boolean(
+ routeStatus?.stream.adapter === 'native-sidecar' && routeStatus.stream.encoding === 'h264',
+ );
+ const nativeH264Active = Boolean(nativeH264Selected && routeStatus?.stream.state === 'active');
+ const showExperimental60 =
+ nativeH264Active || (nativeH264Selected && streamProfile === 'experimental60');
const grant =
status?.ok && attachedInstance
? status.deviceGrants.find(
@@ -363,6 +466,27 @@ export function IOSSimulatorTabBody({
? t(`rightSidebar.iosSimulator.route.state.${routeStatus.input.state}`)
: t('rightSidebar.iosSimulator.route.state.detecting');
+ useEffect(() => {
+ const gate = nativeRecoveryGateRef.current;
+ if (gate.routeKey !== viewerRouteKey) resetNativeRecoveryGate(gate, viewerRouteKey);
+ const nativeActive = Boolean(
+ (routeStatus?.stream.adapter === 'native-sidecar' &&
+ routeStatus.stream.state === 'active') ||
+ (routeStatus?.input.adapter === 'native-sidecar' && routeStatus.input.state === 'active'),
+ );
+ if (nativeActive && !isRecoverableNativeFallback(routeStatus)) {
+ resetNativeRecoveryGate(gate, viewerRouteKey);
+ }
+ }, [
+ routeStatus?.input.adapter,
+ routeStatus?.input.reasonCode,
+ routeStatus?.input.state,
+ routeStatus?.stream.adapter,
+ routeStatus?.stream.reasonCode,
+ routeStatus?.stream.state,
+ viewerRouteKey,
+ ]);
+
useEffect(() => {
const nextId = attachedInstance?.instanceId ?? null;
if ((state.instanceId ?? null) !== nextId) ctx.patchState({ instanceId: nextId });
@@ -389,6 +513,7 @@ export function IOSSimulatorTabBody({
let nativeDecoderFallback = false;
let mediaDisconnected = false;
let routeInactive = false;
+ let foregroundRecoveryArmed = document.visibilityState !== 'visible';
const routeKey = `${route.instanceId}:${route.generation}`;
const decoderRuntime = createBrowserIOSSimulatorH264DecoderRuntime();
let decoder: IOSSimulatorH264Decoder | null = null;
@@ -399,9 +524,6 @@ export function IOSSimulatorTabBody({
const disconnectViewer = () => {
if (cancelled) return;
mediaDisconnected = true;
- preferredEncoding = 'jpeg';
- decoder?.close();
- decoder = null;
clearViewerPresentation('disconnected');
};
const acceptStream = (stream: IOSSimulatorFramePumpSnapshot | null) => {
@@ -423,20 +545,10 @@ export function IOSSimulatorTabBody({
}
if (!frame || frame.sequence <= frameSequenceRef.current) return;
frameSequenceRef.current = frame.sequence;
- const now = performance.now();
- if (fpsWindowRef.current.startedAt === 0) fpsWindowRef.current.startedAt = now;
- fpsWindowRef.current.frames += 1;
- const elapsed = now - fpsWindowRef.current.startedAt;
- if (elapsed >= 1_000) {
- setStreamFps((fpsWindowRef.current.frames * 1_000) / elapsed);
- fpsWindowRef.current = { startedAt: now, frames: 0 };
- }
if (frame.encoding === 'h264') {
- preferredEncoding = 'h264';
void decoder?.decode(frame, stream.generation);
return;
}
- preferredEncoding = 'jpeg';
const bytes = frame.bytes instanceof Uint8Array ? frame.bytes : new Uint8Array(frame.bytes);
const candidateUrl = URL.createObjectURL(
new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'image/jpeg' }),
@@ -490,6 +602,58 @@ export function IOSSimulatorTabBody({
const nextMutation = resultMutation(result);
if (!cancelled && nextMutation) setLiveMutation(nextMutation);
};
+ const attemptNativeRecovery = async (): Promise<IOSSimulatorToolResponse | null> => {
+ if (
+ cancelled ||
+ !viewerVisible ||
+ preferredEncoding !== 'h264' ||
+ nativeDecoderFallback ||
+ document.visibilityState !== 'visible' ||
+ !isRecoverableNativeFallback(currentRouteStatusRef.current)
+ ) {
+ return null;
+ }
+ const gate = nativeRecoveryGateRef.current;
+ if (gate.routeKey !== routeKey) resetNativeRecoveryGate(gate, routeKey);
+ const now = performance.now();
+ if (gate.inFlight || now < gate.retryAfter) return null;
+ gate.inFlight = true;
+ gate.attemptCount += 1;
+ gate.retryAfter = now + nativeRecoveryBackoff(gate.attemptCount);
+ try {
+ return await window.electronAPI.maker.iosSimulator.setViewerVisibility({
+ ...route,
+ visible: true,
+ preferredEncoding: 'h264',
+ });
+ } finally {
+ if (nativeRecoveryGateRef.current.routeKey === routeKey) {
+ nativeRecoveryGateRef.current.inFlight = false;
+ }
+ }
+ };
+ const activateCompatibilityViewer = () =>
+ window.electronAPI.maker.iosSimulator.setViewerVisibility({
+ ...route,
+ visible: true,
+ preferredEncoding: 'jpeg',
+ });
+ const recoverNativeOnForeground = () => {
+ if (document.visibilityState !== 'visible') {
+ foregroundRecoveryArmed = true;
+ return;
+ }
+ if (!foregroundRecoveryArmed) return;
+ foregroundRecoveryArmed = false;
+ if (!viewerVisible || nativeDecoderFallback || preferredEncoding !== 'h264') return;
+ void attemptNativeRecovery()
+ .then((result) => {
+ // A failed optional recovery must not blank the healthy WDA fallback.
+ if (result?.ok) acceptViewerResult(result);
+ })
+ .catch(() => undefined);
+ };
+ document.addEventListener('visibilitychange', recoverNativeOnForeground);
const acceptPushedH264Frame = (payload: IOSSimulatorH264FramePush) => {
if (
cancelled ||
@@ -579,7 +743,7 @@ export function IOSSimulatorTabBody({
const recovered = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
...route,
visible: true,
- preferredEncoding: 'jpeg',
+ preferredEncoding,
...(nativeDecoderFallback
? { fallbackReason: 'native-decoder-fallback' as const }
: {}),
@@ -619,16 +783,35 @@ export function IOSSimulatorTabBody({
pollTimer = null;
void poll().finally(schedulePoll);
},
- mediaDisconnected ? 250 : preferredEncoding === 'h264' ? 1_000 : 50,
+ mediaDisconnected
+ ? 250
+ : frameEncodingRef.current === 'jpeg' || preferredEncoding === 'jpeg'
+ ? 50
+ : 1_000,
);
};
const startViewer = async () => {
try {
- const result = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
- ...route,
- visible: viewerVisible,
- preferredEncoding,
- });
+ let result: IOSSimulatorToolResponse;
+ if (viewerVisible && preferredEncoding === 'h264' && !nativeDecoderFallback) {
+ const nativeResult = isRecoverableNativeFallback(currentRouteStatusRef.current)
+ ? await attemptNativeRecovery().catch(() => null)
+ : await window.electronAPI.maker.iosSimulator
+ .setViewerVisibility({
+ ...route,
+ visible: true,
+ preferredEncoding: 'h264',
+ })
+ .catch(() => null);
+ if (cancelled) return;
+ result = nativeResult?.ok ? nativeResult : await activateCompatibilityViewer();
+ } else {
+ result = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
+ ...route,
+ visible: viewerVisible,
+ preferredEncoding,
+ });
+ }
acceptViewerResult(result);
} catch {
disconnectViewer();
@@ -642,6 +825,7 @@ export function IOSSimulatorTabBody({
cancelled = true;
decoder?.close();
unsubscribeH264Frame();
+ document.removeEventListener('visibilitychange', recoverNativeOnForeground);
if (pollTimer !== null) window.clearTimeout(pollTimer);
void window.electronAPI.maker.iosSimulator
.setViewerVisibility({ ...route, visible: false })
@@ -742,20 +926,42 @@ export function IOSSimulatorTabBody({
}
}, [attachedInstance, ctx.sessionId, mutation?.agentPaused, t]);
+ const sendStreamProfile = useCallback(
+ async (
+ profileName: StreamProfileName,
+ useNativeProfile: boolean,
+ ): Promise<IOSSimulatorToolResponse | null> => {
+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return null;
+ const route = routeFor(attachedInstance);
+ const result = await window.electronAPI.maker.iosSimulator.setStreamProfile({
+ sessionId: ctx.sessionId,
+ ...route,
+ ...viewerStreamProfile(profileName, useNativeProfile),
+ });
+ if (result.ok) {
+ nativeProfileAppliedRef.current = useNativeProfile
+ ? {
+ routeKey: `${route.instanceId}:${route.generation}`,
+ profile: profileName,
+ }
+ : null;
+ }
+ return result;
+ },
+ [attachedInstance, ctx.sessionId],
+ );
+
const applyStreamProfile = useCallback(
- async (next: StreamProfileName) => {
+ async (requested: StreamProfileName) => {
if (!attachedInstance) return;
+ const next = requested === 'experimental60' && !nativeH264Active ? 'high' : requested;
const previous = streamProfile;
setStreamProfile(next);
streamProfileRef.current = next;
setActionError(null);
try {
- const result = await window.electronAPI.maker.iosSimulator.setStreamProfile({
- sessionId: ctx.sessionId,
- ...routeFor(attachedInstance),
- profile: STREAM_PROFILES[next],
- });
- if (!result.ok) {
+ const result = await sendStreamProfile(next, nativeH264Active);
+ if (result && !result.ok) {
setStreamProfile(previous);
streamProfileRef.current = previous;
setActionError(result.message);
@@ -766,48 +972,83 @@ export function IOSSimulatorTabBody({
setActionError(t('rightSidebar.iosSimulator.operationError'));
}
},
- [attachedInstance, ctx.sessionId, streamProfile, t],
+ [attachedInstance, nativeH264Active, sendStreamProfile, streamProfile, t],
);
useEffect(() => {
setStreamProfile('balanced');
streamProfileRef.current = 'balanced';
+ nativeProfileAppliedRef.current = null;
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
void window.electronAPI.maker.iosSimulator
.setStreamProfile({
sessionId: ctx.sessionId,
...routeFor(attachedInstance),
- profile: STREAM_PROFILES.balanced,
+ ...viewerStreamProfile('balanced', false),
})
.catch(() => undefined);
- }, [attachedInstance, ctx.sessionId]);
+ }, [
+ attachedInstance?.generation,
+ attachedInstance?.instanceId,
+ attachedInstance?.lease.id,
+ attachedInstance?.lifecycleState,
+ ctx.sessionId,
+ ]);
const applyTransientStreamProfile = useCallback(
async (profile: StreamProfileName) => {
- if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
- await window.electronAPI.maker.iosSimulator
- .setStreamProfile({
- sessionId: ctx.sessionId,
- ...routeFor(attachedInstance),
- profile: STREAM_PROFILES[profile],
- })
- .catch(() => undefined);
+ await sendStreamProfile(profile, nativeH264Active).catch(() => undefined);
},
- [attachedInstance, ctx.sessionId],
+ [nativeH264Active, sendStreamProfile],
);
+ useEffect(() => {
+ const previous = profileRouteRef.current;
+ const nextRoute = {
+ routeKey: viewerRouteKey,
+ nativeSelected: nativeH264Selected,
+ nativeActive: nativeH264Active,
+ };
+ profileRouteRef.current = nextRoute;
+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
+
+ if (!nativeH264Selected) {
+ if (previous?.nativeSelected || streamProfileRef.current === 'experimental60') {
+ const nextProfile =
+ streamProfileRef.current === 'experimental60' ? 'high' : streamProfileRef.current;
+ setStreamProfile(nextProfile);
+ streamProfileRef.current = nextProfile;
+ void sendStreamProfile(nextProfile, false).catch(() => undefined);
+ }
+ return;
+ }
+ if (!nativeH264Active || !viewerRouteKey) return;
+ const applied = nativeProfileAppliedRef.current;
+ if (applied?.routeKey === viewerRouteKey && applied.profile === streamProfileRef.current)
+ return;
+ void sendStreamProfile(streamProfileRef.current, true)
+ .then((result) => {
+ if (result && !result.ok) setActionError(result.message);
+ })
+ .catch(() => undefined);
+ }, [attachedInstance, nativeH264Active, nativeH264Selected, sendStreamProfile, viewerRouteKey]);
+
const beginInteractiveFrameRate = useCallback(() => {
if (profileRestoreTimerRef.current !== null) {
window.clearTimeout(profileRestoreTimerRef.current);
profileRestoreTimerRef.current = null;
}
- if (!interactiveProfileActiveRef.current && streamProfileRef.current !== 'high') {
+ if (
+ !interactiveProfileActiveRef.current &&
+ (streamProfileRef.current === 'low' || streamProfileRef.current === 'balanced')
+ ) {
interactiveProfileActiveRef.current = true;
void applyTransientStreamProfile('high');
}
}, [applyTransientStreamProfile]);
const endInteractiveFrameRate = useCallback(() => {
+ if (!interactiveProfileActiveRef.current) return;
if (profileRestoreTimerRef.current !== null) {
window.clearTimeout(profileRestoreTimerRef.current);
}
@@ -906,21 +1147,117 @@ export function IOSSimulatorTabBody({
[ctx.sessionId, viewerInteractive],
);
+ const finishPointerGesture = useCallback(
+ (
+ gesture: PointerGesture,
+ options: {
+ phase: 'end' | 'cancel';
+ point: { xRatio: number; yRatio: number };
+ fallback?: { name: 'tap' | 'swipe'; args: Record<string, unknown> };
+ restoreProfile?: boolean;
+ },
+ ) => {
+ if (gesture.terminalQueued) return;
+ gesture.terminalQueued = true;
+ if (options.phase === 'cancel') gesture.pendingMove = null;
+ clearPointerGestureIdleTimer(gesture);
+ if (pointerGestureRef.current === gesture) pointerGestureRef.current = null;
+ releaseGesturePointerCapture(gesture);
+
+ const restoreProfile = options.restoreProfile !== false;
+ if (!restoreProfile) {
+ if (profileRestoreTimerRef.current !== null) {
+ window.clearTimeout(profileRestoreTimerRef.current);
+ profileRestoreTimerRef.current = null;
+ }
+ interactiveProfileActiveRef.current = false;
+ }
+
+ gesture.tail = gesture.tail
+ .then(async () => {
+ if (options.phase === 'cancel') {
+ if (gesture.beginAcknowledged) {
+ await invokeLiveTouch(gesture, 'cancel', options.point).catch(() => undefined);
+ }
+ return;
+ }
+
+ if (!gesture.failed) {
+ try {
+ await invokeLiveTouch(gesture, 'end', options.point);
+ return;
+ } catch {
+ gesture.failed = true;
+ }
+ }
+
+ if (gesture.beginAcknowledged) {
+ await invokeLiveTouch(gesture, 'cancel', options.point).catch(() => undefined);
+ return;
+ }
+
+ if (options.fallback) {
+ await runInteraction(options.fallback.name, options.fallback.args);
+ }
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ if (restoreProfile) endInteractiveFrameRate();
+ });
+ void gesture.tail;
+ },
+ [endInteractiveFrameRate, invokeLiveTouch, runInteraction],
+ );
+
+ const cancelPointerGesture = useCallback(
+ (gesture: PointerGesture, restoreProfile = true) => {
+ finishPointerGesture(gesture, {
+ phase: 'cancel',
+ point: { xRatio: gesture.lastXRatio, yRatio: gesture.lastYRatio },
+ restoreProfile,
+ });
+ },
+ [finishPointerGesture],
+ );
+
+ const armPointerGestureWatchdog = useCallback(
+ (gesture: PointerGesture) => {
+ clearPointerGestureIdleTimer(gesture);
+ gesture.idleTimer = window.setTimeout(() => {
+ gesture.idleTimer = null;
+ if (pointerGestureRef.current === gesture) cancelPointerGesture(gesture);
+ }, POINTER_GESTURE_IDLE_TIMEOUT_MS);
+ },
+ [cancelPointerGesture],
+ );
+
const queueLiveMove = useCallback(
(gesture: PointerGesture, point: { xRatio: number; yRatio: number }) => {
+ if (gesture.terminalQueued || gesture.failed) return;
gesture.pendingMove = point;
if (gesture.moveDrainQueued) return;
gesture.moveDrainQueued = true;
gesture.tail = gesture.tail.then(async () => {
- while (gesture.pendingMove) {
- const latest = gesture.pendingMove;
+ try {
+ while (!gesture.failed && gesture.pendingMove) {
+ const latest = gesture.pendingMove;
+ gesture.pendingMove = null;
+ await invokeLiveTouch(gesture, 'move', latest);
+ }
+ } catch {
+ gesture.failed = true;
gesture.pendingMove = null;
- await invokeLiveTouch(gesture, 'move', latest);
+ } finally {
+ gesture.moveDrainQueued = false;
+ }
+ });
+ void gesture.tail.then(() => {
+ if (gesture.failed && gesture.beginAcknowledged && !gesture.terminalQueued) {
+ cancelPointerGesture(gesture);
}
- gesture.moveDrainQueued = false;
});
},
- [invokeLiveTouch],
+ [cancelPointerGesture, invokeLiveTouch],
);
const onViewerPointerDown = useCallback(
@@ -934,10 +1271,16 @@ export function IOSSimulatorTabBody({
return;
}
const point = pointerRatio(event);
+ try {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ } catch {
+ return;
+ }
const gesture: PointerGesture = {
pointerId: event.pointerId,
gestureId: `viewer-${Date.now()}-${++gestureSequenceRef.current}`,
route: routeFor(attachedInstance),
+ captureTarget: event.currentTarget,
startedAt: performance.now(),
startClientX: event.clientX,
startClientY: event.clientY,
@@ -947,21 +1290,76 @@ export function IOSSimulatorTabBody({
lastYRatio: point.yRatio,
pendingMove: null,
moveDrainQueued: false,
+ beginAcknowledged: false,
+ failed: false,
+ terminalQueued: false,
+ idleTimer: null,
tail: Promise.resolve(),
};
- gesture.tail = invokeLiveTouch(gesture, 'begin', point);
+ gesture.tail = invokeLiveTouch(gesture, 'begin', point)
+ .then(() => {
+ gesture.beginAcknowledged = true;
+ })
+ .catch(() => {
+ gesture.failed = true;
+ });
pointerGestureRef.current = gesture;
beginInteractiveFrameRate();
- event.currentTarget.setPointerCapture(event.pointerId);
+ armPointerGestureWatchdog(gesture);
+ event.preventDefault();
+ },
+ [
+ armPointerGestureWatchdog,
+ attachedInstance,
+ beginInteractiveFrameRate,
+ invokeLiveTouch,
+ pointerRatio,
+ viewerInteractive,
+ ],
+ );
+
+ const completeViewerPointerGesture = useCallback(
+ (event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {
+ const gesture = pointerGestureRef.current;
+ if (!gesture || gesture.pointerId !== event.pointerId) return;
+ const end = pointerRatio(event);
+ gesture.lastXRatio = end.xRatio;
+ gesture.lastYRatio = end.yRatio;
+ const distance = Math.hypot(
+ event.clientX - gesture.startClientX,
+ event.clientY - gesture.startClientY,
+ );
+ const durationMs = Math.min(2_000, Math.max(100, performance.now() - gesture.startedAt));
+ finishPointerGesture(gesture, {
+ phase: 'end',
+ point: end,
+ fallback:
+ distance < 8
+ ? { name: 'tap', args: { xRatio: end.xRatio, yRatio: end.yRatio } }
+ : {
+ name: 'swipe',
+ args: {
+ startXRatio: gesture.startXRatio,
+ startYRatio: gesture.startYRatio,
+ endXRatio: end.xRatio,
+ endYRatio: end.yRatio,
+ durationMs: Math.round(durationMs),
+ },
+ },
+ });
event.preventDefault();
},
- [attachedInstance, beginInteractiveFrameRate, invokeLiveTouch, pointerRatio, viewerInteractive],
+ [finishPointerGesture, pointerRatio],
);
const onViewerPointerMove = useCallback(
(event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {
const gesture = pointerGestureRef.current;
if (!viewerInteractive || !gesture || gesture.pointerId !== event.pointerId) return;
+ if ((event.buttons & 1) === 0) {
+ completeViewerPointerGesture(event);
+ return;
+ }
const coalesced = event.nativeEvent.getCoalescedEvents?.() ?? [event.nativeEvent];
const latest = coalesced.at(-1) ?? event.nativeEvent;
const bounds = event.currentTarget.getBoundingClientRect();
@@ -971,86 +1369,37 @@ export function IOSSimulatorTabBody({
};
gesture.lastXRatio = point.xRatio;
gesture.lastYRatio = point.yRatio;
+ armPointerGestureWatchdog(gesture);
queueLiveMove(gesture, point);
event.preventDefault();
},
- [queueLiveMove, viewerInteractive],
+ [armPointerGestureWatchdog, completeViewerPointerGesture, queueLiveMove, viewerInteractive],
);
- const onViewerPointerUp = useCallback(
+ const onViewerPointerUp = completeViewerPointerGesture;
+
+ const onViewerPointerCancel = useCallback(
(event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {
const gesture = pointerGestureRef.current;
- if (!gesture || gesture.pointerId !== event.pointerId) return;
- pointerGestureRef.current = null;
- if (event.currentTarget.hasPointerCapture(event.pointerId)) {
- event.currentTarget.releasePointerCapture(event.pointerId);
- }
- const end = pointerRatio(event);
- gesture.lastXRatio = end.xRatio;
- gesture.lastYRatio = end.yRatio;
- const distance = Math.hypot(
- event.clientX - gesture.startClientX,
- event.clientY - gesture.startClientY,
- );
- const durationMs = Math.min(2_000, Math.max(100, performance.now() - gesture.startedAt));
- if (distance >= 8) queueLiveMove(gesture, end);
- gesture.tail = gesture.tail
- .then(() => invokeLiveTouch(gesture, 'end', end))
- .catch(async () => {
- await invokeLiveTouch(gesture, 'cancel', end).catch(() => undefined);
- if (distance < 8) {
- await runInteraction('tap', { xRatio: end.xRatio, yRatio: end.yRatio });
- } else {
- await runInteraction('swipe', {
- startXRatio: gesture.startXRatio,
- startYRatio: gesture.startYRatio,
- endXRatio: end.xRatio,
- endYRatio: end.yRatio,
- durationMs: Math.round(durationMs),
- });
- }
- })
- .finally(endInteractiveFrameRate);
+ if (gesture?.pointerId === event.pointerId) cancelPointerGesture(gesture);
},
- [endInteractiveFrameRate, invokeLiveTouch, pointerRatio, queueLiveMove, runInteraction],
+ [cancelPointerGesture],
);
- const onViewerPointerCancel = useCallback(
+ const onViewerLostPointerCapture = useCallback(
(event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {
- if (pointerGestureRef.current?.pointerId === event.pointerId) {
- const gesture = pointerGestureRef.current;
- pointerGestureRef.current = null;
- const point = { xRatio: gesture.lastXRatio, yRatio: gesture.lastYRatio };
- gesture.pendingMove = null;
- gesture.tail = gesture.tail
- .catch(() => undefined)
- .then(() => invokeLiveTouch(gesture, 'cancel', point))
- .catch(() => undefined)
- .finally(endInteractiveFrameRate);
- }
+ const gesture = pointerGestureRef.current;
+ if (gesture?.pointerId === event.pointerId) cancelPointerGesture(gesture);
},
- [endInteractiveFrameRate, invokeLiveTouch],
+ [cancelPointerGesture],
);
const cancelActivePointerGesture = useCallback(
(restoreProfile: boolean) => {
const gesture = pointerGestureRef.current;
const hadInteractiveProfile = interactiveProfileActiveRef.current;
- pointerGestureRef.current = null;
if (gesture) {
- gesture.pendingMove = null;
- void gesture.tail
- .catch(() => undefined)
- .then(() =>
- invokeLiveTouch(gesture, 'cancel', {
- xRatio: gesture.lastXRatio,
- yRatio: gesture.lastYRatio,
- }),
- )
- .catch(() => undefined)
- .finally(() => {
- if (restoreProfile) endInteractiveFrameRate();
- });
+ cancelPointerGesture(gesture, restoreProfile);
} else if (restoreProfile && hadInteractiveProfile) {
endInteractiveFrameRate();
}
@@ -1062,13 +1411,26 @@ export function IOSSimulatorTabBody({
interactiveProfileActiveRef.current = false;
}
},
- [endInteractiveFrameRate, invokeLiveTouch],
+ [cancelPointerGesture, endInteractiveFrameRate],
);
useEffect(() => {
if (!viewerInteractive) cancelActivePointerGesture(true);
}, [cancelActivePointerGesture, viewerInteractive]);
+ useEffect(() => {
+ const cancelForLostContext = () => cancelActivePointerGesture(true);
+ const cancelWhenHidden = () => {
+ if (document.visibilityState !== 'visible') cancelForLostContext();
+ };
+ window.addEventListener('blur', cancelForLostContext);
+ document.addEventListener('visibilitychange', cancelWhenHidden);
+ return () => {
+ window.removeEventListener('blur', cancelForLostContext);
+ document.removeEventListener('visibilitychange', cancelWhenHidden);
+ };
+ }, [cancelActivePointerGesture]);
+
useEffect(
() => () => {
cancelActivePointerGesture(false);
@@ -1299,11 +1661,24 @@ export function IOSSimulatorTabBody({
{t('rightSidebar.iosSimulator.streamProfiles.low')}
</option>
<option value="balanced">
- {t('rightSidebar.iosSimulator.streamProfiles.balanced')}
+ {t(
+ nativeH264Active
+ ? 'rightSidebar.iosSimulator.streamProfiles.balancedNative'
+ : 'rightSidebar.iosSimulator.streamProfiles.balanced',
+ )}
</option>
<option value="high">
- {t('rightSidebar.iosSimulator.streamProfiles.high')}
+ {t(
+ nativeH264Active
+ ? 'rightSidebar.iosSimulator.streamProfiles.highNative'
+ : 'rightSidebar.iosSimulator.streamProfiles.high',
+ )}
</option>
+ {showExperimental60 && (
+ <option value="experimental60">
+ {t('rightSidebar.iosSimulator.streamProfiles.experimental60')}
+ </option>
+ )}
</select>
</div>
<div
@@ -1349,6 +1724,7 @@ export function IOSSimulatorTabBody({
onPointerMove={onViewerPointerMove}
onPointerUp={onViewerPointerUp}
onPointerCancel={onViewerPointerCancel}
+ onLostPointerCapture={onViewerLostPointerCapture}
/>
)}
<canvas
@@ -1374,6 +1750,7 @@ export function IOSSimulatorTabBody({
onPointerMove={onViewerPointerMove}
onPointerUp={onViewerPointerUp}
onPointerCancel={onViewerPointerCancel}
+ onLostPointerCapture={onViewerLostPointerCapture}
/>
{!presentationMatchesRoute && (
<div className="flex flex-col items-center gap-2 p-8 text-center text-[11px] text-[var(--text-secondary)]">
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
index f689e363aa..f2102decd3 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
@@ -10,6 +10,7 @@ import type {
IOSSimulatorRouteStatusPush,
IOSSimulatorSessionStatus,
IOSSimulatorToolResponse,
+ IOSSimulatorViewerVisibilityRequest,
} from '../../../../../../shared/iosSimulatorIpc';
import type { TabKindHostContext } from '../../../types';
@@ -102,6 +103,44 @@ function readyStatus(instance = readyInstance()): IOSSimulatorSessionStatus {
};
}
+function preparePointerTarget(container: HTMLElement): HTMLImageElement {
+ const image = container.querySelector('img') as HTMLImageElement | null;
+ if (!image) throw new Error('Expected the simulator viewer image.');
+ Object.defineProperties(image, {
+ setPointerCapture: { configurable: true, value: vi.fn() },
+ hasPointerCapture: { configurable: true, value: vi.fn(() => true) },
+ releasePointerCapture: { configurable: true, value: vi.fn() },
+ getBoundingClientRect: {
+ configurable: true,
+ value: () => ({ left: 0, top: 0, width: 200, height: 400 }),
+ },
+ });
+ return image;
+}
+
+function installFakeH264DecoderRuntime(): void {
+ class FakeVideoDecoder {
+ static async isConfigSupported() {
+ return { supported: true };
+ }
+ constructor() {}
+ configure() {}
+ decode() {}
+ close() {}
+ }
+ class FakeEncodedVideoChunk {
+ constructor(readonly init: unknown) {}
+ }
+ Object.defineProperty(globalThis, 'VideoDecoder', {
+ configurable: true,
+ value: FakeVideoDecoder,
+ });
+ Object.defineProperty(globalThis, 'EncodedVideoChunk', {
+ configurable: true,
+ value: FakeEncodedVideoChunk,
+ });
+}
+
function installStatus(statusValue: IOSSimulatorSessionStatus) {
let currentStatusValue = statusValue;
const status = vi.fn(async () => currentStatusValue);
@@ -110,10 +149,15 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
data: {},
}));
const setAgentControl = vi.fn(async () => ({ ok: true as const, data: {} }));
- const setViewerVisibility = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
- ok: true,
- data: { stream: null },
- }));
+ const setViewerVisibility = vi.fn(
+ async (request: IOSSimulatorViewerVisibilityRequest): Promise<IOSSimulatorToolResponse> => {
+ void request;
+ return {
+ ok: true,
+ data: { stream: null },
+ };
+ },
+ );
const setStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));
let h264FrameListener: ((payload: IOSSimulatorH264FramePush) => void) | null = null;
let routeStatusListener: ((payload: IOSSimulatorRouteStatusPush) => void) | null = null;
@@ -129,7 +173,9 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
if (routeStatusListener === callback) routeStatusListener = null;
};
});
- const liveTouch = vi.fn(async (request: IOSSimulatorLiveTouchRequest) => {
+ const liveTouch = vi.fn(async (
+ request: IOSSimulatorLiveTouchRequest,
+ ): Promise<IOSSimulatorToolResponse> => {
void request;
return {
ok: true as const,
@@ -383,6 +429,150 @@ describe('IOSSimulatorTabBody', () => {
expect(screen.getByText('rightSidebar.iosSimulator.route.nativeHid')).toBeTruthy();
});
+ it('offers 60 FPS only for active Native H.264 and keeps a 20 FPS WDA fallback', async () => {
+ const instance = readyInstance();
+ const statusValue = readyStatus(instance);
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ const nativeRouteStatus: IOSSimulatorRouteStatusPush = {
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ stream: {
+ adapter: 'native-sidecar',
+ encoding: 'h264',
+ state: 'active',
+ reasonCode: 'native-active',
+ },
+ input: {
+ adapter: 'wda',
+ state: 'fallback',
+ continuous: false,
+ multiTouch: false,
+ reasonCode: 'native-capability-unavailable',
+ },
+ };
+ statusValue.routeStatuses = [
+ {
+ ...nativeRouteStatus,
+ updatedAt: '2026-08-05T23:59:59.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-sidecar-unavailable',
+ },
+ },
+ ];
+ const api = installStatus(statusValue);
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+
+ const rendered = render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+
+ const profileSelect = await screen.findByRole('combobox');
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ expect(
+ screen.queryByRole('option', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.experimental60',
+ }),
+ ).toBeNull();
+ act(() => api.emitRouteStatus(nativeRouteStatus));
+ await waitFor(() => {
+ expect(
+ screen.getByRole('option', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.highNative',
+ }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('option', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.experimental60',
+ }),
+ ).toBeTruthy();
+ });
+
+ fireEvent.change(profileSelect, { target: { value: 'high' } });
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ });
+ });
+
+ fireEvent.change(profileSelect, { target: { value: 'experimental60' } });
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ nativeProfile: { framesPerSecond: 60, scalingPercent: 70 },
+ });
+ });
+
+ api.setStreamProfile.mockClear();
+ const image = rendered.container.querySelector('img') as HTMLImageElement;
+ Object.defineProperties(image, {
+ setPointerCapture: { configurable: true, value: vi.fn() },
+ hasPointerCapture: { configurable: true, value: vi.fn(() => true) },
+ releasePointerCapture: { configurable: true, value: vi.fn() },
+ getBoundingClientRect: {
+ configurable: true,
+ value: () => ({ left: 0, top: 0, width: 200, height: 400 }),
+ },
+ });
+ fireEvent.pointerDown(image, { pointerId: 9, button: 0, clientX: 20, clientY: 40 });
+ fireEvent.pointerUp(image, { pointerId: 9, clientX: 180, clientY: 360 });
+ await waitFor(() => {
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual(['begin', 'end']);
+ });
+ await act(async () => {
+ await new Promise((resolve) => window.setTimeout(resolve, 300));
+ });
+ expect(api.setStreamProfile).not.toHaveBeenCalled();
+
+ act(() => {
+ api.emitRouteStatus({
+ ...nativeRouteStatus,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole('option', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.experimental60',
+ }),
+ ).toBeNull();
+ expect((profileSelect as HTMLSelectElement).value).toBe('high');
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith({
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ });
+ });
+ });
+
it('starts frame polling only while the pane is active and visible', async () => {
const api = installStatus({
ok: true,
@@ -416,78 +606,452 @@ describe('IOSSimulatorTabBody', () => {
graceExpiresAt: null,
errorCode: null,
},
- ],
- environment: {
- platform: 'darwin',
- supported: true,
- ready: true,
- xcodeVersion: 'Xcode 26.4',
- runtimes: [],
- devices: [],
- issue: null,
- error: null,
- setupSteps: [],
+ ],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+ const rendered = render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: 'instance-a' }}
+ ctx={ctx}
+ active={false}
+ shellVisible
+ />,
+ );
+
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-a',
+ visible: false,
+ preferredEncoding: 'jpeg',
+ });
+ expect(api.setStreamProfile).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-a',
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ });
+ });
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'high' } });
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ instanceId: 'instance-a',
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ }),
+ );
+ });
+ expect(api.latestFrame).not.toHaveBeenCalled();
+
+ rendered.rerender(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ instanceId: 'instance-a', visible: true }),
+ );
+ expect(api.latestFrame).toHaveBeenCalled();
+ });
+
+ rendered.rerender(
+ <IOSSimulatorTabBody
+ state={{ instanceId: 'instance-a' }}
+ ctx={ctx}
+ active
+ shellVisible={false}
+ />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenLastCalledWith(
+ expect.objectContaining({ instanceId: 'instance-a', visible: false }),
+ );
+ });
+ });
+
+ it('re-arms a native fallback once on foreground and backs off repeated attempts', async () => {
+ installFakeH264DecoderRuntime();
+ let visibilityState: DocumentVisibilityState = 'visible';
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibilityState);
+ let now = 10_000;
+ vi.spyOn(performance, 'now').mockImplementation(() => now);
+
+ const instance = readyInstance();
+ const statusValue = readyStatus(instance);
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ const nativeActive: IOSSimulatorRouteStatusPush = {
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ stream: {
+ adapter: 'native-sidecar',
+ encoding: 'h264',
+ state: 'active',
+ reasonCode: 'native-active',
+ },
+ input: {
+ adapter: 'native-sidecar',
+ state: 'active',
+ continuous: true,
+ multiTouch: true,
+ reasonCode: 'native-active',
+ },
+ };
+ const nativeFallback: IOSSimulatorRouteStatusPush = {
+ ...nativeActive,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ input: {
+ adapter: 'wda',
+ state: 'fallback',
+ continuous: false,
+ multiTouch: false,
+ reasonCode: 'native-sidecar-unavailable',
+ },
+ };
+ statusValue.routeStatuses = [nativeActive];
+ const api = installStatus(statusValue);
+ const connectingH264: IOSSimulatorToolResponse = {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ state: 'connecting',
+ reconnectAttempt: 0,
+ latestFrame: null,
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+ api.setViewerVisibility.mockResolvedValue(connectingH264);
+ api.latestFrame.mockResolvedValue(connectingH264);
+
+ render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
+ );
+ });
+ api.setViewerVisibility.mockClear();
+
+ act(() => api.emitRouteStatus(nativeFallback));
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();
+ });
+ const foreground = () => {
+ act(() => {
+ visibilityState = 'hidden';
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ act(() => {
+ visibilityState = 'visible';
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ };
+ const nativeRecoveryRequests = () =>
+ api.setViewerVisibility.mock.calls
+ .map(([request]) => request)
+ .filter((request) => request.visible && request.preferredEncoding === 'h264');
+
+ foreground();
+ await waitFor(() => expect(nativeRecoveryRequests()).toHaveLength(1));
+ foreground();
+ await act(async () => Promise.resolve());
+ expect(nativeRecoveryRequests()).toHaveLength(1);
+
+ now = 15_001;
+ foreground();
+ await waitFor(() => expect(nativeRecoveryRequests()).toHaveLength(2));
+
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeActive,
+ updatedAt: '2026-08-06T00:00:02.000Z',
+ input: nativeFallback.input,
+ }),
+ );
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.nativeH264')).toBeTruthy();
+ });
+ act(() =>
+ api.emitRouteStatus({ ...nativeFallback, updatedAt: '2026-08-06T00:00:03.000Z' }),
+ );
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();
+ });
+ foreground();
+ await act(async () => Promise.resolve());
+ expect(nativeRecoveryRequests()).toHaveLength(2);
+
+ act(() => api.emitRouteStatus({ ...nativeActive, updatedAt: '2026-08-06T00:00:04.000Z' }));
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.nativeH264')).toBeTruthy();
+ });
+ act(() =>
+ api.emitRouteStatus({ ...nativeFallback, updatedAt: '2026-08-06T00:00:05.000Z' }),
+ );
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();
+ });
+ foreground();
+ await waitFor(() => expect(nativeRecoveryRequests()).toHaveLength(3));
+ });
+
+ it('does not retry an explicit H.264 decoder fallback when returning foreground', async () => {
+ installFakeH264DecoderRuntime();
+ let visibilityState: DocumentVisibilityState = 'visible';
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibilityState);
+ const instance = readyInstance();
+ const statusValue = readyStatus(instance);
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ const nativeActive: IOSSimulatorRouteStatusPush = {
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ stream: {
+ adapter: 'native-sidecar',
+ encoding: 'h264',
+ state: 'active',
+ reasonCode: 'native-active',
+ },
+ input: {
+ adapter: 'native-sidecar',
+ state: 'active',
+ continuous: true,
+ multiTouch: true,
+ reasonCode: 'native-active',
+ },
+ };
+ statusValue.routeStatuses = [nativeActive];
+ const api = installStatus(statusValue);
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+
+ render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+ await waitFor(() => expect(api.setViewerVisibility).toHaveBeenCalled());
+ api.setViewerVisibility.mockClear();
+ act(() => {
+ api.emitRouteStatus({
+ ...nativeActive,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-decoder-fallback',
+ },
+ });
+ });
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();
+ });
+
+ act(() => {
+ visibilityState = 'hidden';
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ act(() => {
+ visibilityState = 'visible';
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await act(async () => Promise.resolve());
+ expect(
+ api.setViewerVisibility.mock.calls.some(
+ ([request]) => request.visible && request.preferredEncoding === 'h264',
+ ),
+ ).toBe(false);
+ });
+
+ it('re-arms once when the simulator pane reopens and uses WDA during recovery backoff', async () => {
+ installFakeH264DecoderRuntime();
+ const instance = readyInstance();
+ const statusValue = readyStatus(instance);
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ statusValue.routeStatuses = [
+ {
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ input: {
+ adapter: 'wda',
+ state: 'fallback',
+ continuous: false,
+ multiTouch: false,
+ reasonCode: 'native-sidecar-unavailable',
+ },
+ },
+ ];
+ const api = installStatus(statusValue);
+ const connectingH264: IOSSimulatorToolResponse = {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ state: 'connecting',
+ reconnectAttempt: 0,
+ latestFrame: null,
+ },
},
- });
+ };
+ api.setViewerVisibility.mockResolvedValue(connectingH264);
+ api.latestFrame.mockResolvedValue(connectingH264);
const rendered = render(
<IOSSimulatorTabBody
- state={{ instanceId: 'instance-a' }}
+ state={{ instanceId: instance.instanceId }}
ctx={ctx}
active={false}
shellVisible
/>,
);
-
await waitFor(() => {
- expect(api.setViewerVisibility).toHaveBeenCalledWith({
- sessionId: 'session-a',
- instanceId: 'instance-a',
- generation: 2,
- leaseId: 'lease-a',
- visible: false,
- preferredEncoding: 'jpeg',
- });
- expect(api.setStreamProfile).toHaveBeenCalledWith({
- sessionId: 'session-a',
- instanceId: 'instance-a',
- generation: 2,
- leaseId: 'lease-a',
- profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
- });
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: false }),
+ );
});
- fireEvent.change(screen.getByRole('combobox'), { target: { value: 'high' } });
+ api.setViewerVisibility.mockClear();
+
+ rendered.rerender(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
await waitFor(() => {
- expect(api.setStreamProfile).toHaveBeenCalledWith(
- expect.objectContaining({
- instanceId: 'instance-a',
- profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
- }),
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
);
});
- expect(api.latestFrame).not.toHaveBeenCalled();
rendered.rerender(
- <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active={false}
+ shellVisible
+ />,
);
await waitFor(() => {
expect(api.setViewerVisibility).toHaveBeenCalledWith(
- expect.objectContaining({ instanceId: 'instance-a', visible: true }),
+ expect.objectContaining({ visible: false }),
);
- expect(api.latestFrame).toHaveBeenCalled();
});
-
+ api.setViewerVisibility.mockClear();
rendered.rerender(
<IOSSimulatorTabBody
- state={{ instanceId: 'instance-a' }}
+ state={{ instanceId: instance.instanceId }}
ctx={ctx}
active
- shellVisible={false}
+ shellVisible
/>,
);
await waitFor(() => {
- expect(api.setViewerVisibility).toHaveBeenLastCalledWith(
- expect.objectContaining({ instanceId: 'instance-a', visible: false }),
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'jpeg' }),
+ );
+ });
+ expect(
+ api.setViewerVisibility.mock.calls.some(
+ ([request]) => request.visible && request.preferredEncoding === 'h264',
+ ),
+ ).toBe(false);
+ });
+
+ it('keeps the compatibility viewer active when pane re-arm rejects', async () => {
+ installFakeH264DecoderRuntime();
+ const instance = readyInstance();
+ const statusValue = readyStatus(instance);
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ statusValue.routeStatuses = [
+ {
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ input: {
+ adapter: 'wda',
+ state: 'fallback',
+ continuous: false,
+ multiTouch: false,
+ reasonCode: 'native-sidecar-unavailable',
+ },
+ },
+ ];
+ const api = installStatus(statusValue);
+ api.setViewerVisibility.mockImplementation(async (request) => {
+ if (request.visible && request.preferredEncoding === 'h264') {
+ throw new Error('Native re-arm failed.');
+ }
+ return streamingJpegResult();
+ });
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+
+ const rendered = render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
);
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'jpeg' }),
+ );
+ expect(rendered.container.querySelector('img')).toBeTruthy();
});
});
@@ -555,7 +1119,7 @@ describe('IOSSimulatorTabBody', () => {
});
fireEvent.pointerDown(image, { pointerId: 7, button: 0, clientX: 20, clientY: 40 });
- fireEvent.pointerMove(image, { pointerId: 7, clientX: 100, clientY: 200 });
+ fireEvent.pointerMove(image, { pointerId: 7, buttons: 1, clientX: 100, clientY: 200 });
fireEvent.pointerUp(image, { pointerId: 7, clientX: 180, clientY: 360 });
await waitFor(() => {
@@ -599,6 +1163,181 @@ describe('IOSSimulatorTabBody', () => {
);
});
+ it('finishes a captured gesture when pointer movement reports that the button is released', async () => {
+ const api = installStatus(readyStatus());
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const image = preparePointerTarget(rendered.container);
+
+ fireEvent.pointerDown(image, {
+ pointerId: 8,
+ button: 0,
+ buttons: 1,
+ clientX: 20,
+ clientY: 40,
+ });
+ fireEvent.pointerMove(image, {
+ pointerId: 8,
+ buttons: 0,
+ clientX: 180,
+ clientY: 360,
+ });
+
+ await waitFor(() => {
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual(['begin', 'end']);
+ });
+ fireEvent.pointerMove(image, {
+ pointerId: 8,
+ buttons: 0,
+ clientX: 100,
+ clientY: 200,
+ });
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual(['begin', 'end']);
+ expect(image.releasePointerCapture).toHaveBeenCalledWith(8);
+ expect(api.call).not.toHaveBeenCalledWith(
+ expect.objectContaining({ name: expect.stringMatching(/^(tap|swipe)$/) }),
+ );
+ });
+
+ it('cancels native touch when pointer capture is lost', async () => {
+ const api = installStatus(readyStatus());
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const image = preparePointerTarget(rendered.container);
+
+ fireEvent.pointerDown(image, {
+ pointerId: 9,
+ button: 0,
+ buttons: 1,
+ clientX: 20,
+ clientY: 40,
+ });
+ fireEvent.lostPointerCapture(image, { pointerId: 9 });
+
+ await waitFor(() => {
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual([
+ 'begin',
+ 'cancel',
+ ]);
+ });
+ expect(api.call).not.toHaveBeenCalledWith(
+ expect.objectContaining({ name: expect.stringMatching(/^(tap|swipe)$/) }),
+ );
+ });
+
+ it('releases a partially delivered native gesture without replaying the swipe', async () => {
+ const api = installStatus(readyStatus());
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+ api.liveTouch.mockImplementation(
+ async (request): Promise<IOSSimulatorToolResponse> =>
+ request.phase === 'move'
+ ? {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The native move failed.',
+ }
+ : { ok: true, data: {} },
+ );
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const image = preparePointerTarget(rendered.container);
+
+ fireEvent.pointerDown(image, {
+ pointerId: 10,
+ button: 0,
+ buttons: 1,
+ clientX: 20,
+ clientY: 40,
+ });
+ fireEvent.pointerMove(image, {
+ pointerId: 10,
+ buttons: 1,
+ clientX: 100,
+ clientY: 200,
+ });
+
+ await waitFor(() => {
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual([
+ 'begin',
+ 'move',
+ 'cancel',
+ ]);
+ });
+ fireEvent.pointerUp(image, { pointerId: 10, clientX: 180, clientY: 360 });
+ expect(api.call).not.toHaveBeenCalledWith(
+ expect.objectContaining({ name: expect.stringMatching(/^(tap|swipe)$/) }),
+ );
+
+ fireEvent.pointerDown(image, {
+ pointerId: 11,
+ button: 0,
+ buttons: 1,
+ clientX: 20,
+ clientY: 40,
+ });
+ fireEvent.pointerUp(image, { pointerId: 11, clientX: 20, clientY: 40 });
+ await waitFor(() => {
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual([
+ 'begin',
+ 'move',
+ 'cancel',
+ 'begin',
+ 'end',
+ ]);
+ });
+ });
+
+ it('uses the discrete compatibility route only when native touch never began', async () => {
+ const api = installStatus(readyStatus());
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+ api.liveTouch.mockResolvedValue({
+ ok: false,
+ errorCode: 'NATIVE_INPUT_UNAVAILABLE',
+ message: 'Continuous native input is unavailable.',
+ });
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const image = preparePointerTarget(rendered.container);
+
+ fireEvent.pointerDown(image, {
+ pointerId: 12,
+ button: 0,
+ buttons: 1,
+ clientX: 20,
+ clientY: 40,
+ });
+ fireEvent.pointerUp(image, { pointerId: 12, clientX: 180, clientY: 360 });
+
+ await waitFor(() => {
+ expect(api.call).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ name: 'swipe',
+ args: expect.objectContaining({
+ instanceId: 'instance-a',
+ startXRatio: 0.1,
+ startYRatio: 0.1,
+ endXRatio: 0.9,
+ endYRatio: 0.9,
+ }),
+ });
+ });
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual(['begin']);
+ });
+
it('rejects a frame that belongs to an obsolete simulator generation', async () => {
const api = installStatus(readyStatus());
api.setViewerVisibility.mockResolvedValue(streamingJpegResult(1));
@@ -907,6 +1646,81 @@ describe('IOSSimulatorTabBody', () => {
});
});
+ it('retries H.264 after a transient stream disconnect instead of silently selecting JPEG', async () => {
+ class FakeVideoDecoder {
+ static async isConfigSupported() {
+ return { supported: true };
+ }
+ constructor() {}
+ configure() {}
+ decode() {}
+ close() {}
+ }
+ class FakeEncodedVideoChunk {
+ constructor(readonly init: unknown) {}
+ }
+ Object.defineProperty(globalThis, 'VideoDecoder', {
+ configurable: true,
+ value: FakeVideoDecoder,
+ });
+ Object.defineProperty(globalThis, 'EncodedVideoChunk', {
+ configurable: true,
+ value: FakeEncodedVideoChunk,
+ });
+ const api = installStatus(readyStatus());
+ const disconnectedH264: IOSSimulatorToolResponse = {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-a',
+ generation: 2,
+ state: 'disconnected',
+ reconnectAttempt: 1,
+ latestFrame: null,
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+ const connectingH264: IOSSimulatorToolResponse = {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-a',
+ generation: 2,
+ state: 'connecting',
+ reconnectAttempt: 1,
+ latestFrame: null,
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+ api.setViewerVisibility
+ .mockResolvedValueOnce(disconnectedH264)
+ .mockResolvedValue(connectingH264);
+ api.latestFrame.mockResolvedValue(connectingH264);
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => {
+ const visibleRequests = api.setViewerVisibility.mock.calls
+ .map(([request]) => request)
+ .filter((request) => request.visible);
+ expect(visibleRequests.length).toBeGreaterThanOrEqual(2);
+ expect(visibleRequests).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
+ ]),
+ );
+ expect(visibleRequests).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ visible: true, preferredEncoding: 'jpeg' }),
+ ]),
+ );
+ });
+ });
+
it('renews an expired viewer route and retries the user interaction once', async () => {
const statusWithLease = (leaseId: string): IOSSimulatorSessionStatus => ({
ok: true,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts
index 81d7f9c297..160a18de1b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts
@@ -69,10 +69,10 @@ interface PendingDecode {
}
const ANNEX_B_START_CODE = new Uint8Array([0, 0, 0, 1]);
-// The producer forces an IDR every two seconds and supports up to 30 FPS.
-// Waiting 60 access units prevents a late-attaching renderer from falling
+// The producer forces an IDR every two seconds and supports up to 60 FPS.
+// Waiting 120 access units prevents a late-attaching renderer from falling
// back immediately before the next valid key frame arrives.
-const DEFAULT_MAX_FRAMES_AWAITING_KEY_FRAME = 60;
+const DEFAULT_MAX_FRAMES_AWAITING_KEY_FRAME = 120;
function readStartCode(bytes: Uint8Array, offset: number): number {
if (offset + 3 > bytes.byteLength || bytes[offset] !== 0 || bytes[offset + 1] !== 0) return 0;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c6b296e300..99f10f4055 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4446,7 +4446,10 @@
"streamProfiles": {
"low": "Low · 5 FPS",
"balanced": "Balanced · 10 FPS",
- "high": "High · 20 FPS"
+ "balancedNative": "Balanced · 20 FPS",
+ "high": "High · 20 FPS",
+ "highNative": "High · 30 FPS",
+ "experimental60": "60 FPS · Experimental"
},
"route": {
"nativeH264": "Native H.264",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index df43f84546..a8321a4039 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4444,7 +4444,10 @@
"streamProfiles": {
"low": "低 · 5 FPS",
"balanced": "バランス · 10 FPS",
- "high": "高 · 20 FPS"
+ "balancedNative": "バランス · 20 FPS",
+ "high": "高 · 20 FPS",
+ "highNative": "高 · 30 FPS",
+ "experimental60": "60 FPS · 実験的"
},
"route": {
"nativeH264": "Native H.264",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ffc49eef21..374c14d07e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4444,7 +4444,10 @@
"streamProfiles": {
"low": "낮음 · 5 FPS",
"balanced": "균형 · 10 FPS",
- "high": "높음 · 20 FPS"
+ "balancedNative": "균형 · 20 FPS",
+ "high": "높음 · 20 FPS",
+ "highNative": "높음 · 30 FPS",
+ "experimental60": "60 FPS · 실험적"
},
"route": {
"nativeH264": "Native H.264",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 76a57b0963..455e372a77 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4444,7 +4444,10 @@
"streamProfiles": {
"low": "低 · 5 FPS",
"balanced": "均衡 · 10 FPS",
- "high": "高 · 20 FPS"
+ "balancedNative": "均衡 · 20 FPS",
+ "high": "高 · 20 FPS",
+ "highNative": "高 · 30 FPS",
+ "experimental60": "60 FPS · 实验"
},
"route": {
"nativeH264": "Native H.264",
diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.ts
index c485b034cd..a252798779 100644
--- a/apps/desktop/src/shared/iosSimulatorIpc.ts
+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts
@@ -4,6 +4,7 @@ import type {
IOSSimulatorDeviceGrant,
IOSSimulatorInstance,
IOSSimulatorMutationState,
+ IOSSimulatorNativeStreamProfile,
IOSSimulatorOrientation,
IOSSimulatorRuntimeInfo,
IOSSimulatorStreamProfile,
@@ -138,8 +139,16 @@ export interface IOSSimulatorViewerVisibilityRequest extends IOSSimulatorViewerR
fallbackReason?: 'native-decoder-fallback';
}
+export type IOSSimulatorNativeH264StreamProfileRequest = Pick<
+ IOSSimulatorNativeStreamProfile,
+ 'framesPerSecond' | 'scalingPercent'
+>;
+
export interface IOSSimulatorStreamProfileRequest extends IOSSimulatorViewerRouteRequest {
+ /** Exact compatibility profile kept ready for WDA/MJPEG fallback. */
profile: IOSSimulatorStreamProfile;
+ /** Optional product profile accepted only while Native H.264 is active. */
+ nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest;
}
export interface IOSSimulatorMutationControlRequest extends IOSSimulatorViewerRouteRequest {
diff --git a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift
index cf5f5573a6..23b1d50045 100644
--- a/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift
+++ b/packages/ios-simulator-runtime/native/ios-simulator-sidecar.swift
@@ -15,7 +15,7 @@ let maxScreenID: UInt32 = 16
let bgraPixelFormat = UInt32(kCVPixelFormatType_32BGRA)
let maxCorrectnessFramesPerSecond = 15
let maxH264CorrectnessFramesPerSecond = 30
-let maxProductH264FramesPerSecond = 30
+let maxProductH264FramesPerSecond = 60
let maxCorrectnessFrames = 900
let maxGestureSamples = 4_096
let maxGestureDurationMilliseconds = 60_000
diff --git a/packages/ios-simulator-runtime/scripts/native-h264-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-smoke.ts
index 2b08cf276a..7be6c86758 100644
--- a/packages/ios-simulator-runtime/scripts/native-h264-smoke.ts
+++ b/packages/ios-simulator-runtime/scripts/native-h264-smoke.ts
@@ -50,9 +50,14 @@ const framesPerSecond = positiveIntegerArgument("--fps", 5);
const maxFrames = positiveIntegerArgument("--frames", 30);
const scalingPercent = positiveIntegerArgument("--scaling", 50);
const productMode = hasFlag("--product");
-if (framesPerSecond > 30 || maxFrames > 900 || scalingPercent > 100) {
+const maxFramesPerSecond = productMode ? 60 : 30;
+if (
+ framesPerSecond > maxFramesPerSecond ||
+ maxFrames > 900 ||
+ scalingPercent > 100
+) {
throw new Error(
- "--fps must be <= 30, --frames must be <= 900, and --scaling must be <= 100",
+ `--fps must be <= ${maxFramesPerSecond}, --frames must be <= 900, and --scaling must be <= 100`,
);
}
diff --git a/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.ts b/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.ts
index d252406e77..312ac5c013 100644
--- a/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.ts
+++ b/packages/ios-simulator-runtime/scripts/native-h264-stability-smoke.ts
@@ -55,9 +55,9 @@ const scalingPercent = positiveIntegerEnvironment(
"CINDY_IOS_H264_STABILITY_SCALING",
50,
);
-if (durationSeconds > 60 * 60 || framesPerSecond > 30 || scalingPercent > 100) {
+if (durationSeconds > 60 * 60 || framesPerSecond > 60 || scalingPercent > 100) {
throw new Error(
- "Stability smoke is bounded to 60 minutes, 30 FPS, and 100% scaling",
+ "Stability smoke is bounded to 60 minutes, 60 FPS, and 100% scaling",
);
}
const maxFrames = durationSeconds * framesPerSecond;
diff --git a/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjs b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjs
index 12357eb1a6..41f2dc2594 100644
--- a/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjs
+++ b/packages/ios-simulator-runtime/scripts/native-h264-webcodecs-smoke.mjs
@@ -43,9 +43,9 @@ if (
const framesPerSecond = positiveIntegerArgument("--fps", 5);
const maxFrames = positiveIntegerArgument("--frames", 5);
const scalingPercent = positiveIntegerArgument("--scaling", 50);
-if (framesPerSecond > 30 || maxFrames > 30 || scalingPercent > 100) {
+if (framesPerSecond > 60 || maxFrames > 60 || scalingPercent > 100) {
throw new Error(
- "--fps and --frames must be <= 30, and --scaling must be <= 100",
+ "--fps and --frames must be <= 60, and --scaling must be <= 100",
);
}
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.ts
index ef8b2cc31e..007b0dd451 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/adapter.test.ts
@@ -104,7 +104,7 @@ describe("IOSSimulatorNativeSidecarAdapter", () => {
});
await adapter.configureNativeStream({
encoding: "h264",
- framesPerSecond: 30,
+ framesPerSecond: 60,
scalingPercent: 50,
});
await adapter.tap({ x: 10, y: 20 });
@@ -440,7 +440,7 @@ describe("IOSSimulatorNativeSidecarAdapter", () => {
await expect(
adapter.configureNativeStream({
encoding: "h264",
- framesPerSecond: 121,
+ framesPerSecond: 61,
scalingPercent: 50,
}),
).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/adapter.ts b/packages/ios-simulator-runtime/src/native-sidecar/adapter.ts
index f5b35a9883..e8d397868d 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/adapter.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/adapter.ts
@@ -18,7 +18,7 @@ import {
const MAX_TOUCH_POINTS = 4_096;
const MAX_GESTURE_DURATION_MS = 60_000;
-const MAX_STREAM_FPS = 120;
+const MAX_STREAM_FPS = 60;
const MAX_STREAM_SCALING_PERCENT = 100;
const MAX_CORRECTNESS_STREAM_FPS = 15;
const MAX_H264_CORRECTNESS_STREAM_FPS = 30;