Skip to content

Open source CapCut alternative.

TypeScript

Label window targets

David Le88fd5b0f2db2
diff --git a/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift b/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift
index 6a531e79..b16979b9 100644
--- a/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/WindowTargetContracts.swift
@@ -104,3 +104,43 @@ public struct MacWindowSelectionRequest: Codable, Equatable, Sendable {
self.windowID = windowID
}
}
+
+public struct LabeledMacWindowTargetCandidate: Codable, Equatable, Sendable {
+ public var label: String
+ public var candidate: MacWindowTargetCandidate
+
+ public init(
+ label: String,
+ candidate: MacWindowTargetCandidate
+ ) {
+ self.label = label
+ self.candidate = candidate
+ }
+}
+
+public struct MacWindowCandidateListSnapshot: Codable, Equatable, Sendable {
+ public var candidates: [LabeledMacWindowTargetCandidate]
+
+ public init(candidates: [MacWindowTargetCandidate]) {
+ self.candidates = candidates.enumerated().map { index, candidate in
+ LabeledMacWindowTargetCandidate(
+ label: "window \(index + 1)",
+ candidate: candidate
+ )
+ }
+ }
+
+ public init(labeledCandidates: [LabeledMacWindowTargetCandidate]) {
+ self.candidates = labeledCandidates
+ }
+
+ public func selectionRequest(
+ forLabel label: String
+ ) -> MacWindowSelectionRequest? {
+ guard let candidate = candidates.first(where: { $0.label == label })?.candidate else {
+ return nil
+ }
+
+ return MacWindowSelectionRequest(windowID: candidate.windowID)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
index aeacd9f7..3f0ac3de 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacWindowResolver.swift
@@ -97,6 +97,10 @@ public final class MacWindowResolver {
}
}
+ public func enumerateCandidateList() -> MacWindowCandidateListSnapshot {
+ MacWindowCandidateListSnapshot(candidates: enumerateCandidates())
+ }
+
public func selectTarget(
_ request: MacWindowSelectionRequest = MacWindowSelectionRequest()
) throws -> MacWindowTargetCandidate {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
index 618c3aa3..7feebf8c 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacWindowResolverTests.swift
@@ -55,6 +55,86 @@ struct MacWindowResolverTests {
#expect(selected.appName == "Safari")
}
+ @Test
+ func candidateListLabelsAreDeterministicWithinSnapshotAndPreserveOrder() throws {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 20, processID: 200, appName: "Safari"),
+ fixtureWindow(windowID: 30, processID: 300, appName: "Notes")
+ ],
+ frontmostProcessID: 100
+ )
+ )
+
+ let snapshot = resolver.enumerateCandidateList()
+
+ #expect(snapshot.candidates.map(\.label) == ["window 1", "window 2", "window 3"])
+ #expect(snapshot.candidates.map(\.candidate.windowID) == [10, 20, 30])
+ #expect(snapshot.selectionRequest(forLabel: "window 2") == MacWindowSelectionRequest(windowID: 20))
+ #expect(snapshot.selectionRequest(forLabel: "window 2") == MacWindowSelectionRequest(windowID: 20))
+ #expect(snapshot.selectionRequest(forLabel: "missing") == nil)
+
+ guard let selection = snapshot.selectionRequest(forLabel: "window 2") else {
+ Issue.record("Expected window 2 to map to a selection request")
+ return
+ }
+ let selected = try resolver.selectTarget(selection)
+ #expect(selected.windowID == 20)
+ }
+
+ @Test
+ func candidateListLabelsAreScopedToOneEnumerationSnapshot() {
+ let firstResolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 2, processID: 200, appName: "Safari")
+ ],
+ frontmostProcessID: 100
+ )
+ )
+ let secondResolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 2, processID: 200, appName: "Safari"),
+ fixtureWindow(windowID: 1, processID: 100, appName: "Terminal")
+ ],
+ frontmostProcessID: 200
+ )
+ )
+
+ let firstSnapshot = firstResolver.enumerateCandidateList()
+ let secondSnapshot = secondResolver.enumerateCandidateList()
+
+ #expect(firstSnapshot.selectionRequest(forLabel: "window 1") == MacWindowSelectionRequest(windowID: 1))
+ #expect(secondSnapshot.selectionRequest(forLabel: "window 1") == MacWindowSelectionRequest(windowID: 2))
+ }
+
+ @Test
+ func candidateListSnapshotRoundTripsThroughJSON() throws {
+ let resolver = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: [
+ fixtureWindow(windowID: 10, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 20, processID: 200, appName: "Safari")
+ ],
+ frontmostProcessID: 100
+ )
+ )
+ let snapshot = resolver.enumerateCandidateList()
+
+ let data = try JSONEncoder().encode(snapshot)
+ let decoded = try JSONDecoder().decode(
+ MacWindowCandidateListSnapshot.self,
+ from: data
+ )
+
+ #expect(decoded == snapshot)
+ #expect(decoded.selectionRequest(forLabel: "window 2") == MacWindowSelectionRequest(windowID: 20))
+ }
+
@Test
func focusedWindowSelectionFallsBackToFrontmostCandidate() throws {
let resolver = MacWindowResolver(
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift
index bedb5142..668a6744 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/WindowScreenshotCaptureServiceTests.swift
@@ -97,6 +97,50 @@ struct WindowScreenshotCaptureServiceTests {
#expect(capturer.capturedWindowIDs == [2])
}
+ @Test
+ func labeledCandidateListSelectionUsesDurableWindowIDForCapture() async throws {
+ let root = temporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let store = try LocalRunArtifactStore(baseDirectory: root)
+ _ = try await store.prepareRun(
+ session: RunSession(id: "run-labeled", userGoal: "capture", targetID: "target-1"),
+ traceID: "trace-labeled"
+ )
+ let windows = [
+ fixtureWindow(windowID: 11, processID: 100, appName: "Terminal"),
+ fixtureWindow(windowID: 22, processID: 200, appName: "Safari")
+ ]
+ let snapshot = MacWindowResolver(
+ provider: FixtureWindowProvider(
+ windows: windows,
+ frontmostProcessID: 100
+ )
+ )
+ .enumerateCandidateList()
+ let capturer = FakeWindowScreenshotCapturer()
+ let service = makeService(
+ store: store,
+ windows: windows,
+ frontmostProcessID: 100,
+ capturer: capturer
+ )
+
+ guard let selection = snapshot.selectionRequest(forLabel: "window 2") else {
+ Issue.record("Expected window 2 to map to a selection request")
+ return
+ }
+ let result = try await service.captureScreenshot(
+ runID: "run-labeled",
+ selection: selection,
+ artifactID: "screenshot-labeled"
+ )
+
+ #expect(snapshot.candidates.map(\.label) == ["window 1", "window 2"])
+ #expect(result.target.windowID == 22)
+ #expect(capturer.capturedWindowIDs == [22])
+ }
+
@Test
func unsafeTargetRefusesBeforeWritingFileOrArtifact() async throws {
let root = temporaryDirectory()
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 687da103..3d68ea8d 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -25,7 +25,7 @@ accessibility/
The artifact store can append ordered event records, reserve safe screenshot or Accessibility artifact paths, record artifact metadata, and keep `summary.json` current.
-Donkey can also resolve visible macOS target-window metadata for the manual capture path. The resolver enumerates on-screen app windows, describes window id, pid, app name, bundle id, title, bounds, focus/frontmost state, iPhone Mirroring hints, and conservative safety metadata. Callers can select an explicit window id or fall back to the focused/frontmost visible window.
+Donkey can also resolve visible macOS target-window metadata for the manual capture path. The resolver enumerates on-screen app windows, describes window id, pid, app name, bundle id, title, bounds, focus/frontmost state, iPhone Mirroring hints, and conservative safety metadata. Callers can request a candidate-list snapshot with ephemeral labels such as `window 1` and `window 2`; labels are valid only for that enumeration snapshot and should be converted to the candidate's durable `windowID` for follow-up capture commands. Callers can select an explicit window id or fall back to the focused/frontmost visible window.
Donkey can create a single read-only target-window screenshot artifact after a run folder has been prepared. The screenshot service resolves the target, refuses blocked or review-required safety surfaces, captures the selected window with ScreenCaptureKit's desktop-independent window path, writes PNG bytes under `screenshots/`, and records flattened target/capture metadata in `summary.json`. Overlap-sensitive fallback capture backends must refuse occluded targets instead of silently recording pixels from another window.
@@ -52,7 +52,7 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, screenshot artifact metadata, unsafe target refusal, and overlap-sensitive capture refusal.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, unsafe target refusal, and overlap-sensitive capture refusal.
## Source Entry Points
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 4403075d..31fe128a 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -84,11 +84,11 @@ Out of scope:
### Target Window Resolution
-Supported as the second vertical slice. `MacWindowResolver` enumerates visible on-screen macOS app windows, normalizes window metadata, supports explicit selection by window id, falls back to the focused/frontmost candidate, marks iPhone Mirroring as a normal candidate with a hint, and attaches conservative safety metadata.
+Supported as the second vertical slice. `MacWindowResolver` enumerates visible on-screen macOS app windows, normalizes window metadata, returns candidate-list snapshots with ephemeral labels for manual/debug selection, supports explicit selection by window id, falls back to the focused/frontmost candidate, marks iPhone Mirroring as a normal candidate with a hint, and attaches conservative safety metadata.
Current boundaries:
-- Window candidate numbering is not durable. A debug UI or command should map short labels like "window 1" to the candidate's macOS `windowID` at the time the user chooses.
+- Window candidate numbering is not durable. Candidate-list snapshots map short labels like "window 1" to the candidate's macOS `windowID` only for the current enumeration; follow-up commands should carry the durable `windowID`.
- Selection by pid/title tuple is still future-facing. Current deterministic selection is explicit window id or focused/frontmost fallback.
- Safety classification is metadata-only. Later capture orchestration must refuse or safety-stop blocked/review-required targets before writing screenshots.
- Overlap is not solved by metadata alone. Screenshot capture must avoid accidentally recording another window that visually covers the selected target.
@@ -185,16 +185,12 @@ accessibility/
## What Should Be Done Next
-Continue the read-only vertical slice from the completed local artifact writer, window resolver, and screenshot artifact service:
+Continue the read-only vertical slice from the completed local artifact writer, window resolver, candidate-list API, and screenshot artifact service:
-1. Add candidate-list support for manual/debug selection.
- - Provide a small read-only API that returns ordered visible candidates with ephemeral labels such as `window 1`, `window 2`, and their durable `windowID` values.
- - Make clear that labels are valid only for the current enumeration snapshot; follow-up commands should carry the durable `windowID`.
- - Add tests that labels remain deterministic for one snapshot and that explicit `windowID` selection is used for multi-window flows.
-2. Add shallow Accessibility tree capture behind permission checks.
+1. Add shallow Accessibility tree capture behind permission checks.
- Serialize a bounded AX snapshot when trusted and record a clear partial-run event when not trusted.
-3. Wire the manual capture flow through `RunCoordinator` events.
+2. Wire the manual capture flow through `RunCoordinator` events.
- Emit ordered lifecycle/tool events for target resolution, screenshot capture, AX snapshot, artifact persistence, completion, and failure paths.
-4. Add integration tests and manual verification.
+3. Add integration tests and manual verification.
- Cover artifact metadata, bounded AX serialization, policy denial for input, and partial summaries.
- Manually verify against iPhone Mirroring and at least one other visible Mac app window, including an overlapped-window scenario.