Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,18 @@ func captureAppWindowScreenshot(app: NSRunningApplication, outPath: String) thro
throw HelperError.commandFailed("app window screenshots require macOS 14 or newer")
}
let pid = app.processIdentifier
let frontWindowID = frontWindowNumber(pid: pid)
let frontWindow = onScreenWindows(pid: pid, windowInfo: appWindowInfo()).first
let frontWindowID = frontWindow?.number
let content = try awaitShareableContent()
let candidates = content.windows.filter {
$0.owningApplication?.processID == pid && $0.windowLayer == 0 && $0.frame.width > 0
&& $0.frame.height > 0
}
guard
let window = candidates.first(where: { Int($0.windowID) == frontWindowID })
?? candidates.max(by: { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height })
else {
throw HelperError.commandFailed(
"screenshot could not find a window for the app",
details: ["reason": "window-not-found", "bundleId": app.bundleIdentifier ?? ""]
)
let candidates = content.windows.filter { $0.owningApplication?.processID == pid }
let window: SCWindow
let selection = frontCaptureWindow(
candidates, frontWindowID: frontWindowID, sharingState: frontWindow?.sharingState, windowID: { Int($0.windowID) })
switch selection {
case .success(let front):
window = front
case .failure(let refusal):
throw screenshotRefusal(refusal, app: app, frontWindowID: frontWindowID)
}

let filter = SCContentFilter(desktopIndependentWindow: window)
Expand Down Expand Up @@ -52,6 +50,54 @@ func captureAppWindowScreenshot(app: NSRunningApplication, outPath: String) thro
try writePNG(capturedImage, to: outPath)
}

/// Why an app screenshot refuses. The capture is the app's front window or nothing: another
/// window of the app would show state the user is not looking at. Pinned with the host by
/// `contracts/fixtures/macos-native-helper-outcomes.json`.
enum AppWindowScreenshotRefusal: String, CaseIterable, Error {
case windowNotFound = "window-not-found"
case frontWindowNotShareable = "front-window-not-shareable"
case frontWindowCaptureExcluded = "front-window-capture-excluded"
}

/// The shareable candidate whose WindowServer ID is the app's front window.
func frontCaptureWindow<Window>(
_ candidates: [Window],
frontWindowID: Int?,
sharingState: Int?,
windowID: (Window) -> Int
) -> Result<Window, AppWindowScreenshotRefusal> {
guard let frontWindowID else { return .failure(.windowNotFound) }
guard sharingState != 0 else { return .failure(.frontWindowCaptureExcluded) }
guard let front = candidates.first(where: { windowID($0) == frontWindowID }) else {
return .failure(.frontWindowNotShareable)
}
return .success(front)
}

private func screenshotRefusal(
_ refusal: AppWindowScreenshotRefusal,
app: NSRunningApplication,
frontWindowID: Int?
) -> HelperError {
var details = ["reason": refusal.rawValue, "bundleId": app.bundleIdentifier ?? ""]
switch refusal {
case .windowNotFound:
return .commandFailed("screenshot could not find an on-screen window for the app", details: details)
case .frontWindowCaptureExcluded:
details["frontWindowId"] = frontWindowID.map(String.init) ?? ""
return .commandFailed(
"screenshot could not capture the app's front window: the app excludes it from capture",
details: details
)
case .frontWindowNotShareable:
details["frontWindowId"] = frontWindowID.map(String.init) ?? ""
return .commandFailed(
"screenshot could not capture the app's front window: ScreenCaptureKit does not offer it",
details: details
)
}
}

