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。

fix(ios-simulator): bind stream profiles to viewers

JiangJiahaofb6fefc294a4
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
index 7a2364ef74..e8ba0f46c3 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
@@ -689,28 +689,39 @@ describe('iOS Simulator IPC handlers', () => {
};
await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
+ viewerToken: 'viewer-token',
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
nativeProfile: { framesPerSecond: 60, scalingPercent: 70 },
});
expect(setViewerStreamProfile).toHaveBeenCalledWith(
'session-a',
{ instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },
+ 17,
+ 'viewer-token',
{ framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
{ framesPerSecond: 60, scalingPercent: 70 },
);
await expect(
harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
+ viewerToken: 'viewer-token',
profile: { framesPerSecond: '10', jpegQuality: 45, scalingPercent: 70 },
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
await expect(
harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
+ viewerToken: 'viewer-token',
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
nativeProfile: { framesPerSecond: '60', scalingPercent: 70 },
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
+ ...route,
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
});
it('validates and routes host-owned live touch samples', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
index 012db7b52e..b4060519fb 100644
--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
@@ -111,6 +111,8 @@ export interface IOSSimulatorHandlerDeps {
setViewerStreamProfile(
sessionId: string,
route: { instanceId: string; generation: number; leaseId: string },
+ viewerWebContentsId: number,
+ viewerToken: string,
profile: { framesPerSecond: number; jpegQuality: number; scalingPercent: number },
nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,
): Promise<IOSSimulatorToolResponse>;
@@ -476,7 +478,14 @@ export function registerIOSSimulatorHandlers(
handle(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
- assertSenderSession(event, sessionId);
+ 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 profile = record.profile;
if (!profile || typeof profile !== 'object' || Array.isArray(profile)) {
throwIpcError('INVALID_PARAMS', 'profile must be an object');
@@ -518,7 +527,14 @@ export function registerIOSSimulatorHandlers(
scalingPercent: Number(candidate.scalingPercent),
};
return callIOSSimulatorHostForSession(event, sessionId, 'set-stream-profile', () =>
- resolved.setViewerStreamProfile(sessionId, route, streamProfile, nativeProfile),
+ resolved.setViewerStreamProfile(
+ sessionId,
+ route,
+ viewerWebContentsId,
+ viewerToken.trim(),
+ streamProfile,
+ nativeProfile,
+ ),
);
});
handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (event, payload) => {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index ca8e85d05c..0f889a6599 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
@@ -3515,9 +3515,13 @@ describe('iOS Simulator host', () => {
endTouch,
} as unknown as IOSSimulatorNativeSidecarDriver;
const getWindowSize = vi.fn(async () => ({ width: 393, height: 852 }));
+ const configureStream = vi.fn(
+ async (_driverSessionId: string, profile: IOSSimulatorStreamProfile) => profile,
+ );
const wdaDriver = {
getWindowSize,
getOrientation: vi.fn(async () => 'PORTRAIT' as const),
+ configureStream,
};
const capabilityReport = () => ({
nativeSidecar: { available: true },
@@ -3663,6 +3667,67 @@ describe('iOS Simulator host', () => {
host.setViewerVisibility('session-a', route, false, 'h264', undefined, 88, 'viewer-d-stale'),
).resolves.toMatchObject({ ok: true, data: { ignored: true } });
+ const profileCallsBeforeStaleRequest = configureStream.mock.calls.length;
+ await expect(
+ host.setViewerStreamProfile('session-a', route, 88, 'viewer-c', {
+ framesPerSecond: 10,
+ jpegQuality: 45,
+ scalingPercent: 70,
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });
+ expect(configureStream).toHaveBeenCalledTimes(profileCallsBeforeStaleRequest);
+
+ const staleProfileDeferred: {
+ resolve: ((profile: IOSSimulatorStreamProfile) => void) | null;
+ } = { resolve: null };
+ configureStream.mockImplementationOnce(
+ (_driverSessionId, profile) =>
+ new Promise((resolve) => {
+ staleProfileDeferred.resolve = resolve;
+ void profile;
+ }),
+ );
+ const staleProfileRequest = host.setViewerStreamProfile(
+ 'session-a',
+ route,
+ 88,
+ 'viewer-e-current',
+ { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ );
+ await vi.waitFor(() => expect(staleProfileDeferred.resolve).not.toBeNull());
+ await expect(
+ host.setViewerVisibility(
+ 'session-a',
+ route,
+ true,
+ 'h264',
+ undefined,
+ 88,
+ 'viewer-profile-current',
+ ),
+ ).resolves.toMatchObject({ ok: true });
+ staleProfileDeferred.resolve?.({
+ framesPerSecond: 10,
+ jpegQuality: 45,
+ scalingPercent: 70,
+ });
+ await expect(staleProfileRequest).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'INSTANCE_NOT_OWNED',
+ });
+ await expect(
+ host.setViewerStreamProfile('session-a', route, 88, 'viewer-profile-current', {
+ framesPerSecond: 20,
+ jpegQuality: 70,
+ scalingPercent: 100,
+ }),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: {
+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
+ },
+ });
+
await expect(
host.updateViewerTouch('session-a', route, 88, {
gestureId: 'gesture-old-viewer',
@@ -3900,7 +3965,7 @@ describe('iOS Simulator host', () => {
};
await expect(
- host.setViewerVisibility('session-a', route, true, 'h264', undefined, 77),
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 77, 'viewer-token'),
).resolves.toMatchObject({
ok: true,
data: { stream: { state: 'connecting' } },
@@ -3953,6 +4018,8 @@ describe('iOS Simulator host', () => {
host.setViewerStreamProfile(
'session-a',
route,
+ 77,
+ 'viewer-token',
fallbackHighProfile,
experimentalNativeProfile,
),
@@ -3964,6 +4031,8 @@ describe('iOS Simulator host', () => {
host.setViewerStreamProfile(
'session-a',
route,
+ 77,
+ 'viewer-token',
fallbackHighProfile,
experimentalNativeProfile,
),
@@ -3985,7 +4054,7 @@ describe('iOS Simulator host', () => {
}),
);
await expect(
- host.setViewerStreamProfile('session-a', route, {
+ host.setViewerStreamProfile('session-a', route, 77, 'viewer-token', {
framesPerSecond: 60,
jpegQuality: 70,
scalingPercent: 70,
@@ -4121,7 +4190,15 @@ describe('iOS Simulator host', () => {
h264Snapshot = { ...h264Snapshot, state: 'connecting' };
await expect(
- host.setViewerVisibility('session-a', latestRoute, true, 'h264'),
+ host.setViewerVisibility(
+ 'session-a',
+ latestRoute,
+ true,
+ 'h264',
+ undefined,
+ 77,
+ 'viewer-token',
+ ),
).resolves.toMatchObject({
ok: true,
data: { stream: { state: 'connecting' } },
@@ -4137,11 +4214,27 @@ describe('iOS Simulator host', () => {
);
await expect(
- host.setViewerVisibility('session-a', latestRoute, false, 'jpeg', undefined, 77),
+ host.setViewerVisibility(
+ 'session-a',
+ latestRoute,
+ false,
+ 'jpeg',
+ undefined,
+ 77,
+ 'viewer-token',
+ ),
).resolves.toMatchObject({ ok: true });
nativeAvailable = false;
await expect(
- host.setViewerVisibility('session-a', latestRoute, true, 'h264', undefined, 77),
+ host.setViewerVisibility(
+ 'session-a',
+ latestRoute,
+ true,
+ 'h264',
+ undefined,
+ 77,
+ 'viewer-reopened',
+ ),
).resolves.toMatchObject({ ok: true });
expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {
rearm: true,
@@ -6635,7 +6728,10 @@ describe('iOS Simulator host', () => {
leaseId: instance.lease.id,
};
await expect(
- host.setViewerStreamProfile('session-a', route, {
+ host.setViewerVisibility('session-a', route, true, 'jpeg', undefined, 17, 'viewer-token'),
+ ).resolves.toMatchObject({ ok: true });
+ await expect(
+ host.setViewerStreamProfile('session-a', route, 17, 'viewer-token', {
framesPerSecond: 10,
jpegQuality: 45,
scalingPercent: 70,
@@ -6644,9 +6740,6 @@ describe('iOS Simulator host', () => {
ok: true,
data: { profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 } },
});
- await expect(
- host.setViewerVisibility('session-a', route, true, 'jpeg', undefined, 17, 'viewer-token'),
- ).resolves.toMatchObject({ ok: true });
await expect(
host.callTool('stop_instance', route, { sessionId: 'session-a', origin: 'agent' }),
).resolves.toMatchObject({ ok: false, errorCode: 'DEVICE_CONTROL_NOT_GRANTED' });
@@ -7360,7 +7453,7 @@ describe('iOS Simulator host', () => {
running = null;
await expect(
- host.setViewerStreamProfile('session-a', route, {
+ host.setViewerStreamProfile('session-a', route, 17, 'viewer-token', {
framesPerSecond: 20,
jpegQuality: 70,
scalingPercent: 100,
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index f59e2781bf..5db5f75d30 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -269,6 +269,8 @@ export interface IOSSimulatorHost {
setViewerStreamProfile(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
+ viewerWebContentsId: number,
+ viewerToken: string,
profile: IOSSimulatorStreamProfile,
nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,
): Promise<IOSSimulatorHostResult>;
@@ -3400,13 +3402,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
sessionId: string,
instanceId: string,
viewerWebContentsId: number,
+ viewerToken?: string,
): void {
const viewer = viewerSessions.get(instanceId);
if (
!viewer ||
viewer.sessionId !== sessionId ||
viewer.webContentsId === null ||
- viewer.webContentsId !== viewerWebContentsId
+ viewer.webContentsId !== viewerWebContentsId ||
+ (viewerToken !== undefined && viewer.viewerToken !== viewerToken)
) {
throw new IOSSimulatorInstanceError(
'INSTANCE_NOT_OWNED',
@@ -4171,7 +4175,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return safeHostError(error, sessionId, `viewer_touch_${touch.phase}`);
}
},
- async setViewerStreamProfile(sessionId, route, profile, nativeProfile) {
+ async setViewerStreamProfile(
+ sessionId,
+ route,
+ viewerWebContentsId,
+ viewerToken,
+ profile,
+ nativeProfile,
+ ) {
let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;
try {
assertHostActive();
@@ -4180,6 +4191,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
removalBarrierOperation = resolved.removalBarrierOperation ?? null;
assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
+ assertCurrentViewer(resolved.sessionId, route.instanceId, viewerWebContentsId, viewerToken);
if (
!Number.isSafeInteger(profile.framesPerSecond) ||
profile.framesPerSecond < 1 ||
@@ -4211,6 +4223,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
const instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });
+ assertCurrentViewer(
+ resolved.sessionId,
+ instance.instanceId,
+ viewerWebContentsId,
+ viewerToken,
+ );
const running = getDriverManager().get(instance.instanceId);
const activeNativeDriver =
nativeProfile && running ? activeNativeH264Driver(instance.instanceId, running) : null;
@@ -4224,6 +4242,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// The viewer may request its fallback profile while WDA is being rebuilt.
// Native-only intent is rejected above because no active route can prove it.
assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
+ assertCurrentViewer(
+ resolved.sessionId,
+ instance.instanceId,
+ viewerWebContentsId,
+ viewerToken,
+ );
streamProfiles.set(instance.instanceId, profile);
nativeStreamProfiles.delete(instance.instanceId);
return { ok: true, data: { profile } };
@@ -4231,6 +4255,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const applied = await running.driver.configureStream(running.driverSessionId, profile);
assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
+ assertCurrentViewer(
+ resolved.sessionId,
+ instance.instanceId,
+ viewerWebContentsId,
+ viewerToken,
+ );
streamProfiles.set(instance.instanceId, applied);
if (nativeProfile) nativeStreamProfiles.set(instance.instanceId, nativeProfile);
else nativeStreamProfiles.delete(instance.instanceId);
@@ -6582,12 +6612,16 @@ export function cleanupIOSSimulatorRemovedSession(sessionId: string): Promise<vo
export function setIOSSimulatorViewerStreamProfile(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
+ viewerWebContentsId: number,
+ viewerToken: string,
profile: IOSSimulatorStreamProfile,
nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,
): Promise<IOSSimulatorHostResult> {
return initializeIOSSimulatorHost().setViewerStreamProfile(
sessionId,
route,
+ viewerWebContentsId,
+ viewerToken,
profile,
nativeProfile,
);
diff --git 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
index 64736f675b..106b168519 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
@@ -431,6 +431,9 @@ export function IOSSimulatorInstanceGrid({
image.onerror = () => URL.revokeObjectURL(url);
image.src = url;
};
+ const viewerTokens = new Map(
+ readyInstances.map((instance) => [instance.instanceId, window.crypto.randomUUID()]),
+ );
const setVisibility = async (visible: boolean) => {
await Promise.all(
readyInstances.map(async (instance) => {
@@ -439,6 +442,7 @@ export function IOSSimulatorInstanceGrid({
...routeFor(instance),
visible,
preferredEncoding: 'jpeg' as const,
+ viewerToken: viewerTokens.get(instance.instanceId)!,
};
const result = await simulatorApi.setViewerVisibility(route).catch(() => null);
if (cancelled) return;
@@ -449,7 +453,12 @@ export function IOSSimulatorInstanceGrid({
instance.instanceId !== selectedInstanceId
) {
await simulatorApi
- .setStreamProfile({ sessionId, ...routeFor(instance), profile: BACKGROUND_PROFILE })
+ .setStreamProfile({
+ sessionId,
+ ...routeFor(instance),
+ viewerToken: viewerTokens.get(instance.instanceId)!,
+ profile: BACKGROUND_PROFILE,
+ })
.catch(() => undefined);
}
}),
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
index 45df41ca5b..86cc8619a2 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
@@ -301,6 +301,7 @@ export function IOSSimulatorTabBody({
const [interactionBusy, setInteractionBusy] = useState(false);
const [textInput, setTextInput] = useState('');
const [streamProfile, setStreamProfile] = useState<StreamProfileName>('balanced');
+ const [viewerReadyToken, setViewerReadyToken] = useState<string | null>(null);
const requestVersionRef = useRef(0);
const frameSequenceRef = useRef(0);
const frameEncodingRef = useRef<'jpeg' | 'h264' | null>(null);
@@ -310,9 +311,15 @@ export function IOSSimulatorTabBody({
const streamProfileRef = useRef<StreamProfileName>('balanced');
const profileRouteRef = useRef<{
routeKey: string | null;
+ viewerToken: string | null;
nativeSelected: boolean;
nativeActive: boolean;
} | null>(null);
+ const viewerIdentityRef = useRef<{
+ routeKey: string;
+ viewerToken: string;
+ ready: Promise<boolean>;
+ } | null>(null);
const nativeProfileAppliedRef = useRef<{
routeKey: string;
profile: StreamProfileName;
@@ -584,7 +591,8 @@ export function IOSSimulatorTabBody({
useEffect(() => {
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
const route = { sessionId: ctx.sessionId, ...routeFor(attachedInstance) };
- const viewerRoute = { ...route, viewerToken: window.crypto.randomUUID() };
+ const viewerToken = window.crypto.randomUUID();
+ const viewerRoute = { ...route, viewerToken };
let cancelled = false;
let polling = false;
let nextRecoveryAt = 0;
@@ -596,6 +604,22 @@ export function IOSSimulatorTabBody({
let routeInactive = false;
let foregroundRecoveryArmed = document.visibilityState !== 'visible';
const routeKey = `${route.instanceId}:${route.generation}`;
+ let viewerReadySettled = false;
+ let resolveViewerReady!: (ready: boolean) => void;
+ const viewerReady = new Promise<boolean>((resolve) => {
+ resolveViewerReady = resolve;
+ });
+ const settleViewerReady = (ready: boolean) => {
+ if (viewerReadySettled) return;
+ viewerReadySettled = true;
+ resolveViewerReady(ready);
+ };
+ const clearViewerReady = () => {
+ setViewerReadyToken((current) => (current === viewerToken ? null : current));
+ };
+ setViewerReadyToken(null);
+ nativeProfileAppliedRef.current = null;
+ viewerIdentityRef.current = { routeKey, viewerToken, ready: viewerReady };
const decoderRuntime = createBrowserIOSSimulatorH264DecoderRuntime();
let decoder: IOSSimulatorH264Decoder | null = null;
frameSequenceRef.current = 0;
@@ -656,6 +680,10 @@ export function IOSSimulatorTabBody({
};
const acceptViewerResult = (result: IOSSimulatorToolResponse) => {
if (!result.ok) {
+ if (result.errorCode !== 'LEASE_EXPIRED' && result.errorCode !== 'STALE_GENERATION') {
+ settleViewerReady(false);
+ clearViewerReady();
+ }
disconnectViewer();
if (
viewerVisible &&
@@ -671,11 +699,17 @@ export function IOSSimulatorTabBody({
}
const nextInstance = resultInstance(result);
if (nextInstance && nextInstance.lifecycleState !== 'ready') {
+ settleViewerReady(false);
+ clearViewerReady();
routeInactive = true;
disconnectViewer();
void refresh();
return;
}
+ if (viewerVisible) {
+ settleViewerReady(true);
+ setViewerReadyToken(viewerToken);
+ }
acceptStream(resultStream(result));
if (nextInstance) void refresh();
const nextViewport = resultViewport(result);
@@ -920,6 +954,11 @@ export function IOSSimulatorTabBody({
void startViewer();
return () => {
cancelled = true;
+ settleViewerReady(false);
+ clearViewerReady();
+ if (viewerIdentityRef.current?.viewerToken === viewerToken) {
+ viewerIdentityRef.current = null;
+ }
decoder?.close();
unsubscribeH264Frame();
document.removeEventListener('visibilitychange', recoverNativeOnForeground);
@@ -1030,9 +1069,15 @@ export function IOSSimulatorTabBody({
): Promise<IOSSimulatorToolResponse | null> => {
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return null;
const route = routeFor(attachedInstance);
+ const routeKey = `${route.instanceId}:${route.generation}`;
+ const viewerIdentity = viewerIdentityRef.current;
+ if (!viewerIdentity || viewerIdentity.routeKey !== routeKey) return null;
+ if (!(await viewerIdentity.ready)) return null;
+ if (viewerIdentityRef.current?.viewerToken !== viewerIdentity.viewerToken) return null;
const result = await window.electronAPI.maker.iosSimulator.setStreamProfile({
sessionId: ctx.sessionId,
...route,
+ viewerToken: viewerIdentity.viewerToken,
...viewerStreamProfile(profileName, useNativeProfile),
});
if (result.ok) {
@@ -1077,19 +1122,11 @@ export function IOSSimulatorTabBody({
streamProfileRef.current = 'balanced';
nativeProfileAppliedRef.current = null;
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
- void window.electronAPI.maker.iosSimulator
- .setStreamProfile({
- sessionId: ctx.sessionId,
- ...routeFor(attachedInstance),
- ...viewerStreamProfile('balanced', false),
- })
- .catch(() => undefined);
}, [
attachedInstance?.generation,
attachedInstance?.instanceId,
attachedInstance?.lease.id,
attachedInstance?.lifecycleState,
- ctx.sessionId,
]);
const applyTransientStreamProfile = useCallback(
@@ -1103,14 +1140,21 @@ export function IOSSimulatorTabBody({
const previous = profileRouteRef.current;
const nextRoute = {
routeKey: viewerRouteKey,
+ viewerToken: viewerReadyToken,
nativeSelected: nativeH264Selected,
nativeActive: nativeH264Active,
};
profileRouteRef.current = nextRoute;
- if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
+ if (!attachedInstance || attachedInstance.lifecycleState !== 'ready' || !viewerReadyToken)
+ return;
+ const viewerChanged = previous?.viewerToken !== viewerReadyToken;
if (!nativeH264Selected) {
- if (previous?.nativeSelected || streamProfileRef.current === 'experimental60') {
+ if (
+ viewerChanged ||
+ previous?.nativeSelected ||
+ streamProfileRef.current === 'experimental60'
+ ) {
const nextProfile =
streamProfileRef.current === 'experimental60' ? 'high' : streamProfileRef.current;
setStreamProfile(nextProfile);
@@ -1119,7 +1163,12 @@ export function IOSSimulatorTabBody({
}
return;
}
- if (!nativeH264Active || !viewerRouteKey) return;
+ if (!nativeH264Active || !viewerRouteKey) {
+ if (viewerChanged) {
+ void sendStreamProfile(streamProfileRef.current, false).catch(() => undefined);
+ }
+ return;
+ }
const applied = nativeProfileAppliedRef.current;
if (applied?.routeKey === viewerRouteKey && applied.profile === streamProfileRef.current)
return;
@@ -1134,6 +1183,7 @@ export function IOSSimulatorTabBody({
nativeH264Active,
nativeH264Selected,
sendStreamProfile,
+ viewerReadyToken,
viewerRouteKey,
]);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
index 31650b902b..3cc0631e58 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
@@ -794,6 +794,7 @@ describe('IOSSimulatorTabBody', () => {
instanceId: instance.instanceId,
generation: instance.generation,
leaseId: instance.lease.id,
+ viewerToken: expect.any(String),
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
});
@@ -806,6 +807,7 @@ describe('IOSSimulatorTabBody', () => {
instanceId: instance.instanceId,
generation: instance.generation,
leaseId: instance.lease.id,
+ viewerToken: expect.any(String),
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
nativeProfile: { framesPerSecond: 60, scalingPercent: 70 },
});
@@ -857,11 +859,45 @@ describe('IOSSimulatorTabBody', () => {
instanceId: instance.instanceId,
generation: instance.generation,
leaseId: instance.lease.id,
+ viewerToken: expect.any(String),
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
});
});
});
+ it('waits for the exact viewer claim before applying its stream profile', async () => {
+ const api = installStatus(readyStatus());
+ let resolveViewerClaim!: (result: IOSSimulatorToolResponse) => void;
+ const viewerClaim = new Promise<IOSSimulatorToolResponse>((resolve) => {
+ resolveViewerClaim = resolve;
+ });
+ api.setViewerVisibility.mockImplementationOnce(async () => viewerClaim);
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => expect(api.setViewerVisibility).toHaveBeenCalledTimes(1));
+ const viewerRequest = api.setViewerVisibility.mock.calls[0]![0];
+ expect(viewerRequest.viewerToken).toEqual(expect.any(String));
+ expect(api.setStreamProfile).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveViewerClaim(streamingJpegResult());
+ await viewerClaim;
+ });
+
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ instanceId: 'instance-a',
+ viewerToken: viewerRequest.viewerToken,
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ }),
+ );
+ });
+ });
+
it('starts frame polling only while the pane is active and visible', async () => {
const api = installStatus({
ok: true,
@@ -929,23 +965,8 @@ describe('IOSSimulatorTabBody', () => {
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.setStreamProfile).not.toHaveBeenCalled();
expect(api.latestFrame).not.toHaveBeenCalled();
rendered.rerender(
@@ -955,8 +976,23 @@ describe('IOSSimulatorTabBody', () => {
expect(api.setViewerVisibility).toHaveBeenCalledWith(
expect.objectContaining({ instanceId: 'instance-a', visible: true }),
);
+ expect(api.setStreamProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ instanceId: 'instance-a',
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ }),
+ );
expect(api.latestFrame).toHaveBeenCalled();
});
+ 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 },
+ }),
+ );
+ });
rendered.rerender(
<IOSSimulatorTabBody
diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.ts
index 13cb0b52ea..e014e1f90a 100644
--- a/apps/desktop/src/shared/iosSimulatorIpc.ts
+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts
@@ -189,6 +189,8 @@ export type IOSSimulatorNativeH264StreamProfileRequest = Pick<
>;
export interface IOSSimulatorStreamProfileRequest extends IOSSimulatorViewerRouteRequest {
+ /** Exact viewer effect lifetime that currently owns stream presentation. */
+ viewerToken: string;
/** Exact compatibility profile kept ready for WDA/MJPEG fallback. */
profile: IOSSimulatorStreamProfile;
/** Optional product profile accepted only while Native H.264 is active. */