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/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-native.swift b/server/src/providers/rectangle-native.swift new file mode 100644 index 00000000..5b68937c --- /dev/null +++ b/server/src/providers/rectangle-native.swift @@ -0,0 +1,414 @@ +import AppKit +import ApplicationServices +import CoreGraphics +import Foundation + +struct Target: Codable { + let pid: Int32 + 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 NextDisplayProbe: Decodable { + let current: Int + let displays: [UInt32] + let excluding: [UInt32] +} + +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 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? { + // 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.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) + } + 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 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) + } +} + +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) + // 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), + let size = sizeAttribute(window, kAXSizeAttribute as CFString) else { return nil } + if let expected, expected.title != title { return nil } + 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) +} + +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 +} + +/// 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 } + 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 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 + 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) + 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 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: + 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 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")) + } + } 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")) + } + // 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. + 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()) +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) +} +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")) } + +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]), 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) +} 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..986fbbb8 --- /dev/null +++ b/server/src/providers/rectangle.ts @@ -0,0 +1,115 @@ +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 { resolveNative } from './native-tool.js' +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({ 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), + 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' +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 resolved = await resolveNative(file, args) + const { stdout } = await execFile(resolved.file, resolved.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, String(target.windowID), ...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 its session-unique window ID 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: 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) + 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..1d31e426 --- /dev/null +++ b/server/test/rectangle.test.ts @@ -0,0 +1,175 @@ +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 + +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' + ? 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('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 } + 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('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', [ + { 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']], + ['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(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 () => { + 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: '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([ + ['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 }) + : 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' }) + }) +})