@available(macOS 14.0, *)
private func awaitShareableContent() throws -> SCShareableContent {
let semaphore = DispatchSemaphore(value: 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -482,39 +482,40 @@ private func numberAttribute(_ element: AXUIElement, attribute: String) -> Doubl
return number.doubleValue
}

private struct OnScreenWindow {
struct OnScreenWindow {
let number: Int
let bounds: CGRect
let sharingState: Int?
}

/// The pid's normal-layer windows, front to back. Bounds and owners need no Screen Recording
/// permission; only titles do.
private func onScreenWindows(pid: pid_t) -> [OnScreenWindow] {
guard
let info = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
as? [[String: Any]]
else {
return []
}
return info.compactMap { entry in
let frontWindowLayer = 0

/// The pid's visible, nonempty normal-layer windows, front to back.
func onScreenWindows(pid: pid_t, windowInfo: [[String: Any]]) -> [OnScreenWindow] {
windowInfo.compactMap { entry in
guard (entry[kCGWindowOwnerPID as String] as? Int32) == pid,
(entry[kCGWindowLayer as String] as? Int) == 0,
(entry[kCGWindowLayer as String] as? Int) == frontWindowLayer,
(entry[kCGWindowIsOnscreen as String] as? Bool) == true,
let alpha = entry[kCGWindowAlpha as String] as? Double, alpha > 0,
let number = entry[kCGWindowNumber as String] as? Int,
let boundsDict = entry[kCGWindowBounds as String] as? NSDictionary,
let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary)
let bounds = CGRect(dictionaryRepresentation: boundsDict as CFDictionary),
bounds.width > 0, bounds.height > 0
else {
return nil
}
return OnScreenWindow(number: number, bounds: bounds)
return OnScreenWindow(
number: number, bounds: bounds, sharingState: entry[kCGWindowSharingState as String] as? Int)
}
}

func frontWindowNumber(pid: pid_t) -> Int? {
onScreenWindows(pid: pid).first?.number
func appWindowInfo() -> [[String: Any]] {
CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
Comment thread
thymikee marked this conversation as resolved.
Resolved
as? [[String: Any]] ?? []
}

private func frontWindowFrame(pid: pid_t) -> CGRect? {
onScreenWindows(pid: pid).first?.bounds
func frontWindowFrame(pid: pid_t, windowInfo: [[String: Any]] = appWindowInfo()) -> CGRect? {
onScreenWindows(pid: pid, windowInfo: windowInfo).first?.bounds
}

private let returnVirtualKey: CGKeyCode = 36
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import CoreGraphics
import XCTest

@testable import AgentDeviceMacOSHelper

private struct Candidate: Equatable {
let id: Int
let area: Double
}

/// An app screenshot captures the front window or refuses; it never substitutes another window.
final class AppWindowScreenshotTests: XCTestCase {
func testCaptureIdentityAndScrollAndClickFallbackFrameSelectTheSameEligibleFrontWindow() {
let windows = [
windowInfo(id: 1, pid: 99),
windowInfo(id: 2, layer: 1),
windowInfo(id: 3, onScreen: false),
windowInfo(id: 4, alpha: 0),
windowInfo(id: 5, width: 0),
windowInfo(id: 6, height: 0),
windowInfo(id: 7, alpha: 0.5, width: 20, height: 20),
windowInfo(id: 8),
]

let frontID = onScreenWindows(pid: 42, windowInfo: windows).first?.number
let selected = frontCaptureWindow([7, 8], frontWindowID: frontID, sharingState: 1, windowID: { $0 })

// Scroll and the click actionWindow fallback both consume frontWindowFrame.
XCTAssertEqual(
frontWindowFrame(pid: 42, windowInfo: windows),
CGRect(x: 10, y: 10, width: 20, height: 20))
XCTAssertEqual(frontID, 7)
XCTAssertEqual(try selected.get(), 7)
}

func testRefusesWhenOnlyInvisibleOrEmptyWindowsRemain() {
let windows = [
windowInfo(id: 1, onScreen: false),
windowInfo(id: 2, alpha: 0),
windowInfo(id: 3, width: 0),
windowInfo(id: 4, height: 0),
]
let frontID = onScreenWindows(pid: 42, windowInfo: windows).first?.number
let selected = frontCaptureWindow([5], frontWindowID: frontID, sharingState: 1, windowID: { $0 })

XCTAssertNil(frontWindowFrame(pid: 42, windowInfo: windows))
XCTAssertNil(frontID)
XCTAssertThrowsError(try selected.get()) { error in
XCTAssertEqual(error as? AppWindowScreenshotRefusal, .windowNotFound)
}
}

func testSelectsTheFrontWindowEvenWhenAnotherIsLarger() {
let candidates = [Candidate(id: 7, area: 10_000), Candidate(id: 3, area: 100)]

let selected = frontCaptureWindow(candidates, frontWindowID: 3, sharingState: 1, windowID: \.id)

XCTAssertEqual(try selected.get(), Candidate(id: 3, area: 100))
}

func testRefusesWhenTheFrontWindowIsNotShareable() {
let candidates = [Candidate(id: 7, area: 10_000), Candidate(id: 8, area: 100)]

let selected = frontCaptureWindow(candidates, frontWindowID: 3, sharingState: 1, windowID: \.id)

XCTAssertThrowsError(try selected.get()) { error in
XCTAssertEqual(error as? AppWindowScreenshotRefusal, .frontWindowNotShareable)
}
}

func testCaptureExclusionSurvivesWindowSelectionAndNeverSubstitutesAnotherWindow() {
let windows = [windowInfo(id: 3, sharingState: 0), windowInfo(id: 7)]
let front = onScreenWindows(pid: 42, windowInfo: windows).first
XCTAssertEqual(front?.number, 3)
XCTAssertEqual(front?.sharingState, 0)

for candidates in [[3, 7], [7]] {
let selected = frontCaptureWindow(
candidates, frontWindowID: front?.number, sharingState: front?.sharingState, windowID: { $0 })
XCTAssertThrowsError(try selected.get()) { error in
XCTAssertEqual(error as? AppWindowScreenshotRefusal, .frontWindowCaptureExcluded)
}
}

var entry = windowInfo(id: 3)
entry.removeValue(forKey: kCGWindowSharingState as String)
let unknown = onScreenWindows(pid: 42, windowInfo: [entry]).first
let selected = frontCaptureWindow(
[3], frontWindowID: unknown?.number, sharingState: unknown?.sharingState, windowID: { $0 })
XCTAssertEqual(try selected.get(), 3)
}

func testRefusesWhenTheAppHasNoOnScreenWindow() {
let selected = frontCaptureWindow(
[Candidate(id: 7, area: 10_000)], frontWindowID: nil, sharingState: nil, windowID: \.id)

XCTAssertThrowsError(try selected.get()) { error in
XCTAssertEqual(error as? AppWindowScreenshotRefusal, .windowNotFound)
}
}
}

private func windowInfo(
id: Int, pid: Int32 = 42, layer: Int = 0, onScreen: Bool = true,
alpha: Double = 1, sharingState: Int = 1, width: Double = 100, height: Double = 100
) -> [String: Any] {
[
kCGWindowNumber as String: id,
kCGWindowOwnerPID as String: pid,
kCGWindowLayer as String: layer,
kCGWindowIsOnscreen as String: onScreen,
kCGWindowAlpha as String: alpha,
kCGWindowSharingState as String: sharingState,
kCGWindowBounds as String: CGRect(x: 10, y: 10, width: width, height: height).dictionaryRepresentation,
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ private struct ScrollGestureFixture: Decodable {
private struct HelperOutcomesFixture: Decodable {
let refusalReasons: [String]
let deliveryMechanisms: [String]
let screenshotRefusalReasons: [String]
}

/// `#filePath` is `<repo>/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/<file>`.
Expand All @@ -43,6 +44,8 @@ final class BackgroundInteractionTests: XCTestCase {
)
XCTAssertEqual(BackgroundRefusal.allCases.map(\.rawValue), fixture.refusalReasons)
XCTAssertEqual(BackgroundDeliveryMechanism.allCases.map(\.rawValue), fixture.deliveryMechanisms)
XCTAssertEqual(
AppWindowScreenshotRefusal.allCases.map(\.rawValue), fixture.screenshotRefusalReasons)
}

/// The native backend scrolls as far as the runner does: its travel agrees with every case of
Expand Down
7 changes: 6 additions & 1 deletion contracts/fixtures/macos-native-helper-outcomes.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"description": "Vocabulary the macOS helper reports for app-surface actions. Swift: BackgroundRefusal and BackgroundDeliveryMechanism in apple/macos-helper. TypeScript: the macOS helper client in packages/platform-apple/src/os/macos/helper.ts.",
"description": "Vocabulary the macOS helper reports for app-surface actions. Swift: BackgroundRefusal, BackgroundDeliveryMechanism, and AppWindowScreenshotRefusal in apple/macos-helper. TypeScript: the macOS helper client in packages/platform-apple/src/os/macos/helper.ts.",
"refusalReasons": [
"background-pointer-gesture",
"no-accessible-target",
Expand All @@ -14,5 +14,10 @@
"ax-confirm",
"ax-scroll-bar",
"key-events"
],
"screenshotRefusalReasons": [
"window-not-found",
"front-window-not-shareable",
"front-window-capture-excluded"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -266,15 +266,26 @@ describe('buildInventory', () => {
}
});

test('names a capture even when no panel reports primary', () => {
test('names the sole lit panel when no panel reports primary', () => {
const inventory = buildInventory([
{ ...outerPanel, primary: false },
{ ...outerPanel, power: 'dark', primary: false },
{ ...innerPanel, power: 'lit', primary: false },
]);
assert.equal(inventory.multiScreen, true);
assert.equal(inventory.ambiguous, true);
// A capture is still named: never the implicit black-producing default.
assert.ok(inventory.activeDisplay);
assert.equal(inventory.activeDisplay?.name, 'LCD-1');
});

test('names no panel when neither primary nor power identifies one', () => {
for (const power of ['lit', 'dark', 'unknown'] as const) {
const inventory = buildInventory([
{ ...outerPanel, power, primary: false },
{ ...innerPanel, power, primary: false },
]);
assert.equal(inventory.multiScreen, true);
assert.equal(inventory.ambiguous, true);
assert.equal(inventory.activeDisplay, undefined, power);
}
});

test('keeps choosing the lit panel when a third panel is present', () => {
Expand Down Expand Up @@ -476,6 +487,58 @@ describe('resolveAppleCaptureTarget', () => {
assert.equal(target.displayRotation, undefined);
});

/** The closed-Duo payload with each panel's `primary` flag and backlight replaced. */
function duoReporting(panels: Record<number, { primary: boolean; backlightState: string }>) {
return JSON.stringify({
result: {
displays: IPHONE_DUO_CLOSED.result.displays.map((entry) => ({
...entry,
...panels[entry.displayId],
})),
},
});
}

test('names the primary panel when panel power is ambiguous', async () => {
mockReadHostTextFile.mockResolvedValue(
duoReporting({
1: { primary: true, backlightState: 'activeOn' },
3: { primary: false, backlightState: 'activeOn' },
}),
);
assert.equal((await resolveAppleCaptureTarget(IOS_TEST_SIMULATOR)).display?.name, 'LCD');
});

test('names the sole lit panel when no panel reports primary', async () => {
mockReadHostTextFile.mockResolvedValue(
duoReporting({
1: { primary: false, backlightState: 'off' },
3: { primary: false, backlightState: 'activeOn' },
}),
);
assert.equal((await resolveAppleCaptureTarget(IOS_TEST_SIMULATOR)).display?.name, 'LCD-1');
});

test('refuses instead of picking a panel by list order when no fact identifies one', async () => {
for (const backlightState of ['activeOn', 'off', 'futureState']) {
mockReadHostTextFile.mockResolvedValue(
duoReporting({
1: { primary: false, backlightState },
3: { primary: false, backlightState },
}),
);
await assert.rejects(
resolveAppleCaptureTarget(IOS_TEST_SIMULATOR),
(error: unknown) =>
error instanceof AppError &&
error.code === 'COMMAND_FAILED' &&
error.details?.reason === 'capture-panel-unidentified' &&
typeof error.details?.hint === 'string',
backlightState,
);
}
});

test('reports nothing when CoreDevice cannot be asked', async () => {
mockRunXcrun.mockResolvedValueOnce({
exitCode: 1,
Expand Down
Loading
Loading