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。

Merge remote-tracking branch 'upstream/main' into feat/issue-397-ios-simulator-native-framebuffer

JiangJiahaoebb355c2fa97
diff --cc apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx
index 06070373ac,0000000000..64736f675b
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx
@@@ -1,644 -1,0 +1,647 @@@
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type PointerEvent as ReactPointerEvent,
+} from 'react';
+import {
+ House,
+ Keyboard,
+ LockKeyhole,
+ RotateCw,
+ Send,
+ Smartphone,
+ UnlockKeyhole,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import type {
+ IOSSimulatorFramePumpSnapshot,
+ IOSSimulatorMutationState,
+ IOSSimulatorStreamProfile,
+} from '@cindy/ios-simulator-runtime';
+import type {
+ IOSSimulatorPublicInstance,
+ IOSSimulatorSessionStatus,
+ IOSSimulatorToolResponse,
+} from '../../../../../shared/iosSimulatorIpc';
+
+interface IOSSimulatorInstanceGridProps {
+ sessionId: string;
+ instances: IOSSimulatorPublicInstance[];
+ mutationStates: IOSSimulatorMutationState[];
+ selectedInstanceId: string | null;
+ active: boolean;
+ shellVisible: boolean;
+ title: string;
+ countLabel: string;
+ onSelect: (instanceId: string) => void;
+ onRefresh: () => Promise<IOSSimulatorSessionStatus | null>;
+}
+
+const BACKGROUND_PROFILE: IOSSimulatorStreamProfile = {
+ framesPerSecond: 5,
+ jpegQuality: 25,
+ scalingPercent: 50,
+};
+
+interface TileState {
+ stream: IOSSimulatorFramePumpSnapshot | null;
+ frameUrl: string | null;
+}
+
+interface TileLiveMutation {
+ routeKey: string;
+ mutation: IOSSimulatorMutationState;
+}
+
+interface TileGesture {
+ pointerId: number;
+ startedAt: number;
+ startClientX: number;
+ startClientY: number;
+ startXRatio: number;
+ startYRatio: number;
+}
+
+function routeFor(instance: IOSSimulatorPublicInstance) {
+ return {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ };
+}
+
+function routeKey(instance: IOSSimulatorPublicInstance): string {
+ return `${instance.generation}:${instance.lease.id}`;
+}
+
+function streamFrom(result: IOSSimulatorToolResponse): IOSSimulatorFramePumpSnapshot | null {
+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;
+ const stream = (result.data as { stream?: unknown }).stream;
+ return stream && typeof stream === 'object' ? (stream as IOSSimulatorFramePumpSnapshot) : null;
+}
+
+function instanceFrom(result: IOSSimulatorToolResponse): IOSSimulatorPublicInstance | null {
+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;
+ const instance = (result.data as { instance?: unknown }).instance;
+ return instance && typeof instance === 'object' ? (instance as IOSSimulatorPublicInstance) : null;
+}
+
+function mutationFrom(result: IOSSimulatorToolResponse): IOSSimulatorMutationState | null {
+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;
+ const mutation = (result.data as { mutation?: unknown }).mutation;
+ return mutation && typeof mutation === 'object' ? (mutation as IOSSimulatorMutationState) : null;
+}
+
+/** Compact multi-instance view with per-tile basic input routed by exact instance. */
+export function IOSSimulatorInstanceGrid({
+ sessionId,
+ instances,
+ mutationStates,
+ selectedInstanceId,
+ active,
+ shellVisible,
+ title,
+ countLabel,
+ onSelect,
+ onRefresh,
+}: IOSSimulatorInstanceGridProps) {
+ const { t } = useTranslation();
+ const [tiles, setTiles] = useState<Record<string, TileState>>({});
+ const [tileBusy, setTileBusy] = useState<Record<string, boolean>>({});
+ const [liveMutations, setLiveMutations] = useState<Record<string, TileLiveMutation>>({});
+ const [invalidatedRouteKeys, setInvalidatedRouteKeys] = useState<Record<string, string>>({});
+ const [tileErrors, setTileErrors] = useState<Record<string, string>>({});
+ const [tileText, setTileText] = useState<Record<string, string>>({});
+ const [tileOrientation, setTileOrientation] = useState<Record<string, 'PORTRAIT' | 'LANDSCAPE'>>(
+ {},
+ );
+ const urlsRef = useRef<Record<string, string>>({});
+ const gesturesRef = useRef<Record<string, TileGesture | null>>({});
+ const invalidatedRouteKeysRef = useRef<Record<string, string>>({});
+ const routeRefreshStateRef = useRef({ pending: false, nextAttemptAt: 0 });
+ const readyInstances = useMemo(
+ () => instances.filter((instance) => instance.lifecycleState === 'ready'),
+ [instances],
+ );
+ const viewerVisible = active && shellVisible;
+ const routeIsInvalidated = useCallback(
+ (instance: IOSSimulatorPublicInstance) =>
+ invalidatedRouteKeysRef.current[instance.instanceId] === routeKey(instance),
+ [],
+ );
+ const agentBusyInstanceIds = useMemo(() => {
+ const busyInstanceIds = new Set(
+ mutationStates
+ .filter(
+ (mutation) =>
+ mutation.activeSource === 'agent' || (mutation.queuedAgentMutations ?? 0) > 0,
+ )
+ .map((mutation) => mutation.instanceId),
+ );
+ for (const instance of readyInstances) {
+ const live = liveMutations[instance.instanceId];
+ if (!live || live.routeKey !== routeKey(instance)) continue;
+ if (live.mutation.activeSource === 'agent' || (live.mutation.queuedAgentMutations ?? 0) > 0) {
+ busyInstanceIds.add(instance.instanceId);
+ } else {
+ busyInstanceIds.delete(instance.instanceId);
+ }
+ }
+ return busyInstanceIds;
+ }, [liveMutations, mutationStates, readyInstances]);
+ const isTileBusy = useCallback(
+ (instance: IOSSimulatorPublicInstance) =>
+ instance.lifecycleState !== 'ready' ||
+ tileBusy[instance.instanceId] === true ||
+ agentBusyInstanceIds.has(instance.instanceId) ||
+ routeIsInvalidated(instance),
+ [agentBusyInstanceIds, routeIsInvalidated, tileBusy],
+ );
+
+ const callTile = useCallback(
+ async (
+ instance: IOSSimulatorPublicInstance,
+ name:
+ | 'tap'
+ | 'swipe'
+ | 'type_text'
+ | 'press_home'
+ | 'set_orientation'
+ | 'lock_screen'
+ | 'unlock_screen',
+ args: Record<string, unknown>,
+ ): Promise<boolean> => {
+ if (isTileBusy(instance)) return false;
+ setTileBusy((previous) => ({ ...previous, [instance.instanceId]: true }));
+ setTileErrors((previous) => {
+ const next = { ...previous };
+ delete next[instance.instanceId];
+ return next;
+ });
+ try {
+ const result = await window.electronAPI.maker.iosSimulator.call({
+ sessionId,
+ name,
+ args: { ...routeFor(instance), ...args },
+ });
+ if (!result.ok) {
+ setTileErrors((previous) => ({ ...previous, [instance.instanceId]: result.message }));
+ return false;
+ }
+ if (
+ name === 'set_orientation' &&
+ (args.orientation === 'PORTRAIT' || args.orientation === 'LANDSCAPE')
+ ) {
+ setTileOrientation((previous) => ({
+ ...previous,
+ [instance.instanceId]: args.orientation as 'PORTRAIT' | 'LANDSCAPE',
+ }));
+ }
+ return true;
+ } catch {
+ setTileErrors((previous) => ({
+ ...previous,
+ [instance.instanceId]: t('rightSidebar.iosSimulator.operationError'),
+ }));
+ return false;
+ } finally {
+ setTileBusy((previous) => ({ ...previous, [instance.instanceId]: false }));
+ }
+ },
+ [isTileBusy, sessionId, t],
+ );
+
+ const tilePoint = useCallback((event: ReactPointerEvent<HTMLImageElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ return {
+ xRatio: Math.min(1, Math.max(0, (event.clientX - bounds.left) / bounds.width)),
+ yRatio: Math.min(1, Math.max(0, (event.clientY - bounds.top) / bounds.height)),
+ };
+ }, []);
+
+ const onTilePointerDown = useCallback(
+ (instance: IOSSimulatorPublicInstance, event: ReactPointerEvent<HTMLImageElement>) => {
+ if (event.button !== 0 || isTileBusy(instance)) return;
+ const point = tilePoint(event);
+ gesturesRef.current[instance.instanceId] = {
+ pointerId: event.pointerId,
+ startedAt: performance.now(),
+ startClientX: event.clientX,
+ startClientY: event.clientY,
+ startXRatio: point.xRatio,
+ startYRatio: point.yRatio,
+ };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ },
+ [isTileBusy, tilePoint],
+ );
+
+ const onTilePointerUp = useCallback(
+ (instance: IOSSimulatorPublicInstance, event: ReactPointerEvent<HTMLImageElement>) => {
+ const gesture = gesturesRef.current[instance.instanceId];
+ if (!gesture || gesture.pointerId !== event.pointerId) return;
+ gesturesRef.current[instance.instanceId] = null;
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ if (isTileBusy(instance)) return;
+ const end = tilePoint(event);
+ const distance = Math.hypot(
+ event.clientX - gesture.startClientX,
+ event.clientY - gesture.startClientY,
+ );
+ if (distance < 8) {
+ void callTile(instance, 'tap', { xRatio: end.xRatio, yRatio: end.yRatio });
+ return;
+ }
+ const durationMs = Math.min(2_000, Math.max(100, performance.now() - gesture.startedAt));
+ void callTile(instance, 'swipe', {
+ startXRatio: gesture.startXRatio,
+ startYRatio: gesture.startYRatio,
+ endXRatio: end.xRatio,
+ endYRatio: end.yRatio,
+ durationMs: Math.round(durationMs),
+ });
+ },
+ [callTile, isTileBusy, tilePoint],
+ );
+
+ const sendTileText = useCallback(
+ async (instance: IOSSimulatorPublicInstance) => {
+ const text = tileText[instance.instanceId] ?? '';
+ if (!text) return;
+ if (await callTile(instance, 'type_text', { text })) {
+ setTileText((previous) => ({ ...previous, [instance.instanceId]: '' }));
+ }
+ },
+ [callTile, tileText],
+ );
+
+ useEffect(() => {
+ const currentIds = new Set(readyInstances.map((instance) => instance.instanceId));
+ const currentRoutes = new Map(
+ readyInstances.map((instance) => [instance.instanceId, routeKey(instance)]),
+ );
+ for (const [instanceId, url] of Object.entries(urlsRef.current)) {
+ if (!currentIds.has(instanceId)) {
+ URL.revokeObjectURL(url);
+ delete urlsRef.current[instanceId];
+ }
+ }
+ setTiles((previous) =>
+ Object.fromEntries(
+ Object.entries(previous).filter(([instanceId]) => currentIds.has(instanceId)),
+ ),
+ );
+ setLiveMutations((previous) =>
+ Object.fromEntries(
+ Object.entries(previous).filter(
+ ([instanceId, live]) => currentRoutes.get(instanceId) === live.routeKey,
+ ),
+ ),
+ );
+ const retainedInvalidatedRoutes = Object.fromEntries(
+ Object.entries(invalidatedRouteKeysRef.current).filter(
+ ([instanceId, invalidatedRoute]) => currentRoutes.get(instanceId) === invalidatedRoute,
+ ),
+ );
+ invalidatedRouteKeysRef.current = retainedInvalidatedRoutes;
+ setInvalidatedRouteKeys(retainedInvalidatedRoutes);
+ if (Object.keys(retainedInvalidatedRoutes).length === 0) {
+ routeRefreshStateRef.current.nextAttemptAt = 0;
+ }
+ }, [readyInstances]);
+
+ useEffect(() => {
+ let cancelled = false;
+ let polling = false;
++ // Keep the preload bridge used by this effect stable through cleanup. The
++ // global bridge can disappear while renderer teardown is still draining
++ // the asynchronous visibility update.
++ const simulatorApi = window.electronAPI.maker.iosSimulator;
+ const requestRouteRefresh = () => {
+ const refreshState = routeRefreshStateRef.current;
+ if (
+ cancelled ||
+ refreshState.pending ||
+ Object.keys(invalidatedRouteKeysRef.current).length === 0 ||
+ Date.now() < refreshState.nextAttemptAt
+ ) {
+ return;
+ }
+ refreshState.pending = true;
+ refreshState.nextAttemptAt = Number.POSITIVE_INFINITY;
+ void Promise.resolve()
+ .then(onRefresh)
+ .catch(() => undefined)
+ .finally(() => {
+ // A returned status may lose a concurrent request-version race in
+ // the parent. Only changed props clear invalidation; until then keep
+ // retrying at a bounded cadence.
+ refreshState.nextAttemptAt =
+ Object.keys(invalidatedRouteKeysRef.current).length > 0 ? Date.now() + 500 : 0;
+ refreshState.pending = false;
+ });
+ };
+ const invalidateRoute = (instance: IOSSimulatorPublicInstance) => {
+ const instanceId = instance.instanceId;
+ if (cancelled || routeIsInvalidated(instance)) return;
+ const hadInvalidatedRoute = Object.keys(invalidatedRouteKeysRef.current).length > 0;
+ invalidatedRouteKeysRef.current = {
+ ...invalidatedRouteKeysRef.current,
+ [instanceId]: routeKey(instance),
+ };
+ if (!hadInvalidatedRoute) routeRefreshStateRef.current.nextAttemptAt = 0;
+ gesturesRef.current[instanceId] = null;
+ setLiveMutations((previous) => {
+ if (!(instanceId in previous)) return previous;
+ const next = { ...previous };
+ delete next[instanceId];
+ return next;
+ });
+ setInvalidatedRouteKeys((previous) => ({
+ ...previous,
+ [instanceId]: routeKey(instance),
+ }));
+ const previousUrl = urlsRef.current[instanceId];
+ if (previousUrl) {
+ URL.revokeObjectURL(previousUrl);
+ delete urlsRef.current[instanceId];
+ }
+ setTiles((previous) => ({
+ ...previous,
+ [instanceId]: { stream: null, frameUrl: null },
+ }));
+ requestRouteRefresh();
+ };
+ const accept = (instance: IOSSimulatorPublicInstance, result: IOSSimulatorToolResponse) => {
+ if (cancelled || routeIsInvalidated(instance)) return;
+ if (!result.ok) {
+ if (result.errorCode === 'LEASE_EXPIRED' || result.errorCode === 'STALE_GENERATION') {
+ invalidateRoute(instance);
+ }
+ return;
+ }
+ const mutation = mutationFrom(result);
+ if (mutation?.instanceId === instance.instanceId) {
+ setLiveMutations((previous) => ({
+ ...previous,
+ [instance.instanceId]: { routeKey: routeKey(instance), mutation },
+ }));
+ }
+ // Host returns an instance only when reconcile or heartbeat advanced the
+ // authoritative route. Stop using the captured generation/lease before
+ // another poll or tile control can race the parent refresh.
+ if (instanceFrom(result)) {
+ invalidateRoute(instance);
+ return;
+ }
+ const stream = streamFrom(result);
+ const frame = stream?.latestFrame;
+ if (!frame) {
+ setTiles((previous) => ({
+ ...previous,
+ [instance.instanceId]: { ...previous[instance.instanceId], stream },
+ }));
+ return;
+ }
+ if (frame.encoding !== 'jpeg') return;
+ const bytes = frame.bytes instanceof Uint8Array ? frame.bytes : new Uint8Array(frame.bytes);
+ const url = URL.createObjectURL(
+ new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'image/jpeg' }),
+ );
+ const image = new Image();
+ image.onload = () => {
+ if (cancelled || routeIsInvalidated(instance)) {
+ URL.revokeObjectURL(url);
+ return;
+ }
+ const previous = urlsRef.current[instance.instanceId];
+ if (previous) URL.revokeObjectURL(previous);
+ urlsRef.current[instance.instanceId] = url;
+ setTiles((current) => ({
+ ...current,
+ [instance.instanceId]: { stream, frameUrl: url },
+ }));
+ };
+ image.onerror = () => URL.revokeObjectURL(url);
+ image.src = url;
+ };
+ const setVisibility = async (visible: boolean) => {
+ await Promise.all(
+ readyInstances.map(async (instance) => {
+ const route = {
+ sessionId,
+ ...routeFor(instance),
+ visible,
+ preferredEncoding: 'jpeg' as const,
+ };
- const result = await window.electronAPI.maker.iosSimulator
- .setViewerVisibility(route)
- .catch(() => null);
++ const result = await simulatorApi.setViewerVisibility(route).catch(() => null);
++ if (cancelled) return;
+ if (visible && result) accept(instance, result);
+ if (
+ visible &&
+ !routeIsInvalidated(instance) &&
+ instance.instanceId !== selectedInstanceId
+ ) {
- await window.electronAPI.maker.iosSimulator
++ await simulatorApi
+ .setStreamProfile({ sessionId, ...routeFor(instance), profile: BACKGROUND_PROFILE })
+ .catch(() => undefined);
+ }
+ }),
+ );
+ };
+ const poll = async () => {
+ if (!viewerVisible || polling || cancelled) return;
+ polling = true;
+ try {
+ requestRouteRefresh();
+ await Promise.all(
+ readyInstances.map(async (instance) => {
+ if (routeIsInvalidated(instance)) return;
- const result = await window.electronAPI.maker.iosSimulator.latestFrame({
++ const result = await simulatorApi.latestFrame({
+ sessionId,
+ ...routeFor(instance),
+ });
+ accept(instance, result);
+ }),
+ );
+ } finally {
+ polling = false;
+ }
+ };
+ void setVisibility(viewerVisible);
+ void poll();
+ const timer = viewerVisible ? window.setInterval(() => void poll(), 500) : null;
+ return () => {
+ cancelled = true;
+ if (timer !== null) window.clearInterval(timer);
+ void setVisibility(false);
+ for (const url of Object.values(urlsRef.current)) URL.revokeObjectURL(url);
+ urlsRef.current = {};
+ };
+ }, [onRefresh, readyInstances, routeIsInvalidated, selectedInstanceId, sessionId, viewerVisible]);
+
+ if (readyInstances.length < 2) return null;
+
+ return (
+ <section
+ aria-label={title}
+ className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3"
+ >
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <h3 className="text-12 font-medium">{title}</h3>
+ <span className="text-10 text-[var(--text-secondary)]">{countLabel}</span>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ {readyInstances.map((instance) => {
+ const tile = tiles[instance.instanceId];
+ const selected = instance.instanceId === selectedInstanceId;
+ const agentBusy = agentBusyInstanceIds.has(instance.instanceId);
+ const routeInvalidated = invalidatedRouteKeys[instance.instanceId] === routeKey(instance);
+ const busy = isTileBusy(instance);
+ const error = tileErrors[instance.instanceId];
+ return (
+ <article
+ key={instance.instanceId}
+ className={`overflow-hidden rounded-xl border text-left ${selected ? 'border-[var(--focus-ring)]' : 'border-[var(--border-default)]'}`}
+ >
+ <button
+ type="button"
+ aria-pressed={selected}
+ onClick={() => onSelect(instance.instanceId)}
+ className="block w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"
+ >
+ <div className="relative flex aspect-[9/16] items-center justify-center bg-[var(--surface)]">
+ {tile?.frameUrl ? (
+ <img
+ src={tile.frameUrl}
+ alt={instance.simulatorName}
+ className={`max-h-full max-w-full touch-none select-none object-contain ${busy ? 'cursor-wait opacity-70' : 'cursor-crosshair'}`}
+ draggable={false}
+ onPointerDown={(event) => onTilePointerDown(instance, event)}
+ onPointerUp={(event) => onTilePointerUp(instance, event)}
+ onPointerCancel={() => {
+ gesturesRef.current[instance.instanceId] = null;
+ }}
+ />
+ ) : (
+ <Smartphone
+ size={20}
+ className="text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ )}
+ <span className="absolute inset-x-1 bottom-1 truncate rounded-lg bg-[var(--surface-chip)] px-1.5 py-1 text-10 text-[var(--text-primary)]">
+ {instance.simulatorName}
+ </span>
+ </div>
+ </button>
+ <div className="flex flex-wrap items-center gap-1.5 border-t border-[var(--border-default)] bg-[var(--surface-elevated)] p-2">
+ <div className="relative min-w-0 flex-1">
+ <Keyboard
+ size={12}
+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ <input
+ value={tileText[instance.instanceId] ?? ''}
+ onChange={(event) =>
+ setTileText((previous) => ({
+ ...previous,
+ [instance.instanceId]: event.target.value,
+ }))
+ }
+ onKeyDown={(event) => {
+ if (
+ event.key === 'Enter' &&
+ !event.nativeEvent.isComposing &&
+ !event.shiftKey
+ ) {
+ event.preventDefault();
+ void sendTileText(instance);
+ }
+ }}
+ disabled={busy}
+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.textInputLabel')}`}
+ placeholder={t('rightSidebar.iosSimulator.textInputPlaceholder')}
+ className="h-7 w-full rounded-full border border-[var(--border-default)] bg-[var(--surface)] pl-7 pr-2 text-10 text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
+ />
+ </div>
+ <button
+ type="button"
+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.sendText')}`}
+ disabled={busy || !(tileText[instance.instanceId] ?? '')}
+ onClick={() => void sendTileText(instance)}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
+ >
+ <Send size={12} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.pressHome')}`}
+ disabled={busy}
+ onClick={() => void callTile(instance, 'press_home', {})}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
+ >
+ <House size={12} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.rotateDevice')}`}
+ disabled={busy}
+ onClick={() =>
+ void callTile(instance, 'set_orientation', {
+ orientation:
+ tileOrientation[instance.instanceId] === 'LANDSCAPE'
+ ? 'PORTRAIT'
+ : 'LANDSCAPE',
+ })
+ }
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
+ >
+ <RotateCw size={12} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.lockScreen')}`}
+ disabled={busy}
+ onClick={() => void callTile(instance, 'lock_screen', {})}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
+ >
+ <LockKeyhole size={12} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ aria-label={`${instance.simulatorName} ${t('rightSidebar.iosSimulator.unlockScreen')}`}
+ disabled={busy}
+ onClick={() => void callTile(instance, 'unlock_screen', {})}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
+ >
+ <UnlockKeyhole size={12} aria-hidden="true" />
+ </button>
+ </div>
+ {agentBusy && (
+ <div className="border-t border-[var(--border-default)] px-2 py-1 text-10 text-[var(--warning-accent)]">
+ {t('rightSidebar.iosSimulator.agentBusyTitle')}
+ </div>
+ )}
+ {error && (
+ <div
+ role="alert"
+ className="border-t border-[var(--border-default)] px-2 py-1 text-10 text-[var(--text-secondary)]"
+ >
+ {error}
+ </div>
+ )}
+ </article>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
diff --cc apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
index 82cb2cc3cf,0000000000..31650b902b
mode 100644,000000..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
@@@ -1,2603 -1,0 +1,2651 @@@
+// @vitest-environment jsdom
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { IOSSimulatorMutationState } from '@cindy/ios-simulator-runtime';
+import type {
+ IOSSimulatorAccessRequest,
+ IOSSimulatorAccessRequestResult,
+ IOSSimulatorFocusRequest,
+ IOSSimulatorH264FramePush,
+ IOSSimulatorLiveTouchRequest,
+ IOSSimulatorPublicInstance,
+ IOSSimulatorRouteStatusPush,
+ IOSSimulatorSessionStatus,
+ IOSSimulatorToolResponse,
+ IOSSimulatorViewerVisibilityRequest,
+} from '../../../../../../shared/iosSimulatorIpc';
+import type { TabKindHostContext } from '../../../types';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { IOSSimulatorTabBody, setupStepKeys } from '../IOSSimulatorTabBody';
+
+const ctx: TabKindHostContext = {
+ tabId: 'tab-a',
+ sessionId: 'session-a',
+ workdir: '/tmp/project',
+ remoteHostId: null,
+ patchState: vi.fn(),
+ onVisibilityChange: vi.fn(),
+ setCloseInterceptor: () => () => undefined,
+};
+
+function streamingJpegResult(generation = 2, sequence = 1): IOSSimulatorToolResponse {
+ return {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-a',
+ generation,
+ state: 'streaming',
+ reconnectAttempt: 0,
+ latestFrame: {
+ instanceId: 'instance-a',
+ generation,
+ sequence,
+ encoding: 'jpeg',
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ bytes: new Uint8Array([1, 2, 3]),
+ },
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+}
+
+function readyInstance(generation = 2): IOSSimulatorPublicInstance {
+ return {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: `lease-${generation}`,
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ };
+}
+
+function readyStatus(instance = readyInstance()): IOSSimulatorSessionStatus {
+ return {
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [instance],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ };
+}
+
+function multiReadyStatus(
+ mutationStates: IOSSimulatorMutationState[] = [],
+): IOSSimulatorSessionStatus {
+ const instanceA: IOSSimulatorPublicInstance = {
+ ...readyInstance(1),
+ simulatorName: 'iPhone A',
+ lease: { ...readyInstance(1).lease, id: 'lease-a' },
+ };
+ const instanceB: IOSSimulatorPublicInstance = {
+ ...readyInstance(2),
+ instanceId: 'instance-b',
+ simulatorUdid: 'DEVICE-B',
+ simulatorName: 'iPhone B',
+ lease: { ...readyInstance(2).lease, id: 'lease-b' },
+ };
+ const status = readyStatus(instanceA);
+ if (!status.ok) throw new Error('Expected a ready status fixture.');
+ return { ...status, mutationStates, instances: [instanceA, instanceB] };
+}
+
+function installGridFrames(
+ api: ReturnType<typeof installStatus>,
+ mutationForInstance: (instanceId: string) => IOSSimulatorMutationState | null = () => null,
+): void {
+ api.latestFrame.mockImplementation(async (request?: unknown) => {
+ const route = request as { instanceId: string; generation: number };
+ const mutation = mutationForInstance(route.instanceId);
+ return {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: route.instanceId,
+ generation: route.generation,
+ state: 'streaming',
+ reconnectAttempt: 0,
+ latestFrame: {
+ instanceId: route.instanceId,
+ generation: route.generation,
+ sequence: 1,
+ encoding: 'jpeg',
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ bytes: new Uint8Array([1, 2, 3]),
+ },
+ },
+ ...(mutation ? { mutation } : {}),
+ },
+ };
+ });
+}
+
+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);
+ const requestAccess = vi.fn(
+ async (_request: IOSSimulatorAccessRequest): Promise<IOSSimulatorAccessRequestResult> => ({
+ granted: true,
+ }),
+ );
+ const call = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
+ ok: true as const,
+ data: {},
+ }));
+ const setAgentControl = vi.fn(async () => ({ ok: true as const, data: {} }));
+ 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;
+ let focusRequestListener: ((payload: IOSSimulatorFocusRequest) => void) | null = null;
+ const onH264Frame = vi.fn((callback: (payload: IOSSimulatorH264FramePush) => void) => {
+ h264FrameListener = callback;
+ return () => {
+ if (h264FrameListener === callback) h264FrameListener = null;
+ };
+ });
+ const onRouteStatus = vi.fn((callback: (payload: IOSSimulatorRouteStatusPush) => void) => {
+ routeStatusListener = callback;
+ return () => {
+ if (routeStatusListener === callback) routeStatusListener = null;
+ };
+ });
+ const onFocusRequest = vi.fn((callback: (payload: IOSSimulatorFocusRequest) => void) => {
+ focusRequestListener = callback;
+ return () => {
+ if (focusRequestListener === callback) focusRequestListener = null;
+ };
+ });
+ const liveTouch = vi.fn(
+ async (request: IOSSimulatorLiveTouchRequest): Promise<IOSSimulatorToolResponse> => {
+ void request;
+ return {
+ ok: true as const,
+ data: {},
+ };
+ },
+ );
+ const latestFrame = vi.fn(async (_request?: unknown): Promise<IOSSimulatorToolResponse> => ({
+ ok: true,
+ data: { stream: null },
+ }));
+ (
+ window as unknown as {
+ electronAPI: {
+ maker: {
+ iosSimulator: {
+ requestAccess: typeof requestAccess;
+ status: typeof status;
+ call: typeof call;
+ setAgentControl: typeof setAgentControl;
+ setViewerVisibility: typeof setViewerVisibility;
+ latestFrame: typeof latestFrame;
+ setStreamProfile: typeof setStreamProfile;
+ liveTouch: typeof liveTouch;
+ onH264Frame: typeof onH264Frame;
+ onRouteStatus: typeof onRouteStatus;
+ onFocusRequest: typeof onFocusRequest;
+ };
+ };
+ };
+ }
+ ).electronAPI = {
+ maker: {
+ iosSimulator: {
+ requestAccess,
+ status,
+ call,
+ setAgentControl,
+ setViewerVisibility,
+ latestFrame,
+ setStreamProfile,
+ liveTouch,
+ onH264Frame,
+ onRouteStatus,
+ onFocusRequest,
+ },
+ },
+ };
+ return {
+ requestAccess,
+ status,
+ call,
+ setAgentControl,
+ setViewerVisibility,
+ latestFrame,
+ setStreamProfile,
+ liveTouch,
+ onH264Frame,
+ onRouteStatus,
+ onFocusRequest,
+ setStatusValue(value: IOSSimulatorSessionStatus) {
+ currentStatusValue = value;
+ },
+ emitH264Frame(payload: IOSSimulatorH264FramePush) {
+ h264FrameListener?.(payload);
+ },
+ emitRouteStatus(payload: IOSSimulatorRouteStatusPush) {
+ routeStatusListener?.(payload);
+ },
+ emitFocusRequest(payload: IOSSimulatorFocusRequest) {
+ focusRequestListener?.(payload);
+ },
+ };
+}
+
+beforeEach(() => {
+ let objectUrlSequence = 0;
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ writable: true,
+ value: vi.fn(() => `blob:ios-simulator-${++objectUrlSequence}`),
+ });
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ configurable: true,
+ writable: true,
+ value: vi.fn(),
+ });
+ vi.stubGlobal(
+ 'Image',
+ class TestImage {
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+
+ set src(_value: string) {
+ queueMicrotask(() => this.onload?.());
+ }
+ },
+ );
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(
+ () => ({ clearRect: vi.fn(), drawImage: vi.fn() }) as never,
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ delete (globalThis as { VideoDecoder?: unknown }).VideoDecoder;
+ delete (globalThis as { EncodedVideoChunk?: unknown }).EncodedVideoChunk;
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ vi.unstubAllGlobals();
+});
+
+describe('IOSSimulatorTabBody', () => {
+ it('requires a user gesture before requesting native access for a restored panel', async () => {
+ const api = installStatus(readyStatus());
+ api.status.mockRejectedValueOnce(
+ new Error(
+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',
+ ),
+ );
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeTruthy();
+ });
+ expect(api.requestAccess).not.toHaveBeenCalled();
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.allowTaskAccess' }),
+ );
+
+ await waitFor(() => {
+ expect(api.requestAccess).toHaveBeenCalledWith({ sessionId: 'session-a' });
+ expect(api.status).toHaveBeenCalledTimes(2);
+ });
+ expect(screen.queryByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeNull();
+ });
+
+ it('animates the access loader on an HTML wrapper instead of the SVG', async () => {
+ const api = installStatus(readyStatus());
+ api.status.mockRejectedValueOnce(
+ new Error(
+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',
+ ),
+ );
+ api.requestAccess.mockImplementationOnce(
+ () => new Promise<IOSSimulatorAccessRequestResult>(() => undefined),
+ );
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'rightSidebar.iosSimulator.allowTaskAccess',
+ }),
+ );
+
+ const button = await screen.findByRole('button', {
+ name: 'rightSidebar.iosSimulator.requestingAccess',
+ });
+ const wrapper = button.querySelector('span.animate-spin');
+ const icon = wrapper?.querySelector('svg');
+ expect(wrapper).toBeTruthy();
+ expect(wrapper?.classList.contains('motion-reduce:animate-none')).toBe(true);
+ expect(icon).toBeTruthy();
+ expect(icon?.classList.contains('animate-spin')).toBe(false);
+ });
+
+ it('keeps the access action visible when native confirmation is cancelled', async () => {
+ const api = installStatus(readyStatus());
+ api.status.mockRejectedValueOnce(
+ new Error(
+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',
+ ),
+ );
+ api.requestAccess.mockResolvedValueOnce({ granted: false });
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+
+ const button = await screen.findByRole('button', {
+ name: 'rightSidebar.iosSimulator.allowTaskAccess',
+ });
+ fireEvent.click(button);
+
+ await waitFor(() => expect(api.requestAccess).toHaveBeenCalledOnce());
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.allowTaskAccess' }),
+ ).toBeTruthy();
+ expect(api.status).toHaveBeenCalledOnce();
+ });
+
+ it('refreshes a restored access-required tab after an authoritative Host focus grant', async () => {
+ const api = installStatus(readyStatus());
+ api.status.mockRejectedValueOnce(
+ new Error(
+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',
+ ),
+ );
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+
+ await screen.findByText('rightSidebar.iosSimulator.accessRequiredTitle');
+ act(() => {
+ api.emitFocusRequest({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ userInitiated: false,
+ });
+ });
+
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(2));
+ expect(screen.queryByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeNull();
+ expect(screen.getByText('iPhone 17 Pro')).toBeTruthy();
+ });
+
+ it('renders exact device identity from the main-owned status report', async () => {
+ const api = installStatus({
+ ok: true,
+ sessionId: 'session-a',
+ instances: [],
+ deviceGrants: [],
+ mutationStates: [],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [
+ {
+ udid: 'DEVICE-UDID-123',
+ name: 'iPhone 17 Pro',
+ state: 'Booted',
+ isAvailable: true,
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
+ runtimeName: 'iOS 26.4',
+ runtimeVersion: '26.4',
+ deviceTypeIdentifier: null,
+ lastBootedAt: null,
+ },
+ ],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+
+ await waitFor(() => expect(screen.getByText('iPhone 17 Pro')).toBeTruthy());
+ expect(screen.getByText(/iOS 26\.4 · Booted/)).toBeTruthy();
+ expect(screen.getByText('DEVICE-UDID-123')).toBeTruthy();
+ expect(api.status).toHaveBeenCalledWith({ sessionId: 'session-a' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.attachDevice' }));
+ await waitFor(() => {
+ expect(api.call).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ name: 'attach_device',
+ args: { udid: 'DEVICE-UDID-123' },
+ });
+ });
+ });
+
+ it('explains task ownership and folds unavailable devices with a safe reason', async () => {
+ installStatus({
+ ok: true,
+ sessionId: 'session-a',
+ instances: [],
+ deviceGrants: [],
+ mutationStates: [],
+ resource: {
+ runningCount: 2,
+ softLimit: 2,
+ hardLimit: 4,
+ maxInstancesPerTask: 4,
+ },
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [
+ {
+ udid: 'DEVICE-UDID-123',
+ name: 'iPhone 17 Pro',
+ state: 'Booted',
+ isAvailable: true,
+ ownership: 'other-task',
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
+ runtimeName: 'iOS 26.4',
+ runtimeVersion: '26.4',
+ deviceTypeIdentifier: null,
+ lastBootedAt: null,
+ },
+ {
+ udid: 'UNAVAILABLE-DEVICE-UDID',
+ name: 'iPhone 16',
+ state: 'Shutdown',
+ isAvailable: false,
+ ownership: 'unowned',
+ unavailableReason: { code: 'missing-runtime', runtimeName: 'iOS 18.4' },
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-18-4',
+ runtimeName: 'iOS 18-4',
+ runtimeVersion: null,
+ deviceTypeIdentifier: null,
+ lastBootedAt: null,
+ },
+ ],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+
+ await waitFor(() => expect(screen.getByText('iPhone 17 Pro')).toBeTruthy());
+ expect(screen.getByText('rightSidebar.iosSimulator.deviceInUseByOtherTask')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.resourceSoftLimitTitle')).toBeTruthy();
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.attachDevice',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(screen.queryByText('iPhone 16')).toBeNull();
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: /rightSidebar\.iosSimulator\.unavailableDevicesTitle/,
+ }),
+ );
+
+ expect(screen.getByText('iPhone 16')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.missingRuntime')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.missingRuntimeHelp')).toBeTruthy();
+ });
+
+ it('maps an ownership race to an actionable localized error', async () => {
+ const statusValue = readyStatus();
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ statusValue.instances = [];
+ statusValue.environment.devices = [
+ {
+ udid: 'DEVICE-UDID-123',
+ name: 'iPhone 17 Pro',
+ state: 'Shutdown',
+ isAvailable: true,
+ ownership: 'unowned',
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
+ runtimeName: 'iOS 26.4',
+ runtimeVersion: '26.4',
+ deviceTypeIdentifier: null,
+ lastBootedAt: null,
+ },
+ ];
+ const api = installStatus(statusValue);
+ api.call.mockResolvedValueOnce({
+ ok: false,
+ errorCode: 'SIMULATOR_ATTACHED_ELSEWHERE',
+ message: 'The simulator is attached to another Cindy session.',
+ });
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+ await waitFor(() => expect(screen.getByText('iPhone 17 Pro')).toBeTruthy());
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.attachDevice' }));
+
+ await waitFor(() => {
+ expect(screen.getByRole('alert').textContent).toBe(
+ 'rightSidebar.iosSimulator.errors.attachedElsewhere',
+ );
+ });
+ expect(screen.queryByText(/The simulator is attached/)).toBeNull();
+ });
+
+ it('shows a localized unsupported state for remote sessions', async () => {
+ installStatus({
+ ok: false,
+ sessionId: 'session-a',
+ errorCode: 'UNSUPPORTED_SESSION_KIND',
+ message: 'Remote sessions cannot access local simulators.',
+ });
+
+ render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: null }}
+ ctx={{ ...ctx, remoteHostId: 'remote-a' }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.remoteUnsupported')).toBeTruthy();
+ });
+ });
+
+ it('shows H.264 and input routes independently and applies host route updates', async () => {
+ const instance = readyInstance();
+ const statusValue = readyStatus(instance);
+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');
+ const initialRouteStatus: IOSSimulatorRouteStatusPush = {
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ updatedAt: '2026-08-05T00: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 = [initialRouteStatus];
+ const api = installStatus(statusValue);
+
+ render(<IOSSimulatorTabBody state={{ instanceId: instance.instanceId }} ctx={ctx} />);
+
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.nativeH264')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaInput')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.route.state.active')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.route.state.fallback')).toBeTruthy();
+ });
+ expect(api.onRouteStatus).toHaveBeenCalledOnce();
+
+ act(() => {
+ api.emitRouteStatus({
+ ...initialRouteStatus,
+ updatedAt: '2026-08-05T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-decoder-fallback',
+ },
+ input: {
+ adapter: 'native-sidecar',
+ state: 'active',
+ continuous: true,
+ multiTouch: false,
+ reasonCode: 'native-active',
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.route.nativeHid')).toBeTruthy();
+ expect(
+ screen.getByText('rightSidebar.iosSimulator.route.multiTouchUnavailable'),
+ ).toBeTruthy();
+ });
+
+ api.setStatusValue({
+ ...statusValue,
+ routeStatuses: [
+ {
+ ...initialRouteStatus,
+ updatedAt: '2026-08-05T00:00:00.500Z',
+ },
+ ],
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.refresh' }));
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(2));
+ expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();
+ 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,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [
+ {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation: 2,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: 'lease-a',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ },
+ ],
+ 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(
+ expect.objectContaining({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-a',
+ visible: false,
+ preferredEncoding: 'jpeg',
+ viewerToken: expect.any(String),
+ }),
+ );
+ 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('recovers Native in the background while keeping a healthy WDA frame visible', async () => {
+ installFakeH264DecoderRuntime();
+ 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({
+ ok: true,
+ data: {
+ stream: {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ state: 'connecting',
+ reconnectAttempt: 0,
+ latestFrame: null,
+ },
+ },
+ });
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+ const rendered = render(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ api.setViewerVisibility.mockClear();
+ act(() =>
+ api.emitRouteStatus({
+ ...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',
+ },
+ }),
+ );
+
+ await waitFor(() =>
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
+ ),
+ );
+ expect(rendered.container.querySelector('img')).toBeTruthy();
+ });
+
+ 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.instanceId }}
+ ctx={ctx}
+ active={false}
+ shellVisible
+ />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: false }),
+ );
+ });
+ api.setViewerVisibility.mockClear();
+
+ rendered.rerender(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
+ );
+ });
+
+ rendered.rerender(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active={false}
+ shellVisible
+ />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: false }),
+ );
+ });
+ api.setViewerVisibility.mockClear();
+ rendered.rerender(
+ <IOSSimulatorTabBody
+ state={{ instanceId: instance.instanceId }}
+ ctx={ctx}
+ active
+ shellVisible
+ />,
+ );
+ await waitFor(() => {
+ 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();
+ });
+ });
+
+ it('streams pointer samples through native touch and temporarily boosts frame rate', async () => {
+ const api = installStatus({
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [
+ {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation: 2,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: 'lease-a',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ },
+ ],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+ 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 = 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: 7, button: 0, clientX: 20, clientY: 40 });
+ fireEvent.pointerMove(image, { pointerId: 7, buttons: 1, clientX: 100, clientY: 200 });
+ fireEvent.pointerUp(image, { pointerId: 7, clientX: 180, clientY: 360 });
+
+ await waitFor(() => {
+ expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual([
+ 'begin',
+ 'move',
+ 'end',
+ ]);
+ });
+ expect(api.liveTouch.mock.calls[0]?.[0]).toMatchObject({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-a',
+ phase: 'begin',
+ xRatio: 0.1,
+ yRatio: 0.1,
+ });
+ expect(api.liveTouch.mock.calls[2]?.[0]).toMatchObject({
+ phase: 'end',
+ xRatio: 0.9,
+ yRatio: 0.9,
+ });
+ expect(api.setStreamProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ }),
+ );
+ await waitFor(
+ () => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ }),
+ );
+ },
+ { timeout: 1_000 },
+ );
+ expect(api.call).not.toHaveBeenCalledWith(
+ expect.objectContaining({ name: expect.stringMatching(/^(tap|swipe)$/) }),
+ );
+ });
+
+ 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));
+ api.latestFrame.mockResolvedValue(streamingJpegResult(1));
+
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ instanceId: 'instance-a', generation: 2, visible: true }),
+ );
+ });
+ expect(rendered.container.querySelector('img')).toBeNull();
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ });
+
+ it('disables simulator input when the presented frame stops refreshing', async () => {
+ const api = installStatus(readyStatus());
+ let resolveViewer!: (result: IOSSimulatorToolResponse) => void;
+ api.setViewerVisibility.mockImplementationOnce(
+ () =>
+ new Promise<IOSSimulatorToolResponse>((resolve) => {
+ resolveViewer = resolve;
+ }),
+ );
+ api.latestFrame.mockImplementation(() => new Promise<IOSSimulatorToolResponse>(() => {}));
+ let expireFreshness: (() => void) | null = null;
+ const originalSetTimeout = window.setTimeout.bind(window);
+ vi.spyOn(window, 'setTimeout').mockImplementation(((
+ handler: TimerHandler,
+ timeout?: number,
+ ...args: unknown[]
+ ) => {
+ if (timeout === 3_000 && typeof handler === 'function') {
+ expireFreshness = () => handler(...args);
+ return 30_001;
+ }
+ return originalSetTimeout(handler, timeout, ...args);
+ }) as typeof window.setTimeout);
+
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => expect(api.setViewerVisibility).toHaveBeenCalledTimes(1));
+ act(() => resolveViewer(streamingJpegResult()));
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const homeButton = screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement;
+ expect(homeButton.disabled).toBe(false);
+
+ act(() => expireFreshness?.());
+
+ expect(homeButton.disabled).toBe(true);
+ });
+
+ it('clears the last frame and keeps only recovery actions after an external shutdown', async () => {
+ const readyInstance = {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local' as const,
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external' as const,
+ bootProvenance: 'preexisting' as const,
+ generation: 2,
+ lifecycleState: 'ready' as const,
+ viewerState: 'attached' as const,
+ healthState: 'healthy' as const,
+ lease: {
+ id: 'lease-a',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ };
+ const stoppedInstance = {
+ ...readyInstance,
+ generation: 3,
+ lifecycleState: 'stopped' as const,
+ stoppedAt: '2026-08-04T09:00:00.000Z',
+ lease: {
+ id: 'lease-b',
+ issuedAt: '2026-08-04T09:00:00.000Z',
+ expiresAt: '2026-08-04T09:10:00.000Z',
+ },
+ };
+ const environment = {
+ platform: 'darwin' as const,
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ };
+ const readyStatus: IOSSimulatorSessionStatus = {
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [readyInstance],
+ environment,
+ };
+ const stoppedStatus: IOSSimulatorSessionStatus = {
+ ...readyStatus,
+ instances: [stoppedInstance],
+ };
+ const api = installStatus(readyStatus);
+ api.status.mockResolvedValueOnce(readyStatus).mockResolvedValue(stoppedStatus);
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ let resolveLatestFrame: ((result: IOSSimulatorToolResponse) => void) | null = null;
+ api.latestFrame.mockImplementationOnce(
+ () =>
+ new Promise<IOSSimulatorToolResponse>((resolve) => {
+ resolveLatestFrame = resolve;
+ }),
+ );
+
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ act(() => {
+ resolveLatestFrame?.({
+ ok: true,
+ data: {
+ instance: stoppedInstance,
+ stream: null,
+ viewport: null,
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(rendered.container.querySelector('img')).toBeNull();
+ expect(screen.getByText('rightSidebar.iosSimulator.viewerStoppedTitle')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.viewerStoppedDescription')).toBeTruthy();
+ });
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:ios-simulator-1');
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.startDevice' }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.detachDevice' }),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'rightSidebar.iosSimulator.pressHome' }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'rightSidebar.iosSimulator.stopDevice' }),
+ ).toBeNull();
+ expect(screen.queryByText('rightSidebar.iosSimulator.agentControlTitle')).toBeNull();
+ });
+
+ it('maps host error codes to stable localized setup steps', () => {
+ expect(setupStepKeys('XCODE_NOT_FOUND')).toEqual([
+ 'rightSidebar.iosSimulator.setup.installXcode',
+ 'rightSidebar.iosSimulator.setup.selectXcode',
+ ]);
+ });
+
+ it('requests H.264 when WebCodecs is available and presents the first decoded canvas frame', async () => {
+ const drawImage = vi.fn();
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(
+ () => ({ clearRect: vi.fn(), drawImage }) as never,
+ );
+ class FakeVideoDecoder {
+ static async isConfigSupported() {
+ return { supported: true };
+ }
+ constructor(
+ private readonly callbacks: {
+ output(frame: { close(): void }): void;
+ error(error: DOMException): void;
+ },
+ ) {}
+ configure() {}
+ decode() {
+ this.callbacks.output({ close: vi.fn() });
+ }
+ 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({
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [
+ {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation: 2,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: 'lease-a',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ },
+ ],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+ const connectingH264: IOSSimulatorToolResponse = {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-a',
+ generation: 2,
+ state: 'connecting',
+ reconnectAttempt: 0,
+ latestFrame: null,
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+ api.setViewerVisibility.mockResolvedValue(connectingH264);
+ api.latestFrame.mockResolvedValue(connectingH264);
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ visible: true, preferredEncoding: 'h264' }),
+ );
+ });
+ act(() => {
+ api.emitH264Frame({
+ frame: {
+ instanceId: 'instance-a',
+ generation: 2,
+ sequence: 1,
+ encoding: 'h264',
+ format: 'annex-b',
+ bytes: new Uint8Array([
+ 0, 0, 0, 1, 0x67, 0x64, 0, 0x28, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80, 0, 0, 0, 1, 0x65,
+ 0x88,
+ ]).buffer,
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ width: 1206,
+ height: 2622,
+ orientation: 'PORTRAIT',
+ scale: 3,
+ colorSpace: 'srgb',
+ timestampMicros: 0,
+ keyFrame: true,
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(drawImage).toHaveBeenCalledWith(expect.anything(), 0, 0, 1206, 2622);
+ expect(rendered.container.querySelector('canvas')?.getAttribute('aria-hidden')).toBe('false');
+ });
+ });
+
+ 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,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [
+ {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation: 2,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: leaseId,
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ },
+ ],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+ const api = installStatus(statusWithLease('lease-expired'));
+ api.status
+ .mockResolvedValueOnce(statusWithLease('lease-expired'))
+ .mockResolvedValueOnce(statusWithLease('lease-renewed'))
+ .mockResolvedValue(statusWithLease('lease-retried'));
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame
+ .mockResolvedValueOnce({
+ ok: false,
+ errorCode: 'LEASE_EXPIRED',
+ message: 'The simulator control lease expired.',
+ })
+ .mockResolvedValue(streamingJpegResult(2, 2));
+ api.call
+ .mockResolvedValueOnce({
+ ok: false,
+ errorCode: 'LEASE_EXPIRED',
+ message: 'The simulator control lease expired.',
+ })
+ .mockResolvedValue({ ok: true, data: {} });
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => {
+ expect(api.status).toHaveBeenCalledTimes(2);
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ leaseId: 'lease-renewed', visible: true }),
+ );
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.pressHome' }));
+
+ await waitFor(() => {
+ expect(api.call).toHaveBeenNthCalledWith(1, {
+ sessionId: 'session-a',
+ name: 'press_home',
+ args: {
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-renewed',
+ },
+ });
+ expect(api.call).toHaveBeenNthCalledWith(2, {
+ sessionId: 'session-a',
+ name: 'press_home',
+ args: {
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-retried',
+ },
+ });
+ });
+ });
+
+ it('shows a compact multi-instance overview and starts background streams for ready devices', async () => {
+ const api = installStatus({
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [
+ {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-A',
+ simulatorName: 'iPhone A',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation: 1,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: 'lease-a',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ },
+ {
+ instanceId: 'instance-b',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-b',
+ simulatorUdid: 'DEVICE-B',
+ simulatorName: 'iPhone B',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation: 2,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: 'lease-b',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ },
+ ],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ });
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText('rightSidebar.iosSimulator.instancesOverview')).toBeTruthy();
+ expect(screen.getAllByText('iPhone A').length).toBeGreaterThanOrEqual(2);
+ expect(screen.getAllByText('iPhone B').length).toBeGreaterThanOrEqual(1);
+ });
- expect(api.setViewerVisibility).toHaveBeenCalledWith(
- expect.objectContaining({ instanceId: 'instance-b', visible: true }),
- );
- expect(api.setStreamProfile).toHaveBeenCalledWith(
- expect.objectContaining({
- instanceId: 'instance-b',
- profile: { framesPerSecond: 5, jpegQuality: 25, scalingPercent: 50 },
- }),
- );
++ await waitFor(() => {
++ expect(api.setViewerVisibility).toHaveBeenCalledWith(
++ expect.objectContaining({ instanceId: 'instance-b', visible: true }),
++ );
++ expect(api.setStreamProfile).toHaveBeenCalledWith(
++ expect.objectContaining({
++ instanceId: 'instance-b',
++ profile: { framesPerSecond: 5, jpegQuality: 25, scalingPercent: 50 },
++ }),
++ );
++ });
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }),
+ );
+ await waitFor(() => {
+ expect(api.call).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ name: 'press_home',
+ args: {
+ instanceId: 'instance-b',
+ generation: 2,
+ leaseId: 'lease-b',
+ },
+ });
+ });
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.rotateDevice',
+ }),
+ );
+ await waitFor(() => {
+ expect(api.call).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ name: 'set_orientation',
+ args: {
+ instanceId: 'instance-b',
+ generation: 2,
+ leaseId: 'lease-b',
+ orientation: 'LANDSCAPE',
+ },
+ });
+ });
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.lockScreen',
+ }),
+ );
+ await waitFor(() => {
+ expect(api.call).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ name: 'lock_screen',
+ args: {
+ instanceId: 'instance-b',
+ generation: 2,
+ leaseId: 'lease-b',
+ },
+ });
+ });
+
+ const tileInput = screen.getByRole('textbox', {
+ name: 'iPhone B rightSidebar.iosSimulator.textInputLabel',
+ });
+ fireEvent.change(tileInput, { target: { value: 'hello' } });
+ fireEvent.keyDown(tileInput, { key: 'Enter', code: 'Enter' });
+ await waitFor(() => {
+ expect(api.call).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ name: 'type_text',
+ args: {
+ instanceId: 'instance-b',
+ generation: 2,
+ leaseId: 'lease-b',
+ text: 'hello',
+ },
+ });
+ });
+ });
+
++ it('does not apply a background stream profile after the grid is hidden', async () => {
++ const api = installStatus(multiReadyStatus());
++ let resolvePendingVisibility!: (result: IOSSimulatorToolResponse) => void;
++ const pendingVisibility = new Promise<IOSSimulatorToolResponse>((resolve) => {
++ resolvePendingVisibility = resolve;
++ });
++ api.setViewerVisibility.mockImplementation(async (request) => {
++ if (request.instanceId === 'instance-b' && request.visible) return pendingVisibility;
++ return { ok: true, data: { stream: null } };
++ });
++
++ const { rerender } = render(
++ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
++ );
++
++ await waitFor(() => {
++ expect(api.setViewerVisibility).toHaveBeenCalledWith(
++ expect.objectContaining({ instanceId: 'instance-b', visible: true }),
++ );
++ });
++
++ rerender(
++ <IOSSimulatorTabBody
++ state={{ instanceId: 'instance-a' }}
++ ctx={ctx}
++ active
++ shellVisible={false}
++ />,
++ );
++
++ await waitFor(() => {
++ expect(api.setViewerVisibility).toHaveBeenCalledWith(
++ expect.objectContaining({ instanceId: 'instance-b', visible: false }),
++ );
++ });
++
++ await act(async () => {
++ resolvePendingVisibility({ ok: true, data: { stream: null } });
++ await pendingVisibility;
++ });
++
++ expect(api.setStreamProfile).not.toHaveBeenCalledWith(
++ expect.objectContaining({ instanceId: 'instance-b' }),
++ );
++ });
++
+ it('blocks grid gestures while an Agent owns or queues device input', async () => {
+ const status = multiReadyStatus([
+ {
+ instanceId: 'instance-b',
+ activeSource: 'agent',
+ lastSource: 'agent',
+ queuedAgentMutations: 0,
+ agentPaused: false,
+ takeoverPending: false,
+ },
+ ]);
+ const api = installStatus(status);
+ installGridFrames(api);
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ const image = (await screen.findByAltText('iPhone B')) 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 }),
+ },
+ });
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+
+ fireEvent.pointerDown(image, { pointerId: 41, button: 0, clientX: 20, clientY: 40 });
+ fireEvent.pointerUp(image, { pointerId: 41, clientX: 180, clientY: 360 });
+
+ expect(image.setPointerCapture).not.toHaveBeenCalled();
+ expect(api.call).not.toHaveBeenCalled();
+ });
+
+ it('releases a grid gesture without dispatching it when Agent input becomes busy', async () => {
+ const initialStatus = multiReadyStatus();
+ const api = installStatus(initialStatus);
+ let liveMutation: IOSSimulatorMutationState | null = null;
+ installGridFrames(api, (instanceId) => (instanceId === 'instance-b' ? liveMutation : null));
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ const image = (await screen.findByAltText('iPhone B')) 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: 42, button: 0, clientX: 20, clientY: 40 });
+ expect(image.setPointerCapture).toHaveBeenCalledWith(42);
+
+ liveMutation = {
+ instanceId: 'instance-b',
+ activeSource: null,
+ lastSource: 'agent',
+ queuedAgentMutations: 1,
+ agentPaused: false,
+ takeoverPending: false,
+ };
+ await waitFor(
+ () =>
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true),
+ { timeout: 2_000 },
+ );
+ expect(api.status).toHaveBeenCalledOnce();
+
+ fireEvent.pointerUp(image, { pointerId: 42, clientX: 180, clientY: 360 });
+
+ expect(image.releasePointerCapture).toHaveBeenCalledWith(42);
+ expect(api.call).not.toHaveBeenCalled();
+ });
+
+ it('drops a stale grid route and retries when its refresh is superseded', async () => {
+ const instanceA: IOSSimulatorPublicInstance = {
+ ...readyInstance(1),
+ simulatorName: 'iPhone A',
+ lease: { ...readyInstance(1).lease, id: 'lease-a' },
+ };
+ const instanceB: IOSSimulatorPublicInstance = {
+ ...readyInstance(2),
+ instanceId: 'instance-b',
+ simulatorUdid: 'DEVICE-B',
+ simulatorName: 'iPhone B',
+ lease: { ...readyInstance(2).lease, id: 'lease-b' },
+ };
+ const stoppedB: IOSSimulatorPublicInstance = {
+ ...instanceB,
+ generation: 3,
+ lifecycleState: 'stopped',
+ lease: { ...instanceB.lease, id: 'lease-b-renewed' },
+ stoppedAt: '2026-07-24T00:00:00.000Z',
+ };
+ const readyBaseStatus = readyStatus(instanceA);
+ if (!readyBaseStatus.ok) throw new Error('Expected a ready status fixture.');
+ const initialStatus: IOSSimulatorSessionStatus = {
+ ...readyBaseStatus,
+ instances: [instanceA, instanceB],
+ };
+ const reconciledStatus: IOSSimulatorSessionStatus = {
+ ...initialStatus,
+ instances: [instanceA, stoppedB],
+ };
+ const api = installStatus(initialStatus);
+ let resolveSupersededRefresh: (status: IOSSimulatorSessionStatus) => void = () => undefined;
+ const supersededRefresh = new Promise<IOSSimulatorSessionStatus>((resolve) => {
+ resolveSupersededRefresh = resolve;
+ });
+ api.status
+ .mockResolvedValueOnce(initialStatus)
+ .mockImplementationOnce(async () => supersededRefresh)
+ .mockRejectedValueOnce(new Error('newer status request failed'))
+ .mockResolvedValue(reconciledStatus);
+ let instanceBPolls = 0;
+ api.latestFrame.mockImplementation(async (request?: unknown) => {
+ const route = request as { instanceId?: string } | undefined;
+ if (route?.instanceId !== 'instance-b') {
+ return { ok: true, data: { stream: null } };
+ }
+ instanceBPolls += 1;
+ if (instanceBPolls === 1) {
+ return {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-b',
+ generation: 2,
+ state: 'streaming',
+ reconnectAttempt: 0,
+ latestFrame: {
+ instanceId: 'instance-b',
+ generation: 2,
+ sequence: 1,
+ encoding: 'jpeg',
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ bytes: new Uint8Array([1, 2, 3]),
+ },
+ },
+ },
+ };
+ }
+ return {
+ ok: true,
+ data: { instance: stoppedB, stream: null, viewport: null },
+ };
+ });
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ const staleImage = (await screen.findByAltText('iPhone B')) as HTMLImageElement;
+ Object.defineProperties(staleImage, {
+ 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(staleImage, {
+ pointerId: 31,
+ button: 0,
+ clientX: 20,
+ clientY: 40,
+ });
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(2), { timeout: 2_000 });
+ await waitFor(() => expect(screen.queryByAltText('iPhone B')).toBeNull());
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:ios-simulator-1');
+ fireEvent.pointerUp(staleImage, {
+ pointerId: 31,
+ clientX: 180,
+ clientY: 360,
+ });
+ expect(api.call).not.toHaveBeenCalled();
+
+ act(() => {
+ api.emitFocusRequest({
+ sessionId: 'session-a',
+ instanceId: 'instance-b',
+ userInitiated: false,
+ });
+ });
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(3), { timeout: 2_000 });
+ await act(async () => {
+ resolveSupersededRefresh(reconciledStatus);
+ await Promise.resolve();
+ });
+
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(4), { timeout: 2_000 });
+ await waitFor(() => expect(screen.queryByAltText('iPhone B')).toBeNull());
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }),
+ ).toBeNull(),
+ );
+
+ const pollsAfterRefresh = api.latestFrame.mock.calls.filter(
+ ([request]) => (request as { instanceId?: string } | undefined)?.instanceId === 'instance-b',
+ ).length;
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 650));
+ });
+ expect(
+ api.latestFrame.mock.calls.filter(
+ ([request]) =>
+ (request as { instanceId?: string } | undefined)?.instanceId === 'instance-b',
+ ),
+ ).toHaveLength(pollsAfterRefresh);
+ });
+});
diff --cc packages/maker-core/src/agents/codex/index.test.ts
index 9a2a23a7b0,4acf3283ed..fe533f3dbe
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@@ -12656,144 -12437,284 +12667,422 @@@ describe('CodexAgent MCP thread contex
await handle.close();
});
+ it('applies a host shell-command denial before Full access auto-approval', async () => {
+ const { logger, warn } = createLoggerSpy();
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy, logger }));
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-command-host-policy',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.commandExecutionApproval) throw new Error('expected commandExecutionApproval handler');
+ const resolver = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+ handle.setInteractionResolver(resolver);
+
+ const command = 'API_TOKEN=super-secret open -a Simulator';
+ const result = await handlers.commandExecutionApproval({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ itemId: 'cmd-1',
+ command,
+ cwd: '/repo',
+ });
+
+ expect(policy).toHaveBeenCalledWith({
+ agentKind: 'codex',
+ command,
+ cwd: '/repo',
+ });
+ expect(resolver).not.toHaveBeenCalled();
+ expect(result).toEqual({ decision: 'decline' });
+ expect(warn).toHaveBeenCalledWith('command execution denied by host policy', {
+ requestId: 'cmd-1',
+ reason: 'use the embedded iOS Simulator',
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('super-secret');
+ await handle.close();
+ });
+
+ it('interrupts an already-started absolute-path shell bypass as a fail-safe', async () => {
+ const { logger, warn } = createLoggerSpy();
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy, logger }));
+ const host = installFakeHost(agent, (method) =>
+ method === Method.TurnInterrupt ? {} : undefined,
+ );
+ const handle = await agent.startSession({
+ sessionId: 'session-command-item-host-policy',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted) throw new Error('expected itemStarted handler');
+
+ const command = 'API_TOKEN=super-secret /usr/bin/open -a Simulator';
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'cmd-absolute',
+ type: 'commandExecution',
+ command,
+ cwd: '/repo',
+ },
+ });
+
+ expect(policy).toHaveBeenCalledWith({
+ agentKind: 'codex',
+ command,
+ cwd: undefined,
+ });
+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ });
+ expect(warn).toHaveBeenCalledWith('command execution interrupted by host policy', {
+ turnId: 'turn-1',
+ reason: 'use the embedded iOS Simulator',
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('super-secret');
+ await handle.close();
+ });
+
+ it('interrupts a raw function_call exec_command shell bypass as a fail-safe', async () => {
+ const policy = vi.fn(() => ({
+ decision: 'deny' as const,
+ reason: 'use the embedded iOS Simulator',
+ }));
+ const agent = new CodexAgent(createDeps({}, { getShellCommandPolicy: policy }));
+ const host = installFakeHost(agent, (method) =>
+ method === Method.TurnInterrupt ? {} : undefined,
+ );
+ const handle = await agent.startSession({
+ sessionId: 'session-function-call-shell-policy',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'bypassPermissions',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted) throw new Error('expected itemStarted handler');
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-raw-function-call',
+ item: {
+ id: 'fc-raw-shell',
+ type: 'function_call',
+ name: 'exec_command',
+ arguments: JSON.stringify({
+ cmd: 'xcrun simctl boot DEVICE',
+ workdir: '/repo',
+ }),
+ },
+ });
+
+ expect(policy).toHaveBeenCalledWith({
+ agentKind: 'codex',
+ command: 'xcrun simctl boot DEVICE',
+ cwd: '/repo',
+ });
+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {
+ threadId: 'start-thread-id',
+ turnId: 'turn-raw-function-call',
+ });
+ await handle.close();
+ });
+
+ it('excludes a server-resolved approval wait from the completed turn duration', async () => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-approval-generation-timing',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'ask',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.commandExecutionApproval ||
+ !handlers.serverRequestResolved ||
+ !handlers.turnStarted ||
+ !handlers.turnCompleted
+ ) {
+ throw new Error('expected approval timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const interactionResolver = vi.fn(() => new Promise<never>(() => {}));
+ handle.setInteractionResolver(interactionResolver);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ now = 2_000;
+ const approvalPromise = handlers.commandExecutionApproval({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ itemId: 'approval-item-1',
+ command: 'pwd',
+ cwd: '/repo',
+ });
+ await waitForExpectation(() => expect(interactionResolver).toHaveBeenCalledTimes(1));
+
+ now = 10_000;
+ handlers.serverRequestResolved({
+ threadId: 'start-thread-id',
+ requestId: 'approval-item-1',
+ });
+ await expect(approvalPromise).resolves.toEqual({ decision: 'decline' });
+
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);
+
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('keeps descendant approval waits out of the root generation timer', async () => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-approval-generation-timing',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ permissionMode: 'ask',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.commandExecutionApproval
+ || !handlers.itemStarted
+ || !handlers.itemCompleted
+ || !handlers.turnStarted
+ || !handlers.turnCompleted
+ ) {
+ throw new Error('expected descendant approval timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const decision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(() => decision.promise);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'root-turn' } });
+ now = 2_000;
+ const collabItem = {
+ id: 'root-collab-item',
+ type: 'collabAgentToolCall',
+ tool: 'spawnAgent',
+ status: 'inProgress',
+ senderThreadId: 'start-thread-id',
+ receiverThreadIds: ['child-thread'],
+ agentsStates: {},
+ };
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'root-turn',
+ item: collabItem,
+ } as never);
+
+ now = 3_000;
+ const approvalPromise = handlers.commandExecutionApproval({
+ threadId: 'child-thread',
+ turnId: 'child-turn',
+ itemId: 'child-command',
+ command: 'pwd',
+ cwd: '/repo',
+ });
+ now = 9_000;
+ decision.resolve({ kind: 'permission', behavior: 'allow' });
+ await expect(approvalPromise).resolves.toEqual({ decision: 'accept' });
+
+ now = 10_000;
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'root-turn',
+ item: { ...collabItem, status: 'completed' },
+ } as never);
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'root-turn', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);
+
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it.each(['answered', 'server-resolved', 'resolver-failed'] as const)(
+ 'excludes a native requestUserInput wait when it is %s',
+ async (outcome) => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: `session-native-user-input-timing-${outcome}`,
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (
+ !handlers?.requestUserInput
+ || !handlers.serverRequestResolved
+ || !handlers.turnStarted
+ || !handlers.turnCompleted
+ ) {
+ throw new Error('expected native user-input timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const decision = deferred<InteractionDecision>();
+ const interactionResolver = vi.fn(() => decision.promise);
+ handle.setInteractionResolver(interactionResolver);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ now = 2_000;
+ const responsePromise = handlers.requestUserInput({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ itemId: 'native-question-1',
+ questions: [{
+ id: 'q1',
+ header: 'Question',
+ question: 'Pick one',
+ isOther: false,
+ isSecret: false,
+ options: null,
+ }],
+ }, { requestId: `native-question-${outcome}` });
+ await waitForExpectation(() => expect(interactionResolver).toHaveBeenCalledTimes(1));
+
+ now = 10_000;
+ if (outcome === 'answered') {
+ decision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': 'yes' },
+ });
+ } else if (outcome === 'server-resolved') {
+ handlers.serverRequestResolved({
+ threadId: 'start-thread-id',
+ requestId: `native-question-${outcome}`,
+ });
+ } else {
+ decision.reject(new Error('interaction resolver failed'));
+ }
+ await responsePromise;
+
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);
+
+ if (outcome === 'server-resolved') {
+ decision.resolve({ kind: 'ask_user_question', answers: {} });
+ }
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ },
+ );
+
+ it('omits native requestUserInput timing when the turn id is missing', async () => {
+ let now = 1_000;
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-native-user-input-missing-turn-id',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.requestUserInput || !handlers.turnStarted || !handlers.turnCompleted) {
+ throw new Error('expected native user-input timing handlers');
+ }
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ const decision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(() => decision.promise);
+
+ handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ now = 2_000;
+ const responsePromise = handlers.requestUserInput({
+ threadId: 'start-thread-id',
+ turnId: null as never,
+ itemId: 'native-question-without-turn',
+ questions: [{
+ id: 'q1',
+ header: 'Question',
+ question: 'Pick one',
+ isOther: false,
+ isSecret: false,
+ options: null,
+ }],
+ }, { requestId: 'native-question-without-turn' });
+ now = 10_000;
+ decision.resolve({ kind: 'ask_user_question', answers: { 'Pick one': 'yes' } });
+ await responsePromise;
+
+ now = 12_000;
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },
+ });
+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));
+ const done = events.find((event) => event.type === 'done');
+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();
+
+ await handle.close();
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
it('routes dynamic ask_user_question tool calls through ask_user_question', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
diff --cc packages/maker-core/src/agents/codex/index.ts
index 7c11cdae64,6ea74d5eeb..b10fb7dd09
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@@ -5839,21 -5768,9 +5879,21 @@@ export class CodexAgent extends BaseAge
const turnGate = gateServerRequestTurn(params.turnId, params.threadId);
if (turnGate === false) return { decision: 'decline' };
if (turnGate instanceof Promise && !(await turnGate)) return { decision: 'decline' };
+ const hostPolicy = this.deps.getShellCommandPolicy?.({
+ agentKind: 'codex',
+ command: params.command ?? '',
+ cwd: params.cwd ?? undefined,
+ });
+ if (hostPolicy?.decision === 'deny') {
+ log.warn('command execution denied by host policy', {
+ requestId: params.approvalId ?? params.itemId,
+ reason: hostPolicy.reason,
+ });
+ return { decision: 'decline' };
+ }
// requestId: approvalId 优先 (zsh-exec-bridge 多 callback 场景); 否则用 itemId
const requestId = params.approvalId ?? params.itemId;
- const decision = await awaitApprovalDecision(requestId, 'commandExecution', {
+ const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'commandExecution', {
kind: 'permission',
requestId,
toolName: 'exec',
@@@ -6572,56 -6459,19 +6628,58 @@@
success: false,
};
}
- const requestId = String(meta.requestId);
- // 挂起期间服务端已取消本请求 (greptile R13 P1): 直接回失败响应, 不注册
- // broker 不上 UI (与 resolved 的 cancel 响应同款文案)。
- if (resolvedWhileBufferedRequestIds.delete(requestId)) {
+
+ const { serverName, toolName } = dynamicToolApprovalIdentity(params);
+ const approvalPolicy = classifyMcpToolApprovalPolicy({
+ serverName,
+ toolName,
+ toolParams: params.arguments,
+ });
+ if (approvalPolicy !== 'auto-approve') {
+ const requestId = `dynamic-tool:${serverName}:${params.turnId}:${params.callId}`;
+ const decision = await awaitApprovalDecision(
++ params.threadId,
++ params.turnId,
+ requestId,
+ 'mcpServerElicitation',
+ {
+ kind: 'permission',
+ requestId,
+ toolName: `dynamic:${serverName}:${toolName}`,
+ input: { serverName, toolName, toolParams: params.arguments },
+ title: `Allow Codex to use ${serverName}?`,
+ description: `Codex requested ${serverName}.${toolName}.`,
+ },
+ { forcePrompt: approvalPolicy === 'prompt-each-time' },
+ );
+ if (decision !== 'accept' && decision !== 'acceptForSession') {
+ return {
+ contentItems: [{ type: 'inputText', text: 'The user declined this tool call.' }],
+ success: false,
+ };
+ }
+ }
+
+ try {
+ const response = await hostDynamicToolProvider.callTool(params, hostDynamicToolContext);
+ if (response) return response;
return {
- contentItems: [{ type: 'inputText', text: 'Request was resolved before user input was submitted.' }],
+ contentItems: [{ type: 'inputText', text: `Unsupported dynamic tool: ${params.tool}` }],
success: false,
};
- }
- const questions = normalizeDynamicAskUserQuestions(params.arguments);
- if (questions.length === 0) {
+ } catch (error) {
+ log.error('host dynamic tool failed', {
+ namespace: params.namespace,
+ tool: params.tool,
+ error: error instanceof Error ? error.message : String(error),
+ });
return {
- contentItems: [{ type: 'inputText', text: 'No valid questions were provided.' }],
+ contentItems: [
+ {
+ type: 'inputText',
+ text: `Host dynamic tool failed: ${error instanceof Error ? error.message : String(error)}`,
+ },
+ ],
success: false,
};
}