Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): iOS Simulator Native 默认使用 30 FPS 原尺寸 (#4996)

JiangJiahao25e7f166389e
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 f6e355471e..551a640e09 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
@@ -439,6 +439,9 @@ export function IOSSimulatorTabBody({
const pointerGestureRef = useRef<PointerGesture | null>(null);
const gestureSequenceRef = useRef(0);
const streamProfileRef = useRef<StreamProfileName>('balanced');
+ // Transport defaults must not replace a profile the user explicitly selected.
+ const streamProfileCustomizedRef = useRef(false);
+ const streamProfileRequestRef = useRef(0);
const profileRouteRef = useRef<{
routeKey: string | null;
viewerToken: string | null;
@@ -1287,6 +1290,7 @@ export function IOSSimulatorTabBody({
const route = routeFor(attachedInstance);
const routeKey = `${route.instanceId}:${route.generation}`;
const viewerIdentity = viewerIdentityRef.current;
+ const requestId = streamProfileRequestRef.current;
if (!viewerIdentity || viewerIdentity.routeKey !== routeKey) return null;
if (!(await viewerIdentity.ready)) return null;
if (viewerIdentityRef.current?.viewerToken !== viewerIdentity.viewerToken) return null;
@@ -1296,7 +1300,11 @@ export function IOSSimulatorTabBody({
viewerToken: viewerIdentity.viewerToken,
...viewerStreamProfile(profileName, useNativeProfile),
});
- if (result.ok) {
+ if (
+ result.ok &&
+ requestId === streamProfileRequestRef.current &&
+ viewerIdentityRef.current === viewerIdentity
+ ) {
nativeProfileAppliedRef.current = useNativeProfile
? {
routeKey: `${route.instanceId}:${route.generation}`,
@@ -1312,21 +1320,32 @@ export function IOSSimulatorTabBody({
const applyStreamProfile = useCallback(
async (requested: StreamProfileName) => {
if (!attachedInstance) return;
+ const requestId = ++streamProfileRequestRef.current;
+ const viewerIdentity = viewerIdentityRef.current;
+ const requestIsCurrent = () =>
+ requestId === streamProfileRequestRef.current &&
+ viewerIdentityRef.current === viewerIdentity;
const next = requested === 'experimental60' && !nativeH264Active ? 'high' : requested;
const previous = streamProfile;
+ const previouslyCustomized = streamProfileCustomizedRef.current;
setStreamProfile(next);
streamProfileRef.current = next;
+ streamProfileCustomizedRef.current = true;
setActionError(null);
try {
const result = await sendStreamProfile(next, nativeH264Active);
+ if (!requestIsCurrent()) return;
if (result && !result.ok) {
setStreamProfile(previous);
streamProfileRef.current = previous;
+ streamProfileCustomizedRef.current = previouslyCustomized;
setActionError(formatActionError(result));
}
} catch {
+ if (!requestIsCurrent()) return;
setStreamProfile(previous);
streamProfileRef.current = previous;
+ streamProfileCustomizedRef.current = previouslyCustomized;
setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));
}
},
@@ -1378,8 +1397,10 @@ export function IOSSimulatorTabBody({
}, [attachedInstance, ctx.sessionId, nativeRecoveryPending, refresh, viewerRouteKey]);
useEffect(() => {
+ streamProfileRequestRef.current += 1;
setStreamProfile('balanced');
streamProfileRef.current = 'balanced';
+ streamProfileCustomizedRef.current = false;
nativeProfileAppliedRef.current = null;
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
}, [
@@ -1405,6 +1426,12 @@ export function IOSSimulatorTabBody({
nativeActive: nativeH264Active,
};
profileRouteRef.current = nextRoute;
+ if (
+ previous?.nativeSelected !== nativeH264Selected ||
+ previous?.nativeActive !== nativeH264Active
+ ) {
+ streamProfileRequestRef.current += 1;
+ }
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready' || !viewerReadyToken)
return;
const viewerChanged = previous?.viewerToken !== viewerReadyToken;
@@ -1415,8 +1442,11 @@ export function IOSSimulatorTabBody({
previous?.nativeSelected ||
streamProfileRef.current === 'experimental60'
) {
- const nextProfile =
- streamProfileRef.current === 'experimental60' ? 'high' : streamProfileRef.current;
+ const nextProfile = !streamProfileCustomizedRef.current
+ ? 'balanced'
+ : streamProfileRef.current === 'experimental60'
+ ? 'high'
+ : streamProfileRef.current;
setStreamProfile(nextProfile);
streamProfileRef.current = nextProfile;
void sendStreamProfile(nextProfile, false).catch(() => undefined);
@@ -1429,20 +1459,38 @@ export function IOSSimulatorTabBody({
}
return;
}
+ const nextProfile = streamProfileCustomizedRef.current ? streamProfileRef.current : 'high';
const applied = nativeProfileAppliedRef.current;
- if (applied?.routeKey === viewerRouteKey && applied.profile === streamProfileRef.current)
+ if (applied?.routeKey === viewerRouteKey && applied.profile === nextProfile) {
+ setStreamProfile(nextProfile);
+ streamProfileRef.current = nextProfile;
return;
- void sendStreamProfile(streamProfileRef.current, true)
+ }
+ const requestId = ++streamProfileRequestRef.current;
+ const viewerIdentity = viewerIdentityRef.current;
+ const requestIsCurrent = () =>
+ requestId === streamProfileRequestRef.current && viewerIdentityRef.current === viewerIdentity;
+ void sendStreamProfile(nextProfile, true)
.then((result) => {
- if (result && !result.ok) setActionError(formatActionError(result));
+ if (!requestIsCurrent()) return;
+ if (result?.ok) {
+ setStreamProfile(nextProfile);
+ streamProfileRef.current = nextProfile;
+ } else if (result) {
+ setActionError(formatActionError(result));
+ }
})
- .catch(() => undefined);
+ .catch(() => {
+ if (requestIsCurrent())
+ setActionError(t('rightSidebar.iosSimulator.operationErrorWithRecovery'));
+ });
}, [
attachedInstance,
formatActionError,
nativeH264Active,
nativeH264Selected,
sendStreamProfile,
+ t,
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 d8c83d1f3c..a083e80121 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
@@ -19,9 +19,10 @@ import type {
} from '../../../../../../shared/iosSimulatorIpc';
import type { TabKindHostContext } from '../../../types';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
+vi.mock('react-i18next', () => {
+ const t = (key: string) => key;
+ return { useTranslation: () => ({ t }) };
+});
const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('@/lib/toast', () => ({ toast: toastMocks }));
@@ -90,7 +91,7 @@ function readyInstance(generation = 2): IOSSimulatorPublicInstance {
};
}
-function readyStatus(instance = readyInstance()): IOSSimulatorSessionStatus {
+function readyStatus(instance = readyInstance()): Extract<IOSSimulatorSessionStatus, { ok: true }> {
return {
ok: true,
sessionId: 'session-a',
@@ -111,6 +112,28 @@ function readyStatus(instance = readyInstance()): IOSSimulatorSessionStatus {
};
}
+function nativeH264RouteStatus(instance = readyInstance()): IOSSimulatorRouteStatusPush {
+ return {
+ sessionId: instance.sessionId,
+ 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',
+ },
+ };
+}
+
function multiReadyStatus(
mutationStates: IOSSimulatorMutationState[] = [],
): IOSSimulatorSessionStatus {
@@ -238,7 +261,10 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
return { ok: true, data: { nativeRecovered: true } };
},
);
- const setStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));
+ const setStreamProfile = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
+ ok: true,
+ data: {},
+ }));
let h264FrameListener: ((payload: IOSSimulatorH264FramePush) => void) | null = null;
let routeStatusListener: ((payload: IOSSimulatorRouteStatusPush) => void) | null = null;
let focusRequestListener: ((payload: IOSSimulatorFocusRequest) => void) | null = null;
@@ -363,6 +389,22 @@ async function openStreamProfileControls(): Promise<void> {
});
}
+function deferredProfileResponse() {
+ let resolve!: (result: IOSSimulatorToolResponse) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<IOSSimulatorToolResponse>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+const profileFailure: IOSSimulatorToolResponse = {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The stream profile could not be applied.',
+};
+
beforeEach(() => {
toastMocks.success.mockReset();
toastMocks.error.mockReset();
@@ -991,6 +1033,518 @@ describe('IOSSimulatorTabBody', () => {
});
});
+ it.each([false, true])(
+ 'defaults Native H.264 to 30 FPS at full scale and restores the WDA default (initially native: %s)',
+ async (initiallyNative) => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus({
+ ...readyStatus(),
+ routeStatuses: initiallyNative ? [nativeRoute] : [],
+ });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+
+ if (!initiallyNative) {
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ }),
+ );
+ });
+ act(() => api.emitRouteStatus(nativeRoute));
+ }
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ }),
+ );
+ });
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.highNative',
+ })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-2',
+ viewerToken: expect.any(String),
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ });
+ });
+ expect(
+ screen
+ .getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.balanced',
+ })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:02.000Z',
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ }),
+ );
+ });
+ expect(
+ screen
+ .getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.highNative',
+ })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ },
+ );
+
+ it.each([
+ { profile: 'low', beforeNative: true, fps: 5, scale: 50, wdaFps: 5, quality: 25 },
+ { profile: 'balanced', beforeNative: true, fps: 20, scale: 70, wdaFps: 10, quality: 45 },
+ { profile: 'low', beforeNative: false, fps: 5, scale: 50, wdaFps: 5, quality: 25 },
+ { profile: 'balanced', beforeNative: false, fps: 20, scale: 70, wdaFps: 10, quality: 45 },
+ ])(
+ 'preserves explicit $profile through Native recovery (selected before Native: $beforeNative)',
+ async ({ profile, beforeNative, fps, scale, wdaFps, quality }) => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus({
+ ...readyStatus(),
+ routeStatuses: beforeNative ? [] : [nativeRoute],
+ });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalled());
+ await openStreamProfileControls();
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: `rightSidebar.iosSimulator.streamProfiles.${
+ profile === 'balanced' && !beforeNative ? 'balancedNative' : profile
+ }`,
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ profile: { framesPerSecond: wdaFps, jpegQuality: quality, scalingPercent: scale },
+ }),
+ );
+ });
+ if (beforeNative) act(() => api.emitRouteStatus(nativeRoute));
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: fps, scalingPercent: scale },
+ }),
+ );
+ });
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-2',
+ viewerToken: expect.any(String),
+ profile: { framesPerSecond: wdaFps, jpegQuality: quality, scalingPercent: scale },
+ });
+ });
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:02.000Z',
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: fps, scalingPercent: scale },
+ }),
+ );
+ });
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', {
+ name: `rightSidebar.iosSimulator.streamProfiles.${
+ profile === 'balanced' ? 'balancedNative' : profile
+ }`,
+ })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ },
+ );
+
+ it('resets the Native default for a new instance generation after a manual selection', async () => {
+ const api = installStatus({ ...readyStatus(), routeStatuses: [nativeH264RouteStatus()] });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ }),
+ );
+ });
+ await openStreamProfileControls();
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.balancedNative',
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: 20, scalingPercent: 70 },
+ }),
+ );
+ });
+ const nextInstance = readyInstance(3);
+ api.setStatusValue({
+ ...readyStatus(nextInstance),
+ routeStatuses: [nativeH264RouteStatus(nextInstance)],
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.refresh' }));
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ generation: 3,
+ leaseId: 'lease-3',
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ }),
+ );
+ });
+ });
+
+ it('keeps following transport defaults when a manual profile request fails', async () => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus({ ...readyStatus(), routeStatuses: [nativeRoute] });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ }),
+ );
+ });
+ await openStreamProfileControls();
+ api.setStreamProfile.mockRejectedValueOnce(new Error('profile unavailable'));
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.low',
+ }),
+ );
+ await screen.findByText('rightSidebar.iosSimulator.operationErrorWithRecovery');
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ }),
+ );
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },
+ }),
+ );
+ });
+ });
+
+ it.each(['response', 'rejection'] as const)(
+ 'ignores an older manual profile failure after a newer selection succeeds (%s)',
+ async (failure) => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus({ ...readyStatus(), routeStatuses: [nativeRoute] });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(1));
+ await openStreamProfileControls();
+ const olderRequest = deferredProfileResponse();
+ api.setStreamProfile.mockImplementationOnce(() => olderRequest.promise);
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.low',
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(2));
+ await openStreamProfileControls();
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.balancedNative',
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(3));
+
+ await act(async () => {
+ if (failure === 'response') olderRequest.resolve(profileFailure);
+ else olderRequest.reject(new Error('Older profile request failed'));
+ });
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.balancedNative',
+ })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ expect(screen.queryByText('rightSidebar.iosSimulator.operationErrorWithRecovery')).toBeNull();
+
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(4));
+ act(() => api.emitRouteStatus({ ...nativeRoute, updatedAt: '2026-08-06T00:00:02.000Z' }));
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ nativeProfile: { framesPerSecond: 20, scalingPercent: 70 },
+ }),
+ );
+ });
+ },
+ );
+
+ it.each(['response', 'rejection'] as const)(
+ 'keeps the prior profile when the Native default fails on a stable route (%s)',
+ async (failure) => {
+ const api = installStatus(readyStatus());
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(1));
+ const pendingDefault = deferredProfileResponse();
+ api.setStreamProfile.mockImplementationOnce(() => pendingDefault.promise);
+ act(() => api.emitRouteStatus(nativeH264RouteStatus()));
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(2));
+ await openStreamProfileControls();
+ const balancedOption = screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.balancedNative',
+ });
+ expect(balancedOption.getAttribute('aria-checked')).toBe('true');
+
+ await act(async () => {
+ if (failure === 'response') pendingDefault.resolve(profileFailure);
+ else pendingDefault.reject(new Error('Default profile request failed'));
+ });
+ expect(balancedOption.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('rightSidebar.iosSimulator.operationErrorWithRecovery')).toBeTruthy();
+ expect(api.setStreamProfile).toHaveBeenCalledTimes(2);
+
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.highNative',
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(3));
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.highNative',
+ })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ },
+ );
+
+ it.each(['success', 'response', 'rejection'] as const)(
+ 'ignores a stale Native default result after a manual selection (%s)',
+ async (completion) => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus(readyStatus());
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(1));
+ const pendingDefault = deferredProfileResponse();
+ api.setStreamProfile.mockImplementationOnce(() => pendingDefault.promise);
+ act(() => api.emitRouteStatus(nativeRoute));
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(2));
+ await openStreamProfileControls();
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.low',
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(3));
+ await act(async () => {
+ if (completion === 'rejection') pendingDefault.reject(new Error('Default failed late'));
+ else
+ pendingDefault.resolve(
+ completion === 'success' ? { ok: true, data: {} } : profileFailure,
+ );
+ });
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', { name: 'rightSidebar.iosSimulator.streamProfiles.low' })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ expect(screen.queryByText('rightSidebar.iosSimulator.operationErrorWithRecovery')).toBeNull();
+
+ // A stale success must not overwrite the record of the newer applied profile either.
+ await act(async () =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: { ...nativeRoute.stream, state: 'reconnecting' },
+ }),
+ );
+ await act(async () =>
+ api.emitRouteStatus({ ...nativeRoute, updatedAt: '2026-08-06T00:00:02.000Z' }),
+ );
+ expect(api.setStreamProfile).toHaveBeenCalledTimes(3);
+ },
+ );
+
+ it('ignores a Native default confirmation after falling back to WDA', async () => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus(readyStatus());
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(1));
+ const pendingDefault = deferredProfileResponse();
+ api.setStreamProfile.mockImplementationOnce(() => pendingDefault.promise);
+ act(() => api.emitRouteStatus(nativeRoute));
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(2));
+ act(() =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(3));
+ await act(async () => pendingDefault.resolve({ ok: true, data: {} }));
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', { name: 'rightSidebar.iosSimulator.streamProfiles.balanced' })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ });
+
+ it('restores the confirmed Native default when the WDA profile request failed', async () => {
+ const nativeRoute = nativeH264RouteStatus();
+ const api = installStatus({ ...readyStatus(), routeStatuses: [nativeRoute] });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(1));
+ api.setStreamProfile.mockRejectedValueOnce(new Error('WDA profile unavailable'));
+ await act(async () =>
+ api.emitRouteStatus({
+ ...nativeRoute,
+ updatedAt: '2026-08-06T00:00:01.000Z',
+ stream: {
+ adapter: 'wda',
+ encoding: 'jpeg',
+ state: 'fallback',
+ reasonCode: 'native-stream-disconnected',
+ },
+ }),
+ );
+ expect(api.setStreamProfile).toHaveBeenCalledTimes(2);
+ await act(async () =>
+ api.emitRouteStatus({ ...nativeRoute, updatedAt: '2026-08-06T00:00:02.000Z' }),
+ );
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', { name: 'rightSidebar.iosSimulator.streamProfiles.highNative' })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ expect(api.setStreamProfile).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not roll an old manual request back into a new instance generation', async () => {
+ const api = installStatus({ ...readyStatus(), routeStatuses: [nativeH264RouteStatus()] });
+ render(<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active />);
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(1));
+ await openStreamProfileControls();
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.balancedNative',
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(2));
+ const olderRequest = deferredProfileResponse();
+ api.setStreamProfile.mockImplementationOnce(() => olderRequest.promise);
+ await openStreamProfileControls();
+ fireEvent.click(
+ screen.getByRole('menuitemradio', {
+ name: 'rightSidebar.iosSimulator.streamProfiles.low',
+ }),
+ );
+ await waitFor(() => expect(api.setStreamProfile).toHaveBeenCalledTimes(3));
+ const nextInstance = readyInstance(3);
+ api.setStatusValue({
+ ...readyStatus(nextInstance),
+ routeStatuses: [nativeH264RouteStatus(nextInstance)],
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.refresh' }));
+ await waitFor(() => {
+ expect(api.setStreamProfile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ generation: 3,
+ nativeProfile: { framesPerSecond: 30, scalingPercent: 100 },
+ }),
+ );
+ });
+ await act(async () => olderRequest.reject(new Error('Old generation request failed')));
+ await openStreamProfileControls();
+ expect(
+ screen
+ .getByRole('menuitemradio', { name: 'rightSidebar.iosSimulator.streamProfiles.highNative' })
+ .getAttribute('aria-checked'),
+ ).toBe('true');
+ expect(screen.queryByText('rightSidebar.iosSimulator.operationErrorWithRecovery')).toBeNull();
+ });
+
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);
diff --git a/apps/mobile/scripts/test-incoming-share-feedback.mjs b/apps/mobile/scripts/test-incoming-share-feedback.mjs
index 4c2d7c31d7..1c824cb0d2 100644
--- a/apps/mobile/scripts/test-incoming-share-feedback.mjs
+++ b/apps/mobile/scripts/test-incoming-share-feedback.mjs
@@ -1,10 +1,39 @@
// Executes the generated Swift launch/feedback methods with deterministic UIKit
-// and clock doubles. Requires macOS + Swift; no simulator or signing is needed.
+// and clock doubles. Requires Swift; no simulator or signing is needed.
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { createRequire } from "node:module";
import { execFileSync } from "node:child_process";
+
+function runPhase(phase, command, args, timeout) {
+ const started = performance.now();
+ console.error(`[share-feedback] START ${phase} (timeout=${timeout}ms)`);
+ try {
+ execFileSync(command, args, {
+ stdio: "inherit",
+ timeout,
+ killSignal: "SIGKILL",
+ });
+ console.error(
+ `[share-feedback] PASS ${phase} (${Math.round(performance.now() - started)}ms)`,
+ );
+ return true;
+ } catch (error) {
+ // Compilation doubles as the capability check: a separate --version process
+ // can time out before the real test starts. Only a missing compiler may skip.
+ if (phase === "compile" && error.code === "ENOENT") {
+ console.error("[share-feedback] SKIP compile (swiftc not found)");
+ process.exitCode = 77;
+ return false;
+ }
+ console.error(
+ `[share-feedback] FAIL ${phase} (${Math.round(performance.now() - started)}ms, ${error.code ?? `exit ${error.status}`})`,
+ );
+ throw error;
+ }
+}
+
const require = createRequire(import.meta.url);
const { patchShareExtension } = require("../plugins/with-incoming-share-files");
const template = readFileSync(
@@ -137,8 +166,11 @@ const dir = mkdtempSync(join(tmpdir(), "cindy-share-feedback-test-"));
try {
const file = join(dir, "main.swift");
writeFileSync(file, harness);
- execFileSync("swiftc", [file, "-o", join(dir, "test")], { stdio: "inherit" });
- execFileSync(join(dir, "test"), [], { stdio: "inherit" });
+ // Allow cold Swift compilation extra headroom on shared CI runners. Keep the
+ // behavior executable's budget short: its clock and callbacks are simulated.
+ if (runPhase("compile", "swiftc", [file, "-o", join(dir, "test")], 120_000)) {
+ runPhase("execute", join(dir, "test"), [], 10_000);
+ }
} finally {
rmSync(dir, { recursive: true, force: true });
}
diff --git a/apps/mobile/src/__tests__/incomingShareFeedbackScript.test.ts b/apps/mobile/src/__tests__/incomingShareFeedbackScript.test.ts
new file mode 100644
index 0000000000..0fe42d231b
--- /dev/null
+++ b/apps/mobile/src/__tests__/incomingShareFeedbackScript.test.ts
@@ -0,0 +1,150 @@
+import { existsSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { execFileSync } = vi.hoisted(() => ({ execFileSync: vi.fn() }));
+vi.mock("node:child_process", () => ({ execFileSync }));
+const originalExitCode = process.exitCode;
+
+beforeEach(() => {
+ vi.resetModules();
+ execFileSync.mockReset();
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ process.exitCode = originalExitCode;
+ vi.restoreAllMocks();
+});
+
+function temporaryDirectory() {
+ return dirname(execFileSync.mock.calls[0][1][0]);
+}
+
+describe("Swift share feedback test runner", () => {
+ it("bounds compilation and execution separately and cleans up after success", async () => {
+ await import("../../scripts/test-incoming-share-feedback.mjs");
+
+ const directory = temporaryDirectory();
+ expect(execFileSync).toHaveBeenNthCalledWith(
+ 1,
+ "swiftc",
+ [join(directory, "main.swift"), "-o", join(directory, "test")],
+ { stdio: "inherit", timeout: 120_000, killSignal: "SIGKILL" },
+ );
+ expect(execFileSync).toHaveBeenNthCalledWith(
+ 2,
+ join(directory, "test"),
+ [],
+ { stdio: "inherit", timeout: 10_000, killSignal: "SIGKILL" },
+ );
+ expect(execFileSync).toHaveBeenCalledTimes(2);
+ expect(process.exitCode).toBe(originalExitCode);
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringMatching(/^\[share-feedback\] PASS compile \(\d+ms\)$/),
+ );
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringMatching(/^\[share-feedback\] PASS execute \(\d+ms\)$/),
+ );
+ expect(existsSync(directory)).toBe(false);
+ });
+
+ it("skips only a missing compiler, without a version preflight or execution", async () => {
+ execFileSync.mockImplementationOnce(() => {
+ throw Object.assign(new Error("swiftc not found"), { code: "ENOENT" });
+ });
+
+ await import("../../scripts/test-incoming-share-feedback.mjs");
+
+ expect(process.exitCode).toBe(77);
+ expect(execFileSync).toHaveBeenCalledTimes(1);
+ expect(execFileSync.mock.calls[0][0]).toBe("swiftc");
+ expect(execFileSync.mock.calls[0][1][0]).toBe(
+ join(temporaryDirectory(), "main.swift"),
+ );
+ expect(console.error).toHaveBeenCalledWith(
+ "[share-feedback] SKIP compile (swiftc not found)",
+ );
+ expect(console.error).not.toHaveBeenCalledWith(
+ expect.stringContaining("PASS"),
+ );
+ expect(existsSync(temporaryDirectory())).toBe(false);
+ });
+
+ it.each([
+ ["compile", "EACCES"],
+ ["execute", "ENOENT"],
+ ])("does not skip %s with %s", async (phase, code) => {
+ const failure = Object.assign(new Error("Swift command failed"), { code });
+ if (phase === "execute") execFileSync.mockReturnValueOnce(undefined);
+ execFileSync.mockImplementationOnce(() => {
+ throw failure;
+ });
+
+ await expect(
+ import("../../scripts/test-incoming-share-feedback.mjs"),
+ ).rejects.toBe(failure);
+ expect(execFileSync).toHaveBeenCalledTimes(phase === "compile" ? 1 : 2);
+ expect(process.exitCode).toBe(originalExitCode);
+ expect(console.error).not.toHaveBeenCalledWith(
+ expect.stringContaining("SKIP"),
+ );
+ expect(existsSync(temporaryDirectory())).toBe(false);
+ });
+
+ it.each(["compile", "execute"])(
+ "propagates %s failures and cleans up without reporting success",
+ async (phase) => {
+ const failure = Object.assign(new Error("Swift command failed"), {
+ status: 1,
+ });
+ if (phase === "execute") execFileSync.mockReturnValueOnce(undefined);
+ execFileSync.mockImplementationOnce(() => {
+ throw failure;
+ });
+
+ await expect(
+ import("../../scripts/test-incoming-share-feedback.mjs"),
+ ).rejects.toBe(failure);
+ expect(execFileSync).toHaveBeenCalledTimes(phase === "compile" ? 1 : 2);
+ expect(process.exitCode).toBe(originalExitCode);
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringMatching(
+ new RegExp(`^\\[share-feedback\\] FAIL ${phase} \\(\\d+ms, exit 1\\)$`),
+ ),
+ );
+ expect(console.error).not.toHaveBeenCalledWith(
+ expect.stringContaining(`PASS ${phase}`),
+ );
+ expect(existsSync(temporaryDirectory())).toBe(false);
+ },
+ );
+
+ it.each(["compile", "execute"])(
+ "reports %s timeouts as failures, not unavailable Swift",
+ async (phase) => {
+ const timeout = Object.assign(new Error("Swift command timed out"), {
+ code: "ETIMEDOUT",
+ });
+ if (phase === "execute") execFileSync.mockReturnValueOnce(undefined);
+ execFileSync.mockImplementationOnce(() => {
+ throw timeout;
+ });
+
+ await expect(
+ import("../../scripts/test-incoming-share-feedback.mjs"),
+ ).rejects.toBe(timeout);
+ expect(execFileSync).toHaveBeenCalledTimes(phase === "compile" ? 1 : 2);
+ expect(process.exitCode).toBe(originalExitCode);
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringMatching(
+ new RegExp(`^\\[share-feedback\\] FAIL ${phase} \\(\\d+ms, ETIMEDOUT\\)$`),
+ ),
+ );
+ expect(console.error).not.toHaveBeenCalledWith(
+ expect.stringContaining(`PASS ${phase}`),
+ );
+ expect(existsSync(temporaryDirectory())).toBe(false);
+ },
+ );
+});
diff --git a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts
index 25187de098..dc12755b30 100644
--- a/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts
+++ b/apps/mobile/src/__tests__/incomingShareNativePlugin.test.ts
@@ -1,4 +1,4 @@
-import { execFileSync, spawnSync } from "node:child_process";
+import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
@@ -17,19 +17,30 @@ const template = readFileSync(
"utf8",
);
-it("runs the generated Swift launch and feedback behavior", () => {
- if (spawnSync("swiftc", ["--version"], { encoding: "utf8" }).status !== 0)
- return;
+it("runs the generated Swift launch and feedback behavior", ({ skip }) => {
const script = join(
dirname(fileURLToPath(import.meta.url)),
"../../scripts/test-incoming-share-feedback.mjs",
);
- const output = execFileSync(process.execPath, [script], {
+ const started = performance.now();
+ console.info("[share-feedback] START harness (timeout=150000ms)");
+ const result = spawnSync(process.execPath, [script], {
encoding: "utf8",
- timeout: 60_000,
+ stdio: ["ignore", "pipe", "inherit"],
+ // The script bounds compilation at 120s and execution at 10s. Leave room
+ // for Node startup and cleanup. Compilation also checks Swift availability.
+ timeout: 150_000,
+ killSignal: "SIGKILL",
});
- expect(output).toContain("PASS: generated Swift share feedback");
-}, 60_000);
+ console.info(
+ `[share-feedback] END harness (${Math.round(performance.now() - started)}ms, status=${result.status}, error=${(result.error as NodeJS.ErrnoException | undefined)?.code ?? "none"})`,
+ );
+ if (result.error) throw result.error;
+ // The harness reserves 77 for compile ENOENT, never for a timeout or failure.
+ if (result.status === 77) return skip();
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain("PASS: generated Swift share feedback");
+}, 180_000);
describe("incoming share native file ownership", () => {
it("isolates both file-copy and raw-image paths without changing display names", () => {
diff --git a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts
index 7920552c0b..d00ae18bc0 100644
--- a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts
+++ b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts
@@ -17,6 +17,9 @@ import {
warnWindowsGitPathProbeFailure,
} from './windows-git-path-powershell.js';
+// Test-only startup/teardown headroom around the unchanged 10s coordinator.
+const PATH_PROBE_TEST_PROCESS_TIMEOUT_MS = 30_000;
+
describe('Windows Git PATH PowerShell probes', () => {
it('locks the registry probe command and distinguishes missing keys from real failures', () => {
const script = buildWindowsRegistryProbeScript([
@@ -149,22 +152,37 @@ describe('Windows Git PATH PowerShell probes', () => {
`Start-Sleep -Milliseconds ${childDelayMs}\n${Buffer.from(encoded, 'base64').toString('utf16le')}`,
'utf16le',
).toString('base64');
- return execFileSync(
- path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
- ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script.replace(encoded, delayedCommand)],
- {
- encoding: 'utf8',
- input: Buffer.from(JSON.stringify(groups), 'utf8'),
- stdio: ['pipe', 'pipe', 'pipe'],
- timeout: 15_000,
- windowsHide: true,
- },
- );
+ const label = `[windows-git-path-test] child-delay=${childDelayMs}ms`;
+ const instrumentedScript = [
+ `[Console]::Error.WriteLine('${label} START coordinator')`,
+ script.replace(encoded, delayedCommand),
+ `[Console]::Error.WriteLine('${label} END coordinator')`,
+ ].join('\n');
+ const started = performance.now();
+ console.info(`${label} START process (timeout=${PATH_PROBE_TEST_PROCESS_TIMEOUT_MS}ms)`);
+ try {
+ return execFileSync(
+ path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', instrumentedScript],
+ {
+ encoding: 'utf8',
+ input: Buffer.from(JSON.stringify(groups), 'utf8'),
+ stdio: ['pipe', 'pipe', 'inherit'],
+ timeout: PATH_PROBE_TEST_PROCESS_TIMEOUT_MS,
+ windowsHide: true,
+ },
+ );
+ } finally {
+ console.info(`${label} END process (${Math.round(performance.now() - started)}ms)`);
+ }
};
if (delayMs > 0) {
// Outlive even the outer deadline, so scheduler pauses cannot make the
// negative case complete before the coordinator observes expiry.
- const expired = runProbe(buildWindowsPathKindProbeScript(4, 10_000, 2), 30_000);
+ const expired = runProbe(
+ buildWindowsPathKindProbeScript(4, 10_000, 2),
+ PATH_PROBE_TEST_PROCESS_TIMEOUT_MS * 2,
+ );
expect(expired).toMatch(/__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__\tpath-process-(timeout|budget)/);
expect(expired).not.toContain(`F\t${Buffer.from(validGit, 'utf16le').toString('base64')}`);
}
@@ -181,7 +199,7 @@ describe('Windows Git PATH PowerShell probes', () => {
rmSync(tempRoot, { recursive: true, force: true });
}
},
- 40_000,
+ PATH_PROBE_TEST_PROCESS_TIMEOUT_MS * 2 + 10_000,
);
it.runIf(process.platform === 'win32')(