import type { PlaygroundRuntimeInfo, PlaygroundSessionTarget, } from '@midscene/playground'; import { sha256Hex } from '@midscene/shared/utils'; import type { DiscoveredDevice, PlatformDiscoveryError, StudioSessionValue, } from '@shared/electron-contract'; import { STUDIO_PLATFORM_IDS } from '@shared/electron-contract'; import type { DiscoveredDevicesByPlatform, DiscoveryErrorsByPlatform, StudioAndroidDeviceItem, StudioSidebarDeviceBuckets, StudioSidebarPlatformKey, } from './types'; function isString(value: unknown): value is string { return typeof value === 'string' && value.length > 0; } function createEmptySidebarDeviceBuckets(): StudioSidebarDeviceBuckets { return { android: [], ios: [], computer: [], harmony: [], web: [], }; } function normalizePort(value: unknown): number | undefined { if (typeof value === 'number' && Number.isFinite(value)) { return value; } if (typeof value === 'string' && value.trim()) { const parsed = Number.parseInt(value, 10); if (Number.isFinite(parsed)) { return parsed; } } return undefined; } function buildHostPortId(host: string, port: number): string { return `${host}:${port}`; } function iosFormValue(formValues: Record, key: string) { const value = formValues[`ios.${key}`] ?? formValues[key]; return typeof value === 'string' && value.trim() ? value.trim() : undefined; } function normalizedGatewayUrl(value: string) { const url = new URL(value); return url.toString().replace(/\/+$/, ''); } export function resolveSelectedIosGatewayId( formValues: Record, ): string | undefined { const baseUrl = iosFormValue(formValues, 'baseUrl'); if (!baseUrl) return undefined; try { const mjpegUrl = iosFormValue(formValues, 'mjpegUrl'); const sessionId = iosFormValue(formValues, 'sessionId'); const mjpegPort = normalizePort( formValues['ios.mjpegPort'] ?? formValues.mjpegPort, ); return `ios-gateway-${sha256Hex( JSON.stringify({ baseUrl: normalizedGatewayUrl(baseUrl), mjpegUrl: mjpegUrl ? new URL(mjpegUrl).toString() : undefined, mjpegPort, sessionId, }), )}`; } catch { return undefined; } } /** * Map any incoming platform string (runtime metadata, form values, desktop * OS aliases like `macos`) to the canonical `StudioPlatformId`. Exported so * other studio renderer modules don't need to keep their own alias tables. */ export function normalizeStudioPlatformId( value: unknown, ): StudioSidebarPlatformKey | undefined { if (!isString(value)) { return undefined; } switch (value.toLowerCase()) { case 'android': return 'android'; case 'ios': return 'ios'; case 'computer': case 'desktop': case 'macos': case 'windows': case 'linux': return 'computer'; case 'harmony': return 'harmony'; case 'web': case 'browser': return 'web'; default: return undefined; } } /** * Platforms use different metadata keys for the device id: * Android / Harmony → metadata.deviceId * Computer → metadata.displayId * iOS → gateway URL digest, or metadata.wdaHost + metadata.wdaPort */ export function resolveConnectedDeviceId( runtimeInfo: PlaygroundRuntimeInfo | null, ): string | undefined { const metadata = runtimeInfo?.metadata || {}; if (isString(metadata.deviceId)) { return metadata.deviceId; } if (isString(metadata.displayId)) { return metadata.displayId; } if (isString(metadata.wdaGatewayId)) { return metadata.wdaGatewayId; } if (isString(metadata.wdaHost)) { const wdaPort = normalizePort(metadata.wdaPort); if (wdaPort !== undefined) { return buildHostPortId(metadata.wdaHost, wdaPort); } } return undefined; } function resolveConnectedSessionValues( runtimeInfo: PlaygroundRuntimeInfo | null, platformKey: StudioSidebarPlatformKey, formValues: Record = {}, ): Record | undefined { const metadata = runtimeInfo?.metadata || {}; switch (platformKey) { case 'android': case 'harmony': return isString(metadata.deviceId) ? { deviceId: metadata.deviceId, } : undefined; case 'computer': return isString(metadata.displayId) ? { displayId: metadata.displayId, } : undefined; case 'ios': { if (isString(metadata.wdaGatewayId)) { return resolveSelectedIosGatewayId(formValues) === metadata.wdaGatewayId ? resolveSelectedSessionValues('ios', formValues) : undefined; } const wdaPort = normalizePort(metadata.wdaPort); if ( isString(metadata.wdaHost) && wdaPort !== undefined && resolveSelectedDeviceId({ ...formValues, platformId: 'ios' }) === buildHostPortId(metadata.wdaHost, wdaPort) ) { return resolveSelectedSessionValues('ios', formValues); } return isString(metadata.wdaHost) && wdaPort !== undefined ? { host: metadata.wdaHost, port: wdaPort, } : undefined; } default: return undefined; } } /** * Human-readable label for whatever device the playground is currently * connected to, across platforms. Prefers the session display name, then * falls back to a concrete device id, then to the platform title, and * finally to `emptyLabel` when nothing is connected. */ export function resolveConnectedDeviceLabel( runtimeInfo: PlaygroundRuntimeInfo | null, options: { emptyLabel: string }, ): string { const metadata = runtimeInfo?.metadata || {}; if (isString(metadata.sessionDisplayName)) { return metadata.sessionDisplayName; } const deviceId = resolveConnectedDeviceId(runtimeInfo); if (deviceId) { if (isString(metadata.wdaGatewayId) && isString(metadata.wdaHost)) { return `${metadata.wdaHost} (WDA gateway)`; } // "Display 1" reads better than a bare numeric id for computer. return isString(metadata.displayId) && !isString(metadata.deviceId) ? `Display ${deviceId}` : deviceId; } if (isString(runtimeInfo?.title)) { return runtimeInfo.title; } return options.emptyLabel; } function buildGenericConnectedDeviceItem( runtimeInfo: PlaygroundRuntimeInfo | null, platformKey: StudioSidebarPlatformKey, formValues: Record, ): StudioAndroidDeviceItem | null { const metadata = runtimeInfo?.metadata || {}; const deviceId = resolveConnectedDeviceId(runtimeInfo); const label = resolveConnectedDeviceLabel(runtimeInfo, { emptyLabel: '' }); if (!label) { return null; } return { id: deviceId || `${platformKey}-connected`, label, description: deviceId && deviceId !== label && !isString(metadata.wdaGatewayId) ? deviceId : undefined, selected: true, status: 'active', sessionValues: resolveConnectedSessionValues( runtimeInfo, platformKey, formValues, ), }; } export function resolveConnectedAndroidDeviceId( runtimeInfo: PlaygroundRuntimeInfo | null, ): string | undefined { return isString(runtimeInfo?.metadata?.deviceId) ? runtimeInfo.metadata.deviceId : undefined; } export function resolveSelectedAndroidDeviceId( formValues: Record, ): string | undefined { if (isString(formValues['android.deviceId'])) { return formValues['android.deviceId']; } return isString(formValues.deviceId) ? formValues.deviceId : undefined; } export function resolveSelectedDeviceId( formValues: Record, ): string | undefined { const selectedPlatform = normalizeStudioPlatformId(formValues.platformId); if (selectedPlatform === 'ios') { const gatewayId = resolveSelectedIosGatewayId(formValues); if (gatewayId) return gatewayId; const host = isString(formValues['ios.host']) ? formValues['ios.host'] : isString(formValues.host) ? formValues.host : undefined; const port = normalizePort(formValues['ios.port'] ?? formValues.port); return host && port !== undefined ? buildHostPortId(host, port) : undefined; } if (selectedPlatform === 'computer') { return isString(formValues['computer.displayId']) ? formValues['computer.displayId'] : isString(formValues.displayId) ? formValues.displayId : undefined; } if (selectedPlatform === 'harmony') { return isString(formValues['harmony.deviceId']) ? formValues['harmony.deviceId'] : isString(formValues.deviceId) ? formValues.deviceId : undefined; } if (selectedPlatform === 'android') { return resolveSelectedAndroidDeviceId(formValues); } if (selectedPlatform === 'web') { return isString(formValues['web.url']) ? formValues['web.url'] : undefined; } return ( resolveSelectedAndroidDeviceId(formValues) || (isString(formValues['computer.displayId']) ? formValues['computer.displayId'] : undefined) || ((): string | undefined => { const host = isString(formValues['ios.host']) ? formValues['ios.host'] : undefined; const port = normalizePort(formValues['ios.port']); return host && port !== undefined ? buildHostPortId(host, port) : undefined; })() ); } function prefixSessionValues( platform: StudioSidebarPlatformKey, sessionValues: Record, ): Record { return Object.fromEntries( Object.entries(sessionValues).map(([key, value]) => [ `${platform}.${key}`, value, ]), ); } function resolveSelectedSessionValues( platform: StudioSidebarPlatformKey, formValues: Record, ): Record | undefined { switch (platform) { case 'android': return isString(formValues['android.deviceId']) ? { deviceId: formValues['android.deviceId'] } : isString(formValues.deviceId) ? { deviceId: formValues.deviceId } : undefined; case 'computer': return isString(formValues['computer.displayId']) ? { displayId: formValues['computer.displayId'] } : isString(formValues.displayId) ? { displayId: formValues.displayId } : undefined; case 'harmony': return isString(formValues['harmony.deviceId']) ? { deviceId: formValues['harmony.deviceId'] } : isString(formValues.deviceId) ? { deviceId: formValues.deviceId } : undefined; case 'ios': { const baseUrl = iosFormValue(formValues, 'baseUrl'); const mjpegUrl = iosFormValue(formValues, 'mjpegUrl'); const sessionId = iosFormValue(formValues, 'sessionId'); const mjpegPort = normalizePort( formValues['ios.mjpegPort'] ?? formValues.mjpegPort, ); if (baseUrl) { return { baseUrl, ...(mjpegUrl ? { mjpegUrl } : {}), ...(mjpegPort !== undefined ? { mjpegPort } : {}), ...(sessionId ? { sessionId } : {}), }; } const host = isString(formValues['ios.host']) ? formValues['ios.host'] : isString(formValues.host) ? formValues.host : undefined; const port = normalizePort(formValues['ios.port'] ?? formValues.port); return host && port !== undefined ? { host, port, ...(mjpegUrl ? { mjpegUrl } : {}), ...(mjpegPort !== undefined ? { mjpegPort } : {}), ...(sessionId ? { sessionId } : {}), } : undefined; } default: return undefined; } } export function buildDeviceSelectionFormValues( platform: StudioSidebarPlatformKey, device: Pick, ): Record { if (device.sessionValues) { if (platform === 'ios') { return { platformId: platform, 'ios.host': null, 'ios.port': null, 'ios.baseUrl': null, 'ios.mjpegUrl': null, 'ios.mjpegPort': null, 'ios.sessionId': null, ...prefixSessionValues(platform, device.sessionValues), }; } return { platformId: platform, ...prefixSessionValues(platform, device.sessionValues), }; } if (platform === 'computer') { return { platformId: platform, [`${platform}.displayId`]: device.id, }; } return { platformId: platform, [`${platform}.deviceId`]: device.id, }; } function buildDeviceDeselectionFormValues( platform: StudioSidebarPlatformKey, ): Record { switch (platform) { case 'android': return { platformId: platform, deviceId: null, 'android.deviceId': null, }; case 'computer': return { platformId: platform, displayId: null, 'computer.displayId': null, }; case 'harmony': return { platformId: platform, deviceId: null, 'harmony.deviceId': null, }; default: return { platformId: platform, }; } } function shouldClearMissingDiscoveredDevice( platform: StudioSidebarPlatformKey, ): boolean { return ( platform === 'android' || platform === 'harmony' || platform === 'computer' ); } export function resolveDiscoveredDeviceSelectionFormValues({ formValues, discoveredDevices, }: { formValues: Record; discoveredDevices: DiscoveredDevicesByPlatform | undefined; }): Record | null { if (!discoveredDevices) { return null; } const selectedPlatform = normalizeStudioPlatformId(formValues.platformId) || 'android'; if (!selectedPlatform || selectedPlatform === 'web') { return null; } const discoveredBucket = discoveredDevices[selectedPlatform] || []; const selectedDeviceId = resolveSelectedDeviceId(formValues); if ( selectedDeviceId && discoveredBucket.some((device) => device.id === selectedDeviceId) ) { return null; } const firstDiscoveredDevice = discoveredBucket[0]; if (firstDiscoveredDevice) { return buildDeviceSelectionFormValues( selectedPlatform, firstDiscoveredDevice, ); } if ( selectedDeviceId && shouldClearMissingDiscoveredDevice(selectedPlatform) ) { return buildDeviceDeselectionFormValues(selectedPlatform); } return null; } export function buildAndroidDeviceItems({ formValues, runtimeInfo, targets, }: { formValues: Record; runtimeInfo: PlaygroundRuntimeInfo | null; targets: PlaygroundSessionTarget[]; }): StudioAndroidDeviceItem[] { const connectedDeviceId = resolveConnectedAndroidDeviceId(runtimeInfo); const selectedDeviceId = resolveSelectedAndroidDeviceId(formValues); if (targets.length === 0 && connectedDeviceId) { return [ { id: connectedDeviceId, label: isString(runtimeInfo?.metadata?.sessionDisplayName) ? runtimeInfo.metadata.sessionDisplayName : connectedDeviceId, selected: true, status: 'active', sessionValues: resolveConnectedSessionValues(runtimeInfo, 'android'), }, ]; } if (targets.length === 0 && selectedDeviceId) { return [ { id: selectedDeviceId, label: selectedDeviceId, selected: true, status: 'idle', sessionValues: { deviceId: selectedDeviceId, }, }, ]; } return targets.map((target) => ({ id: target.id, label: target.label, description: target.description, selected: target.id === connectedDeviceId || (!connectedDeviceId && target.id === selectedDeviceId), status: target.id === connectedDeviceId ? 'active' : 'idle', sessionValues: { deviceId: target.id, }, })); } export function buildStudioSidebarDeviceBuckets({ formValues, runtimeInfo, targets, }: { formValues: Record; runtimeInfo: PlaygroundRuntimeInfo | null; targets: PlaygroundSessionTarget[]; }): StudioSidebarDeviceBuckets { const deviceBuckets = createEmptySidebarDeviceBuckets(); const runtimePlatformKey = normalizeStudioPlatformId( runtimeInfo?.platformId ?? runtimeInfo?.interface?.type, ); if ( runtimePlatformKey === 'android' || (runtimePlatformKey === undefined && (targets.length > 0 || resolveConnectedAndroidDeviceId(runtimeInfo) || normalizeStudioPlatformId(formValues.platformId) === 'android')) ) { deviceBuckets.android = buildAndroidDeviceItems({ formValues, runtimeInfo, targets, }); return deviceBuckets; } if (runtimePlatformKey && runtimeInfo !== null) { const connectedItem = buildGenericConnectedDeviceItem( runtimeInfo, runtimePlatformKey, formValues, ); if (connectedItem) { deviceBuckets[runtimePlatformKey] = [connectedItem]; } } const selectedPlatformKey = normalizeStudioPlatformId(formValues.platformId); const selectedDeviceId = resolveSelectedDeviceId(formValues); if ( selectedPlatformKey && selectedDeviceId && deviceBuckets[selectedPlatformKey].length === 0 ) { deviceBuckets[selectedPlatformKey] = [ { id: selectedDeviceId, label: selectedDeviceId, selected: true, status: 'idle', sessionValues: resolveSelectedSessionValues( selectedPlatformKey, formValues, ), }, ]; } return deviceBuckets; } export function resolveVisibleSidebarPlatforms( deviceBuckets: StudioSidebarDeviceBuckets, ): StudioSidebarPlatformKey[] { return ( Object.entries(deviceBuckets) as Array< [StudioSidebarPlatformKey, StudioAndroidDeviceItem[]] > ) .filter(([, devices]) => devices.length > 0) .map(([platformKey]) => platformKey); } /** * Bucket a flat discovery result by platform, driven off the canonical * platform id set so a new platform can't be silently dropped. */ export function bucketDiscoveredDevices( devices: DiscoveredDevice[], ): DiscoveredDevicesByPlatform { const buckets = Object.fromEntries( STUDIO_PLATFORM_IDS.map((key) => [key, [] as DiscoveredDevice[]]), ) as DiscoveredDevicesByPlatform; for (const device of devices) { const bucket = buckets[device.platformId]; if (bucket) { bucket.push(device); } } return buckets; } /** * Index discovery errors by platform id so renderers can look up an * error for the platform section they are about to render. */ export function bucketDiscoveryErrors( errors: PlatformDiscoveryError[], ): DiscoveryErrorsByPlatform { const indexed: DiscoveryErrorsByPlatform = {}; for (const error of errors) { indexed[error.platformId] = error; } return indexed; } /** * Platforms that expose a real-time discovery source (ADB / HDC / * display enumeration) in the main process. For these, discovery is * the authoritative "physically present" list — once it has polled at * least once, a session item that isn't discovered anymore is stale * (e.g. the user unplugged the device while a session was still open). */ const AUTHORITATIVE_DISCOVERY_PLATFORMS = [ 'android', 'harmony', 'computer', ] as const; const ADDITIVE_DISCOVERY_PLATFORMS = ['ios'] as const; /** * Merge session-setup buckets with the live discovery snapshot. For * discoverable platforms, discovery wins — items not present in the * discovery snapshot are dropped (catches unplug while connected), and * items only present in discovery are appended as idle entries. * * iOS discovery is additive only: local WDA probes are appended to the * sidebar, but they do not evict existing session rows because Studio can * still connect to manually entered non-local WDA hosts. * * If `discovered` is undefined (first poll hasn't landed yet), the * session buckets are returned as-is rather than being wiped out. */ export function mergeSidebarDeviceBucketsWithDiscovery( sessionBuckets: StudioSidebarDeviceBuckets, discovered: DiscoveredDevicesByPlatform | undefined, ): StudioSidebarDeviceBuckets { if (!discovered) { return sessionBuckets; } const merged: StudioSidebarDeviceBuckets = { ...sessionBuckets }; for (const key of AUTHORITATIVE_DISCOVERY_PLATFORMS) { const discoveredBucket = discovered[key]; // Discovery is the source of truth for order — preserve it across // selection changes so the sidebar doesn't reshuffle when the user // clicks an item. For each discovered device, reuse the matching // session entry (it already carries label/selected/active metadata), // otherwise emit a fresh idle entry. Session items not present in // discovery are dropped (catches unplug while connected). const sessionItemsById = new Map( sessionBuckets[key].map((item) => [item.id, item]), ); merged[key] = discoveredBucket.map( (dev) => sessionItemsById.get(dev.id) ?? { id: dev.id, label: dev.label, description: dev.description, selected: false, status: 'idle', sessionValues: dev.sessionValues, }, ); } for (const key of ADDITIVE_DISCOVERY_PLATFORMS) { const existingIds = new Set(sessionBuckets[key].map((item) => item.id)); const additions: StudioAndroidDeviceItem[] = []; for (const dev of discovered[key]) { if (!existingIds.has(dev.id)) { additions.push({ id: dev.id, label: dev.label, description: dev.description, selected: false, status: 'idle', sessionValues: dev.sessionValues, }); } } merged[key] = [...sessionBuckets[key], ...additions]; } return merged; } export function resolveAndroidDeviceLabel( items: StudioAndroidDeviceItem[], ): string { const currentDevice = items.find((item) => item.status === 'active') || items.find((item) => item.selected); return currentDevice?.label ?? 'No Android device selected'; }