Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(ios-simulator): improve viewer recovery and layout
JiangJiahao438eea33c86c
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.tsindex 0fc5c18514..2ebbbb69a7 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts@@ -38,6 +38,7 @@ describe('iOS Simulator IPC handlers', () => {MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL,MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL,MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY,+ MAKER_INVOKE.IOS_SIMULATOR_RETRY_NATIVE_ROUTE,MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME,MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE,MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH,@@ -624,8 +625,12 @@ describe('iOS Simulator IPC handlers', () => {it('validates exact frame routes before forwarding visibility and frame reads', async () => {const harness = new IpcHarness();const setViewerVisibility = vi.fn(async () => ({ ok: true as const, data: {} }));+ const retryNativeRoute = vi.fn(async () => ({+ ok: true as const,+ data: { nativeRecovered: true },+ }));const getLatestFrame = vi.fn(async () => ({ ok: true as const, data: { stream: null } }));- registerTrusted(harness, { setViewerVisibility, getLatestFrame });+ registerTrusted(harness, { setViewerVisibility, retryNativeRoute, getLatestFrame });const route = {sessionId: 'session-a',instanceId: 'instance-a',@@ -650,6 +655,10 @@ describe('iOS Simulator IPC handlers', () => {fallbackReason: 'native-decoder-fallback',});await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route);+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_RETRY_NATIVE_ROUTE, {+ ...route,+ viewerToken: 'viewer-a',+ });expect(setViewerVisibility).toHaveBeenCalledWith('session-a',@@ -687,6 +696,16 @@ describe('iOS Simulator IPC handlers', () => {},17,);+ expect(retryNativeRoute).toHaveBeenCalledWith(+ 'session-a',+ {+ instanceId: 'instance-a',+ generation: 3,+ leaseId: 'lease-a',+ },+ 17,+ 'viewer-a',+ );await expect(harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route),).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });@@ -724,6 +743,12 @@ describe('iOS Simulator IPC handlers', () => {viewerToken: '',}),).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ await expect(+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_RETRY_NATIVE_ROUTE, {+ ...route,+ viewerToken: '',+ }),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });});it('validates and routes bounded stream profiles', async () => {diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 4ac12800ae..33cd100eb2 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -629,6 +629,7 @@ export const MAKER_INVOKE = {IOS_SIMULATOR_SET_AGENT_CONTROL: 'maker:ios-simulator:set-agent-control',IOS_SIMULATOR_SET_MUTATION_CONTROL: 'maker:ios-simulator:set-mutation-control',IOS_SIMULATOR_SET_VIEWER_VISIBILITY: 'maker:ios-simulator:set-viewer-visibility',+ IOS_SIMULATOR_RETRY_NATIVE_ROUTE: 'maker:ios-simulator:retry-native-route',IOS_SIMULATOR_LATEST_FRAME: 'maker:ios-simulator:latest-frame',IOS_SIMULATOR_SET_STREAM_PROFILE: 'maker:ios-simulator:set-stream-profile',IOS_SIMULATOR_LIVE_TOUCH: 'maker:ios-simulator:live-touch',diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.tsindex cbed3243d0..587ee94ef3 100644--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts@@ -12,6 +12,7 @@ import {callIOSSimulatorHostTool,getIOSSimulatorLatestFrame,getIOSSimulatorSessionStatus,+ retryIOSSimulatorNativeRoute,setIOSSimulatorAgentControlGrant,setIOSSimulatorAgentMutationPaused,setIOSSimulatorViewerVisibility,@@ -43,6 +44,7 @@ type IOSSimulatorIpcOperation =| 'call-tool'| 'set-agent-control'| 'set-viewer-visibility'+ | 'retry-native-route'| 'set-mutation-control'| 'latest-frame'| 'set-stream-profile'@@ -54,6 +56,7 @@ const IOS_SIMULATOR_SAFE_IPC_MESSAGES: Record<IOSSimulatorIpcOperation, string>'call-tool': 'iOS Simulator operation failed.','set-agent-control': 'iOS Simulator control permission could not be updated.','set-viewer-visibility': 'iOS Simulator viewer state could not be updated.',+ 'retry-native-route': 'iOS Simulator Native acceleration could not be restored.','set-mutation-control': 'iOS Simulator control state could not be updated.','latest-frame': 'iOS Simulator frame is temporarily unavailable.','set-stream-profile': 'iOS Simulator stream settings could not be updated.',@@ -112,6 +115,12 @@ export interface IOSSimulatorHandlerDeps {viewerWebContentsId?: number,viewerToken?: string,): Promise<IOSSimulatorToolResponse>;+ retryNativeRoute(+ sessionId: string,+ route: { instanceId: string; generation: number; leaseId: string },+ viewerWebContentsId: number,+ viewerToken: string,+ ): Promise<IOSSimulatorToolResponse>;setViewerStreamProfile(sessionId: string,route: { instanceId: string; generation: number; leaseId: string },@@ -159,6 +168,7 @@ const defaultDeps: IOSSimulatorHandlerDeps = {setAgentControlGrant: setIOSSimulatorAgentControlGrant,setAgentMutationPaused: setIOSSimulatorAgentMutationPaused,setViewerVisibility: setIOSSimulatorViewerVisibility,+ retryNativeRoute: retryIOSSimulatorNativeRoute,setViewerStreamProfile: setIOSSimulatorViewerStreamProfile,getLatestFrame: getIOSSimulatorLatestFrame,updateViewerTouch: updateIOSSimulatorViewerTouch,@@ -479,6 +489,31 @@ export function registerIOSSimulatorHandlers(),);});+ handle(MAKER_INVOKE.IOS_SIMULATOR_RETRY_NATIVE_ROUTE, async (event, payload) => {+ const record = readRecord(payload);+ const sessionId = readSessionId(record);+ const viewerWebContentsId = assertSenderSession(event, sessionId);+ const viewerToken = record.viewerToken;+ if (+ typeof viewerToken !== 'string' ||+ !viewerToken.trim() ||+ viewerToken.length > 128+ ) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'viewerToken must be a non-empty string of at most 128 chars',+ );+ }+ const route = readViewerRoute(record);+ return callIOSSimulatorHostForSession(event, sessionId, 'retry-native-route', () =>+ resolved.retryNativeRoute(+ sessionId,+ route,+ viewerWebContentsId,+ viewerToken.trim(),+ ),+ );+ });handle(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, async (event, payload) => {const record = readRecord(payload);const sessionId = readSessionId(record);diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.tsindex d2a85f21a9..b00e8a1b1d 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@ -4336,6 +4336,18 @@ describe('iOS Simulator host', () => {ok: false,errorCode: 'INSTANCE_NOT_OWNED',});+ await expect(+ host.retryNativeRoute('session-a', route, 88, 'viewer-token'),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });+ await expect(+ host.retryNativeRoute('session-a', route, 77, 'stale-viewer-token'),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });expect(h264FramePump.snapshot).not.toHaveBeenCalled();expect(framePump.snapshot).not.toHaveBeenCalled();@@ -4522,7 +4534,50 @@ describe('iOS Simulator host', () => {},});+ driverManager.recoverNativeSidecar.mockImplementationOnce(async () => running);+ await expect(+ host.retryNativeRoute('session-a', latestRoute, 77, 'viewer-token'),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ nativeRecovered: false,+ stream: { state: 'reconnecting' },+ },+ });+ expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {+ rearm: true,+ });+ expect(framePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({ visible: true }),+ );+ expect(h264FramePump.clear).toHaveBeenLastCalledWith(started.instanceId);+ expect(routeStatuses.at(-1)).toMatchObject({+ stream: {+ adapter: 'wda',+ encoding: 'jpeg',+ state: 'reconnecting',+ reasonCode: 'native-sidecar-unavailable',+ },+ });+h264Snapshot = { ...h264Snapshot, state: 'connecting' };+ await expect(+ host.retryNativeRoute('session-a', latestRoute, 77, 'viewer-token'),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ nativeRecovered: true,+ stream: { state: 'connecting' },+ },+ });+ expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {+ rearm: true,+ });+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({ driver: recoveredNativeDriver, visible: true }),+ );++ nativeAvailable = false;await expect(host.setViewerVisibility('session-a',@@ -4573,6 +4628,34 @@ describe('iOS Simulator host', () => {expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {rearm: true,});++ await expect(+ host.setViewerVisibility(+ 'session-a',+ latestRoute,+ true,+ 'jpeg',+ undefined,+ 77,+ 'viewer-reopened',+ ),+ ).resolves.toMatchObject({ ok: true });+ nativeAvailable = false;+ framePump.setVisible.mockClear();+ h264FramePump.setVisible.mockClear();+ await expect(+ host.retryNativeRoute('session-a', latestRoute, 77, 'viewer-reopened'),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ nativeRecovered: true,+ stream: { instanceId: started.instanceId },+ },+ });+ expect(framePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({ driver: wdaDriver, visible: true }),+ );+ expect(h264FramePump.setVisible).not.toHaveBeenCalled();});it('stops the embedded viewer when the exact external simulator is shut down', async () => {diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 7dfdbf9615..6d95044d13 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -281,6 +281,12 @@ export interface IOSSimulatorHost {viewerWebContentsId?: number,viewerToken?: string,): Promise<IOSSimulatorHostResult>;+ retryNativeRoute(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ viewerWebContentsId: number,+ viewerToken: string,+ ): Promise<IOSSimulatorHostResult>;getLatestFrame(sessionId: string,route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,@@ -4089,6 +4095,116 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IremovalBarrierOperation?.finish();}},+ async retryNativeRoute(sessionId, route, viewerWebContentsId, viewerToken) {+ let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;+ try {+ assertHostActive();+ const resolved = await resolveSession(sessionId, { registerRemovalBarrier: true });+ if (!resolved.ok) return resolved;+ removalBarrierOperation = resolved.removalBarrierOperation ?? null;+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);+ assertHostActive();+ assertCurrentViewer(resolved.sessionId, route.instanceId, viewerWebContentsId, viewerToken);+ let instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });+ instance = await reconcileLiveDevice(instance);+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);+ assertHostActive();+ assertCurrentViewer(+ resolved.sessionId,+ instance.instanceId,+ viewerWebContentsId,+ viewerToken,+ );+ if (instance.lifecycleState !== 'ready') return viewerRouteRefreshResult(instance);++ const driverManager = getDriverManager();+ let running = await getHealthyDriver(instance.instanceId);+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);+ assertHostActive();+ assertCurrentViewer(+ resolved.sessionId,+ instance.instanceId,+ viewerWebContentsId,+ viewerToken,+ );+ let current = currentReadyGeneration(instance);+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));+ instance = current;+ if (!running) {+ throw new IOSSimulatorInstanceError(+ 'INVALID_INSTANCE_STATE',+ 'The simulator automation driver is unavailable.',+ true,+ );+ }++ if (!nativeH264Driver(running) && driverManager.recoverNativeSidecar) {+ running =+ (await driverManager.recoverNativeSidecar(instance.instanceId, { rearm: true })) ??+ running;+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);+ assertHostActive();+ assertCurrentViewer(+ resolved.sessionId,+ instance.instanceId,+ viewerWebContentsId,+ viewerToken,+ );+ current = currentReadyGeneration(instance);+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));+ instance = current;+ }++ const nativeRecovered = nativeH264Driver(running) !== null;+ const preferredEncoding =+ viewerPreferredEncodings.get(instance.instanceId) ??+ viewerEncodings.get(instance.instanceId) ??+ 'jpeg';+ const viewport = viewports.get(instance.instanceId) ?? (await readViewport(running));+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);+ assertHostActive();+ assertCurrentViewer(+ resolved.sessionId,+ instance.instanceId,+ viewerWebContentsId,+ viewerToken,+ );+ current = currentReadyGeneration(instance);+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));+ instance = actor.heartbeatOwned(resolved.sessionId, current.instanceId);+ assertCurrentViewer(+ resolved.sessionId,+ instance.instanceId,+ viewerWebContentsId,+ viewerToken,+ );+ const stream = startViewerStream(+ instance,+ running,+ preferredEncoding,+ viewport.orientation,+ null,+ viewerWebContentsId,+ viewerToken,+ );+ return {+ ok: true,+ data: {+ nativeRecovered,+ ...(instance.generation !== route.generation || instance.lease.id !== route.leaseId+ ? { instance: publicInstance(instance) }+ : {}),+ stream,+ viewport: viewports.get(instance.instanceId) ?? viewport,+ mutation: actor.mutationState(instance.instanceId),+ },+ };+ } catch (error) {+ return safeHostError(error, sessionId, 'retry_native_route');+ } finally {+ removalBarrierOperation?.finish();+ }+ },async getLatestFrame(sessionId, route, viewerWebContentsId) {let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;try {@@ -6600,6 +6716,20 @@ export function setIOSSimulatorViewerVisibility();}+export function retryIOSSimulatorNativeRoute(+ sessionId: string,+ route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ viewerWebContentsId: number,+ viewerToken: string,+): Promise<IOSSimulatorHostResult> {+ return initializeIOSSimulatorHost().retryNativeRoute(+ sessionId,+ route,+ viewerWebContentsId,+ viewerToken,+ );+}+export function setIOSSimulatorAgentMutationPaused(sessionId: string,route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.tsindex 22be7135e7..6729163fef 100644--- a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts@@ -315,7 +315,7 @@ describe('sidebar nested namespace contract', () => {]));expect(iosSimulatorKeys).toEqual(expect.arrayContaining(['requestAccess', 'status', 'call', 'setAgentControl', 'setMutationControl',- 'setViewerVisibility', 'latestFrame', 'setStreamProfile', 'liveTouch',+ 'setViewerVisibility', 'retryNativeRoute', 'latestFrame', 'setStreamProfile', 'liveTouch','onH264Frame', 'onRouteStatus', 'onFocusRequest',]));});diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 6b1ce91a35..2c4455b586 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -160,6 +160,7 @@ import type {IOSSimulatorRouteStatusPush,IOSSimulatorLiveTouchRequest,IOSSimulatorMutationControlRequest,+ IOSSimulatorRetryNativeRouteRequest,IOSSimulatorStatusRequest,IOSSimulatorToolRequest,IOSSimulatorToolResponse,@@ -6503,6 +6504,10 @@ contextBridge.exposeInMainWorld('electronAPI', {request: IOSSimulatorViewerVisibilityRequest,): Promise<IOSSimulatorToolResponse> =>ipcRenderer.invoke('maker:ios-simulator:set-viewer-visibility', request),+ retryNativeRoute: (+ request: IOSSimulatorRetryNativeRouteRequest,+ ): Promise<IOSSimulatorToolResponse> =>+ ipcRenderer.invoke('maker:ios-simulator:retry-native-route', request),latestFrame: (request: IOSSimulatorViewerRouteRequest): Promise<IOSSimulatorToolResponse> =>ipcRenderer.invoke('maker:ios-simulator:latest-frame', request),setStreamProfile: (diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex a2fa98e51c..8f5c710214 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -548,6 +548,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:ios-simulator:set-mutation-control', request),setViewerVisibility: (request: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:ios-simulator:set-viewer-visibility', request),+ retryNativeRoute: (request: unknown): Promise<unknown> =>+ ipcRenderer.invoke('maker:ios-simulator:retry-native-route', request),latestFrame: (request: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:ios-simulator:latest-frame', request),setStreamProfile: (request: unknown): Promise<unknown> =>diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsxindex 86cc8619a2..5addfdf55e 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx@@ -141,6 +141,7 @@ function nativeRecoveryBackoff(attemptCount: number): number {function isRecoverableNativeFallback(status: IOSSimulatorPublicRouteStatus | null): boolean {if (!status) return false;+ if (status.stream.reasonCode === 'native-decoder-fallback') return false;return (status.stream.reasonCode === 'native-stream-disconnected' ||status.stream.reasonCode === 'native-sidecar-unavailable' ||@@ -214,6 +215,11 @@ function resultMutation(result: IOSSimulatorToolResponse): IOSSimulatorMutationSreturn mutation && typeof mutation === 'object' ? (mutation as IOSSimulatorMutationState) : null;}+function resultNativeRecovered(result: IOSSimulatorToolResponse): boolean {+ if (!result.ok || !result.data || typeof result.data !== 'object') return false;+ return (result.data as { nativeRecovered?: unknown }).nativeRecovered === true;+}+function mergeRouteStatus(previous: Record<string, IOSSimulatorPublicRouteStatus>,incoming: IOSSimulatorPublicRouteStatus,@@ -302,7 +308,10 @@ export function IOSSimulatorTabBody({const [textInput, setTextInput] = useState('');const [streamProfile, setStreamProfile] = useState<StreamProfileName>('balanced');const [viewerReadyToken, setViewerReadyToken] = useState<string | null>(null);+ const [nativeRecoveryPending, setNativeRecoveryPending] = useState(false);+ const [nativeRecoveryFailed, setNativeRecoveryFailed] = useState(false);const requestVersionRef = useRef(0);+ const nativeRecoveryRequestRef = useRef(0);const frameSequenceRef = useRef(0);const frameEncodingRef = useRef<'jpeg' | 'h264' | null>(null);const fpsWindowRef = useRef({ startedAt: 0, frames: 0 });@@ -574,6 +583,12 @@ export function IOSSimulatorTabBody({viewerRouteKey,]);+ useEffect(() => {+ nativeRecoveryRequestRef.current += 1;+ setNativeRecoveryPending(false);+ setNativeRecoveryFailed(false);+ }, [viewerRouteKey]);+useEffect(() => {const nextId = attachedInstance?.instanceId ?? null;if ((state.instanceId ?? null) !== nextId) ctx.patchState({ instanceId: nextId });@@ -1117,6 +1132,50 @@ export function IOSSimulatorTabBody({[attachedInstance, formatActionError, nativeH264Active, sendStreamProfile, streamProfile, t],);+ const retryNativeRoute = useCallback(async () => {+ if (+ !attachedInstance ||+ attachedInstance.lifecycleState !== 'ready' ||+ !viewerRouteKey ||+ nativeRecoveryPending+ ) {+ return;+ }+ const viewerIdentity = viewerIdentityRef.current;+ if (!viewerIdentity || viewerIdentity.routeKey !== viewerRouteKey) return;+ const requestId = ++nativeRecoveryRequestRef.current;+ const requestIsCurrent = () => {+ const current = viewerIdentityRef.current;+ return (+ nativeRecoveryRequestRef.current === requestId &&+ current?.routeKey === viewerIdentity.routeKey &&+ current.viewerToken === viewerIdentity.viewerToken+ );+ };+ setNativeRecoveryPending(true);+ setNativeRecoveryFailed(false);+ try {+ if (!(await viewerIdentity.ready)) {+ if (requestIsCurrent()) setNativeRecoveryFailed(true);+ return;+ }+ if (!requestIsCurrent()) return;+ const result = await window.electronAPI.maker.iosSimulator.retryNativeRoute({+ sessionId: ctx.sessionId,+ ...routeFor(attachedInstance),+ viewerToken: viewerIdentity.viewerToken,+ });+ if (!requestIsCurrent()) return;+ const nativeRecovered = resultNativeRecovered(result);+ if (nativeRecovered || resultInstance(result)) await refresh();+ if (requestIsCurrent() && !nativeRecovered) setNativeRecoveryFailed(true);+ } catch {+ if (requestIsCurrent()) setNativeRecoveryFailed(true);+ } finally {+ if (requestIsCurrent()) setNativeRecoveryPending(false);+ }+ }, [attachedInstance, ctx.sessionId, nativeRecoveryPending, refresh, viewerRouteKey]);+useEffect(() => {setStreamProfile('balanced');streamProfileRef.current = 'balanced';@@ -1889,6 +1948,35 @@ export function IOSSimulatorTabBody({</span></>)}+ {isRecoverableNativeFallback(routeStatus) && (+ <>+ <span aria-hidden="true">·</span>+ <span+ role={nativeRecoveryFailed ? 'alert' : undefined}+ aria-live={nativeRecoveryFailed ? 'assertive' : 'polite'}+ className="text-pretty leading-relaxed"+ >+ {t(+ nativeRecoveryPending+ ? 'rightSidebar.iosSimulator.nativeRecovery.recovering'+ : nativeRecoveryFailed+ ? 'rightSidebar.iosSimulator.nativeRecovery.failed'+ : 'rightSidebar.iosSimulator.nativeRecovery.available',+ )}+ </span>+ <ActionButton+ label={t(+ nativeRecoveryPending+ ? 'rightSidebar.iosSimulator.nativeRecovery.recoveringAction'+ : 'rightSidebar.iosSimulator.nativeRecovery.action',+ )}+ icon={nativeRecoveryPending ? Loader2 : RefreshCw}+ spinning={nativeRecoveryPending}+ disabled={nativeRecoveryPending || !viewerReadyToken}+ onClick={() => void retryNativeRoute()}+ />+ </>+ )}</div><div className="mt-3 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface)]"><div className="relative flex min-h-48 items-center justify-center p-2">@@ -1900,7 +1988,7 @@ export function IOSSimulatorTabBody({})}title={t('rightSidebar.iosSimulator.gestureHint')}className={cn(- 'max-h-[520px] max-w-full touch-none select-none object-contain',+ 'block h-auto w-full touch-none select-none object-contain',framePresentation === 'jpeg' ? null : 'hidden',busy? 'cursor-wait opacity-80'@@ -1925,7 +2013,7 @@ export function IOSSimulatorTabBody({aria-hidden={!(presentationMatchesRoute && framePresentation === 'h264')}title={t('rightSidebar.iosSimulator.gestureHint')}className={cn(- 'max-h-[520px] max-w-full touch-none select-none object-contain',+ 'block h-auto w-full touch-none select-none object-contain',presentationMatchesRoute && framePresentation === 'h264'? null: 'hidden',diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsxindex 3cc0631e58..9ef8f18330 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@@ -11,6 +11,7 @@ import type {IOSSimulatorH264FramePush,IOSSimulatorLiveTouchRequest,IOSSimulatorPublicInstance,+ IOSSimulatorRetryNativeRouteRequest,IOSSimulatorRouteStatusPush,IOSSimulatorSessionStatus,IOSSimulatorToolResponse,@@ -217,6 +218,12 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {};},);+ const retryNativeRoute = vi.fn(+ async (request: IOSSimulatorRetryNativeRouteRequest): Promise<IOSSimulatorToolResponse> => {+ void request;+ return { ok: true, data: { nativeRecovered: true } };+ },+ );const setStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));let h264FrameListener: ((payload: IOSSimulatorH264FramePush) => void) | null = null;let routeStatusListener: ((payload: IOSSimulatorRouteStatusPush) => void) | null = null;@@ -262,6 +269,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {call: typeof call;setAgentControl: typeof setAgentControl;setViewerVisibility: typeof setViewerVisibility;+ retryNativeRoute: typeof retryNativeRoute;latestFrame: typeof latestFrame;setStreamProfile: typeof setStreamProfile;liveTouch: typeof liveTouch;@@ -280,6 +288,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {call,setAgentControl,setViewerVisibility,+ retryNativeRoute,latestFrame,setStreamProfile,liveTouch,@@ -295,6 +304,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {call,setAgentControl,setViewerVisibility,+ retryNativeRoute,latestFrame,setStreamProfile,liveTouch,@@ -1276,11 +1286,23 @@ describe('IOSSimulatorTabBody', () => {state: 'fallback',reasonCode: 'native-decoder-fallback',},+ input: {+ adapter: 'wda',+ state: 'fallback',+ continuous: false,+ multiTouch: false,+ reasonCode: 'native-sidecar-unavailable',+ },});});await waitFor(() => {expect(screen.getByText('rightSidebar.iosSimulator.route.wdaJpeg')).toBeTruthy();});+ expect(+ screen.queryByRole('button', {+ name: 'rightSidebar.iosSimulator.nativeRecovery.action',+ }),+ ).toBeNull();act(() => {visibilityState = 'hidden';@@ -1457,6 +1479,197 @@ describe('IOSSimulatorTabBody', () => {});});+ it('lets the current viewer explicitly re-arm Native without disabling WDA controls', 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-sidecar-unavailable',+ },+ input: {+ adapter: 'wda',+ state: 'fallback',+ continuous: false,+ multiTouch: false,+ reasonCode: 'native-sidecar-unavailable',+ },+ },+ ];+ const api = installStatus(statusValue);+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());+ api.latestFrame.mockResolvedValue(streamingJpegResult());+ let resolveRecovery!: (value: IOSSimulatorToolResponse) => void;+ api.retryNativeRoute.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveRecovery = resolve;+ }),+ );++ const rendered = render(+ <IOSSimulatorTabBody+ state={{ instanceId: instance.instanceId }}+ ctx={ctx}+ active+ shellVisible+ />,+ );++ const recoveryButton = await screen.findByRole('button', {+ name: 'rightSidebar.iosSimulator.nativeRecovery.action',+ });+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());+ const image = rendered.container.querySelector('img');+ expect(image?.className).toContain('w-full');+ expect(image?.className).not.toContain('max-h-[520px]');+ const textInput = screen.getByLabelText(+ 'rightSidebar.iosSimulator.textInputLabel',+ ) as HTMLInputElement;+ expect(textInput.disabled).toBe(false);++ fireEvent.click(recoveryButton);+ await waitFor(() => {+ expect(api.retryNativeRoute).toHaveBeenCalledWith({+ sessionId: 'session-a',+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ viewerToken: expect.any(String),+ });+ expect(+ (+ screen.getByRole('button', {+ name: 'rightSidebar.iosSimulator.nativeRecovery.recoveringAction',+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(true);+ });+ expect(textInput.disabled).toBe(false);++ resolveRecovery({ ok: true, data: { nativeRecovered: false } });+ await screen.findByText('rightSidebar.iosSimulator.nativeRecovery.failed');+ expect(rendered.container.querySelector('img')).toBeTruthy();+ expect(textInput.disabled).toBe(false);+ });++ it('ignores an explicit Native recovery result after the viewer switches devices', async () => {+ const statusValue = multiReadyStatus();+ if (!statusValue.ok) throw new Error('Expected a ready simulator status.');+ statusValue.routeStatuses = statusValue.instances.map((instance) => ({+ 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-sidecar-unavailable',+ },+ input: {+ adapter: 'wda',+ state: 'fallback',+ continuous: false,+ multiTouch: false,+ reasonCode: 'native-sidecar-unavailable',+ },+ }));+ const api = installStatus(statusValue);+ const jpegResult = (+ request: IOSSimulatorViewerVisibilityRequest,+ ): IOSSimulatorToolResponse => ({+ ok: true,+ data: {+ stream: {+ instanceId: request.instanceId,+ generation: request.generation,+ state: 'streaming',+ reconnectAttempt: 0,+ latestFrame: {+ instanceId: request.instanceId,+ generation: request.generation,+ sequence: 1,+ encoding: 'jpeg',+ receivedAt: '2026-08-06T00:00:00.000Z',+ bytes: new Uint8Array([1, 2, 3]),+ },+ },+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },+ },+ });+ api.setViewerVisibility.mockImplementation(async (request) => jpegResult(request));+ api.latestFrame.mockImplementation(async (request?: unknown) =>+ jpegResult({+ ...(request as IOSSimulatorViewerVisibilityRequest),+ viewerToken: 'poll',+ visible: true,+ preferredEncoding: 'jpeg',+ }),+ );+ let resolveA!: (value: IOSSimulatorToolResponse) => void;+ let resolveB!: (value: IOSSimulatorToolResponse) => void;+ api.retryNativeRoute.mockImplementation(+ (request) =>+ new Promise((resolve) => {+ if (request.instanceId === 'instance-a') resolveA = resolve;+ else resolveB = resolve;+ }),+ );++ const rendered = render(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,+ );+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'rightSidebar.iosSimulator.nativeRecovery.action',+ }),+ );+ await waitFor(() => expect(api.retryNativeRoute).toHaveBeenCalledTimes(1));++ rendered.rerender(+ <IOSSimulatorTabBody state={{ instanceId: 'instance-b' }} ctx={ctx} active shellVisible />,+ );+ const recoveryButtonB = await screen.findByRole('button', {+ name: 'rightSidebar.iosSimulator.nativeRecovery.action',+ });+ fireEvent.click(recoveryButtonB);+ await waitFor(() => {+ expect(api.retryNativeRoute).toHaveBeenCalledTimes(2);+ expect(api.retryNativeRoute).toHaveBeenLastCalledWith(+ expect.objectContaining({ instanceId: 'instance-b' }),+ );+ });++ await act(async () => {+ resolveA({ ok: true, data: { nativeRecovered: false } });+ await Promise.resolve();+ });+ expect(+ (+ screen.getByRole('button', {+ name: 'rightSidebar.iosSimulator.nativeRecovery.recoveringAction',+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(true);+ expect(screen.queryByText('rightSidebar.iosSimulator.nativeRecovery.failed')).toBeNull();++ await act(async () => {+ resolveB({ ok: true, data: { nativeRecovered: false } });+ await Promise.resolve();+ });+ await screen.findByText('rightSidebar.iosSimulator.nativeRecovery.failed');+ });+it('streams pointer samples through native touch and temporarily boosts frame rate', async () => {const api = installStatus({ok: true,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 3dbfa71296..4e03711b7a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4758,6 +4758,13 @@"unavailable": "Unavailable"}},+ "nativeRecovery": {+ "available": "Native acceleration is unavailable. WDA stays active while you try again.",+ "action": "Restore Native",+ "recovering": "Restoring Native acceleration. The current WDA view and controls stay active.",+ "recoveringAction": "Restoring Native…",+ "failed": "Native acceleration could not be restored. WDA is still active; try again later."+ },"stream": {"idle": "Idle","connecting": "Connecting",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 3ff84b50d4..980d8e2bd2 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4756,6 +4756,13 @@"unavailable": "利用不可"}},+ "nativeRecovery": {+ "available": "Native アクセラレーションは現在利用できません。再試行中も WDA の画面と操作は利用できます。",+ "action": "Native を復旧",+ "recovering": "Native アクセラレーションを復旧しています。現在の WDA の画面と操作は引き続き利用できます。",+ "recoveringAction": "Native を復旧中…",+ "failed": "Native アクセラレーションを復旧できませんでした。WDA は引き続き利用できます。しばらくしてから再試行してください。"+ },"stream": {"idle": "待機中","connecting": "接続中",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 114c479548..46595ba384 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4756,6 +4756,13 @@"unavailable": "사용할 수 없음"}},+ "nativeRecovery": {+ "available": "현재 Native 가속을 사용할 수 없습니다. 다시 시도하는 동안에도 WDA 화면과 제어는 계속 사용할 수 있습니다.",+ "action": "Native 복구 시도",+ "recovering": "Native 가속을 복구하는 중입니다. 현재 WDA 화면과 제어는 계속 사용할 수 있습니다.",+ "recoveringAction": "Native 복구 중…",+ "failed": "Native 가속을 복구하지 못했습니다. WDA는 계속 사용할 수 있으니 나중에 다시 시도하세요."+ },"stream": {"idle": "대기 중","connecting": "연결 중",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 23253eb3a4..7386799fe5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4756,6 +4756,13 @@"unavailable": "不可用"}},+ "nativeRecovery": {+ "available": "Native 加速当前不可用。重试期间,WDA 画面和控制会保持可用。",+ "action": "尝试恢复 Native",+ "recovering": "正在恢复 Native 加速,当前 WDA 画面和控制会保持可用。",+ "recoveringAction": "正在恢复 Native…",+ "failed": "暂未恢复 Native 加速,WDA 仍可正常使用。请稍后重试。"+ },"stream": {"idle": "待连接","connecting": "连接中",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 00dac4d299..ebd5748da0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4756,6 +4756,13 @@"unavailable": "不可用"}},+ "nativeRecovery": {+ "available": "Native 加速目前無法使用。重試期間,WDA 畫面和控制會保持可用。",+ "action": "嘗試恢復 Native",+ "recovering": "正在恢復 Native 加速,目前的 WDA 畫面和控制會保持可用。",+ "recoveringAction": "正在恢復 Native…",+ "failed": "暫時無法恢復 Native 加速,WDA 仍可正常使用。請稍後再試。"+ },"stream": {"idle": "待連線","connecting": "連線中",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 7bf33a637f..f0ef508069 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -46,6 +46,8 @@ type IOSSimulatorViewerRouteRequest =import('../shared/iosSimulatorIpc').IOSSimulatorViewerRouteRequest;type IOSSimulatorViewerVisibilityRequest =import('../shared/iosSimulatorIpc').IOSSimulatorViewerVisibilityRequest;+type IOSSimulatorRetryNativeRouteRequest =+ import('../shared/iosSimulatorIpc').IOSSimulatorRetryNativeRouteRequest;type IOSSimulatorStreamProfileRequest =import('../shared/iosSimulatorIpc').IOSSimulatorStreamProfileRequest;type ProviderRoutingPayload = import('@cindy/model-providers').Provider['routing'];@@ -5952,6 +5954,9 @@ interface ElectronAPI {setViewerVisibility: (request: IOSSimulatorViewerVisibilityRequest,) => Promise<IOSSimulatorToolResponse>;+ retryNativeRoute: (+ request: IOSSimulatorRetryNativeRouteRequest,+ ) => Promise<IOSSimulatorToolResponse>;latestFrame: (request: IOSSimulatorViewerRouteRequest) => Promise<IOSSimulatorToolResponse>;setStreamProfile: (request: IOSSimulatorStreamProfileRequest,diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.tsindex e014e1f90a..d8c44a9edc 100644--- a/apps/desktop/src/shared/iosSimulatorIpc.ts+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts@@ -183,6 +183,11 @@ export interface IOSSimulatorViewerVisibilityRequest extends IOSSimulatorViewerRfallbackReason?: 'native-decoder-fallback';}+export interface IOSSimulatorRetryNativeRouteRequest extends IOSSimulatorViewerRouteRequest {+ /** Exact viewer effect lifetime that is allowed to re-arm Native acceleration. */+ viewerToken: string;+}+export type IOSSimulatorNativeH264StreamProfileRequest = Pick<IOSSimulatorNativeStreamProfile,'framesPerSecond' | 'scalingPercent'