diff --git a/README.md b/README.md
index b41a9ab9..f4f29e8f 100644
--- a/README.md
+++ b/README.md
@@ -170,7 +170,7 @@ to avoid duplicate Mobile Dev servers. See [Cursor's plugin guide](https://curso
### Mac app
The Mac app shows the devices and tools in their own window, without a chat. Pick
-a tool and the visible platforms in the sidebar. It runs the same server as the
+a tool in the sidebar and devices from **+ Add device** in the tab strip. It runs the same server as the
plugins, so the device panels, logs, performance, storage, and TraceSift work the
same way. Chat actions such as Send to chat and annotations are hidden because
there is no chat to send to.
@@ -216,7 +216,7 @@ its device panel, inspection, logs, and performance tools.
Ask your agent to open the simulator beside this chat. In Codex, you can also
open Mobile Dev from the sidebar; in Cursor, ask **"Open Mobile Dev"** in an agent chat.
Pick a device from the toolbar; selecting a stopped simulator or AVD
-boots it. Use the iOS and Android toggles to show either platform or both.
+boots it. Choose additional iOS or Android devices from **+ Add device** in the tab strip to open them side by side. Drag a device tab to an edge to split the view, or into another group to collect its tabs.
Click an iOS simulator or Android screen to focus it, then press **Ctrl+V** on Windows or **Command-V** on macOS to
paste text into the device. Paste accepts up to 4,096 printable US-ASCII characters;
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 47369e08..350a32ea 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -10,7 +10,7 @@ Native helpers statically link [Sentry Native 0.17.1](https://github.com/getsent
This plugin also includes [agent-device 0.21.37](https://github.com/callstack/agent-device/tree/v0.21.37) by Callstack under the MIT License. Its license sits at `dist/agent-device/node_modules/agent-device/LICENSE`. The package includes the official npm release, its Apple runner source, and its bundled JavaScript dependencies. `runtimes/agent-device/package-lock.json` pins the package and its integrity hash. `dist/agent-device/release.json` records the npm archive, integrity hash, and lockfile SHA-256. The agent-device skill's workflow guide, `skills/agent-device/references/workflow.md`, is that CLI version's `help workflow` output.
-The Baguette MCP server and panel bundle the Model Context Protocol SDK, MCP Apps SDK, OpenAI MCP Extensions, Zod, ws, React, Radix UI, Legend List, Sentry's React and Node SDKs, and their required JavaScript code. The panel uses shadcn/ui components under the MIT License and Tailwind CSS styles. It bundles Lucide icons under the ISC License, with Feather icons under the MIT License and Inter under the SIL Open Font License 1.1. `dist/third-party-licenses.txt` contains their licenses. The build preserves bundled license comments too.
+The Baguette MCP server and panel bundle the Model Context Protocol SDK, MCP Apps SDK, OpenAI MCP Extensions, Zod, ws, React, Radix UI, Legend List, Sentry's React and Node SDKs, and their required JavaScript code. The panel uses Dockview and shadcn/ui components under the MIT License and Tailwind CSS styles. It bundles Lucide icons under the ISC License, with Feather icons under the MIT License and Inter under the SIL Open Font License 1.1. `dist/third-party-licenses.txt` contains their licenses. The build preserves bundled license comments too.
This plugin includes [serve-emu 0.0.6](https://github.com/jiunshinn/serve-emu) by jiunshinn under the Apache License 2.0. Its server source is checked in at `runtimes/serve-emu/src`; the fork, dependencies, and licenses ship in `dist/serve-emu`. `runtimes/serve-emu/upstream.json` records the copied release's npm tarball and integrity hash. `runtimes/serve-emu/package-lock.json` pins the fork’s Node dependencies and integrity hashes. `dist/serve-emu/release.json` records these hashes and the SHA-256 of the bundled [scrcpy 4.0 server](https://github.com/Genymobile/scrcpy/releases/tag/v4.0), also under the Apache License 2.0. The plugin includes a source fork with a Node.js port of serve-emu's CLI and HTTP/WebSocket server, using the bundled MIT-licensed ws library. Its scrcpy protocol, input queues, and session recovery are preserved.
diff --git a/apps/codex-plugin/test/workspace-opening.test.ts b/apps/codex-plugin/test/workspace-opening.test.ts
index c665ddb9..7393b2f3 100644
--- a/apps/codex-plugin/test/workspace-opening.test.ts
+++ b/apps/codex-plugin/test/workspace-opening.test.ts
@@ -96,6 +96,7 @@ for (const notification of ["input", "result"] as const) test(`workspace applies
}
if (notification === "input") {
const captured = telemetry.join("\n");
+ assert.match(captured, /ui\.devices\.visible/);
assert.match(captured, /"device_platform":\{"value":"android"/);
assert.match(captured, /"device_kind":\{"value":"emulator"/);
assert.match(captured, /"layout":\{"value":"android"/);
@@ -117,16 +118,11 @@ for (const notification of ["input", "result"] as const) test(`workspace applies
else send({ method: "ui/notifications/tool-result", params: { content: [], structuredContent: { panelTarget: target } } });
await until(() => calls.includes("mobile_list_android_devices"));
await until(() => {
- const label = window.document.getElementById("platform-select")?.textContent ?? "";
- return label.includes("Android");
+ const label = window.document.querySelector('[data-device-pane][data-platform="android"]')?.getAttribute("aria-label");
+ return label === "Pixel";
});
- await setTimeout(10);
- const ios = window.document.getElementById("ios-panel");
- const android = window.document.getElementById("android-panel");
- assert.equal(ios?.hidden, true);
- assert.equal(android?.hidden, false);
- const devices = android?.querySelector('[data-element="devices"]')?.textContent ?? "";
- assert.match(devices, /Pixel/);
+ assert.equal(window.document.querySelectorAll("[data-device-pane]").length, 1);
+ assert.equal(window.document.querySelector('[data-platform="ios"]'), null);
const unexpected = calls.filter(name => name.endsWith("_stream_session") || name.startsWith("mobile_boot"));
assert.deepEqual(unexpected, []);
if (nativeComposer) {
@@ -142,9 +138,9 @@ for (const notification of ["input", "result"] as const) test(`workspace applies
window.dispatchEvent(new window.Event("focus"));
await until(() => reports.length === 4);
assert.deepEqual(reports[3], selected, "Refocusing restores the selection even after the server restarts");
- window.document.getElementById("platform-select")?.click();
- await until(() => window.document.getElementById("platform-android") !== null);
- window.document.getElementById("platform-android")?.click();
+ const closeTab = window.document.querySelector('[role="tab"] [role="button"], [role="tab"] button');
+ assert.ok(closeTab);
+ closeTab.click();
await until(() => reports.at(-1)?.devices?.length === 0);
const cleared = reports.at(-1);
assert.deepEqual(cleared?.devices, []);
diff --git a/apps/codex-plugin/tooling/smoke-package.mjs b/apps/codex-plugin/tooling/smoke-package.mjs
index b5b6552f..0f511ebe 100644
--- a/apps/codex-plugin/tooling/smoke-package.mjs
+++ b/apps/codex-plugin/tooling/smoke-package.mjs
@@ -235,7 +235,7 @@ try {
assert.equal(resource.contents[0].mimeType, "text/html;profile=mcp-app");
assert.ok(resource.contents[0].text.includes('id="root"'));
// React creates these controls from the bundled script after the app mounts.
- for (const control of ["canvas", "logs-drawer", "log-chat", "tool-select", "tool-performance", "tool-app-intel", "app-intelligence-panel", "tool-tracesift", "performance-drawer", "performance-app", "platform-select", "simulator-panels"]) {
+ for (const control of ["canvas", "logs-drawer", "log-chat", "tool-select", "tool-performance", "tool-app-intel", "app-intelligence-panel", "tool-tracesift", "performance-drawer", "performance-app", "data-device-add", "simulator-panels"]) {
assert.ok(resource.contents[0].text.includes(control), `Missing bundled UI control: ${control}`);
}
assert.ok(!resource.contents[0].text.includes(""));
diff --git a/apps/mac/Sources/MobileDev/DeviceLayout.swift b/apps/mac/Sources/MobileDev/DeviceLayout.swift
deleted file mode 100644
index a2199610..00000000
--- a/apps/mac/Sources/MobileDev/DeviceLayout.swift
+++ /dev/null
@@ -1,19 +0,0 @@
-/// Which device platforms are visible. Raw values match the web page's layout names.
-enum DeviceLayout: String {
- case ios
- case android
- case both
- case none
-
- init(showsIOS: Bool, showsAndroid: Bool) {
- switch (showsIOS, showsAndroid) {
- case (true, true): self = .both
- case (true, false): self = .ios
- case (false, true): self = .android
- case (false, false): self = .none
- }
- }
-
- var showsIOS: Bool { self == .ios || self == .both }
- var showsAndroid: Bool { self == .android || self == .both }
-}
diff --git a/apps/mac/Sources/MobileDev/PageBridge.swift b/apps/mac/Sources/MobileDev/PageBridge.swift
index 90564d42..e52ea008 100644
--- a/apps/mac/Sources/MobileDev/PageBridge.swift
+++ b/apps/mac/Sources/MobileDev/PageBridge.swift
@@ -40,12 +40,8 @@ final class PageBridge: NSObject, WKScriptMessageHandler {
webView.evaluateJavaScript("window.mobileDevShell?.selectTool(\(argument))", completionHandler: nil)
}
- func select(layout: DeviceLayout) {
- webView.evaluateJavaScript("window.mobileDevShell?.selectLayout('\(layout.rawValue)')", completionHandler: nil)
- }
-
- func setTitlebarInset(_ size: CGSize) {
- webView.evaluateJavaScript("window.mobileDevShell?.setTitlebarInset(\(size.width), \(size.height))", completionHandler: nil)
+ func setTitlebarHeight(_ height: CGFloat) {
+ webView.evaluateJavaScript("window.mobileDevShell?.setTitlebarHeight(\(height))", completionHandler: nil)
}
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
diff --git a/apps/mac/Sources/MobileDev/ShellMessage.swift b/apps/mac/Sources/MobileDev/ShellMessage.swift
index 41aaffb1..2ee21a1c 100644
--- a/apps/mac/Sources/MobileDev/ShellMessage.swift
+++ b/apps/mac/Sources/MobileDev/ShellMessage.swift
@@ -2,8 +2,6 @@
enum ShellMessage {
/// The page connected to the server and its device panels are available.
case ready
- /// The page chose a layout itself, for example after the server opened a device.
- case layout(DeviceLayout)
case error(String)
init?(body: Any) {
@@ -11,9 +9,6 @@ enum ShellMessage {
switch type {
case "ready":
self = .ready
- case "layout":
- guard let raw = fields["layout"] as? String, let layout = DeviceLayout(rawValue: raw) else { return nil }
- self = .layout(layout)
case "error":
self = .error(fields["message"] as? String ?? "The page reported an error.")
default:
diff --git a/apps/mac/Sources/MobileDev/SidebarView.swift b/apps/mac/Sources/MobileDev/SidebarView.swift
index bcc05e58..c4146cae 100644
--- a/apps/mac/Sources/MobileDev/SidebarView.swift
+++ b/apps/mac/Sources/MobileDev/SidebarView.swift
@@ -10,14 +10,6 @@ struct SidebarView: View {
Label(tool.title, systemImage: tool.systemImage).tag(tool)
}
}
- Section("Devices") {
- Toggle(isOn: Binding(get: { model.layout.showsIOS }, set: { model.setShowsIOS($0) })) {
- Label("iOS", systemImage: "iphone")
- }
- Toggle(isOn: Binding(get: { model.layout.showsAndroid }, set: { model.setShowsAndroid($0) })) {
- Label("Android", systemImage: "candybarphone")
- }
- }
}
.listStyle(.sidebar)
.safeAreaInset(edge: .bottom) { ServerStatusView(model: model) }
diff --git a/apps/mac/Sources/MobileDev/WindowControls.swift b/apps/mac/Sources/MobileDev/WindowControls.swift
index d9a2fbc7..c975d705 100644
--- a/apps/mac/Sources/MobileDev/WindowControls.swift
+++ b/apps/mac/Sources/MobileDev/WindowControls.swift
@@ -1,8 +1,6 @@
import CoreGraphics
-/// The area the traffic lights and the system sidebar button cover at the top-left
-/// of the detail column once the sidebar is collapsed, in points.
+/// Height reserved for the native window controls when the sidebar is collapsed.
enum WindowControls {
- static let width: CGFloat = 144
static let height: CGFloat = 52
}
diff --git a/apps/mac/Sources/MobileDev/WorkspaceModel.swift b/apps/mac/Sources/MobileDev/WorkspaceModel.swift
index c5606f7c..a7ebba28 100644
--- a/apps/mac/Sources/MobileDev/WorkspaceModel.swift
+++ b/apps/mac/Sources/MobileDev/WorkspaceModel.swift
@@ -7,8 +7,6 @@ import os
@Observable
final class WorkspaceModel {
private(set) var tool: Tool? = .logs
- /// The page chooses the first layout from the devices it finds and reports it.
- private(set) var layout: DeviceLayout = .none
private(set) var status: ServerStatus = .starting {
didSet { log.info("Status: \(self.status.label, privacy: .public)") }
}
@@ -33,12 +31,9 @@ final class WorkspaceModel {
/// Moves the page's top-left controls clear of the window controls while the sidebar is collapsed.
func setSidebarVisible(_ visible: Bool) {
sidebarVisible = visible
- page.setTitlebarInset(visible ? .zero : CGSize(width: WindowControls.width, height: WindowControls.height))
+ page.setTitlebarHeight(visible ? 0 : WindowControls.height)
}
- func setShowsIOS(_ shows: Bool) { select(layout: DeviceLayout(showsIOS: shows, showsAndroid: layout.showsAndroid)) }
- func setShowsAndroid(_ shows: Bool) { select(layout: DeviceLayout(showsIOS: layout.showsIOS, showsAndroid: shows)) }
-
/// Restarts the server and reloads the page, for example after the server exits.
func restart() {
server?.stop()
@@ -48,12 +43,6 @@ final class WorkspaceModel {
func stop() { server?.stop() }
- private func select(layout: DeviceLayout) {
- guard layout != self.layout else { return }
- self.layout = layout
- page.select(layout: layout)
- }
-
private func start() {
status = .starting
let process: ServerProcess
@@ -98,9 +87,6 @@ final class WorkspaceModel {
page.select(tool: tool)
setSidebarVisible(sidebarVisible)
SmokeSnapshot.capture(page.webView)
- case .layout(let layout):
- // The page already applied this layout; reflect it without sending it back.
- self.layout = layout
case .error(let message):
status = .failed(message)
}
diff --git a/apps/mac/web/mac-bridge.ts b/apps/mac/web/mac-bridge.ts
index 3259fdaa..dd2d5df4 100644
--- a/apps/mac/web/mac-bridge.ts
+++ b/apps/mac/web/mac-bridge.ts
@@ -7,7 +7,6 @@ import { PLUGIN_VERSION } from "@mobile-dev/shared/version.ts";
type ShellMessage =
| { type: "ready" }
- | { type: "layout"; layout: string }
| { type: "tool"; tool: string }
| { type: "error"; message: string };
diff --git a/apps/mac/web/mac-workspace.tsx b/apps/mac/web/mac-workspace.tsx
index 86afbcb6..96bb350e 100644
--- a/apps/mac/web/mac-workspace.tsx
+++ b/apps/mac/web/mac-workspace.tsx
@@ -1,55 +1,35 @@
-import { useEffect } from "react";
+import { useEffect, useSyncExternalStore } from "react";
import { useGroupRef } from "react-resizable-panels";
import type { ToolName, WorkspaceTools } from "@mobile-dev/ui/workspace-tools.ts";
-import type { DeviceLayout } from "@mobile-dev/ui/device-layout.ts";
+import type { DeviceWorkspace } from "@mobile-dev/ui/device-workspace.ts";
import { LogsView } from "@mobile-dev/ui/components/logs-view.tsx";
import { PerformanceView } from "@mobile-dev/ui/components/performance-view.tsx";
-import { SimulatorView } from "@mobile-dev/ui/components/simulator-view.tsx";
+import { DevicePicker, EmptyDeviceTabBar } from "@mobile-dev/ui/components/device-picker.tsx";
+import { DevicePanes } from "@mobile-dev/ui/components/device-panes.tsx";
import { StorageView } from "@mobile-dev/ui/components/storage-view.tsx";
import { TraceSiftView } from "@mobile-dev/ui/components/tracesift-view.tsx";
import { AppIntelligenceView } from "@mobile-dev/ui/components/app-intelligence-view.tsx";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@mobile-dev/ui/components/ui/resizable.tsx";
-
-/**
- * The Mac app's content area. The native sidebar chooses the tool and the visible
- * platforms, so this view has no toolbar of its own: a tool on the left, the
- * device panels on the right. Both device panels stay mounted, because their
- * controllers attach to the DOM once.
- */
-export function MacWorkspace({ panels, tool, layout }: { panels: WorkspaceTools; tool?: ToolName; layout: DeviceLayout }) {
+export function MacWorkspace({ panels, tool, devices }: { panels: WorkspaceTools; tool?: ToolName; devices: DeviceWorkspace }) {
const workspaceGroup = useGroupRef();
- const deviceGroup = useGroupRef();
+ const state = useSyncExternalStore(devices.subscribe, devices.getSnapshot);
+ const hasDevices = state.panes.length > 0;
+ const size = tool === undefined ? 100 : Math.min(80, state.visible.length * 40);
useEffect(() => {
- const devices = layout === "none" ? 0 : tool === undefined ? 100 : 40;
- workspaceGroup.current?.setLayout({ "mac-tools": 100 - devices, "mac-devices": devices });
- if (layout !== "none") deviceGroup.current?.setLayout({ "mac-ios": layout === "android" ? 0 : layout === "both" ? 50 : 100, "mac-android": layout === "ios" ? 0 : layout === "both" ? 50 : 100 });
- }, [tool, layout]);
- const leading = tool !== undefined ? "tool" : layout === "android" ? "android" : "ios";
- const leadingClass = (panel: string) => panel === leading ? "mac-leading h-full" : "h-full";
+ workspaceGroup.current?.setLayout({ "mac-tools": 100 - size, "mac-devices": size });
+ }, [size]);
const toolView = tool === "logs" ?
: tool === "performance" ?
: tool === "storage" ?
: tool === "app-intel" ?
- : tool === "tracesift" ?
- : ;
- return
+ : tool === "tracesift" ? : null;
+ return
+ {!hasDevices && }
- {toolView}
-
-
-
-
-
-
-
-
+ {toolView}
+
+
- ;
-}
-
-function EmptyTool({ layout }: { layout: DeviceLayout }) {
- return
- {layout === "none" ? "Choose a device platform or a tool in the sidebar." : "Choose a tool in the sidebar."}
-
;
+ ;
}
diff --git a/apps/mac/web/mac.css b/apps/mac/web/mac.css
index ab3747d3..4f0a2ede 100644
--- a/apps/mac/web/mac.css
+++ b/apps/mac/web/mac.css
@@ -1,11 +1,2 @@
-/* While the native sidebar is collapsed, the window's traffic lights and sidebar
- button sit over the page's top-left corner. Swift sets --mac-titlebar-inset to
- their width, and the leading panel's top row makes room for them. */
-.mac-leading .panel-toolbar {
- padding-left: calc(var(--mac-titlebar-inset, 0px) + 0.5rem);
- transition: padding-left 150ms ease;
-}
-/* Views without a toolbar row, such as TraceSift, move below the controls instead. */
-.mac-leading:not(:has(.panel-toolbar)) {
- padding-top: var(--mac-titlebar-height, 0px);
-}
+/* Keep the tab strip clear of native window controls when the sidebar collapses. */
+.mac-workspace { padding-top: var(--mac-titlebar-height, 0px); }
diff --git a/apps/mac/web/main.tsx b/apps/mac/web/main.tsx
index a1645fd9..2e813053 100644
--- a/apps/mac/web/main.tsx
+++ b/apps/mac/web/main.tsx
@@ -5,40 +5,27 @@ import "./mac.css";
import { applyDocumentTheme } from "@modelcontextprotocol/ext-apps";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
-import type { DeviceLayout } from "@mobile-dev/ui/device-layout.ts";
import { DeviceWorkspace } from "@mobile-dev/ui/device-workspace.ts";
import { ErrorBoundary, captureUiError, startUiTelemetry, stopUiTelemetry } from "@mobile-dev/ui/telemetry.ts";
import { isToolName, WorkspaceTools, type ToolName } from "@mobile-dev/ui/workspace-tools.ts";
import { MacHostBridge, postToShell } from "./mac-bridge.ts";
import { MacWorkspace } from "./mac-workspace.tsx";
-const layouts = ["ios", "android", "both", "none"] as const;
-const isLayout = (value: unknown): value is DeviceLayout => layouts.includes(value as DeviceLayout);
-
const bridge = new MacHostBridge();
startUiTelemetry(bridge);
// The Mac app has no chat, so the panels have no host attachments.
const panels = WorkspaceTools.create(bridge);
let tool: ToolName | undefined;
-let layout: DeviceLayout = "none";
+const devices = new DeviceWorkspace(bridge, panels);
const reactRoot = createRoot(document.getElementById("root")!);
function render() {
reactRoot.render(Mobile Dev could not render. Reload the window to try again.
}>
-
+
);
}
flushSync(render);
-const devices = new DeviceWorkspace(bridge, panels, {
- onAutomaticLayout: next => {
- layout = next;
- render();
- postToShell({ type: "layout", layout: next });
- },
- connectionFailed,
-});
panels.logs.setLayout(true);
-devices.changeLayout("none");
function connectionFailed(error: unknown) {
captureUiError(error, "host.connect");
@@ -55,24 +42,15 @@ function selectTool(next: ToolName | undefined) {
render();
}
-function selectLayout(next: DeviceLayout) {
- if (next === layout) return;
- layout = next;
- devices.changeLayout(next, true);
- render();
-}
-
declare global {
interface Window {
/** The native sidebar drives the content area through these calls. */
- mobileDevShell?: { selectTool(tool: string | null): void; selectLayout(layout: string): void; setTitlebarInset(width: number, height: number): void };
+ mobileDevShell?: { selectTool(tool: string | null): void; setTitlebarHeight(height: number): void };
}
}
window.mobileDevShell = {
selectTool: value => selectTool(isToolName(value) ? value : undefined),
- selectLayout: value => { if (isLayout(value)) selectLayout(value); },
- setTitlebarInset: (width, height) => {
- document.documentElement.style.setProperty("--mac-titlebar-inset", `${Math.max(0, width)}px`);
+ setTitlebarHeight: height => {
document.documentElement.style.setProperty("--mac-titlebar-height", `${Math.max(0, height)}px`);
},
};
@@ -97,9 +75,7 @@ void (async () => {
panels.setAvailable(true);
await devices.setAvailable(true);
postToShell({ type: "ready" });
- // Codex opens the panel through a tool call that names a target. The app has
- // none, so the panels restore or pick devices and choose the layout themselves
- // unless the sidebar changes it first.
+ // The standalone app opens without a target and can select a running device.
await devices.open({});
} catch (error) {
connectionFailed(error);
diff --git a/docs/devices.md b/docs/devices.md
index 95a2e175..5ca40499 100644
--- a/docs/devices.md
+++ b/docs/devices.md
@@ -16,21 +16,21 @@ Android tools look for the SDK in `ANDROID_HOME`, `ANDROID_SDK_ROOT`, and the de
## Device panel
-Open a new chat after installing. Open Mobile Dev in the sidebar or call `mobile_open_workspace` for the fullscreen view. Call `mobile_open_simulator` for the panel beside a chat. Both opening tools accept optional `platform`, `kind`, and discovered `deviceId` arguments. For example, `{ platform: "android", kind: "emulator" }` opens Android and selects an emulator before connecting; `kind: "physical"` selects a connected phone. An unavailable requested target stays unselected, with a message and the device picker available. Opening never boots a device. Without targeting, iOS opens when both platforms have running devices; Android opens when it has the only running device. Later manual platform or device selections replace the opening choice.
+Open a new chat after installing. Open Mobile Dev in the sidebar or call `mobile_open_workspace` for the fullscreen view. Call `mobile_open_simulator` for the panel beside a chat. Both opening tools accept optional `platform`, `kind`, and discovered `deviceId` arguments. For example, `{ platform: "android", kind: "emulator" }` opens Android and selects an emulator before connecting; `kind: "physical"` selects a connected phone. An unavailable requested target stays unselected, with a message and the device picker available. Opening never boots a device. Without targeting, iOS opens when both platforms have running devices; Android opens when it has the only running device. Later manual device selections replace the opening choice.
-Enable both platforms from the platform menu to show the panels side by side. Each panel has a device dropdown, Home, App Switcher, and Screenshot. Pick a device in each panel. In the sidebar panel, the bar under the simulators holds the tools menu on the left and the platform menu on the right; fullscreen shows them above the tools. Use the platform menu to show either, both, or neither simulator. Selecting a device boots it if needed, then connects its screen. A selected running device connects automatically. The panel uses Apple’s device bezel and screen mask from the installed DeviceKit assets, with a simple frame as a fallback when assets are unavailable. Use the settings button at the bottom right for appearance, text size, location, and the device frame. iOS also offers contrast; Android offers rotation. The menu shows only settings supported by the bundled backend. Click the screen to type or drag. Closing the panel closes its stream.
+Choose **+ Add device** in a tab strip and select the screens to display. The menu groups devices into iOS and Android columns. Choosing a device closes the menu. Open **+ Add device** again to choose another. Selecting a stopped simulator or emulator starts it. Each screen has its own Home, App Switcher, Screenshot, and Select controls. Each new device opens in a split to the right of that group. Drag a tab to the left, right, top, or bottom edge of a view to split it. Drop it in the center to join that group or on the tab strip to reorder it. Drag a divider to resize the views. Drag the empty part of a tab strip to move the whole group. Each group streams its selected tab. Deselecting a device closes its screen and leaves the device running. The panel uses Apple’s device bezel and screen mask from the installed DeviceKit assets, with a simple frame as a fallback when assets are unavailable. Use the settings button at the bottom right for appearance, text size, location, and the device frame. iOS also offers contrast; Android offers rotation. The menu shows only settings supported by the bundled backend. Click the screen to type or drag. Closing the panel closes its stream.
Click an iOS simulator or Android screen to focus it, then press **Ctrl+V** on Windows or **Command-V** on macOS to paste text into the device. Paste accepts up to 4,096 printable US-ASCII characters. Empty or non-text clipboard content sends nothing; line breaks, other characters, and oversized text show a notice without sending partial text. Paste is disabled during Select, while input is blocked, and until the stream is ready. Physical iOS keyboard input remains unavailable.
Use Select in the simulator toolbar to pause the screen. Hover to outline a component, then click to add a note. React Native development apps can supply runtime elements when accessibility omits a view. Drag to mark a region when neither source exposes it. Saved notes leave numbered blue bubbles. Notes attach text and available element details to your next chat message. The captured screen stays local for editing; annotations never attach screenshots. Click a bubble to edit or remove a note, or use Send to chat to send all notes for that device. If chat is unavailable, the panel keeps the notes and retries when you return. A sent or cleared batch starts again at 1.
-The iOS dropdown shows **Connected devices** first, with USB or Wi-Fi labels, then **Simulators**. It refreshes every three seconds while the iOS panel is visible, and when opening the dropdown. Selecting a physical device opens interactive screen mirroring through its paired developer connection. The phone sends HEVC video; a bundled native Node-API addon assembles compressed frames and transfers them into Node without copying the frame payload, then the panel decodes them through WebCodecs. MCP serializes the compressed bytes as base64, so the full path is not zero copy. The capture queue is limited to eight frames or 4 MiB and requests a keyframe after overflow. Physical iOS supports pointer taps, long presses, and drags through CoreDevice UniversalHID on the same developer tunnel. Input starts after a fresh video frame, uses normalized touchscreen coordinates, and releases held touches when the stream closes or resets. Screenshot captures the displayed mirrored frame as a PNG, attaches it to chat, and copies the same image to the macOS clipboard. Select annotates screen regions using the mirrored frame's pixel coordinates; native accessibility component names are unavailable. Both controls require a connected device and a ready video frame. Keyboard and hardware-button controls remain disabled. CPU and memory monitoring can attach to an already running development app on a paired iOS 17.4+ device. Mirroring requires Developer Mode and a host with HEVC WebCodecs support. `mobile_list_ios_devices` also returns remembered disconnected devices with their connection state; the picker shows connected devices only. Discovery errors remain visible while available simulators continue to work.
+The iOS column shows **Connected devices** first, with USB or Wi-Fi labels, then **Simulators**. It refreshes every three seconds while the iOS panel is visible, and when opening the dropdown. Selecting a physical device opens interactive screen mirroring through its paired developer connection. The phone sends HEVC video; a bundled native Node-API addon assembles compressed frames and transfers them into Node without copying the frame payload, then the panel decodes them through WebCodecs. MCP serializes the compressed bytes as base64, so the full path is not zero copy. The capture queue is limited to eight frames or 4 MiB and requests a keyframe after overflow. Physical iOS supports pointer taps, long presses, and drags through CoreDevice UniversalHID on the same developer tunnel. Input starts after a fresh video frame, uses normalized touchscreen coordinates, and releases held touches when the stream closes or resets. Screenshot captures the displayed mirrored frame as a PNG, attaches it to chat, and copies the same image to the macOS clipboard. Select annotates screen regions using the mirrored frame's pixel coordinates; native accessibility component names are unavailable. Both controls require a connected device and a ready video frame. Keyboard and hardware-button controls remain disabled. CPU and memory monitoring can attach to an already running development app on a paired iOS 17.4+ device. Mirroring requires Developer Mode and a host with HEVC WebCodecs support. `mobile_list_ios_devices` also returns remembered disconnected devices with their connection state; the picker shows connected devices only. Discovery errors remain visible while available simulators continue to work.
Panels in multiple chats share one physical iOS capture through a local, per-user service. Each panel has an independent queue limited to eight frames or 4 MiB. Opening another panel requests a fresh keyframe without resetting the hardware stream or other panels’ decoders. A slow panel drops its own backlog and requests recovery when it resumes reading; other panels continue receiving frames. Closing a panel removes only its subscription. The final subscription closes the native capture, and the service exits after 30 idle seconds. Concurrent gestures are serialized, and a held touch belongs to the panel that started it. Device Hub runs its own hardware capture and cannot subscribe to this service; close its mirroring window while using Mobile Dev.
Physical iOS mirroring uses the same Apple DeviceKit bezel and framebuffer mask as the matching simulator model. Discovery preserves the hardware product type, which selects the installed Xcode device profile. The bundled Baguette CLI renders its bezel without starting a simulator, and macOS rasterizes its mask. These assets are cached per model outside the video path. A device type stands for its own model identifier plus any regional or cellular variants its profile lists. Older Xcode profiles list none. If Xcode has no matching device type or the render fails, the screen mirrors without a frame, and the plugin looks for that model's frame again after five minutes.
-Ask the agent to inspect or control the app on the selected device. The panel shares both visible device IDs and platforms with the chat. Click a device panel to make it the active device for logs. Hiding a simulator keeps the current log source and buffered logs. Use Mobile Dev's screenshot, accessibility and input tools for the selected platform. Baguette streams iOS and serve-emu streams Android in the panel.
+Ask the agent to inspect or control the app on the selected device. The panel shares all visible device IDs and their platforms with the chat. Click a device panel to make it the active device for logs. Hiding a simulator keeps the current log source and buffered logs. Use Mobile Dev's screenshot, accessibility and input tools for the selected platform. Baguette streams iOS and serve-emu streams Android in the panel.
For mobile app development, the bundled skill tells the agent to open the panel beside the chat before the first device launch, or reuse an open panel. It covers iOS, Android, Expo, React Native, and SwiftUI work. The agent follows your device choice, reuses a suitable running device, or chooses and boots an installed simulator or AVD. It asks only when the choice changes what the task needs. The app project's own tools build, install, and launch the app on that device; the agent reuses an existing app dev server.
@@ -65,7 +65,7 @@ For a custom SDK, set `ANDROID_HOME` to the **Android SDK Location** shown in SD
The Android panel lists devices without booting one. Selecting an AVD boots it if needed, then starts the bundled Node.js serve-emu CLI on a private loopback port. Home, Back, Recents, Lock, pointer gestures, and typing use scrcpy's control socket. Closing the panel leaves the emulator running. AVDs start without a separate emulator window. A failed emulator process reports its exit right away instead of waiting for the boot timeout.
-The Android dropdown shows **Connected devices** first, with USB or Wi-Fi labels, then **Emulators**. It refreshes every three seconds while the Android panel is visible, and when opening the dropdown. Physical devices use ADB discovery: enable USB debugging and authorize the computer, or pair the device for wireless debugging. Offline and unauthorized devices remain visible with their state. Emulators keep their AVD name while unauthorized. An emulator restored from a quick-boot snapshot can stay unauthorized because adb does not repeat the key exchange; the panel reconnects adb at most every 5 seconds while an AVD boots, and for up to 15 seconds after you select an already running emulator. Selecting an authorized phone connects its screen and shares its serial and transport with the chat. Bundled scrcpy mirrors and controls the phone without installing a companion app. Physical Android devices support the existing screen, input, screenshot, native log, and performance tools; emulator boot and stop controls do not apply to them.
+The Android column shows **Connected devices** first, with USB or Wi-Fi labels, then **Emulators**. It refreshes every three seconds while the Android panel is visible, and when opening the dropdown. Physical devices use ADB discovery: enable USB debugging and authorize the computer, or pair the device for wireless debugging. Offline and unauthorized devices remain visible with their state. Emulators keep their AVD name while unauthorized. An emulator restored from a quick-boot snapshot can stay unauthorized because adb does not repeat the key exchange; the panel reconnects adb at most every 5 seconds while an AVD boots, and for up to 15 seconds after you select an already running emulator. Selecting an authorized phone connects its screen and shares its serial and transport with the chat. Bundled scrcpy mirrors and controls the phone without installing a companion app. Physical Android devices support the existing screen, input, screenshot, native log, and performance tools; emulator boot and stop controls do not apply to them.
Android H.264 packets travel through MCP resource reads. The panel decodes them with WebCodecs, so the host must support H.264 `VideoDecoder`. Each device gets its own backend and each panel gets its own stream session. Decoder errors and video backlog request a fresh keyframe on the same connection. The panel drops delta frames until it can decode that keyframe. Requests have a cooldown, and stale decoder callbacks cannot repaint a closed stream. The plugin reuses a matching serve-emu server at port 3300. Set `SERVE_EMU_URL` to reuse another loopback HTTP server; it must already stream the selected serial. Closing MCP stops only backends the plugin started.
diff --git a/docs/telemetry.md b/docs/telemetry.md
index a1f26c7e..4eecd5f0 100644
--- a/docs/telemetry.md
+++ b/docs/telemetry.md
@@ -543,6 +543,8 @@ Since 0.1.69, inspection timing also includes the bounded Metro source-map looku
Since 0.1.92, Android inspection timing also includes the full-resolution display-size read and bounds scaling. Existing inspection, fallback and tree-processing coverage stays on the active selection path. Display sizes and element bounds remain local.
+The device workspace records the number of visible screens in the numeric gauge `ui.devices.visible`. Since 0.1.193 this counts the selected tab in each split. A background tab suspends its stream and frame measurements until it becomes visible. The layout attribute describes the platforms shown. Workspaces with multiple screens omit device platform and kind attributes because their timing windows can contain work from several devices. Platform-specific frame counters continue to count each painted frame.
+
Since 0.1.93, `ui.video.paint` and the platform frame counters also cover frames drawn to the local buffer while Select freezes the visible screen. These remain bounded plugin processing measurements, not device FPS. Recovery uses the same surface attribution and timing units; screenshots and element details remain local.
`ui.annotations.send` measures the host send round trip, including composer retries. Outcome counters distinguish success, a missing composer, timeout and other failures. Unexpected send failures use a fixed error message. No message content goes to Sentry. A timeout keeps notes for a manual retry; it never triggers an automatic resend, since delivery may have succeeded without acknowledgement.
diff --git a/package-lock.json b/package-lock.json
index 2395f3b0..09142fa7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "mobile-dev",
- "version": "0.1.192",
+ "version": "0.1.193",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mobile-dev",
- "version": "0.1.192",
+ "version": "0.1.193",
"workspaces": [
"packages/shared",
"packages/core",
@@ -34,6 +34,7 @@
"ajv": "8.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "dockview-react": "^8.9.1",
"enhanced-resolve": "^5.26.1",
"lucide-react": "^1.49.0",
"radix-ui": "^1.6.7",
@@ -6752,6 +6753,34 @@
"node": ">=0.3.1"
}
},
+ "node_modules/dockview": {
+ "version": "8.9.1",
+ "resolved": "https://registry.npmjs.org/dockview/-/dockview-8.9.1.tgz",
+ "integrity": "sha512-y35BxYANBtHJ4q7AIkd2c1Oh2pPx3dsaMhm6s4YvMXyIWlklxHRZupXtN6bS8QuJ/hmy/5ih/Ow2oARbEx4Yog==",
+ "license": "MIT",
+ "dependencies": {
+ "dockview-core": "^8.9.1"
+ }
+ },
+ "node_modules/dockview-core": {
+ "version": "8.9.1",
+ "resolved": "https://registry.npmjs.org/dockview-core/-/dockview-core-8.9.1.tgz",
+ "integrity": "sha512-OzqB63P65qeSquFoyYjQi5yT85ERcmceaJ0+YdQL68IZJmBd5kAfe4UD9bl3xILuXJ1tlXIoExdZ+vLpv30u1g==",
+ "license": "MIT"
+ },
+ "node_modules/dockview-react": {
+ "version": "8.9.1",
+ "resolved": "https://registry.npmjs.org/dockview-react/-/dockview-react-8.9.1.tgz",
+ "integrity": "sha512-xH63jytJwoLPNhK1XohVAQ3RnoWu+wh8U5ISlHQpxQ/jWxS94HuPMDB2JZbszfJ2ziBRafG1XHzrDlyvhIOdCw==",
+ "license": "MIT",
+ "dependencies": {
+ "dockview": "^8.9.1"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/dot-prop": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-6.0.1.tgz",
diff --git a/package.json b/package.json
index a47d5703..27fd73ce 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "mobile-dev",
- "version": "0.1.192",
+ "version": "0.1.193",
"private": true,
"workspaces": [
"packages/shared",
@@ -89,6 +89,7 @@
"ajv": "8.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "dockview-react": "^8.9.1",
"enhanced-resolve": "^5.26.1",
"lucide-react": "^1.49.0",
"radix-ui": "^1.6.7",
diff --git a/packages/core/test/testing-panel-ui.test.ts b/packages/core/test/testing-panel-ui.test.ts
index 53986980..50ba4b44 100644
--- a/packages/core/test/testing-panel-ui.test.ts
+++ b/packages/core/test/testing-panel-ui.test.ts
@@ -35,7 +35,9 @@ test("the element menu renders the runner's own steps over the mirror and record
testRecorder.start("udid", "ios");
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ const firstMirror = createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" });
+ const secondMirror = createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "another-iphone" });
+ await act(async () => { root.render(createElement("div", null, firstMirror, secondMirror)); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
@@ -45,6 +47,7 @@ test("the element menu renders the runner's own steps over the mirror and record
await act(async () => { await testRecorder.openMenu({ x: 150, y: 420 }); });
assert.ok(menu(), "the right-click opens the menu over the outline");
+ assert.equal(dom.window.document.querySelectorAll("[data-element=recorder-menu]").length, 1, "only the recording device shows the menu");
// The selector is named once and rows stay compact; exact code is still available as a tooltip.
assert.match(menu()?.textContent ?? "", /Selected element"Go To Explore List" \(button\)/);
assert.deepEqual(rows().map(row => row.textContent), [
@@ -109,7 +112,7 @@ test("a row that needs a value asks for it instead of emitting an empty string",
});
testRecorder.start("udid", "ios");
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" })); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
@@ -329,7 +332,7 @@ test("the element menu survives a tree invalidation that takes the hover outline
testRecorder.attach("udid", "ios", { readComponents: async () => [button], screen: () => SCREEN, release: () => undefined });
testRecorder.start("udid", "ios");
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" })); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
@@ -363,7 +366,7 @@ test("a coordinate gets the tap row and is told why that is all", async t => {
testRecorder.attach("udid", "ios", { readComponents: async () => [button], screen: () => SCREEN, release: () => undefined });
testRecorder.start("udid", "ios");
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" })); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
@@ -413,7 +416,7 @@ test("the command list is a submenu of its own, opened by pointing at its row",
testRecorder.attach("udid", "ios", { readComponents: async () => [button], screen: () => SCREEN, release: () => undefined });
testRecorder.start("udid", "ios");
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" })); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
@@ -481,7 +484,7 @@ test("the agentic branches cascade to the side, and record a sentence with its p
});
testRecorder.start("udid", "ios");
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" })); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
@@ -615,7 +618,7 @@ test("the recording blocker explains how to show an already-running device", asy
await act(async () => { root.render(createElement(TestingView, { panel: panelStub(), deviceApps })); });
- assert.match(dom.window.document.querySelector("[data-testing-blocker]")?.textContent ?? "", /choose Platforms → iOS or Android to show it/);
+ assert.match(dom.window.document.querySelector("[data-testing-blocker]")?.textContent ?? "", /choose it from Add device/);
await act(async () => { root.unmount(); });
});
@@ -698,7 +701,7 @@ test("Record says the mirror is not ready yet, until selection actually is", asy
testRecorder.attach("udid", "ios", { readComponents: () => tree, screen: () => SCREEN, release: () => undefined });
const root = createRoot(dom.window.document.getElementById("root")!);
- await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios" })); });
+ await act(async () => { root.render(createElement(TestRecorderOverlay, { store: annotations, platform: "ios", deviceId: "udid" })); });
onTeardown(async () => {
await act(async () => { root.unmount(); });
await new Promise(resolve => dom.window.requestAnimationFrame(resolve));
diff --git a/packages/mcp-app/src/components/workspace.tsx b/packages/mcp-app/src/components/workspace.tsx
index 8b66c21c..9a225c7a 100644
--- a/packages/mcp-app/src/components/workspace.tsx
+++ b/packages/mcp-app/src/components/workspace.tsx
@@ -3,7 +3,8 @@ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import type { ReactNode } from "react";
import type { ToolName, WorkspaceTools } from "@mobile-dev/ui/workspace-tools.ts";
import { PerformanceView } from "@mobile-dev/ui/components/performance-view.tsx";
-import { SimulatorView } from "@mobile-dev/ui/components/simulator-view.tsx";
+import { DevicePanes } from "@mobile-dev/ui/components/device-panes.tsx";
+import { DevicePicker, EmptyDeviceTabBar } from "@mobile-dev/ui/components/device-picker.tsx";
import { LogsView } from "@mobile-dev/ui/components/logs-view.tsx";
import { StorageView } from "@mobile-dev/ui/components/storage-view.tsx";
import { TraceSiftView } from "@mobile-dev/ui/components/tracesift-view.tsx";
@@ -11,7 +12,7 @@ import { AppIntelligenceView } from "@mobile-dev/ui/components/app-intelligence-
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@mobile-dev/ui/components/ui/base-select.tsx";
import { Button } from "@mobile-dev/ui/components/ui/button.tsx";
-import { usePanelRef, useGroupRef } from "react-resizable-panels";
+import { usePanelRef, useGroupRef, type Layout } from "react-resizable-panels";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@mobile-dev/ui/components/ui/resizable.tsx";
import { useMediaQuery } from "@mobile-dev/ui/components/use-media-query.ts";
import { setUiSurface, setUiTelemetryContext } from "@mobile-dev/ui/telemetry.ts";
@@ -20,8 +21,7 @@ import { RecordingCard } from "@mobile-dev/ui/components/recording-card.tsx";
import { AppFlowView } from "@mobile-dev/ui/components/app-flow-view.tsx";
import { TestingView } from "@mobile-dev/ui/components/testing-view.tsx";
-import type { DeviceLayout } from "@mobile-dev/ui/device-layout.ts";
-export type { DeviceLayout } from "@mobile-dev/ui/device-layout.ts";
+import type { DeviceWorkspace } from "@mobile-dev/ui/device-workspace.ts";
// Menu item IDs stay literal so tests and the package smoke check can find them in the bundle.
const tools = {
@@ -36,7 +36,7 @@ const tools = {
type Tool = keyof typeof tools;
const isTool = (value: string): value is Tool => value in tools;
-export function Workspace({ panels, recordingController, banner, displayModeControl, contextControl, automaticLayout, automaticTool, automaticToolRevision = 0, onLayout }: { panels: WorkspaceTools; recordingController: RecordingController; banner?: ReactNode; displayModeControl?: ReactNode; contextControl?: ReactNode; automaticLayout?: DeviceLayout; automaticTool?: ToolName; automaticToolRevision?: number; onLayout: (layout: DeviceLayout, manual?: boolean) => void }) {
+export function Workspace({ panels, recordingController, banner, displayModeControl, contextControl, automaticTool, automaticToolRevision = 0, devices }: { panels: WorkspaceTools; recordingController: RecordingController; banner?: ReactNode; displayModeControl?: ReactNode; contextControl?: ReactNode; automaticTool?: ToolName; automaticToolRevision?: number; devices: DeviceWorkspace }) {
const { logs, performance, storage, tracesift } = panels;
const appIntel = panels["app-intel"];
const appFlow = panels["app-flow"];
@@ -44,44 +44,23 @@ export function Workspace({ panels, recordingController, banner, displayModeCont
const [tool, setTool] = useState("logs");
const [savedVisible, setSavedVisible] = useState(false);
const [simulatorsCollapsed, setSimulatorsCollapsed] = useState(false);
- const [layout, setLayout] = useState(automaticLayout ?? "none");
- const manualLayout = useRef(false);
- const layoutRef = useRef(layout);
- layoutRef.current = layout;
+ const deviceState = useSyncExternalStore(devices.subscribe, devices.getSnapshot);
const recordingState = useSyncExternalStore(recordingController.subscribe, recordingController.getSnapshot);
- useEffect(() => {
- if (automaticLayout === undefined || manualLayout.current || recordingState.recording !== undefined) return;
- setLayout(automaticLayout);
- onLayout(automaticLayout);
- }, [automaticLayout]);
useEffect(() => {
if (recordingState.recording === undefined) return;
- manualLayout.current = true;
setTool("performance");
setSavedVisible(true);
- setLayout("none");
- onLayout("none");
+ devices.clear();
panels.hide();
}, [recordingState.recording?.id]);
// An agent recording opens the Testing Studio tab for the user: they asked their agent for a test, and
// the steps appearing one at a time are the whole point. Which tool is on screen is this
// component's own state, so the panel asks rather than reaches.
useEffect(() => testing.onAgentRecordingStarted(() => {
- manualLayout.current = true;
setTool("testing");
setSavedVisible(false);
panels.show("testing");
}), [testing]);
- // Picking a lane in the results shows that lane's platform. Only a single-mirror layout moves,
- // and only on the pick itself: the manual platform picker and a mirror switched back by hand
- // are never overridden.
- useEffect(() => testing.onLanePicked(platform => {
- const current = layoutRef.current;
- if (current === "both" || current === "none" || current === platform) return;
- manualLayout.current = true;
- setLayout(platform);
- onLayout(platform, true);
- }), [testing]);
const performanceState = useSyncExternalStore(performance.subscribe, performance.getSnapshot);
const wide = useMediaQuery("(min-width: 900px)");
const fullscreen = document.documentElement.dataset.view === "workspace";
@@ -126,76 +105,43 @@ export function Workspace({ panels, recordingController, banner, displayModeCont
useEffect(() => { if (automaticTool) { setTool(automaticTool); setSavedVisible(false); panels.show(automaticTool); } }, [automaticTool, automaticToolRevision]);
const logsRef = usePanelRef();
const simulatorsRef = usePanelRef();
- const simulatorGroupRef = useGroupRef();
+ const showDevices = deviceState.panes.length > 0 || !!deviceState.message || !open;
+ const deviceShare = testingOpen ? 25 : split ? Math.min(80, 36 * Math.max(1, deviceState.visible.length)) : 60;
const workspaceGroupRef = useGroupRef();
- useEffect(() => { if (open) logsRef.current?.expand(); else logsRef.current?.collapse(); }, [open, split, layout]);
+ const resizedLayout = useRef(undefined);
+ useEffect(() => { if (open) logsRef.current?.expand(); else logsRef.current?.collapse(); }, [open, split]);
useEffect(() => {
- let simulatorsPending = layout !== "none";
- let workspacePending = true;
- // Hidden hosts defer group initialization; retain the request until the groups are measurable.
+ // Hidden hosts defer group initialization until the page becomes measurable.
+ const container = document.getElementById("workspace-panels")!;
+ let pending = true;
+ resizedLayout.current = undefined;
const applyLayout = () => {
- const simulators = simulatorGroupRef.current;
- if (simulatorsPending && simulators) {
- const current = simulators.getLayout();
- const panelIds = Object.keys(current);
- if (panelIds.length > 0) {
- simulatorsPending = false;
- simulators.setLayout({ "ios-resizable": layout === "android" ? 0 : layout === "both" ? 50 : 100, "android-resizable": layout === "ios" ? 0 : layout === "both" ? 50 : 100 });
- }
- }
+ if (!container.clientWidth || !container.clientHeight) { pending = true; return; }
+ if (!pending) return;
const workspace = workspaceGroupRef.current;
- if (workspacePending && workspace) {
- const current = workspace.getLayout();
- const panelIds = Object.keys(current);
- if (panelIds.length > 0) {
- workspacePending = false;
- // The Testing Studio panel is read as three panes — mirror, preview, steps — and the preview
- // and the steps split the tools pane 60/40 of their own accord. A quarter of the
- // workspace for the mirror is what makes those 45% and 30%: the mirror is tapped, while
- // the two beside it are read, and reading a generated file needs the room.
- const toolsShare = testingOpen ? 75 : split ? 64 : 40;
- workspace.setLayout({ "tools-resizable": toolsShare, "simulators-resizable": 100 - toolsShare });
- // No visible platform is the panel being collapsed, not a share of 0. A share is the
- // group's last *requested* layout, which it re-applies whenever a panel's constraints
- // change — and the Testing Studio panel changes them as it opens. A 0 requested while nothing
- // was bootable therefore outlived the device: discovery selected a simulator, the
- // platform selector read "iOS", and the mirror stayed shut until the user toggled the
- // platform off and on again. Collapsing says the same thing in the group's own terms,
- // so expanding it is all that finding a device has to do.
- if (layout === "none") simulatorsRef.current?.collapse();
- else simulatorsRef.current?.expand();
- if (isOpen() === false) logsRef.current?.collapse();
- }
- }
- if (simulatorsPending === false && workspacePending === false) observer.disconnect();
+ if (!workspace) return;
+ const current = workspace.getLayout();
+ if (Object.keys(current).length === 0) return;
+ pending = false;
+ const share = showDevices ? deviceShare : 0;
+ workspace.setLayout(resizedLayout.current ?? { "tools-resizable": 100 - share, "simulators-resizable": share });
+ if (showDevices) simulatorsRef.current?.expand();
+ else simulatorsRef.current?.collapse();
+ if (isOpen() === false) logsRef.current?.collapse();
};
const observer = new ResizeObserver(applyLayout);
- observer.observe(document.getElementById("simulator-panels")!);
- observer.observe(document.getElementById("workspace-panels")!);
+ observer.observe(container);
applyLayout();
- // And again on the next frame, because the group re-derives its own layout from the panels'
- // defaults when their constraints change — which is what opening the Testing Studio panel does, since
- // its mirror and its tools declare sizes of their own. Asking during the commit is asking
- // before that, so the answer was thrown away; the frame after it is when it sticks.
- const frame = requestAnimationFrame(() => { workspacePending = true; simulatorsPending = layout !== "none"; applyLayout(); });
+ // Testing Studio changes the panel constraints during layout. Reapply the split once they settle.
+ const frame = requestAnimationFrame(() => { pending = true; applyLayout(); });
return () => { cancelAnimationFrame(frame); observer.disconnect(); };
- }, [layout, split, sideBySide, tool, testingOpen]);
- const toolPanel = {
- if (!previous) return;
- if (size.inPixels <= collapsedToolSize + 1 && isOpen()) closeTools();
- else if (size.inPixels > 80 && isOpen() === false) showTool(tool);
- }}>{tool === "logs" && }{tool === "storage" && }{tool === "app-intel" && }{tool === "tracesift" && }{tool === "app-flow" && open && }{tool === "testing" && open && }{tool === "performance" && open && (savedVisible ? { setSavedVisible(false); performance.show(); }}>Live performance
: )} ;
- // The sidebar keeps these controls under its simulators. Fullscreen, or no visible
- // platform, moves them above the tools.
- const bottomToolbar = !fullscreen && layout !== "none";
+ }, [showDevices, sideBySide, testingOpen, tool, deviceShare]);
+ const bottomToolbarClosed = !fullscreen && !open;
+ const toolPanel = {tool === "logs" && }{tool === "storage" && }{tool === "app-intel" && }{tool === "testing" && open && }{tool === "tracesift" && }{tool === "app-flow" && open && }{tool === "performance" && open && (savedVisible ? { setSavedVisible(false); performance.show(); }}>Live performance
: )} ;
+ const bottomToolbar = !fullscreen;
const menuSide = bottomToolbar ? "top" : "bottom";
const ToolIcon = tools[tool].icon;
- // The Testing Studio panel records by tapping the mirror and reads the test it emits beside it, so the
- // mirror leads and the preview follows it — the reading order of the thing being done. Every
- // other tool is a readout the simulator is secondary to, and keeps the simulator on the right.
- // Only side by side: stacked, "left" is the top panel, which the simulator already is.
- const mirrorFirst = testingOpen && sideBySide;
- const toolbar =
+ const toolbar =
{displayModeControl}
({ value, label }))]} value={open ? tool : "none"} onValueChange={value => {
if (value === "none") closeTools();
@@ -207,37 +153,26 @@ export function Workspace({ panels, recordingController, banner, displayModeCont
{Object.entries(tools).map(([value, { id, label, icon: Icon }]) => {label} )}
- {
- const next: DeviceLayout = values.length === 0 ? "none" : values.length === 2 ? "both" : values[0] === "ios" ? "ios" : "android";
- manualLayout.current = true;
- setLayout(next); onLayout(next, true);
- }}>
- {layout === "both" ? "Both" : layout === "none" ? "Platforms" : layout === "ios" ? "iOS" : "Android"}
-
- iOS
- Android
-
-
;
const simulatorPanel = setSimulatorsCollapsed(size.inPixels < 1)}>
-
-
-
-
-
-
- {bottomToolbar && toolbar}
-
+
;
// A collapsed simulator area would put the handle's line against the toolbar's border, doubling it.
// The handle stays draggable so the simulators can be pulled back open.
- const divider = ;
- return
+ const divider = ;
+ return
{banner}
{contextControl}
- {!bottomToolbar && toolbar}
-
- {sideBySide ? (mirrorFirst ? [simulatorPanel, divider, toolPanel] : [toolPanel, divider, simulatorPanel]) : [simulatorPanel, divider, toolPanel]}
+ {toolbar}
+ {deviceState.panes.length === 0 && }
+ {
+ if (!meta.isUserInteraction) return;
+ resizedLayout.current = meta.requestedLayout ?? layout;
+ const collapsed = logsRef.current?.isCollapsed();
+ if (collapsed && isOpen()) closeTools();
+ else if (collapsed === false && !isOpen()) showTool(tool);
+ }}>
+ {sideBySide && !testingOpen ? [toolPanel, divider, simulatorPanel] : [simulatorPanel, divider, toolPanel]}
- ;
+ ;
}
diff --git a/packages/mcp-app/src/workspace-app.tsx b/packages/mcp-app/src/workspace-app.tsx
index a8bf2a3a..5c21890e 100644
--- a/packages/mcp-app/src/workspace-app.tsx
+++ b/packages/mcp-app/src/workspace-app.tsx
@@ -10,7 +10,6 @@ import { flushSync } from "react-dom";
import { Workspace } from "./components/workspace";
import { DisplayModeButton } from "./components/display-mode-button";
import { ContextAttachments } from "./components/context-attachments";
-import type { DeviceLayout } from "@mobile-dev/ui/device-layout.ts";
import { panelTargetSchema } from "@mobile-dev/shared/panel-target.ts";
import { DeviceWorkspace } from "@mobile-dev/ui/device-workspace.ts";
import { WorkspaceTools } from "@mobile-dev/ui/workspace-tools.ts";
@@ -36,21 +35,18 @@ export function startWorkspaceApp(options: WorkspaceOptions = {}) {
const reactRoot = createRoot(document.getElementById("root")!);
let automaticTool: ToolName | undefined;
let automaticToolRevision = 0;
- function renderWorkspace(automaticLayout?: DeviceLayout) {
+ const devices = new DeviceWorkspace(app, panels);
+ function renderWorkspace() {
const workspace = Mobile Dev could not render. Reopen the panel to try again.}>
- } contextControl={ } automaticLayout={automaticLayout} automaticTool={automaticTool} automaticToolRevision={automaticToolRevision} onLayout={changeLayout} />
+ } contextControl={ } devices={devices} automaticTool={automaticTool} automaticToolRevision={automaticToolRevision} />
;
reactRoot.render(workspace);
}
flushSync(() => { renderWorkspace(); });
- const devices = new DeviceWorkspace(app, panels, { onAutomaticLayout: renderWorkspace, connectionFailed });
panels.testing.setMirrorFocus(platform => devices.focusPlatform(platform));
panels.testing.setMirrorDevice((platform, deviceId) => devices.showDevice(platform, deviceId));
panels.logs.setLayout(document.documentElement.dataset.view === "workspace");
- devices.changeLayout("none");
-
- function changeLayout(layout: DeviceLayout, manual = false) { devices.changeLayout(layout, manual); }
let stopLiveReload = () => {};
let disposingUI: Promise | undefined;
diff --git a/packages/shared/src/version.ts b/packages/shared/src/version.ts
index 496b158e..69707030 100644
--- a/packages/shared/src/version.ts
+++ b/packages/shared/src/version.ts
@@ -1 +1 @@
-export const PLUGIN_VERSION = "0.1.192";
+export const PLUGIN_VERSION = "0.1.193";
diff --git a/packages/ui/src/components/device-panes.tsx b/packages/ui/src/components/device-panes.tsx
new file mode 100644
index 00000000..bcde90b9
--- /dev/null
+++ b/packages/ui/src/components/device-panes.tsx
@@ -0,0 +1,121 @@
+import { DockviewReact, DockviewDefaultTab, type DockviewApi, type IDockviewHeaderActionsProps, type IDockviewPanelHeaderProps, type IDockviewPanelProps, type DockviewTheme } from "dockview-react";
+import "dockview-react/dist/styles/dockview.css";
+import { PanelsLeftRightIcon } from "lucide-react";
+import { createContext, useContext, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
+import type { DeviceWorkspace } from "../device-workspace";
+import { AddDeviceButton } from "./device-picker";
+import { SimulatorView } from "./simulator-view";
+
+const WorkspaceContext = createContext(null);
+const theme: DockviewTheme = { name: "Mobile Dev", className: "dockview-theme-light device-dock", gap: 1 };
+
+function DeviceScreen({ api }: IDockviewPanelProps) {
+ const workspace = useContext(WorkspaceContext)!;
+ const { panes, active } = useSyncExternalStore(workspace.subscribe, workspace.getSnapshot);
+ const key = Number(api.id);
+ const pane = panes.find(item => item.key === key);
+ if (!pane) return null;
+ return ;
+}
+
+function DeviceTab(props: IDockviewPanelHeaderProps) {
+ const workspace = useContext(WorkspaceContext)!;
+ const key = Number(props.api.id);
+ const close = () => workspace.remove(key);
+ return ;
+}
+
+function GroupActions({ group }: IDockviewHeaderActionsProps) {
+ function reference() {
+ const panel = group.activePanel;
+ if (panel) return Number(panel.id);
+ }
+ return ;
+}
+
+const components = { device: DeviceScreen };
+
+function DeviceDock({ workspace }: { workspace: DeviceWorkspace }) {
+ const [dock, setDock] = useState();
+ const container = useRef(null);
+ const { panes, active } = useSyncExternalStore(workspace.subscribe, workspace.getSnapshot);
+
+ useLayoutEffect(() => {
+ if (!dock) return;
+ let pending = false;
+ let disposed = false;
+ // Moving a tab can momentarily empty its old group. Publish the settled layout
+ // so a screen that stays visible keeps its decoder and input session.
+ const scheduleSelection = () => {
+ if (pending) return;
+ pending = true;
+ queueMicrotask(() => {
+ pending = false;
+ if (disposed || !dock.activePanel) return;
+ if (container.current) {
+ container.current.style.minWidth = `${dock.minimumWidth}px`;
+ container.current.style.minHeight = `${dock.minimumHeight}px`;
+ }
+ const visible: number[] = [];
+ for (const group of dock.groups) {
+ if (!group.activePanel) continue;
+ const key = Number(group.activePanel.id);
+ visible.push(key);
+ }
+ const active = Number(dock.activePanel.id);
+ workspace.setDockSelection(visible, active);
+ });
+ };
+ const selection = dock.onDidActivePanelChange(scheduleSelection);
+ const layout = dock.onDidLayoutChange(scheduleSelection);
+ return () => {
+ disposed = true;
+ selection.dispose();
+ layout.dispose();
+ };
+ }, [dock, workspace]);
+
+ useLayoutEffect(() => {
+ if (!dock) return;
+ const ids = new Set();
+ for (const pane of panes) {
+ const id = String(pane.key);
+ ids.add(id);
+ }
+ for (const panel of dock.panels) {
+ if (!ids.has(panel.id)) dock.removePanel(panel);
+ }
+ for (const pane of panes) {
+ const id = String(pane.key);
+ const panel = dock.getPanel(id);
+ if (panel) {
+ if (panel.title !== pane.last.name) panel.api.setTitle(pane.last.name);
+ continue;
+ }
+ const beside = String(pane.beside);
+ const referencePanel = dock.getPanel(beside);
+ const position = referencePanel ? { referencePanel, direction: "right" as const } : undefined;
+ dock.addPanel({ id, component: "device", title: pane.last.name, minimumWidth: 220, minimumHeight: 180, position });
+ }
+ }, [dock, panes]);
+
+ useLayoutEffect(() => {
+ if (!dock || active === undefined) return;
+ const id = String(active);
+ if (dock.activePanel?.id !== id) dock.getPanel(id)?.api.setActive();
+ }, [dock, active]);
+
+ return
+ setDock(api)} />
+ ;
+}
+
+export function DevicePanes({ workspace }: { workspace: DeviceWorkspace }) {
+ const { panes, message } = useSyncExternalStore(workspace.subscribe, workspace.getSnapshot);
+ return
+ {panes.length > 0 ?
:
+
{message || "Choose devices to see their screens."}
+
}
+
;
+}
diff --git a/packages/ui/src/components/device-picker.tsx b/packages/ui/src/components/device-picker.tsx
index a601adbe..d5a81901 100644
--- a/packages/ui/src/components/device-picker.tsx
+++ b/packages/ui/src/components/device-picker.tsx
@@ -1,45 +1,111 @@
-import { ChevronDownIcon, LoaderCircleIcon, SmartphoneIcon, SquareIcon, TabletIcon } from "lucide-react";
-import type { DeviceOption } from "../device-picker";
-import { Fragment, useState, useSyncExternalStore, useRef } from "react";
-import { bindDevicePicker, DevicePickerStore } from "../device-picker";
+import { CheckIcon, LoaderCircleIcon, PlusIcon, SmartphoneIcon, SquareIcon, TabletIcon } from "lucide-react";
+import { createContext, Fragment, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
+import { platforms, type Platform } from "../device-inventory";
+import type { SimulatorDevice } from "@mobile-dev/shared/protocol.ts";
+import type { DeviceWorkspace } from "../device-workspace";
import { Button } from "./ui/button";
-import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
+import { Popover, PopoverAnchor, PopoverClose, PopoverContent } from "./ui/popover";
-function DeviceLabel({ item, wrap = false }: { item: DeviceOption; wrap?: boolean }) {
- const Icon = item.kind === "tablet" ? TabletIcon : SmartphoneIcon;
- return
- {item.running && }
-
- {item.label}
- {wrap && item.detail && {item.detail} }
-
- ;
+type PickerAnchor = { button: HTMLButtonElement; reference: () => number | undefined };
+type PickerState = { anchor: PickerAnchor | null; setAnchor: (value: PickerAnchor | null) => void; available: boolean; id: string };
+const PickerContext = createContext(null);
+const firstDevice = () => undefined;
+
+export function AddDeviceButton({ reference = firstDevice }: { reference?: PickerAnchor["reference"] }) {
+ const { anchor, setAnchor, available, id } = useContext(PickerContext)!;
+ const button = useRef(null);
+ const expanded = !!anchor && anchor.button === button.current;
+ return {
+ if (expanded) setAnchor(null);
+ else setAnchor({ button: event.currentTarget, reference });
+ }}> Add device ;
+}
+
+export function EmptyDeviceTabBar() {
+ return ;
}
-export function DevicePicker({ id, label }: { id: string; label: string }) {
- const [store] = useState(() => new DevicePickerStore());
- const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
- const [open, setOpen] = useState(false);
- const selected = state.items.find(item => item.value === state.value);
- const container = useRef(null);
- const selectedButton = useRef(null);
- return { container.current = element; if (element) bindDevicePicker(element, store); }}>
-
{ setOpen(open); if (open) void store.refresh?.().catch(error => store.update({ stopError: error instanceof Error ? error.message : String(error) })); }}>
- {selected ? : state.placeholder}
- { if (selectedButton.current) { event.preventDefault(); selectedButton.current.focus(); } }}>
- {state.items.map((item, index) =>
- {item.group && (index === 0 || state.items[index - 1].group !== item.group) && {item.group}
}
-
-
{
- setOpen(false);
- store.value = item.value;
- container.current?.dispatchEvent(new Event("change"));
- }}>
- {item.canStop &&
void store.stopDevice(item.value)}>{state.stoppingId === item.value ? : } }
+export function DevicePicker({ workspace, children }: { workspace: DeviceWorkspace; children: ReactNode }) {
+ const state = useSyncExternalStore(workspace.subscribe, workspace.getSnapshot);
+ const [anchor, changeAnchor] = useState
(null);
+ const lastButton = useRef(null);
+ const setAnchor = useCallback((value: PickerAnchor | null) => {
+ if (value) lastButton.current = value.button;
+ changeAnchor(value);
+ }, []);
+ const [error, setError] = useState("");
+ const id = useId();
+ const open = anchor !== null;
+ const context = useMemo(() => ({ anchor, setAnchor, available: state.available, id }), [anchor, state.available, id]);
+ const virtualRef = useMemo(() => ({ current: anchor?.button ?? null }), [anchor]);
+ useEffect(() => {
+ workspace.setPickerOpen(open);
+ return () => workspace.setPickerOpen(false);
+ }, [workspace, open]);
+ function toggle(platform: Platform, device: SimulatorDevice) {
+ const reference = anchor?.reference();
+ workspace.toggle(platform, device, reference);
+ }
+
+ function column(platform: Platform) {
+ const { items, status, error: discoveryError } = workspace.inventory[platform];
+ const setupHint = status?.setupHint || (platform === "android" ? status?.error : undefined);
+ const emptyMessage = status?.localIosSupported === false ? "Local iOS devices require macOS." : setupHint || (status ? "No devices found" : "Finding devices…");
+ const label = platform === "ios" ? "iOS" : "Android";
+ const missing = state.panes.filter(pane => pane.platform === platform && !pane.device);
+ return
+ {label}
+ {items.map((item, index) => {
+ const selected = state.panes.some(pane => pane.platform === platform && pane.device?.udid === item.value);
+ const Icon = item.tablet ? TabletIcon : SmartphoneIcon;
+ return
+ {items[index - 1]?.group !== item.group && {item.group}
}
+
+
toggle(platform, item.device)}>
+ {item.running && }
+ {item.title}{item.detail && {item.detail} }
+ {selected && }
+
+ {item.canStop &&
{
+ setError("");
+ try { await workspace.stop(platform, item.device); }
+ catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
+ }}>{state.stopping === item.value ? : } }
- )}
- {state.stopError && {state.stopError}
}
+ ;
+ })}
+ {missing.map(pane => workspace.remove(pane.key)}>{pane.last.name} · Offline )}
+ {!items.length && !missing.length && {emptyMessage}
}
+ {discoveryError && discoveryError !== emptyMessage && Discovery details {discoveryError}
}
+ ;
+ }
+
+ return
+ {children}
+ { if (!value) setAnchor(null); }}>
+
+ {
+ const target = event.target;
+ if (target instanceof Element && target.closest("[data-device-add]")) event.preventDefault();
+ }}
+ onCloseAutoFocus={event => {
+ event.preventDefault();
+ const trigger = lastButton.current;
+ if (trigger?.isConnected) trigger.focus();
+ else {
+ // Selecting the first or removing the last device replaces the tab strip.
+ const next = document.querySelector(`[data-device-add="${id}"]`);
+ next?.focus();
+ }
+ }}
+ className="max-h-(--radix-popover-content-available-height) w-[min(32rem,var(--radix-popover-content-available-width))] overflow-y-auto p-0">
+ {platforms.map(column)}
+ {error && {error}
}
- ;
+ ;
}
diff --git a/packages/ui/src/components/simulator-view.tsx b/packages/ui/src/components/simulator-view.tsx
index da95a50e..ec58aa40 100644
--- a/packages/ui/src/components/simulator-view.tsx
+++ b/packages/ui/src/components/simulator-view.tsx
@@ -1,8 +1,9 @@
import { CameraIcon, HouseIcon, CopyIcon, PowerIcon, SmartphoneIcon, type LucideIcon } from "lucide-react";
-import { memo, useState } from "react";
+import { memo, useLayoutEffect, useRef, useState } from "react";
import { Button } from "./ui/button";
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "./ui/empty";
-import { DevicePicker } from "./device-picker";
+import type { DeviceWorkspace } from "../device-workspace";
+import type { Platform } from "../device-inventory";
import { DeviceSettings } from "./device-settings";
import { bindScreenAnnotations, ScreenAnnotationsStore } from "../screen-annotations";
import { ScreenAnnotationOverlay, ScreenSelectButton } from "./screen-annotations";
@@ -14,15 +15,16 @@ const deviceButtons: { action: string; icon: LucideIcon; label: string }[] = [
];
// The stream controller owns the canvas after mount; keep this subtree stable so log batches never reset a live device.
-export const SimulatorView = memo(function SimulatorView({ platform, visible }: { platform: "ios" | "android"; visible: boolean }) {
+export const SimulatorView = memo(function SimulatorView({ workspace, paneKey, deviceId, platform, name, active }: { workspace: DeviceWorkspace; paneKey: number; deviceId?: string; platform: Platform; name: string; active: boolean }) {
const [annotations] = useState(() => new ScreenAnnotationsStore());
const label = platform === "ios" ? "iOS" : "Android";
const sidebar = document.documentElement.dataset.view !== "workspace";
- const id = (name: string) => `${platform}-${name}`;
- return , document.body);
}
-export function TestRecorderOverlay({ store, platform }: { store: ScreenAnnotationsStore; platform: "ios" | "android" }) {
+export function TestRecorderOverlay({ store, deviceId, platform }: { store: ScreenAnnotationsStore; deviceId?: string; platform: "ios" | "android" }) {
const { viewport: v } = useSyncExternalStore(store.subscribe, store.getSnapshot);
- const { hover, menu, preparing, recordingPlatform } = useSyncExternalStore(testRecorder.subscribe, testRecorder.getSnapshot);
+ const { hover, menu, preparing, recordingPlatform, recordingDeviceId } = useSyncExternalStore(testRecorder.subscribe, testRecorder.getSnapshot);
// State rather than a ref: the menu is a child, and a child's layout effect runs before the
// parent's ref is attached, so a ref here is still null the first time the menu measures itself.
const [host, setHost] = useState(null);
@@ -231,8 +231,9 @@ export function TestRecorderOverlay({ store, platform }: { store: ScreenAnnotati
}, [host, bounds, screen, v]);
// The canvas closes the menu when it is clicked through, but the menu is no longer inside the
// stage and the rest of the panel is not the canvas: a click anywhere else closes it too.
+ const recordingHere = deviceId === recordingDeviceId && recorderShowsOn(recordingPlatform, platform);
useEffect(() => {
- if (!menu) return;
+ if (!menu || !recordingHere) return;
const dismiss = (event: PointerEvent) => {
const target = event.target as Element | null;
if (target?.closest("[data-element=recorder-menu],[data-element=recorder-commands]")) return;
@@ -240,9 +241,8 @@ export function TestRecorderOverlay({ store, platform }: { store: ScreenAnnotati
};
window.addEventListener("pointerdown", dismiss);
return () => window.removeEventListener("pointerdown", dismiss);
- }, [menu]);
- // Both mirrors mount this overlay and share one recorder snapshot, so each draws only what is about its own device.
- if (!recorderShowsOn(recordingPlatform, platform)) return null;
+ }, [menu, recordingHere]);
+ if (!recordingHere) return null;
if (!v.width || !v.height) return null;
// Record arms the recorder at once, but nothing on the mirror can be selected until the runner's
// element tree has been read, and that takes a second or two. Without this the panel said
diff --git a/packages/ui/src/components/testing-view.tsx b/packages/ui/src/components/testing-view.tsx
index f33a7351..80bcb955 100644
--- a/packages/ui/src/components/testing-view.tsx
+++ b/packages/ui/src/components/testing-view.tsx
@@ -286,7 +286,7 @@ export function TestingView({ panel, deviceApps }: { panel: TestingPanel; device
: state.loadingProject ? ""
: state.targets.length === 0 ? (panel.noProject ? "Open the app you want to record in the mirror. Testing Studio records against the app in the foreground." : "No mobile app identifier was found. Open the app in the mirror, or use E2E setup to enter one.")
: !target?.bundleId ? `Target "${target?.name}" has no app identifier. Enter one in E2E setup.`
- : !booted ? "Recording needs a booted simulator or emulator in the mirror. If one is already running, choose Platforms → iOS or Android to show it."
+ : !booted ? "Recording needs a booted simulator or emulator in the mirror. If one is already running, choose it from Add device."
: !isRecordableDevice(device) ? "Recording works on an iOS simulator or an Android emulator, not a physical device."
: mismatch;
return
@@ -952,7 +952,7 @@ function TestingRecorder({ panel, recordable, deviceId }: { panel: TestingPanel;
if (panelState.selectedTestPath) return ;
return
- {!recordable && !recording && !panelState.agent?.active &&
Recording needs a booted iOS simulator or Android emulator in the mirror. If one is already running, choose Platforms → iOS or Android to show it.
}
+ {!recordable && !recording && !panelState.agent?.active &&
Recording needs a booted iOS simulator or Android emulator in the mirror. If one is already running, choose it from Add device.
}
{panelState.agent?.active &&
The mirror is the agent's while it records, so clicking it does nothing. Press Stop to take it back.
}
diff --git a/packages/ui/src/components/ui/popover.tsx b/packages/ui/src/components/ui/popover.tsx
index 0d834e98..bc600695 100644
--- a/packages/ui/src/components/ui/popover.tsx
+++ b/packages/ui/src/components/ui/popover.tsx
@@ -4,6 +4,7 @@ import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "../../lib/utils"
+const PopoverAnchor = PopoverPrimitive.Anchor
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverClose = PopoverPrimitive.Close
@@ -15,4 +16,4 @@ function PopoverContent({ className, align = "center", sideOffset = 4, ...props
}
-export { Popover, PopoverTrigger, PopoverContent, PopoverClose }
+export { Popover, PopoverAnchor, PopoverTrigger, PopoverContent, PopoverClose }
diff --git a/packages/ui/src/device-inventory.ts b/packages/ui/src/device-inventory.ts
new file mode 100644
index 00000000..93867791
--- /dev/null
+++ b/packages/ui/src/device-inventory.ts
@@ -0,0 +1,101 @@
+import { androidBookingNamesSchema, type AndroidBookingNames } from "@mobile-dev/shared/android-devices.ts";
+import { physicalConnectionLabel, type PhysicalIosDevice } from "@mobile-dev/shared/ios-devices.ts";
+import { errorMessage, type SimulatorDevice, type Status } from "@mobile-dev/shared/protocol.ts";
+import type { HostBridge } from "./host-bridge.ts";
+
+export type Platform = "ios" | "android";
+export const platforms: readonly Platform[] = ["ios", "android"];
+
+export function describeDevice(device: SimulatorDevice, platform: Platform, bookingNames: AndroidBookingNames = {}) {
+ const physical = device.kind === "physical";
+ const running = device.state === "Booted" || physical && device.state === "connected";
+ const runtime = device.runtime.replace(/^com\.apple\.CoreSimulator\.SimRuntime\./, "").replace(/^(iOS|tvOS|watchOS|visionOS)-/, "$1 ").replace(/-/g, ".");
+ let detail = physical ? physicalConnectionLabel(device.transportType) : runtime;
+ if (physical && !running) detail += device.state === "unauthorized" ? " · Unauthorized" : " · Offline";
+ const specs = detail ? `${device.name} · ${detail}` : device.name;
+ const booked = platform === "android" && physical && running && Object.hasOwn(bookingNames, device.udid);
+ const title = booked ? bookingNames[device.udid] : device.name;
+ return {
+ device, value: device.udid, title, label: booked ? title : specs, detail: booked ? specs : detail,
+ group: physical ? "Connected devices" : platform === "ios" ? "Simulators" : "Emulators",
+ tablet: /ipad|tablet|pixel.*tab/i.test(physical ? device.model ?? device.name : device.name),
+ running, statusLabel: physical ? "Connected" : "Running",
+ canStop: !physical && running && (platform === "ios" || /^emulator-\d+$/.test(device.udid)),
+ };
+}
+
+export type DeviceOption = ReturnType
;
+
+/** One inventory per platform shares discovery and lifecycle results across all its screens. */
+export class DeviceInventory {
+ readonly platform: Platform;
+ private readonly app: HostBridge;
+ private listeners = new Set<() => void>();
+ private reading?: Promise;
+ private revision = 0;
+ private physical: PhysicalIosDevice[] = [];
+ status?: Status;
+ items: DeviceOption[] = [];
+ error = "";
+
+ constructor(app: HostBridge, platform: Platform) { this.app = app; this.platform = platform; }
+
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener);
+ return () => { this.listeners.delete(listener); };
+ };
+
+ private async call(name: string, args: Record = {}, timeout?: number) {
+ const result = await this.app.callServerTool({ name, arguments: args }, { timeout });
+ if (result.isError) {
+ const messages = result.content.flatMap(item => item.type === "text" ? [item.text] : []);
+ throw new Error(messages.join("\n"));
+ }
+ return result;
+ }
+
+ refresh() {
+ this.reading ??= this.read().finally(() => { this.reading = undefined; });
+ return this.reading;
+ }
+
+ private async read() {
+ const revision = this.revision;
+ const android = this.platform === "android";
+ const devicesRead = this.call(android ? "mobile_list_android_devices" : "mobile_list_simulators");
+ const physicalRead = android ? undefined : this.call("mobile_list_ios_devices");
+ const [devices, physical] = await Promise.allSettled([devicesRead, physicalRead]);
+ if (revision !== this.revision) return;
+ let status: Status;
+ if (devices.status === "fulfilled") status = devices.value.structuredContent as Status;
+ else status = { connected: false, managed: false, baseUrl: "", devices: [], error: errorMessage(devices.reason) };
+ const physicalData = physical.status === "fulfilled" ? physical.value?.structuredContent as { physicalDevices: PhysicalIosDevice[] } | undefined : undefined;
+ this.physical = physicalData?.physicalDevices.filter(device => device.state === "connected") ?? [];
+ const errors = [status.error];
+ if (physical.status === "rejected") errors.push(errorMessage(physical.reason));
+ this.error = errors.filter(Boolean).join(" · ");
+ this.apply(status, devices.status === "fulfilled" ? devices.value._meta?.bookingNames : undefined);
+ }
+
+ apply(status: Status, metadata?: unknown) {
+ const parsed = androidBookingNamesSchema.safeParse(metadata);
+ const names = parsed.success ? parsed.data : {};
+ this.revision++;
+ const devices = [...this.physical, ...status.devices];
+ this.status = { ...status, devices };
+ const sorted = [...devices].sort((a, b) => Number(b.kind === "physical") - Number(a.kind === "physical"));
+ this.items = sorted.map(device => describeDevice(device, this.platform, names));
+ for (const listener of this.listeners) listener();
+ }
+
+ async power(device: SimulatorDevice, boot: boolean) {
+ if (device.kind === "physical") throw new Error("Only simulators and emulators can be started or stopped.");
+ const android = this.platform === "android";
+ const action = boot ? "boot" : "shutdown";
+ const name = `mobile_${action}_${android ? "android_emulator" : "simulator"}`;
+ const args = android ? { deviceId: device.udid } : { udid: device.udid };
+ const timeout = boot ? 300000 : android ? 150000 : 30000;
+ const result = await this.call(name, args, timeout);
+ this.apply(result.structuredContent as Status, result._meta?.bookingNames);
+ }
+}
diff --git a/packages/ui/src/device-layout.ts b/packages/ui/src/device-layout.ts
index 6da21224..c61975ad 100644
--- a/packages/ui/src/device-layout.ts
+++ b/packages/ui/src/device-layout.ts
@@ -2,25 +2,19 @@ import type { SimulatorDevice } from "@mobile-dev/shared/protocol.ts";
import { panelTargetPlatform } from "@mobile-dev/shared/panel-target.ts";
import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts";
-export type DeviceLayout = "both" | "ios" | "android" | "none";
-
export function isDeviceActive(device?: SimulatorDevice): boolean {
if (device?.kind === "physical" && device.platform === "ios") return device.state === "connected";
return device?.state === "Booted";
}
-// Open one platform by default. iOS wins when both have an active device; the
-// platform select can still show both.
-export function activeDeviceLayout(ios?: SimulatorDevice, android?: SimulatorDevice): DeviceLayout {
- if (isDeviceActive(ios)) return "ios";
- return isDeviceActive(android) ? "android" : "none";
-}
-
export function initialPanelDevice(devices: SimulatorDevice[], platform: "ios" | "android", previous?: string, target?: PanelTarget): SimulatorDevice | undefined {
const requestedPlatform = target ? panelTargetPlatform(target) : undefined;
if (requestedPlatform !== undefined && requestedPlatform !== platform) return;
const candidates = devices.filter(device => {
- if (target?.deviceId !== undefined && device.udid !== target.deviceId) return false;
+ if (target?.deviceId !== undefined && device.udid !== target.deviceId) {
+ const bootedAvd = platform === "android" && device.kind !== "physical" && target.deviceId === `avd:${device.name}` && device.state === "Booted";
+ if (!bootedAvd) return false;
+ }
const kind = device.kind ?? (platform === "ios" ? "simulator" : "emulator");
return target?.kind === undefined || kind === target.kind;
});
diff --git a/packages/ui/src/device-picker.ts b/packages/ui/src/device-picker.ts
deleted file mode 100644
index 7b1ef4ff..00000000
--- a/packages/ui/src/device-picker.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { elementStores } from "./element-store.ts";
-export type DeviceOption = { value: string; label: string; detail?: string; group?: string; kind?: "phone" | "tablet"; running?: boolean; statusLabel?: string; canStop?: boolean };
-export class DevicePickerStore {
- private state = { items: [] as DeviceOption[], value: "", disabled: true, placeholder: "Loading devices...", stoppingId: "", stopError: "" };
- stop?: (id: string) => Promise;
- refresh?: () => Promise;
- private listeners = new Set<() => void>();
- subscribe = (listener: () => void) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };
- getSnapshot = () => this.state;
- update(patch: Partial) {
- this.state = { ...this.state, ...patch };
- for (const listener of this.listeners) listener();
- }
- get value() { return this.state.value; }
- set value(value: string) { this.update({ value }); }
- set disabled(disabled: boolean) { if (disabled !== this.state.disabled) this.update({ disabled }); }
- async stopDevice(id: string) {
- if (!this.stop || this.state.disabled || this.state.stoppingId || !this.state.items.some(item => item.value === id && item.canStop)) return;
- this.update({ stoppingId: id, stopError: "" });
- try { await this.stop(id); }
- catch (error) { this.update({ stopError: error instanceof Error ? error.message : String(error) }); }
- finally { this.update({ stoppingId: "" }); }
- }
-}
-const stores = elementStores(() => new DevicePickerStore());
-export const bindDevicePicker = stores.bind;
-export const getDevicePicker = stores.get;
diff --git a/packages/ui/src/device-workspace.ts b/packages/ui/src/device-workspace.ts
index f50bfe05..e259fd02 100644
--- a/packages/ui/src/device-workspace.ts
+++ b/packages/ui/src/device-workspace.ts
@@ -1,113 +1,264 @@
-import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts";
-import type { DeviceLayout } from "./device-layout.ts";
+import { panelTargetPlatform, type PanelTarget } from "@mobile-dev/shared/panel-target.ts";
+import type { SimulatorDevice } from "@mobile-dev/shared/protocol.ts";
+import { initialPanelDevice, isDeviceActive } from "./device-layout.ts";
+import { DeviceInventory, platforms, type Platform } from "./device-inventory.ts";
import type { HostBridge } from "./host-bridge.ts";
import { createSimulatorPanel } from "./simulator-panel.ts";
-import { setUiTelemetryContext } from "./telemetry.ts";
-import { WorkspaceDevices } from "./workspace-devices.ts";
+import { setUiGauge, setUiTelemetryContext } from "./telemetry.ts";
import type { WorkspaceTools } from "./workspace-tools.ts";
-type Platform = "ios" | "android";
+export type DevicePane = { key: number; beside?: number; platform: Platform; last: SimulatorDevice; device?: SimulatorDevice };
+type Snapshot = { panes: DevicePane[]; visible: number[]; active?: number; available: boolean; message: string; stopping?: string };
+
+/** A stopped AVD has an avd: ID and acquires a serial while running. Keep the same screen across that transition. */
+export function resolvePaneDevice(devices: SimulatorDevice[], last: SimulatorDevice, platform: Platform) {
+ const match = devices.find(device => device.udid === last.udid);
+ if (match || platform !== "android" || last.kind === "physical") return match;
+ const stoppedId = `avd:${last.name}`;
+ if (last.udid === stoppedId) return devices.find(device => device.kind !== "physical" && device.name === last.name && device.state === "Booted");
+ return devices.find(device => device.udid === stoppedId);
+}
-/**
- * The iOS and Android device panels of one workspace, shared by every host.
- * The host renders `SimulatorView` for both platforms before constructing this,
- * and owns the chrome that changes the layout.
- */
export class DeviceWorkspace {
- readonly panels: readonly [ReturnType, ReturnType];
+ readonly inventory: Record;
+ private readonly app: HostBridge;
private readonly tools: Pick;
- /** Assigned after the panels, which call back into it only once they are listing devices. */
- private devices!: WorkspaceDevices;
- private readonly connectionFailed: (error: unknown) => void;
- private activePlatform: Platform = "ios";
-
- constructor(app: HostBridge, tools: Pick, options: {
- /** A layout chosen for the user, such as after the host opens a device. */
- onAutomaticLayout: (layout: DeviceLayout) => void;
- connectionFailed: (error: unknown) => void;
- }) {
+ private panels = new Map>();
+ private listeners = new Set<() => void>();
+ private closing = new Set>();
+ private state: Snapshot = { panes: [], visible: [], available: false, message: "" };
+ private opening?: PanelTarget;
+ private opened = false;
+ private pickerOpen = false;
+ private initialRead = false;
+ private disposed = false;
+ private nextKey = 0;
+ private bootOnMount = new Set();
+ private timer?: ReturnType;
+
+ constructor(app: HostBridge, tools: Pick) {
+ this.app = app;
this.tools = tools;
- this.connectionFailed = options.connectionFailed;
- const create = (platform: Platform) => {
- const root = document.getElementById(`${platform}-panel`)!;
- return createSimulatorPanel(app, root, platform, tools.context, (_device, active) => {
- if (active) this.activePlatform = platform;
- this.updateSelection();
- // Discovery finding a device is also the answer to a layout that resolved to "none"
- // because the first device list came back before the backend had found anything.
- this.devices?.settleLayout();
- });
- };
- this.panels = [create("ios"), create("android")];
- this.devices = new WorkspaceDevices(this.panels, layout => {
- this.changeLayout(layout);
- options.onAutomaticLayout(layout);
- });
+ this.inventory = { ios: new DeviceInventory(app, "ios"), android: new DeviceInventory(app, "android") };
+ for (const platform of platforms) this.inventory[platform].subscribe(() => this.inventoryChanged(platform));
}
- updateSelection() {
- const visible = this.panels.filter(panel => !panel.root.hidden);
- const active = visible.find(panel => panel.platform === this.activePlatform) ?? visible[0];
- const selected = active?.selected;
- const devicePlatform = selected ? active?.platform : undefined;
- const virtualKind = devicePlatform === "android" ? "emulator" : "simulator";
- const deviceKind = selected?.kind ?? (selected ? virtualKind : undefined);
- setUiTelemetryContext({ device_platform: devicePlatform, device_kind: deviceKind });
- this.tools.context.selectSimulators(visible.flatMap(panel => panel.selected ? [panel.selected] : []), selected);
- this.tools.deviceApps.selectDevice(selected);
- for (const panel of this.panels) panel.root.dataset.active = String(panel === active);
- }
-
- changeLayout(layout: DeviceLayout, manual = false) {
- if (manual) this.devices.selectLayout();
- setUiTelemetryContext({ layout });
- if (layout === "ios" || layout === "android") this.activePlatform = layout;
- for (const panel of this.panels) {
- panel.root.hidden = layout !== "both" && layout !== panel.platform;
+ getSnapshot = () => this.state;
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener);
+ return () => { this.listeners.delete(listener); };
+ };
+
+ private update(patch: Partial) {
+ this.state = { ...this.state, ...patch };
+ if (patch.visible) {
+ for (const [key, panel] of this.panels) {
+ const visible = patch.visible.includes(key);
+ panel.setVisible(visible);
+ }
}
- requestAnimationFrame(() => { for (const panel of this.panels) if (!panel.root.hidden) panel.fitScreen(); });
- this.updateSelection();
- if (manual) {
- for (const panel of this.panels) {
- if (panel.root.hidden === false) void panel.resume().catch(this.connectionFailed);
+ for (const listener of this.listeners) listener();
+ }
+
+ private publishSelection() {
+ const { panes, active, visible } = this.state;
+ const displayed = panes.filter(item => visible.includes(item.key));
+ const pane = panes.find(item => item.key === active);
+ const device = pane?.device;
+ const ios = displayed.some(item => item.platform === "ios");
+ const android = displayed.some(item => item.platform === "android");
+ const layout = ios && android ? "both" : ios ? "ios" : android ? "android" : "none";
+ const kind = device?.kind ?? (pane?.platform === "android" ? "emulator" : "simulator");
+ const single = displayed.length === 1 && device !== undefined;
+ setUiTelemetryContext({ layout, device_platform: single ? pane?.platform : undefined, device_kind: single ? kind : undefined });
+ setUiGauge("ui.devices.visible", displayed.length);
+ const selected = displayed.flatMap(item => item.device ? [item.device] : []);
+ this.tools.context.selectSimulators(selected, device);
+ this.tools.deviceApps.selectDevice(device);
+ }
+
+ private inventoryChanged(platform: Platform) {
+ if (this.disposed) return;
+ const inventory = this.inventory[platform];
+ const devices = inventory.status?.devices ?? [];
+ const panes = this.state.panes.map(pane => {
+ if (pane.platform !== platform) return pane;
+ const device = resolvePaneDevice(devices, pane.last, platform);
+ this.panels.get(pane.key)?.acceptDevice(device);
+ return { ...pane, device, last: device ?? pane.last };
+ });
+ this.update({ panes });
+ if (this.initialRead) this.applyOpening();
+ this.publishSelection();
+ }
+
+ private applyOpening() {
+ if (this.opening === undefined) return;
+ for (const platform of platforms) {
+ const inventory = this.inventory[platform];
+ const device = initialPanelDevice(inventory.status?.devices ?? [], platform, undefined, this.opening);
+ if (device) {
+ this.opening = undefined;
+ this.add(platform, device, false);
+ return;
}
}
+ const target = this.opening;
+ let message: string | undefined;
+ if (target.deviceId || target.platform || target.kind) {
+ const platform = panelTargetPlatform(target);
+ const label = platform === "ios" ? "iOS device" : platform === "android" ? "Android device" : "device";
+ message = `Requested ${label} unavailable. Connect it or choose another device.`;
+ } else if (this.inventory.ios.status?.localIosSupported === false) {
+ const android = this.inventory.android;
+ message = android.status?.setupHint || android.error;
+ }
+ if (message && message !== this.state.message) this.notice(message);
+ }
+
+ private add(platform: Platform, device: SimulatorDevice, boot: boolean, beside = this.state.active) {
+ const key = ++this.nextKey;
+ if (boot && device.kind !== "physical" && device.state === "Shutdown") this.bootOnMount.add(key);
+ const panes = [...this.state.panes, { key, beside, platform, last: device, device }];
+ const visible = [...this.state.visible, key];
+ this.update({ panes, visible, active: key, message: "" });
+ this.publishSelection();
+ }
+
+ async open(target: PanelTarget) {
+ if (this.opened || this.disposed) return;
+ this.opened = true;
+ this.opening = target;
+ await this.initialize();
+ }
+
+ async setAvailable(available: boolean) {
+ this.update({ available });
+ for (const panel of this.panels.values()) panel.setAvailable(available);
+ await this.initialize();
+ }
+
+ private async initialize() {
+ if (!this.opened || !this.state.available || this.disposed || this.timer !== undefined) return;
+ this.timer = setInterval(() => {
+ if (document.visibilityState === "hidden" || !this.state.available) return;
+ for (const platform of platforms) {
+ if (this.pickerOpen || this.opening || this.state.panes.some(pane => pane.platform === platform)) void this.inventory[platform].refresh();
+ }
+ }, 3000);
+ await Promise.all(platforms.map(platform => this.inventory[platform].refresh()));
+ if (this.disposed) return;
+ this.initialRead = true;
+ this.applyOpening();
+ this.publishSelection();
+ }
+
+ setPickerOpen(open: boolean) {
+ this.pickerOpen = open;
+ if (open && this.state.available) for (const platform of platforms) void this.inventory[platform].refresh();
+ }
+
+ toggle(platform: Platform, device: SimulatorDevice, beside?: number) {
+ this.opened = true;
+ this.opening = undefined;
+ void this.initialize();
+ const pane = this.state.panes.find(item => item.platform === platform && item.last.udid === device.udid);
+ if (pane) this.remove(pane.key);
+ else this.add(platform, device, true, beside);
+ }
+
+ remove(key: number) {
+ this.bootOnMount.delete(key);
+ const panes = this.state.panes.filter(pane => pane.key !== key);
+ const active = this.state.active === key ? panes.at(-1)?.key : this.state.active;
+ const visible = this.state.visible.filter(item => item !== key);
+ this.update({ panes, visible, active });
+ this.publishSelection();
+ }
+
+ clear() {
+ this.opened = true;
+ this.opening = undefined;
+ this.bootOnMount.clear();
+ void this.initialize();
+ this.update({ panes: [], visible: [], active: undefined, message: "" });
+ this.publishSelection();
+ }
+
+ activate(key: number) {
+ if (key === this.state.active) return;
+ this.update({ active: key });
+ this.publishSelection();
}
- /**
- * Makes one platform's mirror the active one, when it is showing a device. Nothing is opened or
- * booted: a platform the layout hides, or one with no device, answers false.
- */
focusPlatform(platform: Platform): boolean {
- const panel = this.panels.find(entry => entry.platform === platform);
- if (!panel || panel.root.hidden || !panel.selected) return false;
- this.activePlatform = platform;
- this.updateSelection();
+ const { panes, visible, active } = this.state;
+ const matches = panes.filter(pane => pane.platform === platform && pane.device && visible.includes(pane.key));
+ const pane = matches.find(item => item.key === active) ?? matches[0];
+ if (!pane) return false;
+ this.activate(pane.key);
return true;
}
- /**
- * Switches a platform's mirror to a listed, booted device, as the device picker does, and makes
- * that platform the active one. Answers false when the layout hides the platform or the device
- * is not listed and booted; nothing is opened or booted.
- */
showDevice(platform: Platform, deviceId: string): boolean {
- const panel = this.panels.find(entry => entry.platform === platform);
- if (!panel || panel.root.hidden || !panel.showDevice(deviceId)) return false;
- this.activePlatform = platform;
- this.updateSelection();
+ const { panes } = this.state;
+ if (panes.length === 0) return false;
+ const device = this.inventory[platform].status?.devices.find(item => item.udid === deviceId);
+ if (!device || !isDeviceActive(device)) return false;
+ const pane = panes.find(item => item.platform === platform && item.device?.udid === deviceId);
+ if (pane) this.activate(pane.key);
+ else this.add(platform, device, false);
return true;
}
- /** Opens the devices a tool call or host intent names. */
- open(target: PanelTarget) { return this.devices.open(target); }
- setAvailable(available: boolean) { return this.devices.setAvailable(available); }
- notice(message: string) { for (const panel of this.panels) panel.notice(message); }
- /** Refits the screens and controls after the host's size or theme changes. */
- refit() { for (const panel of this.panels) { panel.fitScreen(); panel.controls(); } }
+ setDockSelection(visible: number[], active: number) {
+ const current = this.state.visible;
+ if (active === this.state.active && visible.length === current.length && visible.every(key => current.includes(key))) return;
+ this.update({ visible, active });
+ this.publishSelection();
+ }
+
+ mount(key: number, root: HTMLElement) {
+ const pane = this.state.panes.find(item => item.key === key);
+ if (!pane || this.disposed) return;
+ const panel = createSimulatorPanel(this.app, root, this.inventory[pane.platform], this.tools.context, () => this.activate(key));
+ this.panels.set(key, panel);
+ const visible = this.state.visible.includes(key);
+ panel.setVisible(visible);
+ panel.setAvailable(this.state.available);
+ panel.acceptDevice(pane.device);
+ if (this.bootOnMount.delete(key)) void panel.start();
+ return () => {
+ this.panels.delete(key);
+ const closing = panel.dispose();
+ this.closing.add(closing);
+ void closing.finally(() => this.closing.delete(closing));
+ };
+ }
+
+ async stop(platform: Platform, device: SimulatorDevice) {
+ const inventory = this.inventory[platform];
+ const option = inventory.items.find(item => item.value === device.udid);
+ if (this.state.stopping || !option?.canStop) return;
+ this.update({ stopping: device.udid });
+ try {
+ const pane = this.state.panes.find(item => item.platform === platform && item.device?.udid === device.udid);
+ const panel = pane && this.panels.get(pane.key);
+ if (panel) await panel.stop();
+ else await inventory.power(device, false);
+ } finally { this.update({ stopping: undefined }); }
+ }
+
+ notice(message: string) {
+ this.update({ message });
+ for (const panel of this.panels.values()) panel.notice(message);
+ }
+ refit() { for (const panel of this.panels.values()) { panel.fitScreen(); panel.controls(); } }
async dispose() {
- this.devices.dispose();
- await Promise.allSettled(this.panels.map(panel => panel.dispose()));
+ this.disposed = true;
+ clearInterval(this.timer);
+ const closing = [...this.panels.values()].map(panel => panel.dispose());
+ await Promise.allSettled([...closing, ...this.closing]);
}
}
diff --git a/packages/ui/src/frame-arrivals.ts b/packages/ui/src/frame-arrivals.ts
index 0bb8f155..8c0be720 100644
--- a/packages/ui/src/frame-arrivals.ts
+++ b/packages/ui/src/frame-arrivals.ts
@@ -27,3 +27,25 @@ export class FrameArrivals {
clear() { this.arrivals.clear(); }
}
+
+// MCP replies from all simulators arrive on the same host window. Each stream
+// consumes only its own resource timestamps from this bounded collection.
+export const frameArrivals = new FrameArrivals();
+let observers = 0;
+function observeFrame(event: MessageEvent) {
+ if (event.source !== window.parent) return;
+ const arrivedAt = performance.timeOrigin + performance.now();
+ frameArrivals.record(event.data, arrivedAt);
+}
+
+export function observeFrameArrivals() {
+ if (observers === 0) window.addEventListener("message", observeFrame);
+ observers++;
+ return () => {
+ observers--;
+ if (observers === 0) {
+ window.removeEventListener("message", observeFrame);
+ frameArrivals.clear();
+ }
+ };
+}
diff --git a/packages/ui/src/model-context.ts b/packages/ui/src/model-context.ts
index 7cbfce81..e5bff0c1 100644
--- a/packages/ui/src/model-context.ts
+++ b/packages/ui/src/model-context.ts
@@ -188,7 +188,7 @@ export class PanelContext {
const transport = device.kind === "physical" ? device.transportType : null;
return [device.udid, device.name, device.runtime, device.state, device.platform ?? "ios", device.kind, transport];
});
- const key = JSON.stringify([active?.udid, devices]);
+ const key = JSON.stringify([active?.platform, active?.udid, devices]);
if (key === this.selectionKey) return;
this.selectionKey = key;
this.simulators = simulators;
@@ -296,7 +296,7 @@ export class PanelContext {
const log = this.attached;
const host = this.attachments();
const devices = this.simulators.map(device => {
- const role = device.udid === selected?.udid ? "Active" : "Visible";
+ const role = device.udid === selected?.udid && device.platform === selected.platform ? "Active" : "Visible";
if (device.kind === "physical" && device.platform === "ios") {
const transport = device.transportType === undefined ? "Transport not reported." : `Transport: ${device.transportType}.`;
return `${role} physical iOS device: ${device.name}. UDID: ${device.udid}. State: ${device.state}. ${transport} The panel mirrors this device through an interactive HEVC stream with pointer taps and drags. Native unified logs use mobile_logs_session with platform ios, kind physical, and this hardware UDID. They do not require launching the app; ordinary print output is unavailable and private values may be redacted. Physical iOS keyboard input, hardware buttons, screenshots, and agent-device control are not implemented yet.`;
diff --git a/packages/ui/src/simulator-panel.ts b/packages/ui/src/simulator-panel.ts
index c575612e..8f06f433 100644
--- a/packages/ui/src/simulator-panel.ts
+++ b/packages/ui/src/simulator-panel.ts
@@ -1,6 +1,6 @@
import { androidNinePatchSkin } from "./android-nine-patch.ts";
import { androidFrameGeometry, androidChromeScale } from "./android-frame-geometry.ts";
-import { getDevicePicker } from "./device-picker.ts";
+import type { DeviceInventory } from "./device-inventory.ts";
import { getDeviceSettings } from "./device-settings.ts";
import { getResourceSaving } from "./resource-saving.ts";
import type { ResourceSavingState } from "@mobile-dev/shared/resource-saving.ts";
@@ -8,13 +8,9 @@ import { getAppTools } from "./app-tools.ts";
import type { DeviceSettings } from "@mobile-dev/shared/device-settings.ts";
import { bezelGeometrySchema } from "@mobile-dev/shared/bezel.ts";
import type { Bezel } from "@mobile-dev/shared/bezel.ts";
-import type { SimulatorDevice, Status, TouchInput } from "@mobile-dev/shared/protocol.ts";
+import type { SimulatorDevice, TouchInput } from "@mobile-dev/shared/protocol.ts";
import { inputSchema } from "@mobile-dev/shared/protocol.ts";
-import { androidBookingNamesSchema } from "@mobile-dev/shared/android-devices.ts";
-import type { AndroidBookingNames } from "@mobile-dev/shared/android-devices.ts";
import { physicalConnectionLabel } from "@mobile-dev/shared/ios-devices.ts";
-import type { PhysicalIosDevice } from "@mobile-dev/shared/ios-devices.ts";
-import type { DeviceOption } from "./device-picker.ts";
import { ReconnectLoop, StopReconnectError } from "./reconnect.ts";
import { captureUiError, countUiEvent, recordUiTiming } from "./telemetry.ts";
import type { PanelContext } from "./model-context.ts";
@@ -27,7 +23,7 @@ import { AndroidVideo } from "./android-video.ts";
import { PhysicalIosVideo } from "./ios-mirror-video.ts";
import { iosVideoBatchSchema } from "@mobile-dev/shared/ios-video.ts";
import { FrameStream } from "./frame-stream.ts";
-import { FrameArrivals } from "./frame-arrivals.ts";
+import { frameArrivals, observeFrameArrivals } from "./frame-arrivals.ts";
import { readFrame } from "./read-frame.ts";
import { BrowserProfile } from "./browser-profile.ts";
import { StreamInput } from "./stream-input.ts";
@@ -35,20 +31,18 @@ import type { StreamMessage } from "./stream-input.ts";
import { IosVideo } from "./ios-video.ts";
import type { AndroidVideoBatch } from "./android-video.ts";
import type { HostBridge } from "./host-bridge.ts";
+import { isDeviceActive } from "./device-layout.ts";
import { isRecordableDevice, recordablePlatform } from "@mobile-dev/shared/panel-target.ts";
-import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts";
-import { initialPanelDevice } from "./device-layout.ts";
export function createSimulatorPanel(
app: HostBridge,
root: HTMLElement,
- platform: "ios" | "android",
+ inventory: DeviceInventory,
panelContext: PanelContext,
- selectionChanged: (device?: SimulatorDevice, active?: boolean) => void,
+ activate: () => void,
) {
function element(id: string): T { return root.querySelector(`[data-element="${id}"]`) as T; }
- const devicePickerElement = element("devices");
- const devices = getDevicePicker(devicePickerElement);
+ const platform = inventory.platform;
const settings = getDeviceSettings(element("settings"));
const resourceSaving = getResourceSaving(element("settings"));
const appTools = getAppTools(element("settings"));
@@ -62,18 +56,10 @@ export function createSimulatorPanel(
let bezel: Bezel | undefined;
let sourceBezel: Bezel | undefined;
let showFrame = true;
- let stoppedDisplay = false;
let useAndroidNinePatch = false;
bezelImage.addEventListener("error", () => { setBezel(); fitScreen(); });
const screenshotButton = element("screenshot");
- let status: Status | undefined;
- let statusRevision = 0;
let selected: SimulatorDevice | undefined;
- let openingTarget: PanelTarget | undefined;
- let physicalDevices: PhysicalIosDevice[] = [];
- let discoveryError = "";
- let listing: Promise | undefined;
- let discoveryTimer: ReturnType | undefined;
type PanelStream = { id: string; frameUri: string; epoch: number; platform: "ios" | "android"; physicalIos: boolean; generation?: number; controller: AbortController; input?: StreamInput; reader?: FrameStream; closing?: Promise };
const reconnect = new ReconnectLoop();
let stream: PanelStream | undefined;
@@ -89,13 +75,15 @@ export function createSimulatorPanel(
let busy = false;
let resumeRequested = false;
let toolsAvailable = false;
+ let visible = true;
let disposed = false;
let disposing: Promise | undefined;
let screenshotAttachmentError = "";
+ let discoveryError = "";
function notice(message = "") {
if (screenshotAttachmentError) message = screenshotAttachmentError;
- else if (message.length === 0) message = inputRepairMessage || (inputBlocked ? "Simulator input is blocked. Ask Codex to repair it." : discoveryError);
+ else if (message.length === 0) message = inputRepairMessage || (inputBlocked ? "Simulator input is blocked. Ask Codex to repair it." : inventory.error);
element("notice-message").textContent = message;
element("notice").title = message;
element("notice").classList?.toggle("text-destructive", inputBlocked);
@@ -111,11 +99,9 @@ export function createSimulatorPanel(
// App tools use simctl and adb, which do not reach paired iPhones.
appTools.configure(platform, selected?.udid ?? "", deviceToolsUnavailable || selected?.kind === "physical" && platform === "ios");
element("start-device").disabled = busy || !toolsAvailable || !selected || selected.kind === "physical" || selected.state === "Booted" || disposed;
- const hasDevices = status?.devices.length || physicalDevices.length;
- devices.disabled = busy || !toolsAvailable || !hasDevices || disposed;
const connected = selectedDeviceConnected();
const physicalIos = selected?.kind === "physical" && selected.platform === "ios";
- const screenshotReady = physicalIos ? ready && stream?.physicalIos === true : status?.connected;
+ const screenshotReady = physicalIos ? ready && stream?.physicalIos === true : inventory.status?.connected;
screenshotButton.disabled = busy || !toolsAvailable || !connected || !screenshotReady || !panelContext.canAttachScreenshots || disposed;
screenshotButton.title = panelContext.canAttachScreenshots ? "Screenshot to chat and clipboard" : "This host does not support screenshot attachments";
const annotationState = annotations.getSnapshot();
@@ -328,9 +314,8 @@ export function createSimulatorPanel(
function isRecordingSelected() {
return selected ? testRecorder.isRecording(selected.udid, recordablePlatform(selected)) : false;
}
- function syncRecorder() {
- if (selected && isRecordableDevice(selected)) testRecorder.attach(selected.udid, recordablePlatform(selected), recorderReader);
- else if (selected) testRecorder.detach(selected.udid, recordablePlatform(selected));
+ function detachRecorder() {
+ if (selected && isRecordableDevice(selected)) testRecorder.detach(selected.udid, recordablePlatform(selected));
}
const stopObservingAnnotations = annotations.subscribe(() => {
@@ -364,10 +349,7 @@ export function createSimulatorPanel(
};
resourceSaving.restart = async () => {
if (selected === undefined || selected.kind === "physical" || disposed) throw new Error("Select a simulator or emulator first.");
- const id = selected.udid;
- const stop = devices.stop;
- if (stop === undefined) throw new Error("Device controls are not available.");
- await stop(id);
+ await stop();
busy = true;
controls();
notice();
@@ -395,7 +377,6 @@ export function createSimulatorPanel(
}
function empty(message: string, description = "") {
- stoppedDisplay = false;
element("stopped").hidden = true;
frame.hidden = true;
element("empty").hidden = false;
@@ -502,105 +483,45 @@ export function createSimulatorPanel(
resizeObserver.observe(stage);
resizeObserver.observe(canvas);
- function runtimeLabel(runtime: string) {
- return runtime.replace(/^com\.apple\.CoreSimulator\.SimRuntime\./, "").replace(/^(iOS|tvOS|watchOS|visionOS)-/, "$1 ").replace(/-/g, ".");
- }
-
- function selectDevice() {
- selected = status?.devices.find(device => device.udid === devices.value);
- if (selected === undefined) selected = physicalDevices.find(device => device.udid === devices.value);
- selectionChanged(selected);
- syncRecorder();
- if (selected?.kind === "physical" && selected.platform === "ios") {
- const connection = physicalConnectionLabel(selected.transportType);
- if (reconnect.active === false) empty(`${selected.name} · ${connection}`, "Opening the physical device screen…");
- } else if (selected?.kind === "physical" && selected.state !== "Booted") {
- const description = selected.state === "unauthorized"
+ function acceptDevice(device?: SimulatorDevice) {
+ if (disposed) return;
+ const wasActive = isDeviceActive(selected);
+ const changed = selected?.udid !== device?.udid;
+ const active = isDeviceActive(device);
+ if (reconnect.active && (changed || !active)) void disconnect();
+ if (changed || (wasActive && !active)) detachRecorder();
+ selected = device;
+ if (selected && isRecordableDevice(selected) && (changed || !wasActive)) {
+ testRecorder.attach(selected.udid, recordablePlatform(selected), recorderReader);
+ }
+ if (device === undefined) {
+ empty("Device unavailable", "Reconnect this device or choose another with Add device.");
+ } else if (device.kind === "physical" && !active) {
+ const description = device.state === "unauthorized"
? "Unlock the device and allow USB debugging, or pair it for wireless debugging."
: "Reconnect the device and check that ADB debugging is enabled.";
- empty(`${selected.name} · ${selected.state}`, description);
- } else if (selected === undefined && (openingTarget?.platform !== undefined || openingTarget?.kind !== undefined || openingTarget?.deviceId !== undefined)) {
- empty("Requested device unavailable.", "The requested device could not be found. Connect it or choose another device from the picker.");
- } else if (!reconnect.active && !stoppedDisplay) empty(selected || status?.devices.length ? "Select a device to open its screen." : (platform === "android" ? "No Android devices. Create an AVD in Android Studio or connect a device." : "No iOS devices. Connect an iPhone or add a simulator in Xcode."));
- controls();
- }
-
- let bookingNames: AndroidBookingNames = {};
-
- function updateBookingNames(metadata: unknown) {
- const parsed = androidBookingNamesSchema.safeParse(metadata);
- bookingNames = parsed.success ? parsed.data : {};
- }
-
- function renderStatus(next: Status, previous = selected?.udid) {
- statusRevision++;
- status = next;
- const available = [...physicalDevices, ...next.devices];
- if (platform === "android" && openingTarget?.deviceId?.startsWith("avd:")) {
- const avdName = openingTarget.deviceId.slice(4);
- const booted = next.devices.find(device => device.kind !== "physical" && device.name === avdName && device.state === "Booted");
- if (booted !== undefined) openingTarget = { ...openingTarget, deviceId: booted.udid };
- } else if (platform === "android" && selected && openingTarget?.deviceId === selected.udid && selected.kind !== "physical") {
- const stoppedId = `avd:${selected.name}`;
- const stopped = next.devices.find(device => device.udid === stoppedId && device.state === "Shutdown");
- if (stopped !== undefined) openingTarget = { ...openingTarget, deviceId: stopped.udid };
+ empty(`${device.name} · ${device.state}`, description);
+ } else if (!active) {
+ element("empty").hidden = true;
+ element("stopped").hidden = false;
+ } else if (changed || !wasActive) {
+ const connection = device.kind === "physical" ? physicalConnectionLabel(device.transportType) : "";
+ empty(connection ? `${device.name} · ${connection}` : "Connecting…", "Opening the device screen.");
}
- const oldDevice = available.find(device => device.udid === previous);
- const nextDevice = initialPanelDevice(available, platform, previous, openingTarget);
- const physicalIos = oldDevice?.kind === "physical" && oldDevice.platform === "ios";
- const availableForMirroring = physicalIos ? oldDevice.state === "connected" : next.connected && oldDevice?.state === "Booted";
- if (reconnect.active && availableForMirroring === false) void disconnect();
- const physicalOptions: DeviceOption[] = physicalDevices.map(device => {
- const connection = physicalConnectionLabel(device.transportType);
- const kind = /ipad/i.test(device.model) ? "tablet" : "phone";
- return { value: device.udid, label: `${device.name} · ${connection}`, group: "Connected devices", kind, running: true, statusLabel: "Connected", canStop: false };
- });
- const virtualDevices = next.devices.filter(device => device.kind !== "physical");
- const androidPhysicalOptions: DeviceOption[] = next.devices.flatMap(device => {
- if (device.kind !== "physical" || device.platform !== "android") return [];
- const connection = physicalConnectionLabel(device.transportType);
- const running = device.state === "Booted";
- const stateLabel = device.state === "unauthorized" ? "Unauthorized" : "Offline";
- const deviceLabel = `${device.name} · ${connection}${running ? "" : ` · ${stateLabel}`}`;
- const bookingName = running && Object.hasOwn(bookingNames, device.udid) ? bookingNames[device.udid] : undefined;
- return [{
- value: device.udid, label: bookingName ?? deviceLabel,
- ...(bookingName !== undefined ? { detail: deviceLabel } : {}),
- group: "Connected devices", kind: /tablet|pixel.*tab/i.test(device.name) ? "tablet" : "phone",
- running, statusLabel: "Connected", canStop: false,
- }];
- });
- const simulatorOptions: DeviceOption[] = virtualDevices.map(device => {
- const runtime = runtimeLabel(device.runtime);
- return {
- value: device.udid, label: `${device.name}${runtime ? ` · ${runtime}` : ""}`,
- group: platform === "ios" ? "Simulators" : "Emulators",
- kind: /ipad|tablet|pixel.*tab/i.test(device.name) ? "tablet" : "phone", running: device.state === "Booted",
- canStop: device.state === "Booted" && (platform === "ios" || /^emulator-\d+$/.test(device.udid)),
- };
- });
- devices.update({
- items: [...physicalOptions, ...androidPhysicalOptions, ...simulatorOptions],
- value: nextDevice?.udid ?? "",
- placeholder: available.length ? "Select a device" : next.connected ? "No devices" : "Devices unavailable",
- });
- selectDevice();
- if (platform === "android" && !available.length && (next.setupHint || !next.connected)) {
- empty(next.connected ? "No Android devices." : "Android devices unavailable.", next.setupHint ?? next.error);
- } else if (next.localIosSupported === false && !available.length) {
- empty("Local iOS devices require macOS.", "Choose Android to use a local emulator or connected Android device.");
- } else if (!next.connected && physicalDevices.length === 0) {
- empty("Could not start the simulator backend.");
- notice(next.error);
+ controls();
+ if (inventory.error !== discoveryError) {
+ discoveryError = inventory.error;
+ notice();
}
+ if (!reconnect.active && active) void resume();
}
async function connect() {
- if (disposed || !toolsAvailable || !selected) return;
+ if (disposed || !visible || !toolsAvailable || !selected) return;
const connected = selected.kind === "physical" && selected.platform === "ios" ? selected.state === "connected" : selected.state === "Booted";
if (connected === false) return;
await disconnect();
- if (document.visibilityState === "hidden" || disposed) return;
+ if (!visible || document.visibilityState === "hidden" || disposed) return;
if (frame.hidden) empty("Connecting…", "Opening the device screen.");
const sessionEpoch = epoch;
const udid = selected.udid;
@@ -656,13 +577,7 @@ export function createSimulatorPanel(
finally { await closePanel(session); }
}
- const arrivals = new FrameArrivals();
- function observeFrame(event: MessageEvent) {
- if (event.source !== window.parent) return;
- const arrivedAt = performance.timeOrigin + performance.now();
- arrivals.record(event.data, arrivedAt);
- }
- if (platform === "ios") window.addEventListener("message", observeFrame);
+ const stopObservingFrames = platform === "ios" ? observeFrameArrivals() : undefined;
async function receiveFrames(session: PanelStream, signal: AbortSignal) {
const uri = new URL(session.frameUri);
@@ -686,7 +601,7 @@ export function createSimulatorPanel(
uri.searchParams.set("after", String(after));
const resource = await app.readServerResource({ uri: uri.href }, { signal: readSignal, timeout: 15000 });
const result = readFrame(resource);
- const browserArrivedAt = arrivals.take(uri.href, result.serverPreparedAt) ?? performance.timeOrigin + performance.now();
+ const browserArrivedAt = frameArrivals.take(uri.href, result.serverPreparedAt) ?? performance.timeOrigin + performance.now();
browserProfile.response(result.serverPreparedAt,
browserArrivedAt, result.frame?.sequence ?? null);
if (result.connectionState === "reconnecting") {
@@ -717,7 +632,6 @@ export function createSimulatorPanel(
browserProfile.stop();
decoder.close();
session.reader = undefined;
- arrivals.clear();
}
}
@@ -730,7 +644,6 @@ export function createSimulatorPanel(
if (pausedFrame.width !== width || pausedFrame.height !== height) { pausedFrame.width = width; pausedFrame.height = height; }
pausedFrame.getContext("2d")?.drawImage(image, 0, 0);
} else {
- stoppedDisplay = false;
element("stopped").hidden = true;
resized = canvas.width !== width || canvas.height !== height;
if (resized) { canvas.width = width; canvas.height = height; }
@@ -825,116 +738,31 @@ export function createSimulatorPanel(
} finally { decoder.close(); }
}
- async function listDevices() {
- if (listing) return listing;
- listing = readDevices();
- try { await listing; }
- finally { listing = undefined; }
- }
-
- async function readDevices() {
- const revision = ++statusRevision;
- const simulatorRead = call(platform === "android" ? "mobile_list_android_devices" : "mobile_list_simulators");
- if (platform === "android") {
- const result = await simulatorRead;
- if (revision === statusRevision && !disposed) {
- updateBookingNames(result._meta?.bookingNames);
- renderStatus(result.structuredContent as Status);
- if (!busy && !reconnect.active) await connect();
- }
- return;
- }
- const physicalRead = call("mobile_list_ios_devices");
- const results = await Promise.allSettled([simulatorRead, physicalRead]);
- if (revision !== statusRevision || disposed) return;
- const [simulators, physical] = results;
- const errors: string[] = [];
- let next: Status;
- if (simulators.status === "fulfilled") next = simulators.value.structuredContent as Status;
- else {
- const error = simulators.reason instanceof Error ? simulators.reason.message : String(simulators.reason);
- next = { connected: false, managed: false, baseUrl: "", devices: [], error };
- }
- if (next.error) errors.push(next.error);
- if (physical.status === "fulfilled") {
- const data = physical.value.structuredContent as { physicalDevices: PhysicalIosDevice[] };
- physicalDevices = data.physicalDevices.filter(device => device.state === "connected");
- } else {
- physicalDevices = [];
- const error = physical.reason instanceof Error ? physical.reason.message : String(physical.reason);
- errors.push(error);
- }
- discoveryError = errors.join(" · ");
- renderStatus(next);
- notice();
- if (!busy && !reconnect.active) await connect();
- }
-
- function scheduleDiscovery() {
- if (disposed || discoveryTimer !== undefined) return;
- discoveryTimer = setTimeout(async () => {
- discoveryTimer = undefined;
- try {
- if (document.visibilityState === "visible" && !root.hidden && !busy && toolsAvailable) await listDevices();
- } catch (error) {
- notice(error instanceof Error ? error.message : String(error));
- } finally { scheduleDiscovery(); }
- }, 3000);
- }
-
async function start() {
- await listDevices();
- if (!selected) return;
- if (selected.kind === "physical") {
- const connected = selected.platform === "ios" ? selected.state === "connected" : selected.state === "Booted";
- if (connected) await connect();
- return;
- }
- if (selected.state !== "Booted") {
- empty("Starting simulator…", "The screen will appear when the device is ready.");
- const before = selected;
- const result = await call(platform === "android" ? "mobile_boot_android_emulator" : "mobile_boot_simulator",
- platform === "android" ? { deviceId: before.udid } : { udid: before.udid }, { timeout: 300000 });
- if (platform === "android") updateBookingNames(result._meta?.bookingNames);
- renderStatus(result.structuredContent as Status);
- if (platform === "android") {
- const booted = status?.devices.find(device => device.kind !== "physical" && device.name === before.name && device.state === "Booted");
- if (booted) { devices.value = booted.udid; selectDevice(); }
- }
+ const device = selected;
+ if (!device || disposed) return;
+ if (device.kind !== "physical" && device.state !== "Booted") {
+ empty("Starting device…", "The screen will appear when the device is ready.");
+ await inventory.power(device, true);
}
await connect();
}
- devices.refresh = async () => { if (!busy && !disposed && toolsAvailable) await listDevices(); };
-
- devices.stop = async id => {
- const device = status?.devices.find(device => device.udid === id);
+ async function stop() {
+ const device = selected;
if (busy || disposed || !toolsAvailable || device?.state !== "Booted") throw new Error("This device is no longer running.");
- if (device.kind === "physical") throw new Error("Only simulators and emulators can be stopped from this panel.");
- const wasSelected = selected?.udid === id;
- statusRevision++;
busy = true;
controls();
try {
- if (wasSelected) await disconnect();
- const result = await call(platform === "android" ? "mobile_shutdown_android_emulator" : "mobile_shutdown_simulator", platform === "android" ? { deviceId: id } : { udid: id }, { timeout: platform === "android" ? 150_000 : 30_000 });
- if (platform === "android") updateBookingNames(result._meta?.bookingNames);
- const next = result.structuredContent as Status;
- const selectedId = wasSelected && platform === "android" ? next.devices.find(item => item.kind !== "physical" && item.name === device.name)?.udid : selected?.udid;
- if (wasSelected && next.connected) stoppedDisplay = true;
- renderStatus(next, selectedId);
- if (wasSelected && stoppedDisplay) {
- element("empty").hidden = true;
- element("stopped").hidden = false;
- fitScreen();
- }
+ await disconnect();
+ await inventory.power(device, false);
} catch (error) {
notice(error instanceof Error ? error.message : String(error));
- await listDevices().catch(() => {});
- if (wasSelected && selected?.udid === id && selected.state === "Booted") await connect().catch(() => {});
+ await inventory.refresh();
+ if (selectedDeviceConnected()) await connect();
throw error;
} finally { busy = false; controls(); }
- };
+ }
function mappedPoint(event: PointerEvent) {
const rect = canvas.getBoundingClientRect();
@@ -990,18 +818,22 @@ export function createSimulatorPanel(
Object.assign(pointer, mappedPoint(event));
send({ type: "touch1-move", x: pointer.x, y: pointer.y, ...points, ...(pointer.edge ? { edge: pointer.edge } : {}) });
});
- canvas.addEventListener("pointerleave", () => { if (annotationPointer === undefined) annotations.hover(); void testRecorder.hover(); });
+ canvas.addEventListener("pointerleave", () => {
+ if (annotationPointer === undefined) annotations.hover();
+ if (isRecordingSelected()) void testRecorder.hover();
+ });
// Right-click asks what can be done with the element the outline is on, instead of the browser's
// own menu over a canvas that has nothing in it to copy. The menu itself is drawn by the
// recorder overlay, which already has the outline's rectangle to anchor to.
// Escape closes the element menu. On the window and in the capture phase, so it beats the
// canvas's own key handling, which would otherwise forward the key to the device.
- window.addEventListener("keydown", event => {
- if (disposed || event.key !== "Escape" || !testRecorder.getSnapshot().menu) return;
+ function dismissRecorderMenu(event: KeyboardEvent) {
+ if (!isRecordingSelected() || event.key !== "Escape" || !testRecorder.getSnapshot().menu) return;
event.preventDefault();
event.stopPropagation();
testRecorder.closeMenu();
- }, { capture: true });
+ }
+ window.addEventListener("keydown", dismissRecorderMenu, true);
canvas.addEventListener("contextmenu", event => {
if (!isRecordingSelected() || annotations.getSnapshot().selecting) return;
event.preventDefault();
@@ -1071,19 +903,6 @@ export function createSimulatorPanel(
send(message.data);
}
canvas.addEventListener("paste", paste);
- devicePickerElement.addEventListener("change", () => {
- openingTarget = undefined;
- void action(async () => { await disconnect(); selectDevice(); await start(); });
- });
- /** Shows a listed, booted device in this mirror exactly as choosing it in the picker does. */
- function showDevice(udid: string): boolean {
- const listed = status?.devices.find(device => device.udid === udid) ?? physicalDevices.find(device => device.udid === udid);
- if (!listed || listed.state !== "Booted" && listed.state !== "connected") return false;
- if (devices.value !== udid) devices.value = udid;
- if (devices.value !== udid) return false;
- if (selected?.udid !== udid) devicePickerElement.dispatchEvent(new Event("change"));
- return true;
- }
element("start-device").addEventListener("click", () => { void action(start); });
root.querySelectorAll("[data-button]").forEach(button => {
button.addEventListener("click", () => { send({ type: "button", button: button.dataset.button === "home" ? "home" : "app-switcher" }); });
@@ -1123,14 +942,14 @@ export function createSimulatorPanel(
}); });
root.addEventListener("pointerdown", activate, { capture: true });
root.addEventListener("focusin", activate);
- function activate() { selectionChanged(selected, true); }
function resume() {
+ if (!visible || document.visibilityState === "hidden") return Promise.resolve();
if (busy) { resumeRequested = true; return Promise.resolve(); }
return action(connect);
}
function onVisibility() {
const connected = selectedDeviceConnected();
- if (document.visibilityState === "hidden") void disconnect();
+ if (!visible || document.visibilityState === "hidden") void disconnect();
else if (toolsAvailable && connected && !ready && !disposed) void resume();
}
document.addEventListener("visibilitychange", onVisibility);
@@ -1142,26 +961,25 @@ export function createSimulatorPanel(
root,
platform,
get selected() { return selected; },
- showDevice,
- get localIosSupported() { return status?.localIosSupported; },
fitScreen,
controls,
notice,
empty,
resume,
- setOpeningTarget(target: PanelTarget | undefined) {
- openingTarget = target;
- if (status !== undefined) renderStatus(status);
+ acceptDevice,
+ start: () => action(start),
+ stop,
+ setVisible(value: boolean) {
+ if (visible === value) return;
+ visible = value;
+ onVisibility();
},
- load: () => action(async () => { await listDevices(); scheduleDiscovery(); await connect(); }),
- acceptStatus(next: Status) { renderStatus(next); if (toolsAvailable && !reconnect.active) void resume(); },
setAvailable(value: boolean) { toolsAvailable = value; controls(); },
dispose() {
if (disposing) return disposing;
disposed = true;
- clearTimeout(discoveryTimer);
- devices.stop = undefined;
- devices.refresh = undefined;
+ detachRecorder();
+ window.removeEventListener("keydown", dismissRecorderMenu, true);
settings.dispose();
resourceSaving.dispose();
appTools.dispose();
@@ -1172,8 +990,7 @@ export function createSimulatorPanel(
window.removeEventListener("blur", releasePointer);
window.removeEventListener("blur", cancelAnnotationPointer);
canvas.removeEventListener("paste", paste);
- window.removeEventListener("message", observeFrame);
- arrivals.clear();
+ stopObservingFrames?.();
document.removeEventListener("visibilitychange", onVisibility);
window.removeEventListener("pageshow", onVisibility);
window.removeEventListener("focus", onVisibility);
diff --git a/packages/ui/src/style.css b/packages/ui/src/style.css
index 434d4f51..4464fd4d 100644
--- a/packages/ui/src/style.css
+++ b/packages/ui/src/style.css
@@ -411,6 +411,30 @@ html[data-theme="dark"] .tracesift-explorer { color-scheme: dark; }
.tracesift-upload .upload-pane { transition: none; }
}
+#simulator-panels .device-dock {
+ color-scheme: inherit;
+ background: var(--border);
+ --dv-group-view-background-color: var(--background);
+ --dv-tabs-and-actions-container-height: 34px;
+ --dv-tabs-and-actions-container-background-color: var(--muted);
+ --dv-activegroup-visiblepanel-tab-background-color: var(--background);
+ --dv-activegroup-hiddenpanel-tab-background-color: transparent;
+ --dv-inactivegroup-visiblepanel-tab-background-color: var(--background);
+ --dv-inactivegroup-hiddenpanel-tab-background-color: transparent;
+ --dv-activegroup-visiblepanel-tab-color: var(--foreground);
+ --dv-inactivegroup-visiblepanel-tab-color: var(--foreground);
+ --dv-activegroup-hiddenpanel-tab-color: var(--muted-foreground);
+ --dv-inactivegroup-hiddenpanel-tab-color: var(--muted-foreground);
+ --dv-separator-border: var(--border);
+ --dv-icon-hover-background-color: var(--accent);
+ --dv-active-sash-color: var(--ring);
+ --dv-drag-over-background-color: color-mix(in srgb, var(--ring) 18%, transparent);
+ --dv-drag-over-border: 1px solid var(--ring);
+ --dv-tab-font-size: 12px;
+}
+.device-dock .dv-active-group .dv-active-tab { box-shadow: inset 0 2px var(--foreground); }
+.device-dock .dv-default-tab { cursor: grab; }
+.device-dock .dv-default-tab-content { max-width: 24ch; overflow: hidden; text-overflow: ellipsis; }
/*
* The recorded test's preview. A step is added by tapping the mirror, where the user is looking —
* not at the preview — so the new lines announce themselves: they settle in, hold a tint long
diff --git a/packages/ui/src/telemetry.ts b/packages/ui/src/telemetry.ts
index 03a1c4cb..4000f1f3 100644
--- a/packages/ui/src/telemetry.ts
+++ b/packages/ui/src/telemetry.ts
@@ -151,11 +151,15 @@ export function setUiSurface(next: Surface) {
}
}
-export function setUiTelemetryContext(next: TelemetryAttributes) {
+export function setUiTelemetryContext(next: Partial) {
const changed = Object.entries(next).some(([key, value]) => attributes[key] !== value);
if (changed === false) return;
flushUiMeasurements();
- attributes = { ...attributes, ...next };
+ attributes = { ...attributes };
+ for (const [key, value] of Object.entries(next)) {
+ if (value === undefined) delete attributes[key];
+ else attributes[key] = value;
+ }
if (running) Sentry.setAttributes(attributes);
}
diff --git a/packages/ui/src/workspace-devices.ts b/packages/ui/src/workspace-devices.ts
deleted file mode 100644
index 553d8615..00000000
--- a/packages/ui/src/workspace-devices.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { panelTargetPlatform } from "@mobile-dev/shared/panel-target.ts";
-import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts";
-import { activeDeviceLayout } from "./device-layout.ts";
-import type { DeviceLayout } from "./device-layout.ts";
-import type { createSimulatorPanel } from "./simulator-panel.ts";
-
-type SimulatorPanel = ReturnType;
-
-export class WorkspaceDevices {
- private readonly panels: readonly [SimulatorPanel, SimulatorPanel];
- private readonly onLayout: (layout: DeviceLayout) => void;
- private target?: PanelTarget;
- private available = false;
- private loading?: Promise;
- private disposed = false;
- private manualLayout = false;
- /**
- * The layout this chose for the user, so an unresolved one can still be finished.
- *
- * The automatic layout used to be decided exactly once, from the **first** device list. A list
- * that came back before the backend had found anything — which is the ordinary case, since the
- * opening tool starts the backend — resolved to "none", both panels stayed hidden, and nothing
- * ever looked again: the user had a booted simulator, an empty workspace, a platform selector
- * reading "Platforms", and a panel telling them to boot a simulator. Discovery finds the device
- * a moment later and the panels select it, so what was missing was somebody asking again.
- */
- private reported?: DeviceLayout;
-
- constructor(panels: readonly [SimulatorPanel, SimulatorPanel], onLayout: (layout: DeviceLayout) => void) {
- this.panels = panels;
- this.onLayout = onLayout;
- }
-
- open(target: PanelTarget): Promise {
- if (this.target !== undefined || this.disposed) return Promise.resolve();
- this.target = target;
- if (this.manualLayout === false) {
- for (const panel of this.panels) panel.setOpeningTarget(target);
- const platform = panelTargetPlatform(target);
- if (platform !== undefined) this.report(platform);
- }
- return this.load();
- }
-
- setAvailable(available: boolean): Promise {
- this.available = available;
- for (const panel of this.panels) panel.setAvailable(available);
- return this.load();
- }
-
- selectLayout() {
- this.manualLayout = true;
- for (const panel of this.panels) panel.setOpeningTarget(undefined);
- }
-
- /**
- * Finishes an automatic layout that resolved to "none", once a panel has a device to show.
- *
- * Called whenever a panel's selection changes, which is what device discovery does when it finds
- * the simulator the first list missed. It only ever turns "none" into a platform: a layout that
- * resolved to something, and any layout the user chose themselves, are left exactly as they are.
- */
- settleLayout() {
- // An unresolved layout is one that was never reported, or was reported as "none".
- if (this.disposed || this.manualLayout) return;
- if (this.reported !== undefined && this.reported !== "none") return;
- const [ios, android] = this.panels;
- const layout = activeDeviceLayout(ios.selected, android.selected);
- if (layout !== "none") this.report(layout);
- }
-
- private report(layout: DeviceLayout) {
- this.reported = layout;
- this.onLayout(layout);
- }
-
- dispose() { this.disposed = true; }
-
- private load(): Promise {
- if (this.available === false || this.target === undefined || this.disposed) return Promise.resolve();
- this.loading ??= this.loadPanels();
- return this.loading;
- }
-
- private async loadPanels() {
- const [ios, android] = this.panels;
- const iosLoad = ios.load();
- const androidLoad = android.load();
- await Promise.all([iosLoad, androidLoad]);
- if (this.disposed || this.manualLayout) return;
- const target = this.target!;
- let layout: DeviceLayout | undefined = panelTargetPlatform(target);
- if (layout === undefined) layout = activeDeviceLayout(ios.selected, android.selected);
- if (layout === "none" && (target.kind !== undefined || target.deviceId !== undefined)) {
- layout = ios.selected ? "ios" : android.selected ? "android" : "both";
- }
- if (layout === "none" && ios.localIosSupported === false) layout = "android";
- this.report(layout);
- }
-}
diff --git a/packages/ui/test/device-layout.test.ts b/packages/ui/test/device-layout.test.ts
index 045d407b..b5f62938 100644
--- a/packages/ui/test/device-layout.test.ts
+++ b/packages/ui/test/device-layout.test.ts
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { activeDeviceLayout, initialPanelDevice } from "../src/device-layout.ts";
+import { isDeviceActive, initialPanelDevice } from "../src/device-layout.ts";
import { panelTargetSchema } from "../../shared/src/panel-target.ts";
import type { SimulatorDevice } from "../../shared/src/protocol.ts";
import type { PanelTarget } from "../../shared/src/panel-target.ts";
@@ -13,27 +13,12 @@ const iosPhone: SimulatorDevice = {
};
const androidPhone: SimulatorDevice = { udid: "phone", name: "Pixel", model: "Pixel", state: "Booted", runtime: "Android", platform: "android", kind: "physical", transportType: "wired" };
-test("one active platform opens by default, preferring iOS when both have active devices", () => {
- for (const ios of [iosSimulator, iosPhone]) {
- assert.equal(activeDeviceLayout(ios), "ios");
- for (const android of [androidEmulator, androidPhone]) {
- assert.equal(activeDeviceLayout(undefined, android), "android");
- assert.equal(activeDeviceLayout(ios, android), "ios");
- }
- }
-});
-
-test("stopped, disconnected, offline, and unauthorized devices do not activate a platform", () => {
- const inactiveIos: SimulatorDevice[] = [{ ...iosSimulator, state: "Shutdown" }, { ...iosPhone, state: "disconnected" }];
- const inactiveAndroid: SimulatorDevice[] = [{ ...androidEmulator, state: "Shutdown" }, { ...androidPhone, state: "offline" }, { ...androidPhone, state: "unauthorized" }];
- assert.equal(activeDeviceLayout(), "none");
- for (const ios of inactiveIos) {
- assert.equal(activeDeviceLayout(ios, androidPhone), "android");
- for (const android of inactiveAndroid) {
- assert.equal(activeDeviceLayout(iosPhone, android), "ios");
- assert.equal(activeDeviceLayout(ios, android), "none");
- }
+test("only booted virtual devices and connected physical devices are active", () => {
+ for (const device of [iosSimulator, androidEmulator, iosPhone, androidPhone]) assert.ok(isDeviceActive(device));
+ for (const state of ["Shutdown", "disconnected", "offline", "unauthorized"]) {
+ assert.equal(isDeviceActive({ ...androidPhone, state }), false);
}
+ assert.equal(isDeviceActive(undefined), false);
});
test("opening targets validate platform and kind without filling in undecided choices", () => {
diff --git a/packages/ui/test/react-ui.test.ts b/packages/ui/test/react-ui.test.ts
index e56a22cb..3c94c9b7 100644
--- a/packages/ui/test/react-ui.test.ts
+++ b/packages/ui/test/react-ui.test.ts
@@ -22,7 +22,8 @@ import { logKey } from "../../shared/src/logs.ts";
import type { StackedLog } from "../../shared/src/logs.ts";
import type { CpuBatch } from "../../shared/src/cpu.ts";
import { UDID } from "../../test-support/fixtures.ts";
-import type { DeviceLayout } from "../src/device-layout.ts";
+import { DeviceWorkspace } from "../src/device-workspace.ts";
+import type { SimulatorDevice } from "../../shared/src/protocol.ts";
test("React log controls filter virtual rows, attach full logs, and preserve simulator DOM", async t => {
const dom = new JSDOM('
', { pretendToBeVisual: true, url: "http://localhost" });
@@ -61,9 +62,9 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
await rm(directory, { recursive: true, force: true });
});
const output = resolve(directory, "workspace.mjs");
- await build({ stdin: { contents: 'export { Workspace } from "./packages/mcp-app/src/components/workspace.tsx"; export { getDeviceSettings } from "./packages/ui/src/device-settings.ts"; export { getDevicePicker } from "./packages/ui/src/device-picker.ts"; export { getAppTools } from "./packages/ui/src/app-tools.ts";', resolveDir: process.cwd(), loader: "ts" }, outfile: output, bundle: true, format: "esm", platform: "node", jsx: "automatic",
+ await build({ stdin: { contents: 'export { Workspace } from "./packages/mcp-app/src/components/workspace.tsx"; export { getDeviceSettings } from "./packages/ui/src/device-settings.ts"; export { getAppTools } from "./packages/ui/src/app-tools.ts";', resolveDir: process.cwd(), loader: "ts" }, outfile: output, bundle: true, format: "esm", platform: "node", jsx: "automatic",
external: ["recharts", "react", "react/*", "react-dom", "react-dom/*", "@legendapp/list/react", "radix-ui", "lucide-react", "@base-ui/react/*", "react-resizable-panels", "@xyflow/react"] });
- const { Workspace, getDeviceSettings, getDevicePicker, getAppTools } = await import(pathToFileURL(output).href);
+ const { Workspace, getDeviceSettings, getAppTools } = await import(pathToFileURL(output).href);
const { act, createElement, Profiler } = await import("react");
const { createRoot } = await import("react-dom/client");
let sentLog: StackedLog | undefined;
@@ -134,79 +135,56 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
deviceApps.setAvailable(true);
const root = createRoot(dom.window.document.getElementById("root")!);
cleanupView = async () => { recordingController.dispose(); await act(async () => { root.unmount(); await panel.dispose(); deviceApps.dispose(); storage.dispose(); tracesift.dispose(); await performance.dispose(); }); };
- const layouts: string[] = [];
+ const iphone: SimulatorDevice = { udid: UDID, name: "iPhone", state: "Booted", runtime: "iOS" };
+ const ipad: SimulatorDevice = { ...iphone, udid: "ipad", name: "iPad" };
+ const pixel: SimulatorDevice = { ...iphone, udid: "emulator-5554", name: "Pixel", platform: "android", kind: "emulator" };
+ const bookedPhone: SimulatorDevice = { ...pixel, kind: "physical", udid: "booked-phone", name: "Pixel 9", state: "connected", transportType: "localNetwork" };
+ const discovery = {
+ async callServerTool({ name }: { name: string }) {
+ if (name === "mobile_list_ios_devices") return { structuredContent: { physicalDevices: [] } };
+ if (name === "mobile_list_android_devices") return { structuredContent: { connected: true, devices: [pixel, bookedPhone] }, _meta: { bookingNames: { [bookedPhone.udid]: "Test " } } };
+ return { structuredContent: { connected: true, devices: [iphone, ipad] } };
+ },
+ };
+ const devices = new DeviceWorkspace(discovery as unknown as App, {
+ context: { selectSimulators() {} } as unknown as PanelContext, deviceApps,
+ });
+ // This view test drives the settings and app stores directly. Stream sessions have separate controller tests.
+ devices.mount = () => undefined;
+ t.after(() => devices.dispose());
+ await devices.setAvailable(true);
+ await devices.open({});
let commits = 0;
- const onLayout = (layout: string) => { layouts.push(layout); };
- const renderWorkspace = (automaticLayout?: DeviceLayout) => {
- const workspace = createElement(Workspace, { panels, recordingController, automaticLayout, onLayout });
+ const renderWorkspace = () => {
+ const workspace = createElement(Workspace, { panels, recordingController, devices });
const profiled = createElement(Profiler, { id: "workspace", onRender() { commits++; } }, workspace);
root.render(profiled);
};
await act(async () => { renderWorkspace(); });
- const canvas = dom.window.document.querySelector('canvas');
- const iosPanel = dom.window.document.getElementById("ios-panel") as HTMLElement;
- const androidPanel = dom.window.document.getElementById("android-panel") as HTMLElement;
- for (const layout of ["android", "both", "none", "ios"] as const) {
- await act(async () => { renderWorkspace(layout); });
- assert.equal(iosPanel.hidden, layout === "android" || layout === "none");
- assert.equal(androidPanel.hidden, layout === "ios" || layout === "none");
- assert.equal(dom.window.document.querySelector("canvas"), canvas, "Device discovery preserves the mounted stream canvas.");
- assert.equal(layouts.at(-1), layout);
- const platformLabel = layout === "both" ? "Both" : layout === "none" ? "Platforms" : layout === "ios" ? "iOS" : "Android";
- const triggerText = dom.window.document.getElementById("platform-select")?.textContent ?? "";
- assert.ok(triggerText.startsWith(platformLabel));
- // The sidebar shows the tools and platform selects in one bar under the simulators.
- const toolbars = dom.window.document.querySelectorAll('nav[aria-label="Developer tools"]');
- assert.equal(toolbars.length, 1);
- const simulators = dom.window.document.getElementById("simulator-panels")!;
- assert.equal(toolbars[0].previousElementSibling === simulators, layout !== "none");
- assert.deepEqual([...toolbars[0].querySelectorAll("button")].map(button => button.id), ["tool-select", "platform-select"]);
- assert.equal(dom.window.document.querySelector('[role="toolbar"] #tool-select'), null);
+ const canvas = dom.window.document.querySelector("canvas");
+ const picker = dom.window.document.querySelector("[data-device-add]") as HTMLButtonElement;
+ async function toggleDevice(id: string) {
+ await act(async () => { picker.click(); });
+ const button = dom.window.document.querySelector(`[data-device-option="${id}"]`) as HTMLButtonElement;
+ await act(async () => { button.click(); });
+ assert.equal(picker.getAttribute("aria-expanded"), "false");
}
- layouts.length = 0;
- const picker = dom.window.document.querySelector('[data-element="devices"] [data-slot="select-trigger"]');
- assert.ok(picker);
- const pickerElement = dom.window.document.querySelector('#ios-panel [data-element="devices"]')!;
- const pickerStore = getDevicePicker(pickerElement);
- let pickerRefreshes = 0;
- pickerStore.refresh = async () => { pickerRefreshes++; };
- let deviceChanges = 0;
- pickerElement.addEventListener("change", () => { deviceChanges++; });
- await act(async () => { pickerStore.update({ value: "iphone", disabled: false, items: [{ value: "iphone", label: "iPhone", running: true, canStop: true }, { value: "ipad", label: "iPad", running: false, canStop: false }] }); });
- await act(async () => { (picker as HTMLButtonElement).click(); });
- await act(async () => { (dom.window.document.querySelector('[data-device-option="iphone"]') as HTMLButtonElement).click(); });
- assert.equal(deviceChanges, 1, "Reselecting a running device retries its connection.");
- assert.equal(pickerRefreshes, 1);
- deviceChanges = 0;
- let stoppedDevice = "";
- pickerStore.stop = async (id: string) => { stoppedDevice = id; pickerStore.update({ items: [{ value: "iphone", label: "iPhone", running: false, canStop: false }, { value: "ipad", label: "iPad", running: false, canStop: false }] }); };
- await act(async () => { (picker as HTMLButtonElement).click(); });
- const stopButton = dom.window.document.querySelector('[aria-label="Stop iPhone"]') as HTMLButtonElement;
- assert.ok(stopButton);
- assert.equal(dom.window.document.querySelector('[aria-label="Stop iPad"]'), null);
- assert.equal(stopButton.querySelector("svg")?.classList.contains("fill-current"), true);
- await act(async () => { stopButton.click(); });
- assert.equal(stoppedDevice, "iphone");
- assert.equal(deviceChanges, 0);
- assert.equal(pickerStore.value, "iphone");
- await act(async () => { (dom.window.document.querySelector('[data-device-option="iphone"]') as HTMLButtonElement).click(); });
- assert.equal(deviceChanges, 1);
- const androidPickerElement = dom.window.document.querySelector('#android-panel [data-element="devices"]')!;
- const androidPicker = getDevicePicker(androidPickerElement);
- const bookingName = "Test on Android";
- const deviceSpecs = "ADC Android 14 2 CPU 3 GiB RAM · Wi-Fi";
- const deviceSerial = "127.0.0.1:15555";
- await act(async () => {
- androidPicker.update({ value: deviceSerial, disabled: false, items: [{ value: deviceSerial, label: bookingName, detail: deviceSpecs, running: true }] });
- });
- const androidTrigger = androidPickerElement.querySelector('[data-slot="select-trigger"]') as HTMLButtonElement;
- assert.equal(androidTrigger.textContent, bookingName);
- await act(async () => { androidTrigger.click(); });
- const bookingOption = dom.window.document.querySelector(`[data-device-option="${deviceSerial}"]`)!;
- assert.equal(bookingOption.textContent, bookingName + deviceSpecs);
- assert.equal(bookingOption.querySelector("checkout"), null);
- await act(async () => { (bookingOption as HTMLButtonElement).click(); });
- const iosSettings = getDeviceSettings(dom.window.document.querySelector('#ios-panel [data-element="settings"]'));
+ await toggleDevice(ipad.udid);
+ await toggleDevice(pixel.udid);
+ assert.equal(dom.window.document.querySelectorAll("canvas").length, 3);
+ await act(async () => { picker.click(); });
+ assert.equal(dom.window.document.querySelectorAll('[data-device-option][aria-pressed="true"]').length, 3);
+ const booking = dom.window.document.querySelector('[data-device-option="booked-phone"]');
+ assert.ok(booking?.textContent?.includes("Test "));
+ assert.ok(booking.textContent.includes("Pixel 9 · Wi-Fi"));
+ assert.equal(booking.querySelector("checkout"), null);
+ await act(async () => { picker.click(); });
+ await toggleDevice(ipad.udid);
+ await toggleDevice(pixel.udid);
+ assert.equal(dom.window.document.querySelector("canvas"), canvas);
+ const closedDialog = dom.window.document.querySelector('[aria-label="Choose devices"]');
+ assert.equal(closedDialog, null);
+ const iosSettings = getDeviceSettings(dom.window.document.querySelector('[data-platform="ios"] [data-element="settings"]'));
const changes: unknown[] = [];
iosSettings.request = async (change: unknown) => { changes.push(change); return { appearance: "light", contentSize: "large", increaseContrast: false, locationSupported: true }; };
await act(async () => { iosSettings.configure("iphone", false); });
@@ -241,7 +219,7 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
assert.equal(iosSettings.getSnapshot().frame, false);
await act(async () => { settingsButton.click(); });
assert.equal(dom.window.document.querySelector("canvas"), canvas);
- const appTools = getAppTools(dom.window.document.querySelector('#ios-panel [data-element="settings"]'));
+ const appTools = getAppTools(dom.window.document.querySelector('[data-platform="ios"] [data-element="settings"]'));
const appCalls: { name: string; args: Record }[] = [];
appTools.call = async (name: string, args: Record) => {
appCalls.push({ name, args });
@@ -335,7 +313,7 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
assert.equal(dom.window.document.querySelectorAll("[data-log-row]").length, 1);
await act(async () => { levelFilter.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
assert.equal(dom.window.document.querySelector("canvas"), canvas);
- assert.equal(dom.window.document.querySelector('[data-element="devices"] [data-slot="select-trigger"]'), picker);
+ assert.equal(dom.window.document.querySelector("[data-device-add]"), picker);
assert.equal(dom.window.document.querySelector('[data-element="screenshot"] svg')?.getAttribute("viewBox"), "0 0 24 24");
await act(async () => { (dom.window.document.querySelector('[aria-label="Log sources"]') as HTMLButtonElement).click(); });
assert.ok(dom.window.document.getElementById("logs-native"));
@@ -496,7 +474,7 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
threadOrder.dispatchEvent(new dom.window.Event("change", { bubbles: true }));
});
assert.equal(dom.window.document.querySelector("canvas"), canvas);
- assert.equal(dom.window.document.querySelector('[data-element="devices"] [data-slot="select-trigger"]'), picker);
+ assert.equal(dom.window.document.querySelector("[data-device-add]"), picker);
await selectTool("logs");
assert.equal(panel.getSnapshot().open, true);
assert.equal(dom.window.document.getElementById("performance-drawer"), null);
@@ -525,25 +503,6 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
await act(async () => { collapseCpu.click(); });
assert.equal(dom.window.document.querySelectorAll("[data-cpu-thread]").length, 0);
await selectTool("logs");
- async function togglePlatform(platform: "ios" | "android") {
- if (!dom.window.document.getElementById(`platform-${platform}`)) {
- await act(async () => { (dom.window.document.getElementById("platform-select") as HTMLButtonElement).click(); });
- }
- await act(async () => { (dom.window.document.getElementById(`platform-${platform}`) as HTMLElement).click(); });
- }
- assert.equal((dom.window.document.getElementById("android-panel") as HTMLElement).hidden, true);
- await togglePlatform("android");
- await togglePlatform("ios");
- await togglePlatform("android");
- assert.deepEqual(layouts, ["both", "android", "none"]);
- await act(async () => { renderWorkspace("both"); });
- assert.equal(iosPanel.hidden, true);
- assert.equal(androidPanel.hidden, true);
- assert.deepEqual(layouts, ["both", "android", "none"], "Late discovery preserves a manual platform choice.");
- await togglePlatform("ios");
- await togglePlatform("android");
- assert.deepEqual(layouts, ["both", "android", "none", "ios", "both"]);
- assert.equal(dom.window.document.querySelector("canvas"), canvas);
await selectTool("storage");
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
assert.deepEqual(storageCalls, ["mobile_list_apps", "mobile_app_icons", "mobile_app_storage"]);
@@ -582,9 +541,9 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim
assert.ok(showsPerformance);
assert.equal(dom.window.document.querySelector(".recording-overview-bar")?.getAttribute("aria-label"), "Selected range: 12.0s–18.0s");
assert.ok(dom.window.document.body.textContent?.includes("Checkout scroll · Run 1"));
- assert.equal(layouts.at(-1), "none", "Opening a saved run gives the detailed chart the workspace.");
- await act(async () => { renderWorkspace("android"); });
- assert.equal(layouts.at(-1), "none", "Device discovery does not interrupt a saved recording.");
+ assert.deepEqual(devices.getSnapshot().panes, [], "Opening a saved run gives the detailed chart the workspace.");
+ await act(async () => { await devices.open({ platform: "android" }); });
+ assert.deepEqual(devices.getSnapshot().panes, [], "Device discovery does not interrupt a saved recording.");
assert.equal(cpuSessionsOpened, sessionsBeforeOpening, "Opening a saved recording does not start another collector.");
- assert.equal(dom.window.document.querySelector("canvas"), canvas, "Saved recordings preserve the existing device DOM.");
+ assert.equal(dom.window.document.querySelector("[data-device-pane]"), null);
});
diff --git a/packages/ui/test/screen-annotations-ui.test.ts b/packages/ui/test/screen-annotations-ui.test.ts
index 53de57ca..7bd66696 100644
--- a/packages/ui/test/screen-annotations-ui.test.ts
+++ b/packages/ui/test/screen-annotations-ui.test.ts
@@ -33,7 +33,7 @@ test("the simulator toolbar opens notes, saves blue markers, and lets users edit
const { act, createElement } = await import("react"); const { createRoot } = await import("react-dom/client");
const root = createRoot(dom.window.document.getElementById("root")!);
cleanup = async () => { await act(async () => { root.unmount(); }); };
- await act(async () => { root.render(createElement(SimulatorView, { platform: "ios", visible: true })); });
+ await act(async () => { root.render(createElement(SimulatorView, { workspace: { mount() {} }, paneKey: 1, platform: "ios", name: "iPhone", active: true })); });
const canvas = dom.window.document.querySelector("canvas");
const store = getScreenAnnotations(dom.window.document.querySelector('[data-element="stage"]'));
const context = new PanelContext({ getHostCapabilities: () => ({ updateModelContext: { image: {} }, message: { text: {} } }), async sendMessage() { return { isError: true }; } } as unknown as App, () => ({ getCurrent: () => undefined, update: async () => ({ updateId: "annotation-update" }) }));
diff --git a/packages/ui/test/simulator-panel.test.ts b/packages/ui/test/simulator-panel.test.ts
index 82dec66a..db3e0060 100644
--- a/packages/ui/test/simulator-panel.test.ts
+++ b/packages/ui/test/simulator-panel.test.ts
@@ -1,4 +1,7 @@
-import { getDevicePicker } from "../src/device-picker.ts";
+import { DeviceInventory } from "../src/device-inventory.ts";
+import { initialPanelDevice } from "../src/device-layout.ts";
+import { DeviceWorkspace, resolvePaneDevice } from "../src/device-workspace.ts";
+import type { PanelTarget } from "../../shared/src/panel-target.ts";
import test from "node:test";
import type { TestContext } from "node:test";
import assert from "node:assert/strict";
@@ -13,8 +16,6 @@ import type { SimulatorDevice } from "../../shared/src/protocol.ts";
import type { AndroidBookingNames, PhysicalAndroidDevice } from "../../shared/src/android-devices.ts";
import type { ScreenAnnotation } from "../../shared/src/screen-annotations.ts";
import type { ScreenshotAttachment } from "../src/model-context.ts";
-import { WorkspaceDevices } from "../src/workspace-devices.ts";
-import type { DeviceLayout } from "../src/device-layout.ts";
const physicalBezel = { rect: { x: 27, y: 18, width: 400, height: 872 }, viewport: { width: 454, height: 908 }, clipRadius: 62, image: "data:image/png;base64,AQID", mask: "data:image/png;base64,BAUG" };
@@ -54,6 +55,14 @@ class Element extends EventTarget {
querySelectorAll() { return this.buttons; }
}
+function createPanelRoot() {
+ const root = new Element();
+ for (const name of ["settings", "screen", "device-frame", "stage", "device-bezel", "screenshot", "notice", "notice-message", "empty", "empty-description", "stopped", "start-device", "screenshot-status"]) root.elements.set(name, new Element());
+ root.elements.get("device-frame")!.hidden = true;
+ for (const button of ["home", "app-switcher"]) { const element = new Element(); element.dataset.button = button; root.buttons.push(element); }
+ return root;
+}
+
function fixture(t: TestContext) {
const calls: { name: string; arguments: Record }[] = [];
const reads = new Set();
@@ -76,6 +85,7 @@ function fixture(t: TestContext) {
let simulatorError = "";
let delayedDiscovery: Promise | undefined;
let androidDevices: SimulatorDevice[] | undefined;
+ let iosDevices: SimulatorDevice[] | undefined;
let bookingNames: AndroidBookingNames | undefined;
const stoppedPlatforms = new Set();
let failedInputPlatform: "ios" | "android" | undefined;
@@ -164,6 +174,7 @@ function fixture(t: TestContext) {
if (physicalError) return { isError: true, content: [{ type: "text", text: physicalError }] };
return { content: [], structuredContent: { physicalDevices } };
}
+ if (call.name === "mobile_list_simulators" && iosDevices) return { content: [], structuredContent: { connected: true, devices: iosDevices } };
if (call.name === "mobile_list_simulators" && simulatorError) return { isError: true, content: [{ type: "text", text: simulatorError }] };
const inputTool = failedInputPlatform === "android" ? "mobile_android_stream_input" : "mobile_stream_input";
if (failedInputPlatform && call.name === inputTool) {
@@ -225,10 +236,7 @@ function fixture(t: TestContext) {
},
} as unknown as App;
const panels = (["ios", "android"] as const).map(platform => {
- const root = new Element();
- for (const name of ["devices", "settings", "screen", "device-frame", "stage", "device-bezel", "screenshot", "notice", "notice-message", "empty", "empty-description", "stopped", "start-device", "screenshot-status"]) root.elements.set(name, new Element());
- root.elements.get("device-frame")!.hidden = true;
- for (const button of ["home", "app-switcher"]) { const element = new Element(); element.dataset.button = button; root.buttons.push(element); }
+ const root = createPanelRoot();
const panelContext = {
canAttach: true, canAttachScreenshots: true, screenAnnotations: attachedAnnotations, subscribe: () => () => {},
async attachScreenshot(screenshot: ScreenshotAttachment) {
@@ -238,12 +246,49 @@ function fixture(t: TestContext) {
},
async attachAnnotation(annotation: ScreenAnnotation) { attachedAnnotations.push(annotation); return true; },
} as unknown as PanelContext;
- const panel = createSimulatorPanel(app, root as unknown as HTMLElement, platform, panelContext, (_device, active) => selections.push({ platform, active }));
+ const inventory = new DeviceInventory(app, platform);
+ const panel = createSimulatorPanel(app, root as unknown as HTMLElement, inventory, panelContext, () => selections.push({ platform, active: true }));
panel.setAvailable(true);
- return { panel, root, element: (name: string) => root.elements.get(name)! };
+ let last: SimulatorDevice | undefined;
+ let target: PanelTarget | undefined;
+ const sync = () => {
+ const devices = inventory.status?.devices ?? [];
+ const device = last ? resolvePaneDevice(devices, last, platform) : initialPanelDevice(devices, platform, undefined, target);
+ if (device) last = device;
+ panel.acceptDevice(device);
+ };
+ inventory.subscribe(sync);
+ const picker = {
+ get value() { return panel.selected?.udid ?? ""; },
+ getSnapshot() { return { items: inventory.items, value: panel.selected?.udid }; },
+ refresh: () => inventory.refresh(),
+ choose(id: string) {
+ const device = inventory.status?.devices.find(item => item.udid === id);
+ last = device;
+ panel.acceptDevice(device);
+ if (device?.state === "Shutdown") void panel.start();
+ },
+ async stopDevice(id: string) {
+ const option = inventory.items.find(item => item.value === id);
+ if (option?.canStop) await panel.stop();
+ },
+ };
+ return { panel, picker, inventory, root, element: (name: string) => root.elements.get(name)!,
+ load(opening?: PanelTarget) {
+ if (opening) { target = opening; last = undefined; }
+ return inventory.refresh();
+ },
+ };
+ });
+ let activeDevice: SimulatorDevice | undefined;
+ const context = { screenAnnotations: [], subscribe: () => () => {}, selectSimulators(_devices: SimulatorDevice[], active?: SimulatorDevice) { activeDevice = active; } } as unknown as PanelContext;
+ const workspace = new DeviceWorkspace(app, { context, deviceApps: { selectDevice() {} } } as ConstructorParameters[1]);
+ t.after(async () => {
+ await workspace.dispose();
+ for (const { panel } of panels) await panel.dispose();
+ for (const reset of restore) reset();
});
- t.after(async () => { await Promise.all(panels.map(({ panel }) => panel.dispose())); for (const reset of restore) reset(); });
- return { calls, closed, selections, failInspection() { inspectionFailure = true; }, setAndroidAccessibility(value: NonNullable) { androidAccessibility = value; }, screenshots, attachedAnnotations, ios: panels[0], android: panels[1], failClipboard() { screenshotCopied = false; }, setAndroidDevices(devices: SimulatorDevice[], names?: AndroidBookingNames) { androidDevices = devices; bookingNames = names; }, setPhysicalDevices(devices: PhysicalIosDevice[]) { physicalDevices = devices; }, failDiscovery(message: string) { physicalError = message; }, failSimulators(message: string) { simulatorError = message; }, delayDiscovery(value: Promise) { delayedDiscovery = value; }, failInput(platform: "ios" | "android") { failedInputPlatform = platform; }, delayOpen(value: Promise) { delayedOpen = value; }, blockIos() { blockedIos = true; }, stopDevices() { stopped = true; },
+ return { workspace, get activeDevice() { return activeDevice; }, setIosDevices(devices: SimulatorDevice[]) { iosDevices = devices; }, calls, closed, selections, failInspection() { inspectionFailure = true; }, setAndroidAccessibility(value: NonNullable) { androidAccessibility = value; }, screenshots, attachedAnnotations, ios: panels[0], android: panels[1], failClipboard() { screenshotCopied = false; }, setAndroidDevices(devices: SimulatorDevice[], names?: AndroidBookingNames) { androidDevices = devices; bookingNames = names; }, setPhysicalDevices(devices: PhysicalIosDevice[]) { physicalDevices = devices; }, failDiscovery(message: string) { physicalError = message; }, failSimulators(message: string) { simulatorError = message; }, delayDiscovery(value: Promise) { delayedDiscovery = value; }, failInput(platform: "ios" | "android") { failedInputPlatform = platform; }, delayOpen(value: Promise) { delayedOpen = value; }, blockIos() { blockedIos = true; }, stopDevices() { stopped = true; },
visibility(value: string) { document.visibilityState = value; document.dispatchEvent(new Event("visibilitychange")); },
frame(platform: "ios" | "android", sequence: number, options: { generation?: number; empty?: boolean } = {}) {
const id = [...pendingReads.keys()].find(id => id.startsWith(platform)); assert.ok(id);
@@ -273,167 +318,181 @@ const androidPhone: PhysicalAndroidDevice = {
platform: "android", kind: "physical", transportType: "wired",
};
-for (const inputFirst of [false, true]) test(`Android opening intent is applied before streams start, input first: ${inputFirst}`, async t => {
- const f = fixture(t);
- f.setAndroidDevices([androidPhone, { udid: "emulator-5554", name: "Pixel AVD", state: "Booted", runtime: "Android", platform: "android", kind: "emulator" }]);
- const layouts: DeviceLayout[] = [];
- const workspace = new WorkspaceDevices([f.ios.panel, f.android.panel], layout => { layouts.push(layout); });
- t.after(() => workspace.dispose());
- const target = { platform: "android", kind: "emulator" } as const;
- if (inputFirst) await workspace.open(target);
- else await workspace.setAvailable(true);
- assert.equal(f.calls.length, 0, "Discovery waits for both the host and the opening intent.");
- if (inputFirst) await workspace.setAvailable(true);
- else await workspace.open(target);
- assert.equal(f.ios.panel.selected, undefined);
- assert.equal(f.android.panel.selected?.udid, "emulator-5554");
- const streams = f.calls.filter(call => call.name.endsWith("_stream_session") || call.name === "mobile_ios_mirror_session");
- assert.equal(streams.length, 1);
- assert.equal(streams[0].name, "mobile_android_stream_session");
- assert.deepEqual(streams[0].arguments, { deviceId: "emulator-5554" });
- assert.deepEqual(layouts, ["android", "android"]);
-});
-
-test("opening an ADC serial streams that device even with another phone of the same model", async t => {
- const f = fixture(t);
- const adcPhone: PhysicalAndroidDevice = { ...androidPhone, udid: "127.0.0.1:15555", transportType: "localNetwork" };
- f.setAndroidDevices([androidPhone, adcPhone]);
- const workspace = new WorkspaceDevices([f.ios.panel, f.android.panel], () => {});
- t.after(() => workspace.dispose());
- await workspace.setAvailable(true);
- await workspace.open({ platform: "android", deviceId: adcPhone.udid });
-
- assert.equal(f.android.panel.selected?.udid, adcPhone.udid);
- const streams = f.calls.filter(call => call.name === "mobile_android_stream_session");
- const targets = streams.map(call => call.arguments);
- assert.deepEqual(targets, [{ deviceId: adcPhone.udid }]);
-});
-
-for (const platform of ["ios", "android"] as const) test(`${platform} physical opening intent selects the phone before any simulator`, async t => {
+for (const inputFirst of [false, true]) test(`opening an exact Android target waits for the host and intent, input first: ${inputFirst}`, async t => {
const f = fixture(t);
- f.setPhysicalDevices([physicalPhone]);
- f.setAndroidDevices([{ udid: "emulator-5554", name: "Pixel AVD", state: "Booted", runtime: "Android", kind: "emulator" }, androidPhone]);
- const layouts: DeviceLayout[] = [];
- const workspace = new WorkspaceDevices([f.ios.panel, f.android.panel], layout => { layouts.push(layout); });
- t.after(() => workspace.dispose());
- await workspace.setAvailable(true);
- await workspace.open({ platform, kind: "physical" });
- const panel = platform === "ios" ? f.ios.panel : f.android.panel;
- assert.equal(panel.selected?.kind, "physical");
- const streams = f.calls.filter(call => call.name.endsWith("_stream_session") || call.name === "mobile_ios_mirror_session");
- assert.equal(streams.length, 1);
- assert.equal(streams[0].name, platform === "ios" ? "mobile_ios_mirror_session" : "mobile_android_stream_session");
- const layout = layouts.at(-1);
- assert.equal(layout, platform);
+ const target = { platform: "android", kind: "physical", deviceId: androidPhone.udid } as const;
+ f.setAndroidDevices([androidPhone]);
+ if (inputFirst) await f.workspace.open(target);
+ else await f.workspace.setAvailable(true);
+ assert.equal(f.calls.length, 0);
+ if (inputFirst) await f.workspace.setAvailable(true);
+ else await f.workspace.open(target);
+ const panes = f.workspace.getSnapshot().panes;
+ assert.deepEqual(panes.map(pane => pane.device?.udid), [androidPhone.udid]);
});
test("missing exact target remains unselected through refreshes, then connects when it arrives", async t => {
const f = fixture(t);
- f.ios.panel.setOpeningTarget({ platform: "ios", kind: "physical", deviceId: physicalPhone.udid });
- await f.ios.panel.load();
+ await f.ios.load({ platform: "ios", kind: "physical", deviceId: physicalPhone.udid });
assert.equal(f.ios.panel.selected, undefined);
const emptyState = f.ios.element("empty");
- assert.equal(emptyState.textContent, "Requested device unavailable.");
- const pickerElement = f.ios.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
- await picker.refresh?.();
+ assert.equal(emptyState.textContent, "Device unavailable");
+ const picker = f.ios.picker;
+ await picker.refresh();
const initialStreams = f.calls.filter(call => call.name === "mobile_stream_session" || call.name === "mobile_ios_mirror_session");
assert.equal(initialStreams.length, 0);
f.setPhysicalDevices([physicalPhone]);
- await picker.refresh?.();
+ await picker.refresh();
await waitFor(() => f.calls.some(call => call.name === "mobile_ios_mirror_session"));
assert.equal(f.ios.panel.selected?.udid, physicalPhone.udid);
f.setPhysicalDevices([]);
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(f.ios.panel.selected, undefined, "Disconnecting the requested phone does not select a simulator.");
- picker.value = "iphone-1";
- dispatch(pickerElement, "change");
+ picker.choose("iphone-1");
await waitFor(() => f.calls.some(call => call.name === "mobile_stream_session"));
- await picker.refresh?.();
- assert.equal(f.ios.panel.selected?.udid, "iphone-1", "The user's later device choice replaces the opening constraint.");
+ await picker.refresh();
+ assert.equal(f.ios.panel.selected?.udid, "iphone-1");
});
-test("automatic opening retains iOS precedence and later manual layout survives duplicate results", async t => {
+test("manual same-platform and mixed selections survive repeated opening notifications", async t => {
const f = fixture(t);
- const layouts: DeviceLayout[] = [];
- const workspace = new WorkspaceDevices([f.ios.panel, f.android.panel], layout => { layouts.push(layout); });
- t.after(() => workspace.dispose());
- await workspace.open({});
- await workspace.setAvailable(true);
- const automaticLayout = layouts.at(-1);
- assert.equal(automaticLayout, "ios");
- workspace.selectLayout();
- layouts.push("android");
- const count = f.calls.length;
- await workspace.open({ platform: "ios" });
- assert.equal(f.calls.length, count);
- const manualLayout = layouts.at(-1);
- assert.equal(manualLayout, "android");
+ f.setPhysicalDevices([physicalPhone]);
+ f.setAndroidDevices([androidPhone]);
+ await f.workspace.open({});
+ await f.workspace.setAvailable(true);
+ const [first] = f.workspace.getSnapshot().panes;
+ assert.equal(first.device?.udid, "iphone-1");
+ f.workspace.toggle("ios", physicalPhone);
+ f.workspace.toggle("android", androidPhone);
+ await f.workspace.open({ platform: "android" });
+ const panes = f.workspace.getSnapshot().panes;
+ assert.deepEqual(panes.map(pane => pane.device?.udid), ["iphone-1", physicalPhone.udid, androidPhone.udid]);
+ f.workspace.activate(first.key);
+ f.workspace.toggle("ios", physicalPhone);
+ assert.equal(f.workspace.getSnapshot().active, first.key);
+ assert.deepEqual(f.workspace.getSnapshot().panes.map(pane => pane.key), [first.key, panes[2].key]);
});
test("targeted stopped AVD opens without booting and tracks its running serial after boot", async t => {
const f = fixture(t);
f.setAndroidDevices([{ udid: "avd:Pixel", name: "Pixel", state: "Shutdown", runtime: "Android", platform: "android", kind: "emulator" }]);
- f.android.panel.setOpeningTarget({ platform: "android", kind: "emulator", deviceId: "avd:Pixel" });
- await f.android.panel.load();
+ await f.android.load({ platform: "android", kind: "emulator", deviceId: "avd:Pixel" });
assert.equal(f.android.panel.selected?.state, "Shutdown");
const startButton = f.android.element("start-device");
assert.equal(startButton.disabled, false);
const lifecycle = f.calls.filter(call => call.name.startsWith("mobile_boot"));
assert.equal(lifecycle.length, 0);
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ const picker = f.android.picker;
f.setAndroidDevices([]);
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(f.android.panel.selected, undefined);
f.setAndroidDevices([{ udid: "emulator-5554", name: "Pixel", state: "Booted", runtime: "Android", platform: "android", kind: "emulator" }]);
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(f.android.panel.selected?.udid, "emulator-5554");
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(f.android.panel.selected?.udid, "emulator-5554");
});
-test("a platform chosen during discovery is not overwritten when startup finishes", async t => {
+test("two same-platform screens and an Android screen route input independently and release only the removed stream", async t => {
+ const f = fixture(t);
+ const iphone: SimulatorDevice = { udid: "iphone-1", name: "iPhone", runtime: "iOS", state: "Booted" };
+ const ipad = { ...iphone, udid: "ipad-2", name: "iPad" };
+ f.setIosDevices([iphone, ipad]);
+ f.setAndroidDevices([androidPhone]);
+ await f.workspace.setAvailable(true);
+ await f.workspace.open({});
+ f.workspace.toggle("ios", ipad);
+ f.workspace.toggle("android", androidPhone);
+ const { panes, active } = f.workspace.getSnapshot();
+ const split = panes.map(pane => pane.key);
+ f.workspace.setDockSelection(split, active!);
+ const screens = panes.map(pane => {
+ const root = createPanelRoot();
+ const unmount = f.workspace.mount(pane.key, root as unknown as HTMLElement)!;
+ return { root, unmount };
+ });
+ await waitFor(() => screens.every(screen => screen.root.elements.get("screen")!.draws > 0));
+ const open = f.calls.filter(call => call.name.endsWith("_stream_session"));
+ assert.deepEqual(open.map(call => call.arguments.udid ?? call.arguments.deviceId), [iphone.udid, ipad.udid, androidPhone.udid]);
+ for (const screen of screens) dispatch(screen.root.buttons[0], "click");
+ await waitFor(() => f.calls.filter(call => call.name.endsWith("_stream_input")).length === 3);
+ const inputs = f.calls.filter(call => call.name.endsWith("_stream_input"));
+ assert.equal(new Set(inputs.map(call => call.arguments.sessionId)).size, 3);
+ dispatch(screens[0].root, "pointerdown");
+ assert.equal(f.activeDevice?.udid, iphone.udid);
+ f.workspace.toggle("ios", ipad);
+ screens[1].unmount();
+ await waitFor(() => f.closed.length === 1);
+ assert.equal(f.closed[0], inputs[1].arguments.sessionId);
+ assert.equal(f.activeDevice?.udid, iphone.udid);
+ assert.equal(f.calls.some(call => call.name.startsWith("mobile_shutdown")), false);
+ screens[0].unmount();
+ screens[2].unmount();
+});
+
+test("background tabs suspend their streams and visible splits survive tab switches", async t => {
+ const f = fixture(t);
+ const iphone: SimulatorDevice = { udid: "iphone-1", name: "iPhone", runtime: "iOS", state: "Booted" };
+ const ipad = { ...iphone, udid: "ipad-2", name: "iPad" };
+ f.setIosDevices([iphone, ipad]);
+ f.setAndroidDevices([androidPhone]);
+ await f.workspace.setAvailable(true);
+ await f.workspace.open({});
+ f.workspace.toggle("ios", ipad);
+ f.workspace.toggle("android", androidPhone);
+ const [phone, tablet, android] = f.workspace.getSnapshot().panes;
+ f.workspace.setDockSelection([phone.key, android.key], android.key);
+ for (const pane of [phone, tablet, android]) {
+ const root = createPanelRoot();
+ f.workspace.mount(pane.key, root as unknown as HTMLElement);
+ }
+ const sessions = () => f.calls.filter(call => call.name.endsWith("_stream_session"));
+ await waitFor(() => sessions().length === 2);
+ assert.deepEqual(sessions().map(call => call.arguments.udid ?? call.arguments.deviceId), [iphone.udid, androidPhone.udid]);
+
+ f.workspace.setDockSelection([tablet.key, android.key], tablet.key);
+ await f.workspace.inventory.ios.refresh();
+ await waitFor(() => f.closed.length === 1 && sessions().length === 3);
+ assert.equal(sessions()[2].arguments.udid, ipad.udid);
+ assert.equal(f.activeDevice?.udid, ipad.udid);
+ f.workspace.setDockSelection([android.key, tablet.key], android.key);
+ await f.workspace.inventory.ios.refresh();
+ assert.equal(f.activeDevice?.udid, androidPhone.udid);
+ assert.equal(sessions().length, 3);
+ assert.equal(f.closed.length, 1);
+});
+
+test("late discovery cannot overwrite a manual selection", async t => {
const f = fixture(t);
- let finishDiscovery: () => void = () => {};
- const discovery = new Promise(resolve => { finishDiscovery = resolve; });
- f.delayDiscovery(discovery);
- const layouts: DeviceLayout[] = [];
- const workspace = new WorkspaceDevices([f.ios.panel, f.android.panel], layout => { layouts.push(layout); });
- t.after(() => workspace.dispose());
- await workspace.setAvailable(true);
- const opening = workspace.open({ platform: "android" });
- workspace.selectLayout();
- layouts.push("ios");
- finishDiscovery();
+ const discovery = Promise.withResolvers();
+ f.delayDiscovery(discovery.promise);
+ await f.workspace.setAvailable(true);
+ const opening = f.workspace.open({ platform: "android" });
+ f.workspace.toggle("ios", physicalPhone);
+ discovery.resolve();
await opening;
- const layout = layouts.at(-1);
- assert.equal(layout, "ios");
+ assert.deepEqual(f.workspace.getSnapshot().panes.map(pane => pane.last.udid), [physicalPhone.udid]);
});
test("an exact Android target keeps the same AVD selected through Stop and Start", async t => {
const f = fixture(t);
- f.android.panel.setOpeningTarget({ platform: "android", kind: "emulator", deviceId: "emulator-5554" });
- await f.android.panel.load();
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ await f.android.load({ platform: "android", kind: "emulator", deviceId: "emulator-5554" });
+ const picker = f.android.picker;
await picker.stopDevice("emulator-5554");
assert.equal(f.android.panel.selected?.udid, "avd:Pixel");
const startButton = f.android.element("start-device");
assert.equal(startButton.disabled, false);
dispatch(startButton, "click");
await waitFor(() => f.android.panel.selected?.state === "Booted" && startButton.disabled);
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(f.android.panel.selected?.udid, "emulator-5554");
});
test("disposing the workspace before host readiness does not start device work", async t => {
const f = fixture(t);
- const layouts: DeviceLayout[] = [];
- const workspace = new WorkspaceDevices([f.ios.panel, f.android.panel], layout => { layouts.push(layout); });
- await workspace.open({ platform: "android" });
- workspace.dispose();
- await workspace.setAvailable(true);
+ await f.workspace.open({ platform: "android" });
+ await f.workspace.dispose();
+ await f.workspace.setAvailable(true);
assert.equal(f.calls.length, 0);
});
@@ -443,19 +502,16 @@ test("physical Android devices appear above emulators and stream without emulato
{ udid: "emulator-5554", name: "Pixel AVD", state: "Booted", runtime: "Android", platform: "android", kind: "emulator" },
androidPhone,
]);
- await f.android.panel.load();
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ await f.android.load();
+ const picker = f.android.picker;
const state = picker.getSnapshot();
const groups = state.items.map(item => item.group);
assert.deepEqual(groups, ["Connected devices", "Emulators"]);
assert.equal(state.items[0].label, "Pixel 9 · USB");
assert.equal(state.items[0].canStop, false);
- picker.value = androidPhone.udid;
- dispatch(pickerElement, "change");
+ picker.choose(androidPhone.udid);
await waitFor(() => {
- const state = picker.getSnapshot();
- return f.android.panel.selected?.udid === androidPhone.udid && state.disabled === false && f.android.element("screen").draws > 0;
+ return f.android.panel.selected?.udid === androidPhone.udid && f.android.element("screen").draws > 0;
});
const session = f.calls.findLast(call => call.name === "mobile_android_stream_session");
assert.deepEqual(session?.arguments, { deviceId: androidPhone.udid });
@@ -470,21 +526,36 @@ test("physical Android devices appear above emulators and stream without emulato
const lifecycle = f.calls.filter(call => call.name.startsWith("mobile_boot") || call.name.startsWith("mobile_shutdown"));
assert.equal(lifecycle.length, 0);
f.setAndroidDevices([{ ...androidPhone, transportType: "localNetwork" }]);
- await picker.refresh?.();
+ await picker.refresh();
const wireless = picker.getSnapshot();
assert.equal(wireless.value, androidPhone.udid);
assert.equal(wireless.items[0].label, "Pixel 9 · Wi-Fi");
});
+test("opening an ADC serial streams that device even with another phone of the same model", async t => {
+ const f = fixture(t);
+ const adcPhone: PhysicalAndroidDevice = { ...androidPhone, udid: "127.0.0.1:15555", transportType: "localNetwork" };
+ f.setAndroidDevices([androidPhone, adcPhone]);
+ await f.workspace.setAvailable(true);
+ await f.workspace.open({ platform: "android", deviceId: adcPhone.udid });
+ const [pane] = f.workspace.getSnapshot().panes;
+ assert.equal(pane.device?.udid, adcPhone.udid);
+ const root = createPanelRoot();
+ f.workspace.mount(pane.key, root as unknown as HTMLElement);
+ await waitFor(() => root.elements.get("screen")!.draws > 0);
+ const streams = f.calls.filter(call => call.name === "mobile_android_stream_session");
+ const targets = streams.map(call => call.arguments);
+ assert.deepEqual(targets, [{ deviceId: adcPhone.udid }]);
+});
+
test("the Android picker shows an ADC booking name above the device specs for the active connection", async t => {
const f = fixture(t);
const name = "Test checkout on Android";
const model = "ADC Android 14 2 CPU 3 GiB RAM";
const device: PhysicalAndroidDevice = { ...androidPhone, udid: "127.0.0.1:15555", name: model, model, transportType: "localNetwork" };
f.setAndroidDevices([device], { [device.udid]: name });
- await f.android.panel.load();
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ await f.android.load();
+ const picker = f.android.picker;
const option = picker.getSnapshot().items[0];
assert.equal(option.label, name);
assert.equal(option.detail, `${model} · Wi-Fi`);
@@ -493,32 +564,29 @@ test("the Android picker shows an ADC booking name above the device specs for th
await picker.refresh?.();
const released = picker.getSnapshot().items[0];
assert.equal(released.label, `${model} · Wi-Fi`);
- assert.equal(released.detail, undefined);
+ assert.equal(released.detail, "Wi-Fi");
});
for (const state of ["unauthorized", "offline"]) test(`physical Android ${state} devices remain discoverable without booting or streaming`, async t => {
const f = fixture(t);
f.setAndroidDevices([{ ...androidPhone, state }]);
- await f.android.panel.load();
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ await f.android.load();
+ const picker = f.android.picker;
const snapshot = picker.getSnapshot();
assert.equal(snapshot.items.length, 1);
assert.equal(snapshot.items[0].running, false);
assert.equal(snapshot.items[0].canStop, false);
assert.match(snapshot.items[0].label, state === "unauthorized" ? /Unauthorized/ : /Offline/);
- picker.value = androidPhone.udid;
- dispatch(pickerElement, "change");
+ picker.choose(androidPhone.udid);
await waitFor(() => {
- const snapshot = picker.getSnapshot();
- return f.android.panel.selected?.udid === androidPhone.udid && snapshot.disabled === false;
+ return f.android.panel.selected?.udid === androidPhone.udid;
});
assert.equal(f.android.element("start-device").disabled, true);
assert.equal(f.android.element("screenshot").disabled, true);
const actions = f.calls.filter(call => call.name.startsWith("mobile_boot") || call.name.endsWith("_stream_session"));
assert.equal(actions.length, 0);
f.setAndroidDevices([androidPhone]);
- await picker.refresh?.();
+ await picker.refresh();
await waitFor(() => f.android.element("screen").draws > 0);
});
@@ -528,7 +596,7 @@ test("Android stream opening waits through device boot and backend readiness", a
let release!: () => void;
const opening = new Promise(resolve => { release = resolve; });
f.delayOpen(opening);
- await f.android.panel.load();
+ await f.android.load();
t.mock.timers.tick(155000);
await flushTasks();
const notice = f.android.element("notice");
@@ -546,18 +614,17 @@ test("Android stream opening waits through device boot and backend readiness", a
test("Android refresh connects an arriving phone once and closes its stream when it disconnects", async t => {
const f = fixture(t);
f.setAndroidDevices([]);
- await f.android.panel.load();
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ await f.android.load();
+ const picker = f.android.picker;
f.setAndroidDevices([androidPhone]);
- await picker.refresh?.();
+ await picker.refresh();
await waitFor(() => f.android.element("screen").draws > 0);
- await picker.refresh?.();
+ await picker.refresh();
const streams = f.calls.filter(call => call.name === "mobile_android_stream_session");
assert.equal(streams.length, 1);
assert.equal(f.android.panel.selected?.udid, androidPhone.udid);
f.setAndroidDevices([]);
- await picker.refresh?.();
+ await picker.refresh();
await waitFor(() => f.closed.length === 1);
assert.equal(f.android.panel.selected, undefined);
assert.equal(f.android.root.buttons[0].disabled, true);
@@ -565,57 +632,11 @@ test("Android refresh connects an arriving phone once and closes its stream when
assert.equal(lifecycle.length, 0);
});
-test("the Android panel shows the server's emulator setup hint when adb is available but the device list is empty", async t => {
- const { android } = fixture(t);
- android.panel.setOpeningTarget({ platform: "android" });
- const setupHint = "Install Android Emulator in SDK Manager, then create an AVD in Device Manager.";
- android.panel.acceptStatus({ connected: true, managed: false, baseUrl: "", devices: [], setupHint });
- assert.equal(android.element("empty").textContent, "No Android devices.");
- assert.equal(android.element("empty-description").textContent, setupHint);
- assert.equal(android.element("empty-description").hidden, false);
- assert.equal(android.element("start-device").disabled, true);
-});
-
-test("Android discovery polls visible panels, shares refreshes, and removes disconnected phones", async t => {
- t.mock.timers.enable({ apis: ["setTimeout"] });
- const f = fixture(t);
- f.setAndroidDevices([]);
- await f.android.panel.load();
- const pickerElement = f.android.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
- f.android.root.hidden = true;
- t.mock.timers.tick(3000);
- const hiddenReads = f.calls.filter(call => call.name === "mobile_list_android_devices");
- assert.equal(hiddenReads.length, 1);
- f.android.root.hidden = false;
- let release!: () => void;
- const gate = new Promise(resolve => { release = resolve; });
- f.delayDiscovery(gate);
- f.setAndroidDevices([{ ...androidPhone, state: "unauthorized" }]);
- t.mock.timers.tick(3000);
- const refreshing = picker.refresh?.();
- const sharedReads = f.calls.filter(call => call.name === "mobile_list_android_devices");
- assert.equal(sharedReads.length, 2);
- release();
- await refreshing;
- const connected = picker.getSnapshot();
- assert.equal(connected.items[0].value, androidPhone.udid);
- f.setAndroidDevices([]);
- await picker.refresh?.();
- const disconnected = picker.getSnapshot();
- assert.equal(disconnected.items.length, 0);
- await f.android.panel.dispose();
- t.mock.timers.tick(10000);
- const disposedReads = f.calls.filter(call => call.name === "mobile_list_android_devices");
- assert.equal(disposedReads.length, 3);
-});
-
test("physical iOS devices mirror above simulators and route touches to their own session", async t => {
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
- await f.ios.panel.load();
- const pickerElement = f.ios.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
+ await f.ios.load();
+ const picker = f.ios.picker;
const state = picker.getSnapshot();
const items = state.items;
const groups = items.map(item => item.group);
@@ -624,11 +645,9 @@ test("physical iOS devices mirror above simulators and route touches to their ow
assert.equal(items[0].statusLabel, "Connected");
assert.equal(items[0].canStop, false);
const previousStreams = f.calls.filter(call => call.name === "mobile_stream_session");
- picker.value = physicalPhone.udid;
- dispatch(pickerElement, "change");
+ picker.choose(physicalPhone.udid);
await waitFor(() => {
- const state = picker.getSnapshot();
- return f.ios.panel.selected?.kind === "physical" && state.disabled === false;
+ return f.ios.panel.selected?.kind === "physical";
});
const empty = f.ios.element("empty");
const description = f.ios.element("empty-description");
@@ -676,7 +695,7 @@ test("physical iOS devices mirror above simulators and route touches to their ow
const shutdowns = f.calls.filter(call => call.name.startsWith("mobile_shutdown"));
assert.equal(shutdowns.length, 0);
f.setPhysicalDevices([{ ...physicalPhone, transportType: "wired" }]);
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(picker.value, physicalPhone.udid);
const wiredState = picker.getSnapshot();
assert.equal(wiredState.items[0].label, "Physical iPhone · USB");
@@ -696,12 +715,11 @@ test("physical iOS devices mirror above simulators and route touches to their ow
const unavailablePhone = { ...physicalPhone, state: "unavailable" };
Reflect.deleteProperty(unavailablePhone, "transportType");
f.setPhysicalDevices([unavailablePhone]);
- await picker.refresh?.();
+ await picker.refresh();
const disconnectedState = picker.getSnapshot();
const phonePresent = disconnectedState.items.some(item => item.value === physicalPhone.udid);
assert.equal(phonePresent, false);
- picker.value = "iphone-1";
- dispatch(pickerElement, "change");
+ picker.choose("iphone-1");
await waitFor(() => {
const buttonsEnabled = f.ios.root.buttons.every(button => !button.disabled);
return f.ios.panel.selected?.kind !== "physical" && buttonsEnabled;
@@ -714,11 +732,9 @@ test("physical iOS devices mirror above simulators and route touches to their ow
test("another panel's held touch does not reconnect the physical video stream", async t => {
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
- await f.ios.panel.load();
- const pickerElement = f.ios.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
- picker.value = physicalPhone.udid;
- dispatch(pickerElement, "change");
+ await f.ios.load();
+ const picker = f.ios.picker;
+ picker.choose(physicalPhone.udid);
await waitFor(() => f.ios.element("screenshot").disabled === false);
const screen = f.ios.element("screen");
f.busyPhysicalInput();
@@ -739,15 +755,13 @@ test("another panel's held touch does not reconnect the physical video stream",
test("physical iOS capture errors stay visible and clear when mirroring recovers", async t => {
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
- await f.ios.panel.load();
- await f.android.panel.load();
+ await f.ios.load();
+ await f.android.load();
await waitFor(() => f.android.element("screen").draws > 0);
const message = "A phone or VoIP call is currently in progress on the device.";
f.failPhysicalCapture(message);
- const pickerElement = f.ios.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
- picker.value = physicalPhone.udid;
- dispatch(pickerElement, "change");
+ const picker = f.ios.picker;
+ picker.choose(physicalPhone.udid);
await waitFor(() => f.ios.element("empty-description").textContent === message);
assert.equal(f.ios.element("empty").hidden, false);
assert.equal(f.ios.element("empty").textContent, "Screen unavailable");
@@ -766,7 +780,7 @@ test("screenshot attachment failures remain visible until the next action on bot
const f = fixture(t);
f.holdInitialFrames();
for (const platform of [f.ios, f.android]) {
- await platform.panel.load();
+ await platform.load();
const screenshot = platform.element("screenshot");
const notice = platform.element("notice");
const message = platform.element("notice-message");
@@ -785,9 +799,8 @@ test("screenshot attachment failures remain visible until the next action on bot
await waitFor(() => screen.draws > 0);
assert.equal(notice.hidden, false);
assert.match(message.textContent, /screenshot.*not.*attached.*chat/i);
- const pickerElement = platform.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
- await picker.refresh?.();
+ const picker = platform.picker;
+ await picker.refresh();
assert.equal(notice.hidden, false);
assert.match(message.textContent, /screenshot.*not.*attached.*chat/i);
f.failScreenshotAttachment("");
@@ -801,7 +814,7 @@ test("screenshot attachment failures remain visible until the next action on bot
test("JPEG encoding failures keep chat empty, show a notice and allow another screenshot", async t => {
const f = fixture(t);
- await f.ios.panel.load();
+ await f.ios.load();
const screenshot = f.ios.element("screenshot");
await waitFor(() => screenshot.disabled === false);
f.failScreenshotEncoding("JPEG encoder failed");
@@ -823,7 +836,7 @@ test("physical iOS screenshots capture the displayed frame without a simulator b
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
f.failSimulators("Simulator backend unavailable");
- await f.ios.panel.load();
+ await f.ios.load();
const screenshot = f.ios.element("screenshot");
f.ios.root.elements.delete("screenshot-status");
await waitFor(() => screenshot.disabled === false);
@@ -851,7 +864,7 @@ test("physical iOS Select annotates screen regions in pixels without simulator a
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
f.failSimulators("Simulator backend unavailable");
- await f.ios.panel.load();
+ await f.ios.load();
const stage = f.ios.element("stage");
const store = getScreenAnnotations(stage as unknown as HTMLElement);
await waitFor(() => store.getSnapshot().disabled === false);
@@ -891,7 +904,7 @@ test("physical iOS Screenshot and Select wait for video and disable when the pho
let release!: () => void;
const pending = new Promise(resolve => { release = resolve; });
f.delayOpen(pending);
- await f.ios.panel.load();
+ await f.ios.load();
const store = getScreenAnnotations(f.ios.element("stage") as unknown as HTMLElement);
const screenshot = f.ios.element("screenshot");
assert.equal(screenshot.disabled, true);
@@ -900,8 +913,8 @@ test("physical iOS Screenshot and Select wait for video and disable when the pho
await waitFor(() => screenshot.disabled === false);
assert.equal(store.getSnapshot().disabled, false);
f.setPhysicalDevices([]);
- const picker = getDevicePicker(f.ios.element("devices") as unknown as HTMLElement);
- await picker.refresh?.();
+ const picker = f.ios.picker;
+ await picker.refresh();
assert.equal(screenshot.disabled, true);
assert.equal(store.getSnapshot().disabled, true);
});
@@ -909,17 +922,14 @@ test("physical iOS Screenshot and Select wait for video and disable when the pho
test("physical discovery failure stays visible while simulator discovery remains usable", async t => {
const f = fixture(t);
f.failDiscovery("Physical discovery requires Xcode 27");
- await f.ios.panel.load();
+ await f.ios.load();
assert.equal(f.ios.panel.selected?.udid, "iphone-1");
- const pickerElement = f.ios.element("devices");
- const picker = getDevicePicker(pickerElement as unknown as HTMLElement);
- const state = picker.getSnapshot();
- assert.equal(state.disabled, false);
+ const picker = f.ios.picker;
await waitFor(() => f.ios.element("screen").draws > 0);
const notice = f.ios.element("notice-message");
assert.match(notice.textContent, /Physical discovery requires Xcode 27/);
f.failDiscovery("");
- await picker.refresh?.();
+ await picker.refresh();
assert.equal(notice.textContent, "");
});
@@ -927,11 +937,9 @@ test("physical devices remain selectable when the simulator backend is unavailab
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
f.failSimulators("Baguette unavailable");
- await f.ios.panel.load();
- const element = f.ios.element("devices");
- const picker = getDevicePicker(element as unknown as HTMLElement);
+ await f.ios.load();
+ const picker = f.ios.picker;
const state = picker.getSnapshot();
- assert.equal(state.disabled, false);
assert.equal(state.value, physicalPhone.udid);
const groups = state.items.map(item => item.group);
assert.deepEqual(groups, ["Connected devices"]);
@@ -940,35 +948,29 @@ test("physical devices remain selectable when the simulator backend is unavailab
assert.equal(sessions.length, 0);
});
-test("discovery polls only visible panels, shares an in-flight refresh, and stops on disposal", async t => {
- t.mock.timers.enable({ apis: ["setTimeout"] });
+test("discovery shares one poll per visible platform and stops on teardown", async t => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
const f = fixture(t);
f.setPhysicalDevices([physicalPhone]);
- f.failSimulators("Baguette unavailable");
- await f.ios.panel.load();
- const element = f.ios.element("devices");
- const picker = getDevicePicker(element as unknown as HTMLElement);
- f.ios.root.hidden = true;
+ await f.workspace.open({});
+ await f.workspace.setAvailable(true);
+ f.workspace.toggle("ios", physicalPhone);
+ const count = (name: string) => f.calls.filter(call => call.name === name).length;
+ f.visibility("hidden");
t.mock.timers.tick(3000);
- const hiddenReads = f.calls.filter(call => call.name === "mobile_list_ios_devices");
- assert.equal(hiddenReads.length, 1);
- f.ios.root.hidden = false;
- let release!: () => void;
- const gate = new Promise(resolve => { release = resolve; });
- f.delayDiscovery(gate);
- f.setPhysicalDevices([]);
+ assert.equal(count("mobile_list_simulators"), 1);
+ f.visibility("visible");
+ const gate = Promise.withResolvers();
+ f.delayDiscovery(gate.promise);
t.mock.timers.tick(3000);
- const refreshing = picker.refresh?.();
- const sharedReads = f.calls.filter(call => call.name === "mobile_list_ios_devices");
- assert.equal(sharedReads.length, 2);
- release();
- await refreshing;
- const state = picker.getSnapshot();
- assert.equal(state.items.length, 0);
- await f.ios.panel.dispose();
+ const reading = f.workspace.inventory.ios.refresh();
+ assert.equal(count("mobile_list_simulators"), 2);
+ assert.equal(count("mobile_list_android_devices"), 1);
+ gate.resolve();
+ await reading;
+ await f.workspace.dispose();
t.mock.timers.tick(10000);
- const disposedReads = f.calls.filter(call => call.name === "mobile_list_ios_devices");
- assert.equal(disposedReads.length, 2);
+ assert.equal(count("mobile_list_simulators"), 2);
});
async function waitFor(predicate: () => boolean) {
@@ -980,14 +982,14 @@ async function waitFor(predicate: () => boolean) {
}
test("missing timing observations do not disconnect valid iOS frames", async t => {
- const f = fixture(t); f.missTiming(); await f.ios.panel.load();
+ const f = fixture(t); f.missTiming(); await f.ios.load();
await waitFor(() => f.ios.element("screen").draws > 0);
assert.equal(f.calls.filter(call => call.name === "mobile_stream_session").length, 1);
assert.equal(f.closed.length, 0);
});
for (const platform of ["ios", "android"] as const) test(`leaving Select restores the latest ${platform} frame even when the device is quiet`, async t => {
- const f = fixture(t); const target = f[platform]; await target.panel.load();
+ const f = fixture(t); const target = f[platform]; await target.load();
await waitFor(() => target.element("screen").draws > 0);
const store = getScreenAnnotations(target.element("stage") as unknown as HTMLElement);
await store.toggle();
@@ -1000,7 +1002,7 @@ for (const platform of ["ios", "android"] as const) test(`leaving Select restore
});
test("returning to a hidden chat reopens its streams and preserves the note input", async t => {
- const f = fixture(t); await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ const f = fixture(t); await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.ios.element("screen").draws > 0 && f.android.element("screen").draws > 0);
const store = getScreenAnnotations(f.ios.element("stage") as unknown as HTMLElement);
await store.toggle(); store.select({ x: 50, y: 40 }); store.setText("Keep this note");
@@ -1015,7 +1017,7 @@ test("returning to a hidden chat reopens its streams and preserves the note inpu
});
test("a stopped receive loop retries when its chat becomes visible again", async t => {
- const f = fixture(t); f.invalidFrame(); await f.ios.panel.load();
+ const f = fixture(t); f.invalidFrame(); await f.ios.load();
await waitFor(() => f.ios.element("notice-message").textContent.includes("invalid frame metadata"));
f.visibility("visible");
await waitFor(() => f.ios.element("screen").draws > 0);
@@ -1025,12 +1027,12 @@ test("a stopped receive loop retries when its chat becomes visible again", async
test("status arriving during startup still connects the selected device", async t => {
const f = fixture(t);
const starting = f.ios.panel.resume();
- f.ios.panel.acceptStatus({ connected: true, managed: true, baseUrl: "http://localhost/", devices: [{ udid: "iphone-1", name: "iPhone", state: "Booted", runtime: "" }] });
+ f.ios.inventory.apply({ connected: true, managed: true, baseUrl: "http://localhost/", devices: [{ udid: "iphone-1", name: "iPhone", state: "Booted", runtime: "" }] });
await starting;
await waitFor(() => f.ios.element("screen").draws > 0);
assert.equal(f.ios.element("empty").hidden, true);
assert.equal(f.calls.filter(call => call.name === "mobile_stream_session").length, 1);
- f.ios.panel.acceptStatus({ connected: true, managed: true, baseUrl: "http://localhost/", devices: [{ udid: "iphone-1", name: "iPhone", state: "Booted", runtime: "" }] });
+ f.ios.inventory.apply({ connected: true, managed: true, baseUrl: "http://localhost/", devices: [{ udid: "iphone-1", name: "iPhone", state: "Booted", runtime: "" }] });
await new Promise(resolve => setTimeout(resolve, 10));
assert.equal(f.calls.filter(call => call.name === "mobile_stream_session").length, 1);
assert.equal(f.closed.length, 0);
@@ -1038,10 +1040,10 @@ test("status arriving during startup still connects the selected device", async
for (const platform of ["ios", "android"] as const) test(`stopping the selected ${platform} device leaves the other stream open and allows restarting it`, async t => {
const f = fixture(t);
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.ios.element("screen").draws > 0 && f.android.element("screen").draws > 0);
const target = f[platform];
- const picker = getDevicePicker(target.element("devices") as unknown as HTMLElement);
+ const picker = target.picker;
await picker.stopDevice(picker.value);
const shutdown = f.calls.find(call => call.name === (platform === "ios" ? "mobile_shutdown_simulator" : "mobile_shutdown_android_emulator"));
assert.deepEqual(shutdown?.arguments, platform === "ios" ? { udid: "iphone-1" } : { deviceId: "emulator-5554" });
@@ -1063,11 +1065,11 @@ for (const platform of ["ios", "android"] as const) test(`stopping the selected
test("refreshing the picker removes stop controls for devices stopped outside the panel", async t => {
const f = fixture(t);
- await f.ios.panel.load();
+ await f.ios.load();
await waitFor(() => f.ios.element("screen").draws > 0);
- const picker = getDevicePicker(f.ios.element("devices") as unknown as HTMLElement);
+ const picker = f.ios.picker;
f.stopDevices();
- await picker.refresh!();
+ await picker.refresh();
assert.equal(picker.getSnapshot().items[0].running, false);
assert.equal(picker.getSnapshot().items[0].canStop, false);
await picker.stopDevice("iphone-1");
@@ -1077,7 +1079,7 @@ test("refreshing the picker removes stop controls for devices stopped outside th
test("device settings target each selected simulator and leave both streams open", async t => {
const f = fixture(t);
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.ios.element("screen").draws > 0 && f.android.element("screen").draws > 0);
const ios = getDeviceSettings(f.ios.element("settings") as unknown as HTMLElement);
const android = getDeviceSettings(f.android.element("settings") as unknown as HTMLElement);
@@ -1107,7 +1109,7 @@ function pasteText(target: Element, text: string) {
for (const platform of ["ios", "android"] as const) test(`Command-V on ${platform} preserves paste and subsequent typing order in its own session`, async t => {
const f = fixture(t);
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.ios.element("screen").draws > 0 && f.android.element("screen").draws > 0);
const screen = f[platform].element("screen");
const shortcut = new Event("keydown", { cancelable: true });
@@ -1132,7 +1134,7 @@ for (const platform of ["ios", "android"] as const) test(`Command-V on ${platfor
for (const platform of ["ios", "android"] as const) test(`${platform} paste rejects unsupported text without sending partial content`, async t => {
const f = fixture(t);
const panel = f[platform];
- await panel.panel.load();
+ await panel.load();
await waitFor(() => panel.element("screen").draws > 0);
const screen = panel.element("screen");
const empty = pasteText(screen, "");
@@ -1161,7 +1163,7 @@ for (const platform of ["ios", "android"] as const) test(`${platform} paste wait
const screen = panel.element("screen");
const beforeReady = pasteText(screen, "before ready");
assert.equal(beforeReady.defaultPrevented, false);
- await panel.panel.load();
+ await panel.load();
await waitFor(() => screen.draws > 0);
const stage = panel.element("stage");
const store = getScreenAnnotations(stage as unknown as HTMLElement);
@@ -1186,14 +1188,13 @@ for (const platform of ["ios", "android"] as const) test(`${platform} paste wait
test("blocked iOS and physical iOS streams do not accept pasted text", async t => {
const f = fixture(t);
f.blockIos();
- await f.ios.panel.load();
+ await f.ios.load();
await waitFor(() => f.ios.element("screen").draws > 0);
const screen = f.ios.element("screen");
const blocked = pasteText(screen, "blocked");
assert.equal(blocked.defaultPrevented, false);
f.setPhysicalDevices([physicalPhone]);
- f.ios.panel.setOpeningTarget({ platform: "ios", kind: "physical", deviceId: physicalPhone.udid });
- await f.ios.panel.load();
+ await f.ios.load({ platform: "ios", kind: "physical", deviceId: physicalPhone.udid });
await waitFor(() => f.calls.some(call => call.name === "mobile_ios_mirror_session") && f.ios.root.buttons[0].disabled);
const physical = pasteText(screen, "physical");
assert.equal(physical.defaultPrevented, false);
@@ -1203,7 +1204,7 @@ test("blocked iOS and physical iOS streams do not accept pasted text", async t =
test("both platforms stream at once and each routes input to its own session", async t => {
const f = fixture(t);
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.ios.element("screen").draws > 0 && f.android.element("screen").draws > 0);
dispatch(f.ios.root.buttons[0], "click");
dispatch(f.android.root.buttons[0], "click");
@@ -1218,9 +1219,9 @@ test("both platforms stream at once and each routes input to its own session", a
test("changing one device leaves the other stream and controls active", async t => {
const f = fixture(t);
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.android.element("screen").draws > 0);
- dispatch(f.ios.element("devices"), "change");
+ await f.ios.panel.resume();
await waitFor(() => f.calls.filter(call => call.name === "mobile_stream_session").length === 2);
assert.equal(f.calls.filter(call => call.name === "mobile_android_stream_session").length, 1);
assert.ok(f.closed.some(id => id.startsWith("ios-")));
@@ -1238,7 +1239,7 @@ for (const platform of ["ios", "android"] as const) test(`${platform} input fail
const other = platform === "ios" ? f.android : f.ios;
const sessionTool = platform === "ios" ? "mobile_stream_session" : "mobile_android_stream_session";
const inputTool = platform === "ios" ? "mobile_stream_input" : "mobile_android_stream_input";
- await Promise.all([panel.panel.load(), other.panel.load()]);
+ await Promise.all([panel.load(), other.load()]);
await waitFor(() => panel.element("screen").draws > 0 && other.element("screen").draws > 0);
f.failInput(platform);
dispatch(panel.root.buttons[0], "click");
@@ -1251,7 +1252,7 @@ for (const platform of ["ios", "android"] as const) test(`${platform} input fail
test("blocked iOS input leaves Android controls working", async t => {
const f = fixture(t); f.blockIos();
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.ios.element("screen").draws > 0 && f.android.element("screen").draws > 0);
assert.equal(f.ios.root.buttons[1].disabled, true);
assert.match(f.ios.element("notice-message").textContent, /input is blocked/);
@@ -1263,7 +1264,7 @@ test("teardown closes both streams and closes sessions that finish opening late"
const f = fixture(t);
let release!: () => void;
f.delayOpen(new Promise(resolve => { release = resolve; }));
- await Promise.all([f.ios.panel.load(), f.android.panel.load()]);
+ await Promise.all([f.ios.load(), f.android.load()]);
await waitFor(() => f.calls.filter(call => call.name.endsWith("_stream_session")).length === 2);
await Promise.all([f.ios.panel.dispose(), f.android.panel.dispose()]);
release();
@@ -1276,7 +1277,7 @@ test("teardown closes both streams and closes sessions that finish opening late"
for (const platform of ["ios", "android"] as const) test(`select mode on ${platform} maps screen coordinates without sending device input`, async t => {
const f = fixture(t); const panel = f[platform];
- await panel.panel.load(); await waitFor(() => panel.element("screen").draws > 0);
+ await panel.load(); await waitFor(() => panel.element("screen").draws > 0);
const store = getScreenAnnotations(panel.element("stage") as unknown as HTMLElement);
await store.toggle();
assert.equal(store.getSnapshot().selecting, true);
@@ -1301,7 +1302,7 @@ for (const platform of ["ios", "android"] as const) test(`select mode on ${platf
for (const recovery of ["generation", "decoder"] as const) test(`Android ${recovery} recovery keeps Select and its frozen capture active`, async t => {
const f = fixture(t), panel = f.android;
- await panel.panel.load();
+ await panel.load();
const store = getScreenAnnotations(panel.element("stage") as unknown as HTMLElement);
await waitFor(() => !store.getSnapshot().disabled && f.waitingForFrame("android"));
await store.toggle();
@@ -1341,7 +1342,7 @@ for (const recovery of ["generation", "decoder"] as const) test(`Android ${recov
for (const platform of ["ios", "android"] as const) test(`failed inspection on ${platform} falls back to native elements and accepts clicks`, async t => {
const f = fixture(t), panel = f[platform];
f.failInspection();
- await panel.panel.load(); await waitFor(() => panel.element("screen").draws > 0);
+ await panel.load(); await waitFor(() => panel.element("screen").draws > 0);
const store = getScreenAnnotations(panel.element("stage") as unknown as HTMLElement);
await store.toggle();
dispatch(panel.element("screen"), "pointermove", { pointerId: 1, clientX: 20, clientY: 30 });
@@ -1360,7 +1361,7 @@ test("Android selection attaches a scaled accessibility element to the composer
f.setAndroidAccessibility({ screen: { width: 1080, height: 2160 }, tree: { nodes: [
{ text: "Continue", resourceId: "app:id/continue", className: "android.widget.Button", bounds: { left: 270, top: 1080, right: 810, bottom: 1296 } },
] } });
- await panel.panel.load(); await waitFor(() => panel.element("screen").draws > 0);
+ await panel.load(); await waitFor(() => panel.element("screen").draws > 0);
const store = getScreenAnnotations(panel.element("stage") as unknown as HTMLElement);
const updates: Parameters[0][] = [];
const messages: Parameters[0][] = [];
@@ -1395,11 +1396,10 @@ test("Android selection attaches a scaled accessibility element to the composer
for (const platform of ["ios", "android"] as const) test(`selecting a stopped ${platform} device boots and streams it without Start`, async t => {
const f = fixture(t); f.stopDevices();
const panel = f[platform];
- await panel.panel.load();
- assert.equal(getDevicePicker(panel.element("devices") as unknown as HTMLElement).value, "");
+ await panel.load();
+ assert.equal(panel.picker.value, "");
assert.equal(f.calls.some(call => call.name.startsWith("mobile_boot")), false);
- getDevicePicker(panel.element("devices") as unknown as HTMLElement).value = platform === "ios" ? "iphone-1" : "emulator-5554";
- dispatch(panel.element("devices"), "change");
+ panel.picker.choose(platform === "ios" ? "iphone-1" : "emulator-5554");
await waitFor(() => panel.element("screen").draws > 0);
assert.equal(f.calls.filter(call => call.name === (platform === "ios" ? "mobile_boot_simulator" : "mobile_boot_android_emulator")).length, 1);
assert.equal(panel.root.buttons[0].disabled, false);
diff --git a/packages/ui/test/workspace-devices.test.ts b/packages/ui/test/workspace-devices.test.ts
index e0328a12..14baa7ca 100644
--- a/packages/ui/test/workspace-devices.test.ts
+++ b/packages/ui/test/workspace-devices.test.ts
@@ -1,85 +1,50 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { WorkspaceDevices } from "../src/workspace-devices.ts";
+import { DeviceWorkspace } from "../src/device-workspace.ts";
+import type { HostBridge } from "../src/host-bridge.ts";
import type { SimulatorDevice } from "../../shared/src/protocol.ts";
-const IPHONE: SimulatorDevice = {
- udid: "11111111-2222-3333-4444-555555555555", name: "iPhone 17 Pro", state: "Booted",
- platform: "ios", kind: "simulator",
-} as SimulatorDevice;
+const phone: SimulatorDevice = { udid: "iphone", name: "iPhone", state: "Booted", platform: "ios", runtime: "iOS" };
+const pixel: SimulatorDevice = { udid: "pixel", name: "Pixel", state: "Booted", platform: "android", runtime: "Android", kind: "emulator" };
-/**
- * A simulator panel as `WorkspaceDevices` uses one: what it is listing, and whether it has been
- * asked to load. The real one is a few thousand lines around a canvas and a device stream.
- */
-function panel(platform: "ios" | "android") {
- const stub = {
- platform,
- selected: undefined as SimulatorDevice | undefined,
- loads: 0,
- available: false,
- openingTarget: undefined as unknown,
- root: { hidden: true } as HTMLElement,
- load: async () => { stub.loads++; },
- setAvailable: (value: boolean) => { stub.available = value; },
- setOpeningTarget: (target: unknown) => { stub.openingTarget = target; },
- };
- return stub;
+function workspace() {
+ const app = { async callServerTool() { return { structuredContent: { devices: [], physicalDevices: [] } }; } } as unknown as HostBridge;
+ const tools = { context: { selectSimulators() {} }, deviceApps: { selectDevice() {} } } as ConstructorParameters[1];
+ return new DeviceWorkspace(app, tools);
}
-function workspace() {
- const panels = [panel("ios"), panel("android")] as const;
- const layouts: string[] = [];
- const devices = new WorkspaceDevices(panels as never, layout => layouts.push(layout));
- return { devices, panels, layouts };
+function discovered(device: SimulatorDevice) {
+ return { connected: true, managed: false, baseUrl: "", devices: [device] };
}
-test("a device discovery finishes a layout the first device list left unresolved", async () => {
- // The bug this covers: the opening tool starts the backend, so the first device list often comes
- // back before anything has been found. That resolved the layout to "none" once and for good —
- // both panels hidden, the platform selector reading "Platforms", and the panel telling the user
- // to boot the simulator they already had booted.
- const { devices, panels, layouts } = workspace();
+test("late discovery opens the first mirror once and respects manual removal", async t => {
+ const devices = workspace();
+ t.after(() => devices.dispose());
await devices.open({});
await devices.setAvailable(true);
- assert.deepEqual(layouts, ["none"], "nothing was found yet, so nothing is shown yet");
-
- // Discovery finds the booted simulator a moment later and the panel selects it, which is the
- // selection change the workspace passes on.
- panels[0].selected = IPHONE;
- devices.settleLayout();
-
- assert.deepEqual(layouts, ["none", "ios"], "the mirror comes up on the platform that has a device");
+ assert.equal(devices.getSnapshot().panes.length, 0);
+ devices.inventory.ios.apply(discovered(phone));
+ devices.inventory.android.apply(discovered(pixel));
+ assert.deepEqual(devices.getSnapshot().panes.map(pane => pane.device?.udid), [phone.udid]);
+ devices.toggle("ios", phone);
+ devices.inventory.ios.apply(discovered(phone));
+ assert.equal(devices.getSnapshot().panes.length, 0);
});
-test("a resolved layout and a layout the user chose are both left alone", async () => {
- const resolved = workspace();
- resolved.panels[0].selected = IPHONE;
- await resolved.devices.open({});
- await resolved.devices.setAvailable(true);
- assert.deepEqual(resolved.layouts, ["ios"]);
- // A second device appearing does not move a workspace that is already showing one.
- resolved.panels[1].selected = { ...IPHONE, platform: "android", kind: "emulator" } as SimulatorDevice;
- resolved.devices.settleLayout();
- assert.deepEqual(resolved.layouts, ["ios"], "an answered layout is not answered again");
-
- const chosen = workspace();
- await chosen.devices.open({});
- await chosen.devices.setAvailable(true);
- assert.deepEqual(chosen.layouts, ["none"]);
- chosen.devices.selectLayout();
- chosen.panels[0].selected = IPHONE;
- chosen.devices.settleLayout();
- assert.deepEqual(chosen.layouts, ["none"], "the user's own choice of platforms is never overridden");
-});
-
-test("a target naming a platform still decides the layout before anything is listed", async () => {
- const { devices, panels, layouts } = workspace();
+test("an opening target waits for its platform and a test lane selects its exact device", async t => {
+ const devices = workspace();
+ t.after(() => devices.dispose());
await devices.open({ platform: "android" });
- assert.deepEqual(layouts, ["android"], "the task's platform is known, so there is nothing to wait for");
- assert.deepEqual(panels.map(entry => entry.openingTarget), [{ platform: "android" }, { platform: "android" }]);
- // And a device turning up on the other platform does not move it.
- panels[0].selected = IPHONE;
- devices.settleLayout();
- assert.deepEqual(layouts, ["android"]);
+ await devices.setAvailable(true);
+ devices.inventory.ios.apply(discovered(phone));
+ assert.equal(devices.getSnapshot().panes.length, 0);
+ devices.inventory.android.apply(discovered(pixel));
+ const other = { ...pixel, udid: "second" };
+ devices.inventory.android.apply({ ...discovered(pixel), devices: [pixel, other] });
+ assert.equal(devices.showDevice("android", other.udid), true);
+ assert.equal(devices.showDevice("android", pixel.udid), true);
+ const { active, panes } = devices.getSnapshot();
+ assert.equal(panes.length, 2);
+ assert.equal(panes.find(pane => pane.key === active)?.device?.udid, pixel.udid);
+ assert.equal(devices.showDevice("android", "missing"), false);
});
diff --git a/tooling/hosts/browser-panel.spec.ts b/tooling/hosts/browser-panel.spec.ts
index 38d86f88..d034bf3d 100644
--- a/tooling/hosts/browser-panel.spec.ts
+++ b/tooling/hosts/browser-panel.spec.ts
@@ -30,9 +30,9 @@ test.describe("Browser panels", { tag: "@browser" }, () => {
const response = await initialized;
const session = response.headers()["mcp-session-id"];
const view = page.frameLocator("iframe");
- await expect(view.locator("#ios-panel")).toBeVisible();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeVisible();
await page.reload();
- await expect(view.locator("#ios-panel")).toBeVisible();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeVisible();
const endpoint = new URL("mcp", browserPanel.url);
await expect.poll(async () => {
const probe = await request.post(endpoint.href, { headers: { "mcp-session-id": session } });
@@ -49,7 +49,7 @@ test.describe("Browser panels", { tag: "@browser" }, () => {
};
expect(await read()).toContain("No Mobile Dev browser panel");
await page.goto(browserPanel.url);
- await expect(page.frameLocator("iframe").locator("#ios-panel")).toBeVisible();
+ await expect(page.frameLocator("iframe").getByRole("button", { name: "Add device" })).toBeVisible();
await expect.poll(read).toContain("Mobile Dev browser panel.");
await page.close();
await expect.poll(read).toContain("No Mobile Dev browser panel");
@@ -61,10 +61,10 @@ test.describe("Browser panels", { tag: "@browser" }, () => {
try {
await other.goto(browserPanel.url);
const view = other.frameLocator("iframe");
- await expect(view.locator("#ios-panel")).toBeVisible();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeVisible();
await page.close();
await other.reload();
- await expect(view.locator("#ios-panel")).toBeVisible();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeVisible();
await browserPanel.host.ping();
} finally { await other.close(); }
});
@@ -73,7 +73,7 @@ test.describe("Browser panels", { tag: "@browser" }, () => {
await page.clock.install();
await page.goto(browserPanel.url);
const view = page.frameLocator("iframe");
- await expect(view.locator("#ios-panel")).toBeVisible();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeVisible();
await browserPanel.close();
await page.clock.runFor(30_000);
await expect(page.getByRole("alert")).toContainText("Mobile Dev disconnected from its chat session");
@@ -90,7 +90,7 @@ test.describe("Browser panels", { tag: "@browser" }, () => {
const url = JSON.stringify(result.content).match(/http:\/\/127\.0\.0\.1:\d+\/[\w-]+\/\?[^"\s\\]+/)?.[0];
expect(url, "The link to show beside the chat").toBeDefined();
await page.goto(url!);
- await expect(page.frameLocator("iframe").locator("#ios-panel")).toBeVisible();
+ await expect(page.frameLocator("iframe").getByRole("button", { name: "Add device" })).toBeVisible();
} finally {
await host.close();
await server.close();
diff --git a/tooling/hosts/device-dock.spec.ts b/tooling/hosts/device-dock.spec.ts
new file mode 100644
index 00000000..a24605d8
--- /dev/null
+++ b/tooling/hosts/device-dock.spec.ts
@@ -0,0 +1,133 @@
+import type { FrameLocator, Locator, Page } from "@playwright/test";
+import { expect, hasPanel, test } from "./fixtures.ts";
+import type { SimulatorDevice } from "../../packages/shared/src/protocol.ts";
+
+const iphone: SimulatorDevice = { udid: "iphone", name: "iPhone 17 Pro", platform: "ios", state: "Shutdown", runtime: "iOS 27" };
+const pixel: SimulatorDevice = { udid: "pixel", name: "Pixel 9", platform: "android", kind: "physical", state: "offline", runtime: "Android" };
+const tablet = { ...pixel, udid: "tablet", name: "Pixel Tablet" };
+const inventory = { ios: [iphone], android: [pixel, tablet] };
+
+async function selectAndroid(view: FrameLocator) {
+ await view.getByRole("button", { name: "Add device" }).click();
+ const picker = view.getByRole("dialog");
+ await picker.getByRole("button", { name: /Pixel 9/ }).click();
+ await expect(picker).toBeHidden();
+ await view.getByRole("button", { name: "Add device" }).last().click();
+ await picker.getByRole("button", { name: /Pixel Tablet/ }).click();
+ await expect(picker).toBeHidden();
+ await expect(view.getByRole("tab")).toHaveCount(3);
+}
+
+async function drag(page: Page, source: Locator, destination: Locator, x: number, y: number) {
+ const start = await source.boundingBox();
+ const end = await destination.boundingBox();
+ if (!start || !end) throw new Error("Missing device tab or drop target");
+ const fromX = start.x + start.width / 3;
+ const fromY = start.y + start.height / 2;
+ await page.mouse.move(fromX, fromY);
+ await page.mouse.down();
+ await page.mouse.move(fromX + 10, fromY + 4, { steps: 4 });
+ await page.mouse.move(end.x + end.width * x, end.y + end.height * y, { steps: 16 });
+ await page.mouse.up();
+}
+
+for (const theme of ["light", "dark"] as const) {
+ test(`mixed device tab groups in ${theme} @visual`, async ({ page, openView, pageErrors }) => {
+ const { view } = await openView("mobile_open_simulator", { arguments: { deviceId: iphone.udid }, displayMode: "inline", theme, width: 900, inventory });
+ await selectAndroid(view);
+ const pane = view.locator("[data-device-pane]:visible");
+ await expect(pane).toHaveCount(3);
+ const pixelTab = view.getByRole("tab", { name: pixel.name });
+ const phone = view.locator(`[data-device-pane][aria-label="${iphone.name}"]`);
+ await drag(page, pixelTab, phone, 0.5, 0.5);
+ await expect(pane).toHaveCount(2);
+ await expect(view.getByRole("tablist")).toHaveCount(2);
+ await expect.soft(view.locator("#simulator-panels")).toHaveScreenshot(`device-tabs-split-${theme}.png`);
+ expect(pageErrors).toEqual([]);
+ });
+}
+
+test("choosing a device dismisses the picker and keeps Add device centered in narrow groups", async ({ openView, server }) => {
+ test.skip(hasPanel(server) === false, "This target opens the workspace in a separate browser tab.");
+ const { view } = await openView("mobile_open_simulator", { displayMode: "inline", width: 360, inventory });
+ await view.getByRole("button", { name: "Add device" }).click();
+ const picker = view.getByRole("dialog");
+ await picker.getByRole("button", { name: /Pixel 9/ }).press("Enter");
+ await expect(picker).toBeHidden();
+ const firstAdd = view.getByRole("button", { name: "Add device" });
+ await expect(firstAdd).toBeFocused();
+ const buttonBox = (await firstAdd.boundingBox())!;
+ const tabBox = (await view.getByRole("tab", { name: pixel.name }).boundingBox())!;
+ const buttonCenter = buttonBox.y + buttonBox.height / 2;
+ const tabCenter = tabBox.y + tabBox.height / 2;
+ expect(Math.abs(buttonCenter - tabCenter)).toBeLessThan(1);
+ await firstAdd.press("Enter");
+ await picker.getByRole("button", { name: /Pixel Tablet/ }).click();
+ await expect(picker).toBeHidden();
+ await expect(view.getByRole("tablist")).toHaveCount(2);
+ const dock = view.locator("#simulator-panels");
+ await expect.poll(() => dock.evaluate(node => node.scrollWidth - node.clientWidth)).toBeGreaterThan(60);
+ const add = dock.getByRole("button", { name: "Add device" }).last();
+ await add.scrollIntoViewIfNeeded();
+ await add.click();
+ await expect(picker).toBeVisible();
+});
+
+test("devices split at every edge, nest, rejoin and reorder without replacing their canvases", async ({ page, openView, pageErrors, server }) => {
+ test.skip(hasPanel(server) === false, "This target opens the workspace in a separate browser tab.");
+ const { view } = await openView("mobile_open_simulator", { arguments: { deviceId: iphone.udid }, displayMode: "inline", width: 1000, inventory });
+ await selectAndroid(view);
+ const dock = view.locator("#simulator-panels");
+ const tab = (name: string) => dock.getByRole("tab", { name, exact: true });
+ const panel = (name: string) => dock.locator(`[data-device-pane][aria-label="${name}"]`);
+ await dock.locator("canvas").evaluateAll(canvases => canvases.forEach(canvas => canvas.setAttribute("data-original", "")));
+ await expect(dock.getByRole("tablist")).toHaveCount(3);
+ const bounds = await dock.locator("[data-device-pane]:visible").evaluateAll(panes => panes.map(pane => pane.getBoundingClientRect().x));
+ expect(new Set(bounds).size).toBe(3);
+ await drag(page, tab(pixel.name), panel(iphone.name), 0.5, 0.5);
+ await drag(page, tab(tablet.name), panel(pixel.name), 0.5, 0.5);
+ await expect(dock.getByRole("tablist")).toHaveCount(1);
+ const edges = [[0.08, 0.5], [0.92, 0.5], [0.5, 0.08], [0.5, 0.92]];
+ for (const [x, y] of edges) {
+ await drag(page, tab(tablet.name), panel(tablet.name), x, y);
+ await expect(dock.getByRole("tablist")).toHaveCount(2);
+ await expect(dock.locator("[data-device-pane]:visible")).toHaveCount(2);
+ const peer = dock.locator(`[data-device-pane]:visible:not([aria-label="${tablet.name}"])`);
+ const from = (await panel(tablet.name).boundingBox())!;
+ const to = (await peer.boundingBox())!;
+ if (x < 0.5) expect(from.x + from.width).toBeLessThanOrEqual(to.x + 2);
+ if (x > 0.5) expect(from.x).toBeGreaterThanOrEqual(to.x + to.width - 2);
+ if (y < 0.5) expect(from.y + from.height).toBeLessThanOrEqual(to.y + 2);
+ if (y > 0.5) expect(from.y).toBeGreaterThanOrEqual(to.y + to.height - 2);
+ await drag(page, tab(tablet.name), peer, 0.5, 0.5);
+ await expect(dock.getByRole("tablist")).toHaveCount(1);
+ }
+ await drag(page, tab(tablet.name), panel(tablet.name), 0.92, 0.5);
+ await drag(page, tab(iphone.name), panel(tablet.name), 0.5, 0.9);
+ await expect(dock.getByRole("tablist")).toHaveCount(3);
+ await drag(page, tab(iphone.name), tab(pixel.name), 0.1, 0.5);
+ await expect(dock.getByRole("tablist")).toHaveCount(2);
+ const group = dock.getByRole("tablist").filter({ has: view.getByRole("tab", { name: pixel.name, exact: true }) });
+ await drag(page, tab(pixel.name), tab(iphone.name), 0.1, 0.5);
+ await expect(group.getByRole("tab").first()).toHaveAccessibleName(pixel.name);
+ const header = dock.locator(".dv-tabs-and-actions-container").filter({ has: view.getByRole("tab", { name: pixel.name, exact: true }) });
+ await drag(page, header.locator(".dv-void-container"), panel(tablet.name), 0.5, 0.92);
+ const moved = (await panel(pixel.name).boundingBox())!;
+ const above = (await panel(tablet.name).boundingBox())!;
+ expect(moved.y).toBeGreaterThanOrEqual(above.y + above.height - 2);
+ await expect(group.getByRole("tab")).toHaveCount(2);
+ await expect(dock.locator("canvas[data-original]")).toHaveCount(3);
+ await tab(pixel.name).getByRole("button").click();
+ await expect(tab(pixel.name)).toHaveCount(0);
+ const phoneGroup = dock.locator(".dv-groupview").filter({ has: view.getByRole("tab", { name: iphone.name, exact: true }) });
+ await tab(tablet.name).click();
+ await phoneGroup.getByRole("button", { name: "Add device" }).click();
+ await expect(view.getByRole("button", { name: /Pixel 9/ })).toHaveAttribute("aria-pressed", "false");
+ await view.getByRole("button", { name: /Pixel 9/ }).click();
+ await expect(view.getByRole("dialog")).toBeHidden();
+ const restored = (await panel(pixel.name).boundingBox())!;
+ const phoneBox = (await panel(iphone.name).boundingBox())!;
+ expect(restored.x).toBeGreaterThanOrEqual(phoneBox.x + phoneBox.width - 2);
+ expect(Math.abs(restored.y - phoneBox.y)).toBeLessThan(2);
+ expect(pageErrors).toEqual([]);
+});
diff --git a/tooling/hosts/fixtures.ts b/tooling/hosts/fixtures.ts
index 0aca286d..84687e5e 100644
--- a/tooling/hosts/fixtures.ts
+++ b/tooling/hosts/fixtures.ts
@@ -5,12 +5,13 @@ import { test as base, expect, type FrameLocator, type Page } from "@playwright/
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import type { CallToolResult, JSONRPCMessage, Tool } from "@modelcontextprotocol/sdk/types.js";
+import type { SimulatorDevice } from "../../packages/shared/src/protocol.ts";
import { HOSTS, type Target, type Theme } from "./profiles.ts";
declare global {
interface Window {
/** The Mac page's entry points for the native sidebar, from apps/mac/web/main.tsx. */
- mobileDevShell?: { selectTool(tool: string | null): void; selectLayout(layout: string): void };
+ mobileDevShell?: { selectTool(tool: string | null): void };
/** Where Swift delivers the server's messages, from apps/mac/web/mac-bridge.ts. */
__mobileDevReceive?: (message: JSONRPCMessage) => void;
}
@@ -38,6 +39,11 @@ export async function startServer(target: Target) {
return { transport, stderr, async close() { await transport.close(); await rm(home, { recursive: true, force: true }); } };
}
+export const hasPanel = (server: { tools: { name: string; _meta?: Record }[] }) =>
+ server.tools.some(tool => tool.name === "mobile_open_workspace" && (tool._meta?.ui as { resourceUri?: string } | undefined)?.resourceUri !== undefined);
+
+type Inventory = { ios: SimulatorDevice[]; android: SimulatorDevice[] };
+
type Opened = { view: FrameLocator; result: CallToolResult };
type Fixtures = {
@@ -47,7 +53,7 @@ type Fixtures = {
/** An MCP client for the target's server, as the host's MCP client. */
server: { client: Client; tools: Tool[] };
/** Opens the view a tool renders, as an MCP Apps host would after the model calls it. */
- openView(tool: string, options?: { arguments?: Record; theme?: Theme; displayMode?: "inline" | "fullscreen"; width?: number; initiallyHidden?: boolean }): Promise;
+ openView(tool: string, options?: { arguments?: Record; theme?: Theme; displayMode?: "inline" | "fullscreen"; width?: number; initiallyHidden?: boolean; inventory?: Inventory }): Promise;
/** Loads the Mac app's page with a stand-in for the WebKit relay to its server. */
openMac(options?: { theme?: Theme }): Promise;
};
@@ -93,9 +99,21 @@ export const test = base.extend({
const name = new URL(route.request().url()).pathname.slice(1) || "host.html";
await route.fulfill({ path: join(build, "harness", name) });
});
- await page.exposeFunction("mcpRequest", (method: string, params: never) =>
- method === "tools/call" ? server.client.callTool(params) : server.client.readResource(params));
- await use(async (name, { arguments: args = {}, theme = "light", displayMode = "fullscreen", width, initiallyHidden } = {}) => {
+ let inventory: Inventory | undefined;
+ await page.exposeFunction("mcpRequest", (method: string, params: never) => {
+ if (method === "resources/read") return server.client.readResource(params);
+ const { name } = params as { name: string };
+ if (inventory) {
+ if (name === "mobile_list_ios_devices") return { content: [], structuredContent: { physicalDevices: [] } };
+ if (name === "mobile_list_simulators" || name === "mobile_list_android_devices") {
+ const devices = name === "mobile_list_simulators" ? inventory.ios : inventory.android;
+ return { content: [], structuredContent: { connected: true, managed: false, baseUrl: "", devices } };
+ }
+ }
+ return server.client.callTool(params);
+ });
+ await use(async (name, { arguments: args = {}, theme = "light", displayMode = "fullscreen", width, initiallyHidden, inventory: devices } = {}) => {
+ inventory = devices;
const tool = server.tools.find(candidate => candidate.name === name);
const uri = (tool?._meta?.ui as { resourceUri?: string } | undefined)?.resourceUri;
if (uri === undefined) throw new Error(`${name} has no UI resource.`);
diff --git a/tooling/hosts/hosts.spec.ts b/tooling/hosts/hosts.spec.ts
index d67a20d1..fa66c1ca 100644
--- a/tooling/hosts/hosts.spec.ts
+++ b/tooling/hosts/hosts.spec.ts
@@ -4,7 +4,7 @@ import Ajv2020 from "ajv/dist/2020.js";
import { codexToolBudget } from "../../apps/codex-plugin/tooling/codex-tool-limits.mjs";
import { oversizedFiles, PANEL_PARTS } from "../host-runtime.mjs";
import { pluginHost, pluginHosts } from "../plugin-hosts.mjs";
-import { expect, test } from "./fixtures.ts";
+import { expect, hasPanel, test } from "./fixtures.ts";
const root = join(import.meta.dirname, "../..");
@@ -12,11 +12,6 @@ const root = join(import.meta.dirname, "../..");
// in a stand-in for its host. Device-backed behavior needs a simulator or emulator
// and is covered by the smoke scripts instead.
-// Claude shows devices in its own simulator views, so its server has no panel.
-// A panel that renders in the chat; Claude's shows beside it, in a browser (browser-panel.spec.ts).
-const hasPanel = (server: { tools: { name: string; _meta?: Record }[] }) =>
- server.tools.some(tool => tool.name === "mobile_open_workspace" && (tool._meta?.ui as { resourceUri?: string } | undefined)?.resourceUri !== undefined);
-
test.describe("MCP Apps hosts", () => {
test("every tool schema compiles as JSON Schema 2020-12", async ({ server }) => {
// Claude rejects tools that declare draft-07, which is what the MCP SDK emits.
@@ -77,7 +72,7 @@ test.describe("MCP Apps hosts", () => {
};
await expect.poll(selection).toMatchObject({ activeDeviceId: deviceId });
await expect.poll(() => readResourceSaving).toBe(true);
- await expect(view.locator("#android-panel").getByRole("button", { name: "Resource saving" })).toHaveCount(0);
+ await expect(view.locator('[data-device-pane][data-platform="android"]').getByRole("button", { name: "Resource saving" })).toHaveCount(0);
const attachments = await page.evaluate(() => window.harness.events.filter(event => event.method === "modelContext"));
expect(attachments).toEqual([]);
await page.evaluate(() => window.harness.teardown());
@@ -98,15 +93,11 @@ test.describe("MCP Apps hosts", () => {
};
}
const { view } = await openView("mobile_open_simulator");
- const android = view.locator("#android-panel");
- await expect(android.getByText(/Install Android SDK Platform-Tools.*SDK Manager/)).toBeVisible();
- await expect(view.locator("#platform-select")).toContainText("Android");
- await view.locator("#platform-select").click();
- await view.getByRole("option", { name: "iOS" }).click();
- await page.keyboard.press("Escape");
- const ios = view.locator("#ios-panel");
- await expect(ios.getByText("Local iOS devices require macOS.")).toBeVisible();
- await expect(ios.getByRole("button", { name: "iOS device", exact: true })).toBeDisabled();
+ await expect(view.locator("#simulator-panels")).toContainText(/Install Android SDK Platform-Tools.*SDK Manager/);
+ await view.getByRole("button", { name: "Add device" }).click();
+ const picker = view.getByRole("dialog", { name: "Choose devices" });
+ await expect(picker.getByText("Local iOS devices require macOS.")).toBeVisible();
+ await expect(picker.getByText(/Install Android SDK Platform-Tools.*SDK Manager/)).toBeVisible();
});
test("the workspace opens every tool without errors", async ({ openView, pageErrors, server }) => {
@@ -167,12 +158,9 @@ test.describe("MCP Apps hosts", () => {
// preview and the steps were left sharing the height below it.
for (const displayMode of ["fullscreen", "inline"] as const) {
await page.setViewportSize({ width: 1280, height: 800 });
- const { view } = await openView("mobile_open_workspace", { displayMode });
- // A mirror needs a platform to show: with none the pane is collapsed, which is the point of
- // the shares below. These hosts see no devices, so the platform is chosen here.
- await view.locator("#platform-select").click();
- await view.getByRole("option", { name: "iOS" }).click();
- await page.keyboard.press("Escape");
+ const device = { udid: "phone", name: "iPhone", runtime: "iOS", state: "Shutdown" };
+ const inventory = { ios: [device], android: [] };
+ const { view } = await openView("mobile_open_workspace", { displayMode, inventory, arguments: { deviceId: device.udid } });
await view.locator("#tool-select").click();
await view.getByRole("option", { name: "Testing" }).click();
await view.locator("[data-testing-recorder-workspace]").waitFor();
@@ -200,22 +188,16 @@ test.describe("MCP Apps hosts", () => {
// selects a simulator a moment later. The mirror used to stay shut through that — the panel
// asked for its own shares during the commit that changed its panels' constraints, where the
// group discards them and keeps what it last requested, which was a mirror of nothing.
- // Both platforms must be available to reproduce the unresolved automatic layout.
- const callTool = server.client.callTool.bind(server.client);
- server.client.callTool = (request, ...options) => request.name === "mobile_list_simulators"
- ? Promise.resolve({ content: [], structuredContent: { connected: true, managed: false, baseUrl: "", devices: [] } })
- : callTool(request, ...options);
+ const device = { udid: "phone", name: "iPhone", runtime: "iOS", state: "Booted" };
+ const inventory = { ios: [] as typeof device[], android: [] };
await page.setViewportSize({ width: 1280, height: 800 });
- const { view } = await openView("mobile_open_workspace", { displayMode: "fullscreen" });
+ const { view } = await openView("mobile_open_workspace", { displayMode: "fullscreen", inventory });
await view.locator("#tool-select").click();
await view.getByRole("option", { name: "Testing" }).click();
await view.locator("[data-testing-recorder-workspace]").waitFor();
const mirror = view.locator("#simulators-resizable");
- // Nothing to mirror yet, so the pane is collapsed rather than an empty quarter of the window.
await expect.poll(async () => Math.round((await mirror.boundingBox())?.width ?? 0)).toBe(0);
- await page.keyboard.press("Escape");
- await view.locator("#platform-select").click();
- await view.getByRole("option", { name: "iOS" }).click();
+ inventory.ios.push(device);
await expect.poll(async () => Math.round((await mirror.boundingBox())?.width ?? 0)).toBe(320);
});
@@ -229,36 +211,29 @@ test.describe("MCP Apps hosts", () => {
test("the panel beside the chat opens inline", async ({ openView, pageErrors, server }) => {
test.skip(hasPanel(server) === false, "This target's server renders no panel in the chat.");
const { view } = await openView("mobile_open_simulator", { displayMode: "inline" });
- await expect(view.locator("#ios-panel, #android-panel").first()).toBeAttached();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeAttached();
expect(pageErrors).toEqual([]);
});
- test("an Android panel initialized while hidden shows its device controls and keeps tools collapsed", async ({ openView, page, pageErrors, target }) => {
+ test("a targeted panel initialized while hidden shows the device picker and keeps tools collapsed", async ({ openView, page, pageErrors, target }) => {
test.skip(target !== "codex", "Codex retains inactive panels before displaying them.");
const { view } = await openView("mobile_open_simulator", {
arguments: { platform: "android" }, displayMode: "inline", initiallyHidden: true,
});
- await expect(view.locator("#platform-select")).toContainText("Android");
- await expect(view.locator("#android-panel")).toHaveJSProperty("hidden", false);
+ const empty = view.locator('[role="status"]').filter({ hasText: "Requested Android device unavailable" });
+ await expect(empty).toBeAttached();
const frame = page.locator("#view");
await frame.evaluate(element => { element.removeAttribute("hidden"); });
-
- await expect(view.locator("#android-panel")).toBeVisible();
- await expect(view.getByRole("toolbar", { name: "Android controls" })).toBeVisible();
- await expect(view.locator("#android-devices")).toBeVisible();
- const android = await view.locator("#android-resizable").boundingBox();
- const ios = await view.locator("#ios-resizable").boundingBox();
- const tools = await view.locator("#tools-resizable").boundingBox();
- expect(android?.width).toBeGreaterThan(0);
- expect(ios?.width).toBe(0);
- expect(tools?.height).toBe(0);
+ await expect(empty).toBeVisible();
+ await expect(view.getByRole("button", { name: "Add device" })).toBeVisible();
+ const toolsPanel = view.locator("#tools-resizable");
+ await expect.poll(async () => (await toolsPanel.boundingBox())?.height).toBe(0);
await expect(view.locator("#tool-select")).toContainText("Tools");
const toolSelect = view.locator("#tool-select");
await toolSelect.click();
const logsOption = view.getByRole("option", { name: "Logs" });
await logsOption.click();
- const toolsPanel = view.locator("#tools-resizable");
await expect(toolsPanel).toBeVisible();
const initialTools = await toolsPanel.boundingBox();
const divider = view.getByRole("separator", { name: "Resize tools and simulators" });
@@ -274,18 +249,17 @@ test.describe("MCP Apps hosts", () => {
expect(resizedTools?.height).toBeLessThan(initialTools.height - 50);
await frame.evaluate(element => { element.setAttribute("hidden", ""); });
- await expect(view.locator("#android-panel")).toBeHidden();
+ await expect(empty).toBeHidden();
await frame.evaluate(element => { element.removeAttribute("hidden"); });
- await expect(view.locator("#android-panel")).toBeVisible();
- const restoredTools = await toolsPanel.boundingBox();
- expect(restoredTools?.height).toBeCloseTo(resizedTools!.height, 1);
+ await expect(empty).toBeVisible();
+ await expect.poll(async () => (await toolsPanel.boundingBox())?.height).toBeCloseTo(resizedTools!.height, 1);
await expect(toolSelect).toContainText("Logs");
expect(pageErrors).toEqual([]);
});
});
test.describe("Mac app", { tag: "@mac" }, () => {
- test("the sidebar switches tools and platforms", async ({ openMac, pageErrors }) => {
+ test("the sidebar switches tools and the workspace offers both device inventories", async ({ openMac, pageErrors }) => {
const page = await openMac();
await page.waitForFunction(() => window.mobileDevShell !== undefined);
for (const tool of ["logs", "performance", "storage", "tracesift"]) {
@@ -293,8 +267,9 @@ test.describe("Mac app", { tag: "@mac" }, () => {
await expect(page.getByText("Choose a tool in the sidebar"), tool).toHaveCount(0);
}
await page.evaluate(() => window.mobileDevShell!.selectTool(null));
- await page.evaluate(() => window.mobileDevShell!.selectLayout("ios"));
- await expect(page.locator("#ios-panel")).toBeVisible();
+ await page.getByRole("button", { name: "Add device" }).click();
+ await expect(page.getByRole("heading", { name: "iOS", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Android", exact: true })).toBeVisible();
expect(pageErrors).toEqual([]);
});
});
diff --git a/tooling/hosts/screenshots/codex/device-picker-dark.png b/tooling/hosts/screenshots/codex/device-picker-dark.png
new file mode 100644
index 00000000..95c49d2b
Binary files /dev/null and b/tooling/hosts/screenshots/codex/device-picker-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/device-picker-light.png b/tooling/hosts/screenshots/codex/device-picker-light.png
new file mode 100644
index 00000000..3498aaf5
Binary files /dev/null and b/tooling/hosts/screenshots/codex/device-picker-light.png differ
diff --git a/tooling/hosts/screenshots/codex/device-tabs-split-dark.png b/tooling/hosts/screenshots/codex/device-tabs-split-dark.png
new file mode 100644
index 00000000..6afbafe9
Binary files /dev/null and b/tooling/hosts/screenshots/codex/device-tabs-split-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/device-tabs-split-light.png b/tooling/hosts/screenshots/codex/device-tabs-split-light.png
new file mode 100644
index 00000000..44646ddc
Binary files /dev/null and b/tooling/hosts/screenshots/codex/device-tabs-split-light.png differ
diff --git a/tooling/hosts/screenshots/codex/panel-dark.png b/tooling/hosts/screenshots/codex/panel-dark.png
index 9787e749..56fb8705 100644
Binary files a/tooling/hosts/screenshots/codex/panel-dark.png and b/tooling/hosts/screenshots/codex/panel-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/panel-light.png b/tooling/hosts/screenshots/codex/panel-light.png
index d892eb73..eae419df 100644
Binary files a/tooling/hosts/screenshots/codex/panel-light.png and b/tooling/hosts/screenshots/codex/panel-light.png differ
diff --git a/tooling/hosts/screenshots/codex/testing-runtime-dark.png b/tooling/hosts/screenshots/codex/testing-runtime-dark.png
index 4bd11380..e9849e77 100644
Binary files a/tooling/hosts/screenshots/codex/testing-runtime-dark.png and b/tooling/hosts/screenshots/codex/testing-runtime-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/testing-runtime-light.png b/tooling/hosts/screenshots/codex/testing-runtime-light.png
index f4793aad..8d116349 100644
Binary files a/tooling/hosts/screenshots/codex/testing-runtime-light.png and b/tooling/hosts/screenshots/codex/testing-runtime-light.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-app-intel-dark.png b/tooling/hosts/screenshots/codex/workspace-app-intel-dark.png
index 0828ce83..a4752871 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-app-intel-dark.png and b/tooling/hosts/screenshots/codex/workspace-app-intel-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-app-intel-light.png b/tooling/hosts/screenshots/codex/workspace-app-intel-light.png
index 36d7bb9c..7c603b7c 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-app-intel-light.png and b/tooling/hosts/screenshots/codex/workspace-app-intel-light.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-logs-dark.png b/tooling/hosts/screenshots/codex/workspace-logs-dark.png
index e394aa8d..8129dc23 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-logs-dark.png and b/tooling/hosts/screenshots/codex/workspace-logs-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-logs-light.png b/tooling/hosts/screenshots/codex/workspace-logs-light.png
index f674e475..3828691c 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-logs-light.png and b/tooling/hosts/screenshots/codex/workspace-logs-light.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-menu-over-performance-dark.png b/tooling/hosts/screenshots/codex/workspace-menu-over-performance-dark.png
index f314d5aa..77c9b853 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-menu-over-performance-dark.png and b/tooling/hosts/screenshots/codex/workspace-menu-over-performance-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-menu-over-performance-light.png b/tooling/hosts/screenshots/codex/workspace-menu-over-performance-light.png
index eba150a8..f56118a8 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-menu-over-performance-light.png and b/tooling/hosts/screenshots/codex/workspace-menu-over-performance-light.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-performance-dark.png b/tooling/hosts/screenshots/codex/workspace-performance-dark.png
index fca16a2e..6999c80e 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-performance-dark.png and b/tooling/hosts/screenshots/codex/workspace-performance-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-performance-light.png b/tooling/hosts/screenshots/codex/workspace-performance-light.png
index b658e5ef..c9a3ee47 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-performance-light.png and b/tooling/hosts/screenshots/codex/workspace-performance-light.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-storage-dark.png b/tooling/hosts/screenshots/codex/workspace-storage-dark.png
index c8408342..1c535800 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-storage-dark.png and b/tooling/hosts/screenshots/codex/workspace-storage-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-storage-light.png b/tooling/hosts/screenshots/codex/workspace-storage-light.png
index 26e50168..0455cee6 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-storage-light.png and b/tooling/hosts/screenshots/codex/workspace-storage-light.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-tracesift-dark.png b/tooling/hosts/screenshots/codex/workspace-tracesift-dark.png
index 55108e4b..794120c6 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-tracesift-dark.png and b/tooling/hosts/screenshots/codex/workspace-tracesift-dark.png differ
diff --git a/tooling/hosts/screenshots/codex/workspace-tracesift-light.png b/tooling/hosts/screenshots/codex/workspace-tracesift-light.png
index 31ff1795..29e470b9 100644
Binary files a/tooling/hosts/screenshots/codex/workspace-tracesift-light.png and b/tooling/hosts/screenshots/codex/workspace-tracesift-light.png differ
diff --git a/tooling/hosts/visual.spec.ts b/tooling/hosts/visual.spec.ts
index eb5657f3..38667c8e 100644
--- a/tooling/hosts/visual.spec.ts
+++ b/tooling/hosts/visual.spec.ts
@@ -26,6 +26,19 @@ for (const theme of themes) test.describe(`${theme}`, { tag: "@visual" }, () =>
}
});
+ test("device picker", async ({ openView }) => {
+ const device = { state: "Shutdown", runtime: "iOS 27.0" };
+ const inventory = {
+ ios: [{ ...device, name: "iPhone 17 Pro", udid: "iphone" }, { ...device, name: "iPad Air", udid: "ipad" }],
+ android: [{ ...device, name: "Pixel 9", udid: "avd:Pixel_9", runtime: "Android" }],
+ };
+ const { view } = await openView("mobile_open_simulator", { theme, displayMode: "inline", width: 480, inventory });
+ await view.getByRole("button", { name: "Add device" }).click();
+ const picker = view.getByRole("dialog", { name: "Choose devices" });
+ await expect(picker.getByText("iPhone 17 Pro")).toBeVisible();
+ await expect.soft(picker).toHaveScreenshot(`device-picker-${theme}.png`);
+ });
+
test("Testing Studio runtime download", async ({ openView, server }) => {
const callTool = server.client.callTool.bind(server.client);
server.client.callTool = async (request, ...options) => {
@@ -47,7 +60,7 @@ for (const theme of themes) test.describe(`${theme}`, { tag: "@visual" }, () =>
test(`panel beside the chat`, async ({ openView }) => {
const { view } = await openView("mobile_open_simulator", { theme, displayMode: "inline", width: 480, arguments: { platform: "ios" } });
- await expect(view.locator("#ios-panel")).toBeVisible();
+ await expect(view.getByText("Requested iOS device unavailable.", { exact: false })).toBeVisible();
await expect.soft(view.locator("body")).toHaveScreenshot(`panel-${theme}.png`);
});
});
diff --git a/website/src/content/docs/docs/devices.md b/website/src/content/docs/docs/devices.md
index 05af0159..a6d186b4 100644
--- a/website/src/content/docs/docs/devices.md
+++ b/website/src/content/docs/docs/devices.md
@@ -13,7 +13,7 @@ Ask your agent to open the simulator beside chat, or open Mobile Dev from the Co
- “Open the iPad simulator beside this chat.”
- “Test this on my physical iPhone.”
-Use the platform menu to show iOS, Android, or both. Pick a device from each panel's dropdown. Selecting a stopped simulator or AVD boots it and starts its stream. Opening the panel by itself does not boot a device.
+Choose **+ Add device** in a tab strip and pick an iOS or Android device. The picker closes and the device opens beside that group. Open the picker again to add another device. Drag a tab to any edge of a view to split it, or to the center of another view to join its group. Drag tabs along the tab strip to reorder them and drag dividers to resize the views. Drag the empty part of a tab strip to move the whole group. Selecting a stopped simulator or AVD boots it and starts its stream. Opening the workspace by itself does not boot a device.
The agent reuses a suitable selected or running device when the task establishes the target. It may ask you to choose when the choice affects the task.