From 1b6680802c5945704f2a229cf7e36c18563d385d Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 08:16:49 +0200 Subject: [PATCH 1/7] Add guarded native macOS window placement provider --- server/src/app.ts | 2 + server/src/providers/rectangle-native.swift | 262 ++++++++++++++++++++ server/src/providers/rectangle.ts | 112 +++++++++ server/test/rectangle.test.ts | 91 +++++++ 4 files changed, 467 insertions(+) create mode 100644 server/src/providers/rectangle-native.swift create mode 100644 server/src/providers/rectangle.ts create mode 100644 server/test/rectangle.test.ts diff --git a/server/src/app.ts b/server/src/app.ts index bb4a8e53..87392417 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -54,6 +54,7 @@ import { seedDefaultBackground } from './backgrounds/seed.js' import { backupRoutes } from './backup/routes.js' import { bambuRoutes } from './bambu/routes.js' import { createShortcutsProvider } from './providers/shortcuts.js' +import { createRectangleProvider } from './providers/rectangle.js' import { createServiceStatusProvider } from './providers/service-status.js' import { createSystemProvider } from './providers/system.js' import { createDiskMapProvider } from './providers/disk-map.js' @@ -180,6 +181,7 @@ export async function buildApp(opts: AppOptions): Promise { // Registered here, not in providers/index.ts, because that is where the config store lives. const instances = (instanceId: string) => findInstance(store.get(), instanceId) registry.register(createShortcutsProvider(undefined, instances)) + registry.register(createRectangleProvider()) registry.register(createServiceStatusProvider({}, instances)) const secrets = createSecretStore(store.get().secrets.backend, opts.dataDir) // v2 → v3 moved the Homey connection to the type its widget declares, and the declaration diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift new file mode 100644 index 00000000..137af300 --- /dev/null +++ b/server/src/providers/rectangle-native.swift @@ -0,0 +1,262 @@ +import AppKit +import ApplicationServices +import CoreGraphics +import Foundation + +struct Target: Codable { + let pid: Int32 + let bundleId: String + let title: String + let application: String +} + +struct Response: Encodable { + let ok: Bool + let error: String? + let target: Target? + let changed: Bool? + + init(ok: Bool, error: String? = nil, target: Target? = nil, changed: Bool? = nil) { + self.ok = ok + self.error = error + self.target = target + self.changed = changed + } +} + +struct Display { + let id: CGDirectDisplayID + let frame: CGRect + let usable: CGRect +} + +func respond(_ response: Response) -> Never { + let encoder = JSONEncoder() + if let data = try? encoder.encode(response), let text = String(data: data, encoding: .utf8) { + print(text) + } else { + print("{\"ok\":false,\"error\":\"response-encoding-failed\"}") + } + exit(0) +} + +func axValue(_ element: AXUIElement, _ attribute: CFString) -> CFTypeRef? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success else { return nil } + return value +} + +func stringAttribute(_ element: AXUIElement, _ attribute: CFString) -> String? { + axValue(element, attribute) as? String +} + +func pointAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGPoint? { + guard let value = axValue(element, attribute) else { return nil } + var point = CGPoint.zero + guard AXValueGetValue(value as! AXValue, .cgPoint, &point) else { return nil } + return point +} + +func sizeAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGSize? { + guard let value = axValue(element, attribute) else { return nil } + var size = CGSize.zero + guard AXValueGetValue(value as! AXValue, .cgSize, &size) else { return nil } + return size +} + +func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CGSize)? { + guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication else { return nil } + let pid = app.processIdentifier + guard let bundleId = app.bundleIdentifier, let appName = app.localizedName else { return nil } + guard !bundleId.localizedCaseInsensitiveContains("fremkit"), + !bundleId.localizedCaseInsensitiveContains("rectangle"), + !appName.localizedCaseInsensitiveContains("fremkit"), + !appName.localizedCaseInsensitiveContains("rectangle") else { return nil } + if let expected, (expected.pid != pid || expected.bundleId != bundleId) { return nil } + + let application = AXUIElementCreateApplication(pid) + guard let rawWindow = axValue(application, kAXFocusedWindowAttribute as CFString) else { return nil } + let window = rawWindow as! AXUIElement + guard let title = stringAttribute(window, kAXTitleAttribute as CFString), + let position = pointAttribute(window, kAXPositionAttribute as CFString), + let size = sizeAttribute(window, kAXSizeAttribute as CFString) else { return nil } + if let expected, expected.title != title { return nil } + let target = Target(pid: pid, bundleId: bundleId, title: title, application: appName) + return (target, window, position, size) +} + +func displays() -> [Display] { + NSScreen.screens.compactMap { screen in + guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { return nil } + let id = CGDirectDisplayID(number.uint32Value) + let frame = CGDisplayBounds(id) + let appKitFrame = screen.frame + let visible = screen.visibleFrame + let usable = CGRect( + x: frame.minX + visible.minX - appKitFrame.minX, + y: frame.minY + appKitFrame.maxY - visible.maxY, + width: visible.width, + height: visible.height + ) + return Display(id: id, frame: frame, usable: usable) + }.sorted { + if $0.frame.minX == $1.frame.minX { return $0.frame.minY < $1.frame.minY } + return $0.frame.minX < $1.frame.minX + } +} + +func displayFor(_ position: CGPoint, _ size: CGSize, in displays: [Display]) -> Int? { + let window = CGRect(origin: position, size: size) + let center = CGPoint(x: window.midX, y: window.midY) + if let exact = displays.firstIndex(where: { $0.frame.contains(center) }) { return exact } + let overlaps = displays.enumerated().map { index, display in (index, window.intersection(display.frame).width * window.intersection(display.frame).height) } + return overlaps.max(by: { $0.1 < $1.1 })?.0 +} + +func setAX(_ window: AXUIElement, attribute: CFString, point: CGPoint) -> Bool { + var value = point + guard let boxed = AXValueCreate(.cgPoint, &value) else { return false } + return AXUIElementSetAttributeValue(window, attribute, boxed) == .success +} + +func setAX(_ window: AXUIElement, attribute: CFString, size: CGSize) -> Bool { + var value = size + guard let boxed = AXValueCreate(.cgSize, &value) else { return false } + return AXUIElementSetAttributeValue(window, attribute, boxed) == .success +} + +func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } + +func waitForGeometry(_ expected: Target, position: CGPoint, size: CGSize) -> Bool { + for _ in 0..<30 { + if let (_, _, actualPosition, actualSize) = focusedTarget(expected: expected), + closeEnough(actualPosition.x, position.x), closeEnough(actualPosition.y, position.y), + closeEnough(actualSize.width, size.width), closeEnough(actualSize.height, size.height) { + return true + } + Thread.sleep(forTimeInterval: 0.05) + } + return false +} + +func children(_ element: AXUIElement) -> [AXUIElement] { + (axValue(element, kAXChildrenAttribute as CFString) as? [AXUIElement]) ?? [] +} + +func role(_ element: AXUIElement) -> String { + stringAttribute(element, kAXRoleAttribute as CFString) ?? "" +} + +func menuAction(_ path: [String], expected: Target) -> Bool { + guard !path.isEmpty, let (target, _, _, _) = focusedTarget(expected: expected), + target.pid == expected.pid, + let menuBarValue = axValue(AXUIElementCreateApplication(expected.pid), kAXMenuBarAttribute as CFString), + CFGetTypeID(menuBarValue) == AXUIElementGetTypeID() else { return false } + let menuBar = menuBarValue as! AXUIElement + guard let windowMenu = children(menuBar).first(where: { + role($0) == kAXMenuBarItemRole as String && stringAttribute($0, kAXTitleAttribute as CFString) == path[0] + }), AXUIElementPerformAction(windowMenu, kAXPressAction as CFString) == .success else { return false } + Thread.sleep(forTimeInterval: 0.05) + guard let topMenu = children(windowMenu).first(where: { role($0) == kAXMenuRole as String }) else { return false } + var currentMenu = topMenu + for (index, title) in path.dropFirst().enumerated() { + guard let item = children(currentMenu).first(where: { + role($0) == kAXMenuItemRole as String && stringAttribute($0, kAXTitleAttribute as CFString) == title + }) else { return false } + let isFinalItem = index == path.count - 2 + guard AXUIElementPerformAction(item, kAXPressAction as CFString) == .success else { return false } + if isFinalItem { return true } + Thread.sleep(forTimeInterval: 0.05) + guard let submenu = children(item).first(where: { role($0) == kAXMenuRole as String }) else { return false } + currentMenu = submenu + } + return false +} + +func runAction(_ action: String, expected: Target) { + guard let (_, window, oldPosition, oldSize) = focusedTarget(expected: expected) else { + respond(Response(ok: false, error: "target-changed-or-unavailable")) + } + let screens = displays() + guard !screens.isEmpty, let currentIndex = displayFor(oldPosition, oldSize, in: screens) else { + respond(Response(ok: false, error: "display-unavailable")) + } + let targetPosition: CGPoint + let targetSize: CGSize + switch action { + case "left-half": + let area = screens[currentIndex].usable + targetPosition = CGPoint(x: area.minX, y: area.minY) + targetSize = CGSize(width: floor(area.width / 2), height: area.height) + case "right-half": + let area = screens[currentIndex].usable + let width = floor(area.width / 2) + targetPosition = CGPoint(x: area.minX + area.width - width, y: area.minY) + targetSize = CGSize(width: width, height: area.height) + case "fill": + let area = screens[currentIndex].usable + targetPosition = CGPoint(x: area.minX, y: area.minY) + targetSize = CGSize(width: area.width, height: area.height) + case "next-display": + guard screens.count > 1 else { respond(Response(ok: false, error: "no-next-display")) } + let next = screens[(currentIndex + 1) % screens.count].usable + targetSize = CGSize(width: min(oldSize.width, next.width), height: min(oldSize.height, next.height)) + targetPosition = CGPoint(x: next.midX - targetSize.width / 2, y: next.midY - targetSize.height / 2) + default: + respond(Response(ok: false, error: "invalid-action")) + } + + var settablePosition = DarwinBoolean(false) + var settableSize = DarwinBoolean(false) + guard AXUIElementIsAttributeSettable(window, kAXPositionAttribute as CFString, &settablePosition) == .success, + AXUIElementIsAttributeSettable(window, kAXSizeAttribute as CFString, &settableSize) == .success, + settablePosition.boolValue, settableSize.boolValue else { + respond(Response(ok: false, error: "window-not-resizable")) + } + + if action == "next-display" { + guard setAX(window, attribute: kAXPositionAttribute as CFString, point: targetPosition) else { + respond(Response(ok: false, error: "window-action-rejected")) + } + } else { + let menuPath: [String] + switch action { + case "left-half": menuPath = ["Window", "Move & Resize", "Left"] + case "right-half": menuPath = ["Window", "Move & Resize", "Right"] + case "fill": menuPath = ["Window", "Fill"] + default: respond(Response(ok: false, error: "invalid-action")) + } + guard menuAction(menuPath, expected: expected) else { + respond(Response(ok: false, error: "native-menu-action-unavailable")) + } + } + // Native tiling animates asynchronously; poll the same guarded window for at most 1.5 seconds. + guard waitForGeometry(expected, position: targetPosition, size: targetSize) else { + respond(Response(ok: false, error: "geometry-unverified")) + } + respond(Response(ok: true, changed: true)) +} + +let arguments = Array(CommandLine.arguments.dropFirst()) +guard let mode = arguments.first else { respond(Response(ok: false, error: "missing-mode")) } +guard AXIsProcessTrusted() else { respond(Response(ok: false, error: "accessibility-permission-required")) } + +if mode == "inspect" { + guard let (target, _, _, _) = focusedTarget() else { respond(Response(ok: false, error: "no-safe-window")) } + respond(Response(ok: true, target: target)) +} + +guard mode == "run", arguments.count >= 6, + let pid = Int32(arguments[1]) else { respond(Response(ok: false, error: "invalid-request")) } +let expected = Target(pid: pid, bundleId: arguments[2], title: arguments[3], application: "") +let invocation = Array(arguments.dropFirst(4)) +if invocation.count == 4, invocation[0] == "menu", invocation[1] == "Window" { + let action = invocation[2] == "Fill" ? "fill" : invocation[3] == "Left" ? "left-half" : invocation[3] == "Right" ? "right-half" : "invalid" + runAction(action, expected: expected) +} else if invocation == ["menu", "Window", "Fill"] { + runAction("fill", expected: expected) +} else if invocation == ["position", "next-display"] { + runAction("next-display", expected: expected) +} else { + respond(Response(ok: false, error: "invalid-request")) +} diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts new file mode 100644 index 00000000..1ea04fd8 --- /dev/null +++ b/server/src/providers/rectangle.ts @@ -0,0 +1,112 @@ +import { randomUUID } from 'node:crypto' +import { execFile as nodeExecFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { z } from 'zod' +import type { CommandContext, Provider } from './types.js' + +const execFile = promisify(nodeExecFile) +const ActionSchema = z.enum(['left-half', 'right-half', 'fill', 'next-display']) +export type RectangleAction = z.infer +const InspectSchema = z.object({}).strict() +const RunSchema = z.object({ action: ActionSchema, targetToken: z.string().uuid() }).strict() +const NativeTargetSchema = z.object({ + pid: z.number().int().positive(), + bundleId: z.string().min(1).max(255), + title: z.string().max(1024), + application: z.string().min(1).max(255), +}) + +const SWIFT = '/usr/bin/swift' +const HELPER = fileURLToPath(new URL('./rectangle-native.swift', import.meta.url)) +const TARGET_LIFETIME_MS = 5 * 60_000 +const MAX_TARGETS = 32 +const COMMAND_TIMEOUT_MS = 15_000 + +export type Runner = (file: string, args: string[]) => Promise +type Target = z.infer +type NativeResponse = { ok: boolean; error?: string; target?: Target; changed?: boolean } + +export function nativeInvocationFor(action: RectangleAction): string[] { + switch (action) { + case 'left-half': return ['menu', 'Window', 'Move & Resize', 'Left'] + case 'right-half': return ['menu', 'Window', 'Move & Resize', 'Right'] + case 'fill': return ['menu', 'Window', 'Fill'] + case 'next-display': return ['position', 'next-display'] + } +} + +const runProgram: Runner = async (file, args) => { + const { stdout } = await execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: 32 * 1024 }) + return stdout +} + +/** Kept exported so tests can prove the only executable is Swift and input is argv, not shell. */ +export function nativeArgsFor(mode: 'inspect'): string[] +export function nativeArgsFor(action: RectangleAction, target: Target): string[] +export function nativeArgsFor(modeOrAction: 'inspect' | RectangleAction, target?: Target): string[] { + if (modeOrAction === 'inspect') return [HELPER, 'inspect'] + if (!target) throw new Error('native target required') + return [HELPER, 'run', String(target.pid), target.bundleId, target.title, ...nativeInvocationFor(modeOrAction)] +} + +function parseResponse(stdout: string): NativeResponse | null { + try { + return z.object({ + ok: z.boolean(), + error: z.string().optional(), + target: NativeTargetSchema.optional(), + changed: z.boolean().optional(), + }).strict().parse(JSON.parse(stdout)) + } catch { + return null + } +} + +/** + * Uses macOS Accessibility APIs and the system display geometry. The widget can act only on a + * window it explicitly inspected, and the helper verifies that exact process and title again. + */ +export function createRectangleProvider(run: Runner = runProgram, now: () => number = Date.now): Provider { + const targets = new Map() + + return { + channel: 'rectangle', + commands: { + async ['inspect-target'](payload: unknown, context?: CommandContext) { + if (!context?.loopback) return { ok: false, error: 'local-only' } + if (!InspectSchema.safeParse(payload).success) return { ok: false, error: 'invalid-request' } + try { + const response = parseResponse(await run(SWIFT, nativeArgsFor('inspect'))) + if (!response?.ok || !response.target) return { ok: false, error: 'no-target' } + const token = randomUUID() + if (targets.size >= MAX_TARGETS) { + for (const [key, value] of targets) if (value.expiresAt <= now()) targets.delete(key) + if (targets.size >= MAX_TARGETS) targets.delete(targets.keys().next().value!) + } + targets.set(token, { target: response.target, expiresAt: now() + TARGET_LIFETIME_MS }) + return { ok: true, target: { token, application: response.target.application } } + } catch { + return { ok: false, error: 'native-window-access-unavailable' } + } + }, + async run(payload: unknown, context?: CommandContext) { + if (!context?.loopback) return { ok: false, error: 'local-only' } + const parsed = RunSchema.safeParse(payload) + if (!parsed.success) return { ok: false, error: 'invalid-request' } + const stored = targets.get(parsed.data.targetToken) + targets.delete(parsed.data.targetToken) + if (!stored || stored.expiresAt <= now()) return { ok: false, error: 'target-expired' } + try { + const response = parseResponse(await run(SWIFT, nativeArgsFor(parsed.data.action, stored.target))) + if (!response?.ok || response.changed !== true) { + return { ok: false, error: response?.error ?? 'geometry-unverified' } + } + return { ok: true, changed: true } + } catch { + return { ok: false, error: 'native-window-action-unavailable' } + } + }, + }, + } +} diff --git a/server/test/rectangle.test.ts b/server/test/rectangle.test.ts new file mode 100644 index 00000000..84a076f7 --- /dev/null +++ b/server/test/rectangle.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it, vi } from 'vitest' +import { createRectangleProvider, nativeArgsFor, nativeInvocationFor } from '../src/providers/rectangle.js' + +const nativeTarget = { + pid: 4242, + bundleId: 'com.apple.TextEdit', + title: 'Fremkit Rectangle Probe.txt', + application: 'TextEdit', +} + +describe('built-in macOS window provider', () => { + it('inspects the active app and returns an opaque target token without exposing its title', async () => { + const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' + ? JSON.stringify({ ok: true, target: nativeTarget }) + : JSON.stringify({ ok: true })) + const provider = createRectangleProvider(run) + + const result = await provider.commands?.['inspect-target']?.({}, { loopback: true }) as { + ok: boolean + target?: { token: string; application: string } + } + + expect(result.ok).toBe(true) + expect(result.target?.application).toBe('TextEdit') + expect(result.target?.token).toMatch(/^[0-9a-f-]{36}$/) + expect(JSON.stringify(result)).not.toContain(nativeTarget.title) + expect(run).toHaveBeenCalledWith('/usr/bin/swift', nativeArgsFor('inspect')) + }) + + it.each(['left-half', 'right-half', 'fill', 'next-display'] as const)( + 'runs the built-in native action %s only for the inspected target', async (action) => { + const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' + ? JSON.stringify({ ok: true, target: nativeTarget }) + : JSON.stringify({ ok: true, changed: true })) + const provider = createRectangleProvider(run) + const inspected = await provider.commands?.['inspect-target']?.({}, { loopback: true }) as { + target: { token: string } + } + + const result = await provider.commands?.run?.({ action, targetToken: inspected.target.token }, { loopback: true }) + + expect(result).toEqual({ ok: true, changed: true }) + expect(run).toHaveBeenLastCalledWith('/usr/bin/swift', nativeArgsFor(action, nativeTarget)) + expect(run.mock.calls.flatMap(([, args]) => args).join(' ')).not.toContain('rectangle://') + }, + ) + + it.each([ + ['left-half', ['menu', 'Window', 'Move & Resize', 'Left']], + ['right-half', ['menu', 'Window', 'Move & Resize', 'Right']], + ['fill', ['menu', 'Window', 'Fill']], + ['next-display', ['position', 'next-display']], + ] as const)('maps %s to a built-in macOS action', (action, invocation) => { + expect(nativeInvocationFor(action)).toEqual(invocation) + expect(nativeArgsFor(action, nativeTarget).slice(5)).toEqual(invocation) + }) + + it('rejects remote, malformed, stale, and arbitrary-target requests without invoking a native action', async () => { + const run = vi.fn(async (_file: string, args: string[]) => JSON.stringify({ ok: true, target: nativeTarget })) + const provider = createRectangleProvider(run) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: false })) + .resolves.toEqual({ ok: false, error: 'local-only' }) + await expect(provider.commands?.run?.({ action: 'run-shell', targetToken: 'nope' }, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'invalid-request' }) + await expect(provider.commands?.run?.({ action: 'left-half', targetToken: '00000000-0000-4000-8000-000000000001' }, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'target-expired' }) + expect(run).not.toHaveBeenCalled() + }) + + it('fails closed when the inspected foreground window is not a safe app window', async () => { + const run = vi.fn(async () => JSON.stringify({ ok: false, error: 'unsafe-target' })) + const provider = createRectangleProvider(run) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'no-target' }) + }) + + it('fails closed when native geometry verification does not succeed', async () => { + const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' + ? JSON.stringify({ ok: true, target: nativeTarget }) + : JSON.stringify({ ok: false, error: 'geometry-unverified' })) + const provider = createRectangleProvider(run) + const inspected = await provider.commands?.['inspect-target']?.({}, { loopback: true }) as { + target: { token: string } + } + + await expect(provider.commands?.run?.({ action: 'left-half', targetToken: inspected.target.token }, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'geometry-unverified' }) + }) +}) From ac5dbfd63fa1384a927a5114e461c04f475637a0 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 09:02:21 +0200 Subject: [PATCH 2/7] Bind native window actions to Core Graphics IDs --- server/src/providers/rectangle-native.swift | 86 +++++++++++++++++++-- server/src/providers/rectangle.ts | 5 +- server/test/rectangle.test.ts | 46 ++++++++++- 3 files changed, 128 insertions(+), 9 deletions(-) diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift index 137af300..6db0b4e9 100644 --- a/server/src/providers/rectangle-native.swift +++ b/server/src/providers/rectangle-native.swift @@ -8,6 +8,30 @@ struct Target: Codable { let bundleId: String let title: String let application: String + let windowID: UInt32 +} + +struct WindowCandidate: Codable { + let windowID: UInt32 + let pid: Int32 + let title: String + let x: Double + let y: Double + let width: Double + let height: Double + + var bounds: CGRect { CGRect(x: x, y: y, width: width, height: height) } +} + +struct IdentityProbe: Decodable { + let pid: Int32 + let title: String + let x: Double + let y: Double + let width: Double + let height: Double + let expectedWindowID: UInt32? + let windows: [WindowCandidate] } struct Response: Encodable { @@ -64,6 +88,36 @@ func sizeAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGSize? { return size } +func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } + +// CGWindowID is unique within the current user session. AX does not expose that ID directly, +// so map its focused window to exactly one Core Graphics row by owner, title, and bounds. +// If the mapping is absent or ambiguous, do not guess which same-titled window was focused. +func matchingWindowID(pid: Int32, title: String, bounds: CGRect, expectedWindowID: UInt32? = nil, candidates: [WindowCandidate]) -> UInt32? { + let matches = candidates.filter { candidate in + candidate.pid == pid && candidate.title == title && + closeEnough(CGFloat(candidate.x), bounds.minX) && closeEnough(CGFloat(candidate.y), bounds.minY) && + closeEnough(CGFloat(candidate.width), bounds.width) && closeEnough(CGFloat(candidate.height), bounds.height) + } + guard matches.count == 1, let match = matches.first, match.windowID != kCGNullWindowID else { return nil } + if let expectedWindowID, expectedWindowID != match.windowID { return nil } + return match.windowID +} + +func onScreenWindowCandidates() -> [WindowCandidate]? { + guard let rawWindows = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else { return nil } + return rawWindows.compactMap { info in + guard let pid = info[kCGWindowOwnerPID as String] as? NSNumber, + let windowID = info[kCGWindowNumber as String] as? NSNumber, + let title = info[kCGWindowName as String] as? String, + let rawBounds = info[kCGWindowBounds as String] as? [String: Any], + let bounds = CGRect(dictionaryRepresentation: rawBounds as CFDictionary), + windowID.uint32Value != kCGNullWindowID else { return nil } + return WindowCandidate(windowID: windowID.uint32Value, pid: pid.int32Value, title: title, + x: bounds.minX, y: bounds.minY, width: bounds.width, height: bounds.height) + } +} + func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CGSize)? { guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication else { return nil } let pid = app.processIdentifier @@ -81,7 +135,10 @@ func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CG let position = pointAttribute(window, kAXPositionAttribute as CFString), let size = sizeAttribute(window, kAXSizeAttribute as CFString) else { return nil } if let expected, expected.title != title { return nil } - let target = Target(pid: pid, bundleId: bundleId, title: title, application: appName) + guard let candidates = onScreenWindowCandidates(), + let windowID = matchingWindowID(pid: pid, title: title, bounds: CGRect(origin: position, size: size), + expectedWindowID: expected?.windowID, candidates: candidates) else { return nil } + let target = Target(pid: pid, bundleId: bundleId, title: title, application: appName, windowID: windowID) return (target, window, position, size) } @@ -125,8 +182,6 @@ func setAX(_ window: AXUIElement, attribute: CFString, size: CGSize) -> Bool { return AXUIElementSetAttributeValue(window, attribute, boxed) == .success } -func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } - func waitForGeometry(_ expected: Target, position: CGPoint, size: CGSize) -> Bool { for _ in 0..<30 { if let (_, _, actualPosition, actualSize) = focusedTarget(expected: expected), @@ -164,6 +219,7 @@ func menuAction(_ path: [String], expected: Target) -> Bool { role($0) == kAXMenuItemRole as String && stringAttribute($0, kAXTitleAttribute as CFString) == title }) else { return false } let isFinalItem = index == path.count - 2 + if isFinalItem, focusedTarget(expected: expected) == nil { return false } guard AXUIElementPerformAction(item, kAXPressAction as CFString) == .success else { return false } if isFinalItem { return true } Thread.sleep(forTimeInterval: 0.05) @@ -215,6 +271,9 @@ func runAction(_ action: String, expected: Target) { } if action == "next-display" { + guard focusedTarget(expected: expected) != nil else { + respond(Response(ok: false, error: "target-changed-or-unavailable")) + } guard setAX(window, attribute: kAXPositionAttribute as CFString, point: targetPosition) else { respond(Response(ok: false, error: "window-action-rejected")) } @@ -238,6 +297,21 @@ func runAction(_ action: String, expected: Target) { } let arguments = Array(CommandLine.arguments.dropFirst()) +if ProcessInfo.processInfo.environment["FREMKIT_RECTANGLE_TESTING"] == "1", arguments.first == "test-window-identity" { + guard arguments.count == 2, + let data = arguments[1].data(using: .utf8), + let probes = try? JSONDecoder().decode([IdentityProbe].self, from: data) else { + respond(Response(ok: false, error: "invalid-test-probe")) + } + let windowIDs = probes.map { probe in + matchingWindowID(pid: probe.pid, title: probe.title, + bounds: CGRect(x: probe.x, y: probe.y, width: probe.width, height: probe.height), + expectedWindowID: probe.expectedWindowID, candidates: probe.windows) + } + if let data = try? JSONEncoder().encode(windowIDs), let output = String(data: data, encoding: .utf8) { print(output) } + else { respond(Response(ok: false, error: "identity-test-encoding-failed")) } + exit(0) +} guard let mode = arguments.first else { respond(Response(ok: false, error: "missing-mode")) } guard AXIsProcessTrusted() else { respond(Response(ok: false, error: "accessibility-permission-required")) } @@ -247,9 +321,9 @@ if mode == "inspect" { } guard mode == "run", arguments.count >= 6, - let pid = Int32(arguments[1]) else { respond(Response(ok: false, error: "invalid-request")) } -let expected = Target(pid: pid, bundleId: arguments[2], title: arguments[3], application: "") -let invocation = Array(arguments.dropFirst(4)) + let pid = Int32(arguments[1]), let windowID = UInt32(arguments[4]) else { respond(Response(ok: false, error: "invalid-request")) } +let expected = Target(pid: pid, bundleId: arguments[2], title: arguments[3], application: "", windowID: windowID) +let invocation = Array(arguments.dropFirst(5)) if invocation.count == 4, invocation[0] == "menu", invocation[1] == "Window" { let action = invocation[2] == "Fill" ? "fill" : invocation[3] == "Left" ? "left-half" : invocation[3] == "Right" ? "right-half" : "invalid" runAction(action, expected: expected) diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts index 1ea04fd8..4ccec66f 100644 --- a/server/src/providers/rectangle.ts +++ b/server/src/providers/rectangle.ts @@ -15,6 +15,7 @@ const NativeTargetSchema = z.object({ bundleId: z.string().min(1).max(255), title: z.string().max(1024), application: z.string().min(1).max(255), + windowID: z.number().int().positive().max(0xffff_ffff), }) const SWIFT = '/usr/bin/swift' @@ -47,7 +48,7 @@ export function nativeArgsFor(action: RectangleAction, target: Target): string[] export function nativeArgsFor(modeOrAction: 'inspect' | RectangleAction, target?: Target): string[] { if (modeOrAction === 'inspect') return [HELPER, 'inspect'] if (!target) throw new Error('native target required') - return [HELPER, 'run', String(target.pid), target.bundleId, target.title, ...nativeInvocationFor(modeOrAction)] + return [HELPER, 'run', String(target.pid), target.bundleId, target.title, String(target.windowID), ...nativeInvocationFor(modeOrAction)] } function parseResponse(stdout: string): NativeResponse | null { @@ -65,7 +66,7 @@ function parseResponse(stdout: string): NativeResponse | null { /** * Uses macOS Accessibility APIs and the system display geometry. The widget can act only on a - * window it explicitly inspected, and the helper verifies that exact process and title again. + * window it explicitly inspected, and the helper verifies its session-unique window ID again. */ export function createRectangleProvider(run: Runner = runProgram, now: () => number = Date.now): Provider { const targets = new Map() diff --git a/server/test/rectangle.test.ts b/server/test/rectangle.test.ts index 84a076f7..8f48f7e3 100644 --- a/server/test/rectangle.test.ts +++ b/server/test/rectangle.test.ts @@ -1,13 +1,23 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { describe, expect, it, vi } from 'vitest' import { createRectangleProvider, nativeArgsFor, nativeInvocationFor } from '../src/providers/rectangle.js' +const nativeHelper = fileURLToPath(new URL('../src/providers/rectangle-native.swift', import.meta.url)) + const nativeTarget = { pid: 4242, bundleId: 'com.apple.TextEdit', title: 'Fremkit Rectangle Probe.txt', application: 'TextEdit', + windowID: 41, } +const resolveWindowIDs = (inputs: unknown[]) => JSON.parse(execFileSync('/usr/bin/swift', [nativeHelper, 'test-window-identity', JSON.stringify(inputs)], { + encoding: 'utf8', + env: { ...process.env, FREMKIT_RECTANGLE_TESTING: '1' }, +})) as Array + describe('built-in macOS window provider', () => { it('inspects the active app and returns an opaque target token without exposing its title', async () => { const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' @@ -45,6 +55,24 @@ describe('built-in macOS window provider', () => { }, ) + it('rejects a same-process same-title focus switch to a different window ID', () => { + const firstWindow = { windowID: 41, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 } + const secondWindow = { ...firstWindow, windowID: 42, x: 720 } + const input = { pid: nativeTarget.pid, title: nativeTarget.title, x: firstWindow.x, y: firstWindow.y, width: firstWindow.width, height: firstWindow.height, windows: [firstWindow, secondWindow] } + + expect(resolveWindowIDs([input, { ...input, expectedWindowID: 42 }])).toEqual([41, null]) + }) + + it.each([ + ['missing window metadata', []], + ['ambiguous same-title and same-bounds windows', [ + { windowID: 41, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 }, + { windowID: 42, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 }, + ]], + ])('fails closed on %s', (_case, windows) => { + expect(resolveWindowIDs([{ pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400, expectedWindowID: 41, windows }])).toEqual([null]) + }) + it.each([ ['left-half', ['menu', 'Window', 'Move & Resize', 'Left']], ['right-half', ['menu', 'Window', 'Move & Resize', 'Right']], @@ -52,7 +80,13 @@ describe('built-in macOS window provider', () => { ['next-display', ['position', 'next-display']], ] as const)('maps %s to a built-in macOS action', (action, invocation) => { expect(nativeInvocationFor(action)).toEqual(invocation) - expect(nativeArgsFor(action, nativeTarget).slice(5)).toEqual(invocation) + expect(nativeArgsFor(action, nativeTarget).slice(6)).toEqual(invocation) + }) + + it('carries the inspected window ID in the private native invocation', () => { + expect(nativeArgsFor('fill', nativeTarget)).toEqual([ + expect.any(String), 'run', '4242', 'com.apple.TextEdit', 'Fremkit Rectangle Probe.txt', '41', 'menu', 'Window', 'Fill', + ]) }) it('rejects remote, malformed, stale, and arbitrary-target requests without invoking a native action', async () => { @@ -76,6 +110,16 @@ describe('built-in macOS window provider', () => { .resolves.toEqual({ ok: false, error: 'no-target' }) }) + it.each([ + ['missing', (({ windowID: _windowID, ...target }) => target)(nativeTarget)], + ['invalid', { ...nativeTarget, windowID: 0 }], + ])('rejects an inspector response with a %s window ID', async (_case, target) => { + const provider = createRectangleProvider(async () => JSON.stringify({ ok: true, target })) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'no-target' }) + }) + it('fails closed when native geometry verification does not succeed', async () => { const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' ? JSON.stringify({ ok: true, target: nativeTarget }) From 9e24a50c2a5c43e1c8fa787c89e8cfd1b1d7bb54 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 01:42:53 +0200 Subject: [PATCH 3/7] Accept the bridge-stamped instanceId in inspect and run The widget bridge adds instanceId to every command payload, so the strict inspect/run schemas rejected every request with invalid-request and the widget showed "no safe target" for any tap. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- server/src/providers/rectangle.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts index 4ccec66f..06ccfb0d 100644 --- a/server/src/providers/rectangle.ts +++ b/server/src/providers/rectangle.ts @@ -8,8 +8,8 @@ import type { CommandContext, Provider } from './types.js' const execFile = promisify(nodeExecFile) const ActionSchema = z.enum(['left-half', 'right-half', 'fill', 'next-display']) export type RectangleAction = z.infer -const InspectSchema = z.object({}).strict() -const RunSchema = z.object({ action: ActionSchema, targetToken: z.string().uuid() }).strict() +const InspectSchema = z.object({ instanceId: z.string().min(1).max(200).optional() }).strict() +const RunSchema = z.object({ action: ActionSchema, targetToken: z.string().uuid(), instanceId: z.string().min(1).max(200).optional() }).strict() const NativeTargetSchema = z.object({ pid: z.number().int().positive(), bundleId: z.string().min(1).max(255), From 20eed304581127667cc3a6167672e84bd990ec94 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Wed, 21 Oct 2026 03:42:19 +0200 Subject: [PATCH 4/7] Fall back to AX when a frontmost window or a tile cannot be confirmed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two gaps showed up against live apps. Some frontmost apps never report a focused window — Electron shells among them — while AXMainWindow or the window list still answer, so inspect now falls back through those attributes; identity is still proven by the Core Graphics window match. And an app can answer the Window → Move & Resize press without honouring it (Warp's menu item exists yet does nothing), which surfaced as geometry-unverified. When the menu did not move the window to the target frame, its position and size are now set directly on the AX window and re-verified. Co-Authored-By: Claude --- server/src/providers/rectangle-native.swift | 24 ++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift index 6db0b4e9..36cc0acf 100644 --- a/server/src/providers/rectangle-native.swift +++ b/server/src/providers/rectangle-native.swift @@ -129,7 +129,14 @@ func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CG if let expected, (expected.pid != pid || expected.bundleId != bundleId) { return nil } let application = AXUIElementCreateApplication(pid) - guard let rawWindow = axValue(application, kAXFocusedWindowAttribute as CFString) else { return nil } + // Some frontmost apps never report a focused window — Electron shells among them — while + // AXMainWindow or the window list still answer. Identity is still proven by the CG match below. + var rawWindow = axValue(application, kAXFocusedWindowAttribute as CFString) + ?? axValue(application, kAXMainWindowAttribute as CFString) + if rawWindow == nil { + rawWindow = (axValue(application, kAXWindowsAttribute as CFString) as? [AXUIElement])?.first + } + guard let rawWindow, CFGetTypeID(rawWindow) == AXUIElementGetTypeID() else { return nil } let window = rawWindow as! AXUIElement guard let title = stringAttribute(window, kAXTitleAttribute as CFString), let position = pointAttribute(window, kAXPositionAttribute as CFString), @@ -285,8 +292,19 @@ func runAction(_ action: String, expected: Target) { case "fill": menuPath = ["Window", "Fill"] default: respond(Response(ok: false, error: "invalid-action")) } - guard menuAction(menuPath, expected: expected) else { - respond(Response(ok: false, error: "native-menu-action-unavailable")) + // The system tiling menu animates and respects per-app quirks, but an app can answer the + // press without honouring it (Warp's menu item exists yet does nothing). Verify the move; + // when the window did not reach the target frame, set its position and size directly. + if menuAction(menuPath, expected: expected), + waitForGeometry(expected, position: targetPosition, size: targetSize) { + respond(Response(ok: true, changed: true)) + } + guard let (_, window, _, _) = focusedTarget(expected: expected) else { + respond(Response(ok: false, error: "target-changed-or-unavailable")) + } + guard setAX(window, attribute: kAXSizeAttribute as CFString, size: targetSize), + setAX(window, attribute: kAXPositionAttribute as CFString, point: targetPosition) else { + respond(Response(ok: false, error: "window-action-rejected")) } } // Native tiling animates asynchronously; poll the same guarded window for at most 1.5 seconds. From 8de08803e5f00560ff94b368e24a826911757db1 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Wed, 21 Oct 2026 04:44:41 +0200 Subject: [PATCH 5/7] Match windows by owner and bounds when the window list hides names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CGWindowList omits window names unless the caller holds Screen Recording, so every candidate was dropped and inspect answered no-safe-window under the helper identity while succeeding under a terminal that has the grant. An empty candidate title now means "unknown" rather than "different": the owner PID and bounds still prove identity, and the widget finally shows the inspector's real error — such as accessibility-permission-required — instead of the generic no-target. Co-Authored-By: Claude --- server/src/providers/rectangle-native.swift | 6 ++++-- server/src/providers/rectangle.ts | 2 +- server/test/rectangle.test.ts | 17 ++++++++++++++++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift index 36cc0acf..a1d86ecf 100644 --- a/server/src/providers/rectangle-native.swift +++ b/server/src/providers/rectangle-native.swift @@ -94,8 +94,10 @@ func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } // so map its focused window to exactly one Core Graphics row by owner, title, and bounds. // If the mapping is absent or ambiguous, do not guess which same-titled window was focused. func matchingWindowID(pid: Int32, title: String, bounds: CGRect, expectedWindowID: UInt32? = nil, candidates: [WindowCandidate]) -> UInt32? { + // Without Screen Recording, CGWindowList hides window names: an empty candidate title then + // means "unknown", not "different" — owner PID and bounds still prove identity. let matches = candidates.filter { candidate in - candidate.pid == pid && candidate.title == title && + candidate.pid == pid && (candidate.title.isEmpty || candidate.title == title) && closeEnough(CGFloat(candidate.x), bounds.minX) && closeEnough(CGFloat(candidate.y), bounds.minY) && closeEnough(CGFloat(candidate.width), bounds.width) && closeEnough(CGFloat(candidate.height), bounds.height) } @@ -109,10 +111,10 @@ func onScreenWindowCandidates() -> [WindowCandidate]? { return rawWindows.compactMap { info in guard let pid = info[kCGWindowOwnerPID as String] as? NSNumber, let windowID = info[kCGWindowNumber as String] as? NSNumber, - let title = info[kCGWindowName as String] as? String, let rawBounds = info[kCGWindowBounds as String] as? [String: Any], let bounds = CGRect(dictionaryRepresentation: rawBounds as CFDictionary), windowID.uint32Value != kCGNullWindowID else { return nil } + let title = info[kCGWindowName as String] as? String ?? "" return WindowCandidate(windowID: windowID.uint32Value, pid: pid.int32Value, title: title, x: bounds.minX, y: bounds.minY, width: bounds.width, height: bounds.height) } diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts index 06ccfb0d..71f1c238 100644 --- a/server/src/providers/rectangle.ts +++ b/server/src/providers/rectangle.ts @@ -79,7 +79,7 @@ export function createRectangleProvider(run: Runner = runProgram, now: () => num if (!InspectSchema.safeParse(payload).success) return { ok: false, error: 'invalid-request' } try { const response = parseResponse(await run(SWIFT, nativeArgsFor('inspect'))) - if (!response?.ok || !response.target) return { ok: false, error: 'no-target' } + if (!response?.ok || !response.target) return { ok: false, error: response?.error ?? 'no-target' } const token = randomUUID() if (targets.size >= MAX_TARGETS) { for (const [key, value] of targets) if (value.expiresAt <= now()) targets.delete(key) diff --git a/server/test/rectangle.test.ts b/server/test/rectangle.test.ts index 8f48f7e3..2ca51ed7 100644 --- a/server/test/rectangle.test.ts +++ b/server/test/rectangle.test.ts @@ -55,6 +55,14 @@ describe('built-in macOS window provider', () => { }, ) + it('matches on owner and bounds when the window list hides names', () => { + const window = { windowID: 41, pid: nativeTarget.pid, title: '', x: 100, y: 100, width: 600, height: 400 } + const otherApp = { windowID: 42, pid: nativeTarget.pid + 1, title: '', x: 100, y: 100, width: 600, height: 400 } + const input = { pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400, windows: [window, otherApp] } + + expect(resolveWindowIDs([input, { ...input, expectedWindowID: 42 }])).toEqual([41, null]) + }) + it('rejects a same-process same-title focus switch to a different window ID', () => { const firstWindow = { windowID: 41, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 } const secondWindow = { ...firstWindow, windowID: 42, x: 720 } @@ -107,7 +115,14 @@ describe('built-in macOS window provider', () => { const provider = createRectangleProvider(run) await expect(provider.commands?.['inspect-target']?.({}, { loopback: true })) - .resolves.toEqual({ ok: false, error: 'no-target' }) + .resolves.toEqual({ ok: false, error: 'unsafe-target' }) + }) + + it('surfaces the inspector error so permission denials reach the widget', async () => { + const provider = createRectangleProvider(async () => JSON.stringify({ ok: false, error: 'accessibility-permission-required' })) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'accessibility-permission-required' }) }) it.each([ From 0e97920ebc5f99ddccad280c1e7177ec6cd86c6b Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Wed, 21 Oct 2026 06:27:17 +0200 Subject: [PATCH 6/7] Run the compiled helper instead of re-driving the Swift frontend Each `swift file.swift` invocation costs several hundred milliseconds in the compiler driver before the script's first line, which made every inspect and every action feel laggy. resolveNative builds the script once under a content hash in the shared cache and runs that binary, falling back to the interpreter when no toolchain is available. Co-Authored-By: Claude --- server/src/providers/native-tool.ts | 49 +++++++++++++++++++++++++++++ server/src/providers/rectangle.ts | 4 ++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 server/src/providers/native-tool.ts diff --git a/server/src/providers/native-tool.ts b/server/src/providers/native-tool.ts new file mode 100644 index 00000000..5ad65c77 --- /dev/null +++ b/server/src/providers/native-tool.ts @@ -0,0 +1,49 @@ +import { execFile as nodeExecFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { access, mkdir, readFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { promisify } from 'node:util' + +const execFileAsync = promisify(nodeExecFile) +const SWIFTC = '/usr/bin/swiftc' +const COMPILE_TIMEOUT_MS = 60_000 +const RETRY_FAILED_AFTER_MS = 60_000 +const CACHE_DIR = join(tmpdir(), 'fremkit-native') + +const inflight = new Map>() +const failedAt = new Map() + +async function compile(script: string): Promise { + try { + const hash = createHash('sha256').update(await readFile(script)).digest('hex').slice(0, 16) + const binary = join(CACHE_DIR, `${basename(script, '.swift')}-${hash}`) + try { await access(binary); return binary } catch { /* stale or missing: build below */ } + await mkdir(CACHE_DIR, { recursive: true }) + await execFileAsync(SWIFTC, ['-O', '-o', binary, script], { timeout: COMPILE_TIMEOUT_MS, shell: false }) + return binary + } catch { + failedAt.set(script, Date.now()) + return null + } +} + +/** + * `swift file.swift` re-drives the compiler frontend on every call — several hundred + * milliseconds before the script's first line. When the script's current content has already + * been built into `$TMPDIR/fremkit-native`, run that binary instead; any compile or lookup + * failure falls back to the interpreter so a missing toolchain never breaks a widget. + */ +export async function resolveNative(file: string, args: string[]): Promise<{ file: string; args: string[] }> { + const script = args[0] + if (file !== '/usr/bin/swift' || !script?.endsWith('.swift')) return { file, args } + const failed = failedAt.get(script) + if (failed !== undefined && Date.now() - failed < RETRY_FAILED_AFTER_MS) return { file, args } + let job = inflight.get(script) + if (!job) { + job = compile(script).finally(() => inflight.delete(script)) + inflight.set(script, job) + } + const binary = await job + return binary ? { file: binary, args: args.slice(1) } : { file, args } +} diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts index 71f1c238..986fbbb8 100644 --- a/server/src/providers/rectangle.ts +++ b/server/src/providers/rectangle.ts @@ -3,6 +3,7 @@ import { execFile as nodeExecFile } from 'node:child_process' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import { z } from 'zod' +import { resolveNative } from './native-tool.js' import type { CommandContext, Provider } from './types.js' const execFile = promisify(nodeExecFile) @@ -38,7 +39,8 @@ export function nativeInvocationFor(action: RectangleAction): string[] { } const runProgram: Runner = async (file, args) => { - const { stdout } = await execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: 32 * 1024 }) + const resolved = await resolveNative(file, args) + const { stdout } = await execFile(resolved.file, resolved.args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: 32 * 1024 }) return stdout } From 0958c17e9caf8aea8db9d357e0ec3601db57e7c2 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 06:53:54 +0200 Subject: [PATCH 7/7] Skip the kiosk display when cycling to the next display MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The next-display action walked every NSScreen, so a window on the last screen in sorted order wrapped onto the Xeneon Edge — the strip is the dashboard itself, not a destination for app windows. kioskDisplayIDs() finds the screen the helper's kiosk covers edge-to-edge (layer > 0 plus an exact CGDisplayBounds match, which the layer-0 admin window that stops at the menu bar can never satisfy) and nextDisplayIndex cycles only through the remaining screens. A window already sitting on the kiosk display moves to the first usable one; when no usable screen remains the action reports no-next-display as before. The selection logic runs under a test-next-display probe like the existing identity tests. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- server/src/providers/rectangle-native.swift | 62 ++++++++++++++++++++- server/test/rectangle.test.ts | 25 +++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift index a1d86ecf..5b68937c 100644 --- a/server/src/providers/rectangle-native.swift +++ b/server/src/providers/rectangle-native.swift @@ -34,6 +34,12 @@ struct IdentityProbe: Decodable { let windows: [WindowCandidate] } +struct NextDisplayProbe: Decodable { + let current: Int + let displays: [UInt32] + let excluding: [UInt32] +} + struct Response: Encodable { let ok: Bool let error: String? @@ -179,6 +185,41 @@ func displayFor(_ position: CGPoint, _ size: CGSize, in displays: [Display]) -> return overlaps.max(by: { $0.1 < $1.1 })?.0 } +/// The displays the kiosk covers edge-to-edge. `next-display` skips them: the strip is the +/// dashboard, not a destination for app windows. A helper window counts as the kiosk only above +/// the normal window level *and* matching a display's bounds — the admin window stays at layer 0 +/// and stops at the menu bar, so it never qualifies. +func kioskDisplayIDs() -> Set { + guard let helper = NSRunningApplication.runningApplications(withBundleIdentifier: "dev.fremkit.helper").first, + let list = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] else { return [] } + let helperFrames = list.compactMap { entry -> CGRect? in + guard (entry[kCGWindowOwnerPID as String] as? Int32) == helper.processIdentifier, + let layer = entry[kCGWindowLayer as String] as? Int, layer > 0, + let dict = entry[kCGWindowBounds as String] as? NSDictionary, + let frame = CGRect(dictionaryRepresentation: dict) else { return nil } + return frame + } + return Set(NSScreen.screens.compactMap { screen in + guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { return nil } + let id = CGDirectDisplayID(number.uint32Value) + let frame = CGDisplayBounds(id) + return helperFrames.contains(where: { + closeEnough($0.minX, frame.minX) && closeEnough($0.minY, frame.minY) && + closeEnough($0.width, frame.width) && closeEnough($0.height, frame.height) + }) ? id : nil + }) +} + +/// The display `next-display` lands on: the next screen after `current` in sorted order that the +/// kiosk does not own. A window already on a kiosk display moves to the first usable one; nil +/// when nothing usable is left (a single screen, or only the kiosk's). +func nextDisplayIndex(current: Int, in screens: [Display], excluding: Set) -> Int? { + let usable = screens.indices.filter { !excluding.contains(screens[$0].id) } + guard let position = usable.firstIndex(of: current) else { return usable.first } + guard usable.count > 1 else { return nil } + return usable[(position + 1) % usable.count] +} + func setAX(_ window: AXUIElement, attribute: CFString, point: CGPoint) -> Bool { var value = point guard let boxed = AXValueCreate(.cgPoint, &value) else { return false } @@ -263,8 +304,10 @@ func runAction(_ action: String, expected: Target) { targetPosition = CGPoint(x: area.minX, y: area.minY) targetSize = CGSize(width: area.width, height: area.height) case "next-display": - guard screens.count > 1 else { respond(Response(ok: false, error: "no-next-display")) } - let next = screens[(currentIndex + 1) % screens.count].usable + guard let nextIndex = nextDisplayIndex(current: currentIndex, in: screens, excluding: kioskDisplayIDs()) else { + respond(Response(ok: false, error: "no-next-display")) + } + let next = screens[nextIndex].usable targetSize = CGSize(width: min(oldSize.width, next.width), height: min(oldSize.height, next.height)) targetPosition = CGPoint(x: next.midX - targetSize.width / 2, y: next.midY - targetSize.height / 2) default: @@ -332,6 +375,21 @@ if ProcessInfo.processInfo.environment["FREMKIT_RECTANGLE_TESTING"] == "1", argu else { respond(Response(ok: false, error: "identity-test-encoding-failed")) } exit(0) } +if ProcessInfo.processInfo.environment["FREMKIT_RECTANGLE_TESTING"] == "1", arguments.first == "test-next-display" { + guard arguments.count == 2, + let data = arguments[1].data(using: .utf8), + let probes = try? JSONDecoder().decode([NextDisplayProbe].self, from: data) else { + respond(Response(ok: false, error: "invalid-test-probe")) + } + let picked = probes.map { probe in + nextDisplayIndex(current: probe.current, + in: probe.displays.map { Display(id: $0, frame: .zero, usable: .zero) }, + excluding: Set(probe.excluding)) + } + if let data = try? JSONEncoder().encode(picked), let output = String(data: data, encoding: .utf8) { print(output) } + else { respond(Response(ok: false, error: "next-display-test-encoding-failed")) } + exit(0) +} guard let mode = arguments.first else { respond(Response(ok: false, error: "missing-mode")) } guard AXIsProcessTrusted() else { respond(Response(ok: false, error: "accessibility-permission-required")) } diff --git a/server/test/rectangle.test.ts b/server/test/rectangle.test.ts index 2ca51ed7..1d31e426 100644 --- a/server/test/rectangle.test.ts +++ b/server/test/rectangle.test.ts @@ -18,6 +18,11 @@ const resolveWindowIDs = (inputs: unknown[]) => JSON.parse(execFileSync('/usr/bi env: { ...process.env, FREMKIT_RECTANGLE_TESTING: '1' }, })) as Array +const resolveNextDisplay = (inputs: unknown[]) => JSON.parse(execFileSync('/usr/bin/swift', [nativeHelper, 'test-next-display', JSON.stringify(inputs)], { + encoding: 'utf8', + env: { ...process.env, FREMKIT_RECTANGLE_TESTING: '1' }, +})) as Array + describe('built-in macOS window provider', () => { it('inspects the active app and returns an opaque target token without exposing its title', async () => { const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' @@ -71,6 +76,26 @@ describe('built-in macOS window provider', () => { expect(resolveWindowIDs([input, { ...input, expectedWindowID: 42 }])).toEqual([41, null]) }) + it('skips the kiosk display when cycling to the next display', () => { + expect(resolveNextDisplay([ + // displays sorted like `displays()`: kiosk strip first, then two real screens + { current: 1, displays: [4, 5, 1], excluding: [4] }, + { current: 2, displays: [4, 5, 1], excluding: [4] }, + // a window already on the kiosk display lands on the first usable screen + { current: 0, displays: [4, 5, 1], excluding: [4] }, + // kiosk unknown or absent: the plain cycle is unchanged + { current: 0, displays: [4, 5, 1], excluding: [] }, + ])).toEqual([2, 1, 1, 1]) + }) + + it.each([ + ['a single screen', { current: 0, displays: [1], excluding: [] }], + ['only the kiosk display remains', { current: 0, displays: [4], excluding: [4] }], + ['one usable screen and the window is on it', { current: 1, displays: [4, 5], excluding: [4] }], + ])('reports no next display with %s', (_case, probe) => { + expect(resolveNextDisplay([probe])).toEqual([null]) + }) + it.each([ ['missing window metadata', []], ['ambiguous same-title and same-bounds windows', [