Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): drag a window onto a Space tile in the New UI to teleport it (CUA-1511) (#5099)

ddupontf157d9c2a916
diff --git a/apps/cua-spaces-desktop/src/bridge/context.ts b/apps/cua-spaces-desktop/src/bridge/context.ts
index 48016a190d..0a653a5b0a 100644
--- a/apps/cua-spaces-desktop/src/bridge/context.ts
+++ b/apps/cua-spaces-desktop/src/bridge/context.ts
@@ -12,6 +12,7 @@ import type { CredentialAnswer, UnlockAnswer } from "../model/keyvault";
import type { TeleportCache } from "../model/teleport";
import type { BridgeEvents } from "./host";
import type { SystemServices } from "./system";
+import type { DropTargetRect } from "../window-drop";
/** What the bridge asks the shell's windows to do (Electron owns them). */
export interface BridgeUi {
@@ -21,6 +22,8 @@ export interface BridgeUi {
setBackground(window: unknown, color: string, appearance: "system" | "light" | "dark" | null): void;
/** Brings the app to the front (a keychain prompt shows over the app that asked). */
activate(): void;
+ /** Where the calling window's Space tiles are, for a real window dragged onto one (macOS; none elsewhere). */
+ setDropTargets?(window: unknown, targets: DropTargetRect[]): void;
/** "Send file…": the native file picker over the calling window (files and folders, several); null when cancelled. */
chooseFiles?(window: unknown): Promise<string[] | null>;
/** A Space's picture-in-picture panels (floating windows). */
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index cb0bee2ca2..eb0dbc0000 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -40,7 +40,7 @@ export const METHODS = [
"keyvault.unlockVault", "keyvault.setup", "keyvault.setDisabled",
"keyvault.approve", "keyvault.deny", "keyvault.revokeGrant",
"keyvault.showItems", "keyvault.delete", "keyvault.run", "keyvault.dismiss",
- "window.setBackgroundColor", "window.setDragRegions",
+ "window.setBackgroundColor", "window.setDragRegions", "window.setDropTargets",
"startup.get", "startup.act",
"relay.usage",
] as const;
diff --git a/apps/cua-spaces-desktop/src/bridge/window.ts b/apps/cua-spaces-desktop/src/bridge/window.ts
index a4d07a3680..f76d3d1017 100644
--- a/apps/cua-spaces-desktop/src/bridge/window.ts
+++ b/apps/cua-spaces-desktop/src/bridge/window.ts
@@ -2,12 +2,14 @@
// Copyright (c) 2026 Cua AI, Inc.
// The window the page is in (`window.*`): its background as the page's
-// appearance changes, and its drag regions. Chromium reads where the window
-// drags from the page's CSS (`app-region`), so the Electron page never sends
-// them (the webkit adapter skips it here); the rects are checked and the
-// CSS stays in charge.
+// appearance changes, its drag regions, and where its Space tiles are.
+// Chromium reads where the window drags from the page's CSS (`app-region`),
+// so the Electron page never sends them (the webkit adapter skips it here);
+// the rects are checked and the CSS stays in charge. The tiles are targets
+// for a real window dragged onto one (macOS; window-drop.ts).
import type { BridgeContext } from "./context";
import { Failure, type Handlers } from "./host";
+import { dropTargetsOf } from "../window-drop";
const APPEARANCES = ["system", "light", "dark"] as const;
@@ -28,5 +30,11 @@ export function windowMethods({ ui }: BridgeContext): Handlers {
if (!Array.isArray(args.rects) || !args.rects.every(isRect)) throw Failure.badArgs("rects: [{x,y,width,height}]");
return null;
},
+ "window.setDropTargets": (args, caller) => {
+ const targets = dropTargetsOf(args.targets);
+ if (!targets) throw Failure.badArgs("targets: [{spaceId,x,y,width,height}]");
+ ui.setDropTargets?.(caller.window, targets);
+ return null;
+ },
};
}
diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.ts
index 2680b886d4..1e14707f13 100644
--- a/apps/cua-spaces-desktop/src/main.ts
+++ b/apps/cua-spaces-desktop/src/main.ts
@@ -33,6 +33,7 @@ import { closesToTray, installTray, isQuitting } from "./tray";
import { countsVideo, startVideoBench, videoBenchEnv } from "./video-bench";
import { createViewerWindows } from "./viewer";
import { applyThemeToWindow, createMainWindow, handleOverlayDim, handleViewerKeyboard, setWindowBackground } from "./window";
+import { WindowDropTargets, windowNumberOf, type DropWindow } from "./window-drop";
// Must match `appId` (Windows; macOS has the Swift app's bundle id) and the
// Linux desktop entry in electron-builder.config.cjs.
@@ -86,6 +87,26 @@ function migrateSwiftApp() {
}
}
+/** One of the app's windows as the window-drop targets see it (one per window). */
+const dropWindows = new WeakMap<BrowserWindow, DropWindow>();
+function dropWindow(win: BrowserWindow): DropWindow {
+ let w = dropWindows.get(win);
+ if (!w) {
+ w = {
+ destroyed: () => win.isDestroyed(),
+ visible: () => win.isVisible() && !win.isMinimized(),
+ contentBounds: () => win.getContentBounds(),
+ zoom: () => win.webContents.getZoomFactor(),
+ number: () => windowNumberOf(win.getMediaSourceId()),
+ send: (event, payload) => {
+ if (!win.isDestroyed()) win.webContents.send(ELECTRON_EVENT_CHANNEL, { event, payload });
+ },
+ };
+ dropWindows.set(win, w);
+ }
+ return w;
+}
+
/** The native host: the library, the model on it and the bridge. */
async function startNativeHost(showRoute: (route: string) => void, globalShortcut: GlobalShortcut | null) {
const dir = nativeDir({
@@ -118,6 +139,15 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu
viewers.closeAll();
});
const prompts = await electronKeyvaultPrompts(native);
+ // macOS: a real window dragged onto a Space tile in the main window (the
+ // notch's drag monitor follows it; window-drop.ts). Which Spaces take a drop is the core's rule.
+ const windowDrops =
+ process.platform === "darwin"
+ ? new WindowDropTargets((spaceId) => {
+ const space = env.model.spaces.find((s) => s.id === spaceId);
+ return !!space && native.appSpaceAcceptsDrop(space as Parameters<typeof native.appSpaceAcceptsDrop>[0]);
+ })
+ : null;
const bridge = createBridge({
model: env.model,
supervisor: env.supervisor,
@@ -133,6 +163,14 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu
if (win instanceof BrowserWindow) setWindowBackground(win, color);
},
activate: () => app.focus({ steal: true }),
+ setDropTargets: (win, targets) => {
+ if (!windowDrops || !(win instanceof BrowserWindow)) return;
+ windowDrops.set(dropWindow(win), targets);
+ if (process.env.CUA_SPACES_NOTCH_DEBUG) {
+ const at = win.getContentBounds();
+ console.log(`[cua-spaces] notch drop targets: ${targets.map((t) => t.spaceId).join(", ") || "none"} in window ${win.getMediaSourceId()} at ${at.x},${at.y}`);
+ }
+ },
chooseFiles: async (win) => {
// Files and folders at once where the picker allows it (macOS); Windows and Linux pick files.
const properties: ("openFile" | "openDirectory" | "multiSelections")[] =
@@ -188,6 +226,7 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu
drop: (spaceId, paths) => void dropOnSpace(model, notchUi, spaceId, paths),
},
teleport: notchTeleport(() => model.backend.teleportHandle()),
+ windowTargets: windowDrops ?? undefined,
});
if (notch) {
feedNotch(notch, model);
diff --git a/apps/cua-spaces-desktop/src/notch.ts b/apps/cua-spaces-desktop/src/notch.ts
index ee80b927c9..68e2050bfe 100644
--- a/apps/cua-spaces-desktop/src/notch.ts
+++ b/apps/cua-spaces-desktop/src/notch.ts
@@ -16,7 +16,7 @@ import { NotchModel, type NotchHost, type NotchModelOptions } from "./notch/mode
import { NotchProcess, type NotchProcessOptions } from "./notch/process";
import { NOTCH_PROTOCOL_VERSION, type HelperMessage, type HostMessage } from "./notch/protocol";
-export type { NotchHost, NotchActions, NotchTeleport, WindowDragEvent } from "./notch/model";
+export type { NotchHost, NotchActions, NotchTeleport, WindowDragEvent, WindowTargets, WindowTargetHit } from "./notch/model";
export type { NotchCore } from "./notch/core";
/** The helper's bundle and executable name. */
@@ -60,8 +60,8 @@ export interface Notch {
export interface StartNotchOptions extends NotchModelOptions {
/** The helper's executable (`helperPath`). */
path: string;
- /** Logs every protocol message both ways (`CUA_SPACES_NOTCH_DEBUG`; images left out). */
- trace?: (line: string) => void;
+ /** How long a `windowUnder` question waits for the helper (ms; default 300). */
+ windowUnderTimeoutMs?: number;
/** Process options for tests (spawn, timers, backoff). */
process?: Partial<Omit<NotchProcessOptions, "path" | "onMessage" | "onStart">>;
}
@@ -77,6 +77,26 @@ export function startNotch(host: NotchHost, options: StartNotchOptions): Notch {
trace?.(`-> ${describe(m)}`);
helper?.send(m);
};
+ // Questions to the helper about the window under a point, by id; one that
+ // goes unanswered (no helper, a restart) resolves to none.
+ const asked = new Map<number, (window: number | null) => void>();
+ let lastAsk = 0;
+ const windowUnder = (x: number, y: number, below: number | undefined) =>
+ new Promise<number | null>((resolve) => {
+ if (!helper?.running) return resolve(null);
+ const id = ++lastAsk;
+ const timer = setTimeout(() => answer(id, null), options.windowUnderTimeoutMs ?? 300);
+ asked.set(id, (w) => {
+ clearTimeout(timer);
+ resolve(w);
+ });
+ send(below === undefined ? { type: "windowUnder", id, x, y } : { type: "windowUnder", id, x, y, below });
+ });
+ const answer = (id: number, window: number | null) => {
+ const done = asked.get(id);
+ asked.delete(id);
+ done?.(window);
+ };
const model = new NotchModel(
host,
{
@@ -89,7 +109,7 @@ export function startNotch(host: NotchHost, options: StartNotchOptions): Notch {
},
ghost: (image) => send({ type: "ghost", image: image ? Buffer.from(image).toString("base64") : undefined }),
},
- { ...options, log },
+ { ...options, log, windowUnder },
);
const onMessage = (m: HelperMessage) => {
@@ -106,6 +126,8 @@ export function startNotch(host: NotchHost, options: StartNotchOptions): Notch {
return model.stageChanged(m.open);
case "error":
return log(`helper: ${m.message}`);
+ case "windowUnder":
+ return answer(m.id, m.window ?? null);
case "action":
switch (m.action) {
case "openSpace":
@@ -150,6 +172,7 @@ export function startNotch(host: NotchHost, options: StartNotchOptions): Notch {
stop: () => {
model.dispose();
helper?.stop();
+ for (const id of [...asked.keys()]) answer(id, null);
},
};
}
diff --git a/apps/cua-spaces-desktop/src/notch/model.ts b/apps/cua-spaces-desktop/src/notch/model.ts
index 6a9a6ce35c..fbf8f11db3 100644
--- a/apps/cua-spaces-desktop/src/notch/model.ts
+++ b/apps/cua-spaces-desktop/src/notch/model.ts
@@ -50,6 +50,25 @@ export interface NotchActions {
drop(spaceId: string, paths: string[]): void;
}
+/** A Space tile in one of the app's own windows under the cursor. */
+export interface WindowTargetHit {
+ spaceId: string;
+ /** That window's number (`kCGWindowNumber`), to tell whether another window covers it there. */
+ window: number;
+}
+
+/**
+ * The Space tiles in the app's own windows, the other target for a window
+ * drag (the SwiftUI app's `SidebarDropTargets`): the page reports where they
+ * are (`window.setDropTargets`), and only Spaces that take a drop count.
+ */
+export interface WindowTargets {
+ /** The drop-target tile under a global top-left point, in a window on screen (not checked for cover). */
+ at(x: number, y: number): WindowTargetHit | null;
+ /** Highlights that tile in its page (null: none). */
+ highlight(spaceId: string | null): void;
+}
+
export interface NotchHost {
/** The cua-spaces-ffi bindings (the app core). */
core: NotchCore;
@@ -58,6 +77,8 @@ export interface NotchHost {
thumbnail?(spaceId: string): Promise<Uint8Array | null | undefined>;
/** Window drags onto the notch (none: the notch takes clicks and file drops only). */
teleport?: NotchTeleport;
+ /** The app's own Space tiles as window-drag targets (none: the notch's tiles only). */
+ windowTargets?: WindowTargets;
}
/** Timers and clocks; tests step them by hand. */
@@ -87,6 +108,13 @@ export interface NotchModelOptions {
highlight?: string;
/** Logs (default: console.warn). */
log?(message: string): void;
+ /**
+ * The window at a global top-left point under the dragged window `below`
+ * (the helper's `windowUnder`); none: a tile is taken as uncovered.
+ */
+ windowUnder?(x: number, y: number, below: number | undefined): Promise<number | null>;
+ /** Diagnostics (`CUA_SPACES_NOTCH_DEBUG`): the protocol, and window drags over the app's own tiles. */
+ trace?: (line: string) => void;
}
/** What the helper gets: the state, and images. */
@@ -118,6 +146,12 @@ export class NotchModel {
private layoutRow = false;
private dragDisplays: unknown[] = [];
private draggedApp: unknown = null;
+ /** The dragged window's number (`start` carries it, `move` doesn't). */
+ private draggedWindow?: number;
+ /** The app's own tile a dragged window is over (highlighted), and the latest hit test's number. */
+ private windowTarget: string | null = null;
+ private windowTargetSeq = 0;
+ private lastTrace = "";
private cancelTimer?: () => void;
private cancelTick?: () => void;
private monitor?: { stop(): void };
@@ -215,6 +249,8 @@ export class NotchModel {
this.trigger = this.host.core.appDragTriggerInitial();
this.cancelTick?.();
this.cancelTick = undefined;
+ this.windowTargetSeq++;
+ this.setWindowTarget(null);
this.permissionPoll?.();
this.permissionPoll = undefined;
this.stageChanged(false);
@@ -510,8 +546,12 @@ export class NotchModel {
handleDrag(event: WindowDragEvent): void {
// Hidden: window drags are not followed (a late event is dropped).
if (!this.shown) return;
+ const wasMove = dragKind(this.trigger.kind) === "move";
const now = this.clock.monotonic();
- if (event.phase === "start") this.draggedApp = event.app ?? null;
+ if (event.phase === "start") {
+ this.draggedApp = event.app ?? null;
+ this.draggedWindow = event.window?.windowId;
+ }
if (event.phase !== "start" && event.frame) this.feed({ tag: "Frame", inner: { frame: event.frame } }, event);
switch (event.phase) {
case "start":
@@ -540,6 +580,62 @@ export class NotchModel {
default:
this.feed({ tag: "Cancel" }, event);
}
+ this.followWindowTargets(event, wasMove);
+ }
+
+ /**
+ * A moved window over a Space tile in the app's own window: that tile is
+ * highlighted, and a release there commits to it (the notch drag then
+ * ends without a drop), as the SwiftUI app's sidebar rows do. A resize
+ * never targets a tile, nor does a tile another window covers there.
+ */
+ private followWindowTargets(event: WindowDragEvent, wasMove: boolean): void {
+ const targets = this.host.windowTargets;
+ if (!targets) return;
+ const seq = ++this.windowTargetSeq;
+ const ending = event.phase !== "start" && event.phase !== "move";
+ const isMove = event.phase === "end" ? wasMove : dragKind(this.trigger.kind) === "move";
+ const below = event.window?.windowId ?? this.draggedWindow;
+ const app = event.app ?? this.draggedApp;
+ if (ending) this.draggedWindow = undefined;
+ const hit = isMove && event.phase !== "cancel" ? targets.at(event.x, event.y) : null;
+ const seen = `${event.phase === "move" ? "move" : event.phase} ${hit ? `${hit.spaceId}@${hit.window}` : "-"}`;
+ if (this.options.trace && (event.phase !== "move" || seen !== this.lastTrace)) {
+ this.options.trace(`window drag ${event.phase} (${event.x}, ${event.y}) kind=${dragKind(this.trigger.kind)} tile=${hit ? `${hit.spaceId} in window ${hit.window}` : "none"}`);
+ }
+ this.lastTrace = seen;
+ if (ending || !hit) this.setWindowTarget(null);
+ if (!hit) return;
+ void this.uncovered(hit, event.x, event.y, below).then((uncovered) => {
+ if (event.phase === "end") {
+ if (!uncovered || !this.shown) return;
+ this.send({ tag: "Drag", inner: { event: { tag: "Cancel" } } });
+ this.draggedApp = null;
+ this.host.actions.teleport(hit.spaceId, app);
+ return;
+ }
+ // A later event decided already.
+ if (seq !== this.windowTargetSeq || !this.shown) return;
+ this.setWindowTarget(uncovered ? hit.spaceId : null);
+ });
+ }
+
+ /** Whether the hit window is the one under the dragged window there. */
+ private async uncovered(hit: WindowTargetHit, x: number, y: number, below: number | undefined): Promise<boolean> {
+ const under = this.options.windowUnder;
+ if (!under) return true;
+ try {
+ return (await under(x, y, below)) === hit.window;
+ } catch (error) {
+ this.log(`no window under the cursor: ${String(error)}`);
+ return false;
+ }
+ }
+
+ private setWindowTarget(spaceId: string | null): void {
+ if (spaceId === this.windowTarget) return;
+ this.windowTarget = spaceId;
+ this.host.windowTargets?.highlight(spaceId);
}
/** The current drag's kind ("pending", "move", "resize"). */
diff --git a/apps/cua-spaces-desktop/src/notch/protocol.ts b/apps/cua-spaces-desktop/src/notch/protocol.ts
index 5c9800232a..376f2db37b 100644
--- a/apps/cua-spaces-desktop/src/notch/protocol.ts
+++ b/apps/cua-spaces-desktop/src/notch/protocol.ts
@@ -150,6 +150,8 @@ export type HostMessage =
| StateMessage
| { type: "thumbnail"; id: string; image?: string }
| { type: "ghost"; image?: string }
+ /** Which window is at a global top-left point under the dragged window `below` (is a tile in this app's window covered there?). */
+ | { type: "windowUnder"; id: number; x: number; y: number; below?: number }
| { type: "quit" };
export type HelperAction =
@@ -165,7 +167,9 @@ export type HelperMessage =
| { type: "event"; event: NotchInput }
| ({ type: "action" } & HelperAction)
| { type: "stage"; open: boolean }
- | { type: "error"; message: string };
+ | { type: "error"; message: string }
+ /** The answer to `windowUnder`: that window's number (`kCGWindowNumber`), none when no window is there. */
+ | { type: "windowUnder"; id: number; window?: number };
/** One message as a line. */
export function encodeMessage(message: HostMessage): string {
@@ -282,6 +286,9 @@ export function parseHelperMessage(line: string): HelperMessage | null {
return typeof m.open === "boolean" ? { type: "stage", open: m.open } : null;
case "error":
return isStr(m.message) ? { type: "error", message: m.message } : null;
+ case "windowUnder":
+ if (!isNum(m.id) || (m.window !== undefined && !isNum(m.window))) return null;
+ return m.window === undefined ? { type: "windowUnder", id: m.id } : { type: "windowUnder", id: m.id, window: m.window };
default:
return null;
}
diff --git a/apps/cua-spaces-desktop/src/window-drop.ts b/apps/cua-spaces-desktop/src/window-drop.ts
new file mode 100644
index 0000000000..7050c9b808
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/window-drop.ts
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// A real window dragged onto a Space tile in the app's own window (the
+// SwiftUI app's `SidebarDropTargets`, which does it for its sidebar rows).
+// The page reports where its tiles are (`window.setDropTargets`: CSS pixels
+// from the top left of the page); the notch model follows the drag with the
+// SDK's window-drag monitor and asks here which tile is under the cursor
+// (`WindowTargets`), highlights it (`window.dropTarget` to that page), and
+// commits a release there to the Teleport review. Which Spaces take a drop
+// is the core's rule (`appSpaceAcceptsDrop`, the notch tiles' too). macOS
+// only: window drags exist nowhere else (the monitor is the notch's). No
+// Electron here (main.ts passes the windows in), so it is tested plainly.
+
+import type { WindowTargetHit, WindowTargets } from "./notch";
+
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/** A tile as the page reports it. */
+export interface DropTargetRect extends Rect {
+ spaceId: string;
+}
+
+/** The event that tells a page which tile to highlight. */
+export const WINDOW_DROP_EVENT = "window.dropTarget";
+
+/** One of the app's windows, as the drop targets need it. */
+export interface DropWindow {
+ /** Whether it is gone (closed). */
+ destroyed(): boolean;
+ /** On screen: shown and not minimized. */
+ visible(): boolean;
+ /** Its page's area in global top-left points (`getContentBounds`). */
+ contentBounds(): Rect;
+ /** The page's zoom (CSS pixels to points). */
+ zoom(): number;
+ /** Its window number (`kCGWindowNumber`), null when unknown. */
+ number(): number | null;
+ /** A host event to its page. */
+ send(event: string, payload: unknown): void;
+}
+
+/** A page's report, checked: tiles with a Space id and a box. */
+export function dropTargetsOf(v: unknown): DropTargetRect[] | null {
+ if (!Array.isArray(v)) return null;
+ const ok = v.every(
+ (t) =>
+ !!t &&
+ typeof t === "object" &&
+ typeof (t as Record<string, unknown>).spaceId === "string" &&
+ ["x", "y", "width", "height"].every((k) => Number.isFinite((t as Record<string, unknown>)[k])),
+ );
+ return ok ? (v as DropTargetRect[]).map(({ spaceId, x, y, width, height }) => ({ spaceId, x, y, width, height })) : null;
+}
+
+/** `window:<number>:0` (Electron's `getMediaSourceId` on macOS) as the window's number. */
+export function windowNumberOf(mediaSourceId: string): number | null {
+ const m = /^window:(\d+):/.exec(mediaSourceId);
+ const n = m ? Number(m[1]) : NaN;
+ return Number.isInteger(n) && n > 0 ? n : null;
+}
+
+const inside = (r: Rect, x: number, y: number) => x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height;
+
+export class WindowDropTargets implements WindowTargets {
+ private readonly pages = new Map<DropWindow, DropTargetRect[]>();
+ private highlighted: { win: DropWindow; spaceId: string } | null = null;
+
+ /** `accepts`: whether a Space takes a drop (the core's rule). */
+ constructor(private readonly accepts: (spaceId: string) => boolean) {}
+
+ /** A page's tiles now (none: it shows none). */
+ set(win: DropWindow, targets: DropTargetRect[]): void {
+ if (targets.length === 0) this.pages.delete(win);
+ else this.pages.set(win, targets);
+ }
+
+ /** The drop-target tile under a global top-left point, in a window on screen (cover is the caller's check). */
+ at(x: number, y: number): WindowTargetHit | null {
+ for (const [win, targets] of this.pages) {
+ if (win.destroyed()) {
+ this.pages.delete(win);
+ continue;
+ }
+ if (!win.visible()) continue;
+ const content = win.contentBounds();
+ if (!inside(content, x, y)) continue;
+ const zoom = win.zoom() || 1;
+ const px = (x - content.x) / zoom;
+ const py = (y - content.y) / zoom;
+ const tile = targets.find((t) => inside(t, px, py) && this.accepts(t.spaceId));
+ const number = win.number();
+ // The first window with a tile there (the main window; viewers show none); the caller checks it is not covered.
+ if (tile && number !== null) return { spaceId: tile.spaceId, window: number };
+ }
+ return null;
+ }
+
+ /** Highlights a tile in the page that has it (and clears the last one). */
+ highlight(spaceId: string | null): void {
+ const prev = this.highlighted;
+ const win = spaceId === null ? undefined : [...this.pages].find(([, ts]) => ts.some((t) => t.spaceId === spaceId))?.[0];
+ if (prev && (prev.win !== win || prev.spaceId !== spaceId) && !prev.win.destroyed()) {
+ prev.win.send(WINDOW_DROP_EVENT, { spaceId: null });
+ }
+ this.highlighted = win && spaceId !== null ? { win, spaceId } : null;
+ if (win && spaceId !== null && !win.destroyed()) win.send(WINDOW_DROP_EVENT, { spaceId });
+ }
+}
diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.ts
index 7a5a22c4e1..799e171cf0 100644
--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts
+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts
@@ -75,6 +75,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
let events: BridgeEvent[];
let opened: [string, string][];
let backgrounds: [unknown, string, string | null][];
+ let dropTargets: [unknown, unknown][];
const pipsOpen = new Map<string, () => void>();
beforeAll(async () => {
@@ -109,6 +110,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
model.createAcceptTimeout = 5;
opened = [];
backgrounds = [];
+ dropTargets = [];
bridge = createBridge({
model,
supervisor: null,
@@ -118,6 +120,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
ui: {
openSpace: (id, name) => opened.push([id, name]),
setBackground: (win, color, appearance) => backgrounds.push([win, color, appearance]),
+ setDropTargets: (win, targets) => dropTargets.push([win, targets]),
activate: () => {},
chooseFiles: async () => ["/Users/ada/Desktop/picked.txt"],
pip: { open: (spec, closed) => pipsOpen.set(`${spec.spaceId}|${spec.key}`, closed), close: (id, key) => pipsOpen.delete(`${id}|${key}`) },
@@ -148,6 +151,7 @@ describe.skipIf(!built)("the bridge on the app core", () => {
["telemetry.track", { signals: [{ type: "step", step: "app_launched", ok: true }] }],
["window.setBackgroundColor", { color: "#16181c" }],
["window.setDragRegions", { rects: [{ x: 78, y: 0, width: 400, height: 38 }] }],
+ ["window.setDropTargets", { targets: [{ spaceId: space, x: 20, y: 60, width: 232, height: 180 }] }],
["startup.get", {}],
["startup.act", { action: "tryAgain" }],
["spaces.usage", { spaceId: space }],
@@ -320,6 +324,14 @@ describe.skipIf(!built)("the bridge on the app core", () => {
expect(await code("window.setDragRegions", { rects: [{ x: 1 }] })).toBe("bad_args");
});
+ it("hands the calling window's Space tiles to the window drops, checked", async () => {
+ dropTargets.length = 0;
+ await call("window.setDropTargets", { targets: [{ spaceId: "local:aurora", x: 20, y: 60, width: 232, height: 180, extra: 1 }] });
+ expect(dropTargets).toEqual([["win-1", [{ spaceId: "local:aurora", x: 20, y: 60, width: 232, height: 180 }]]]);
+ expect(await code("window.setDropTargets", { targets: [{ spaceId: 4, x: 0, y: 0, width: 1, height: 1 }] })).toBe("bad_args");
+ expect(await code("window.setDropTargets", {})).toBe("bad_args");
+ });
+
it("tells the page when the list changed, once, and not when nothing did", async () => {
await tick(5);
events.length = 0;
diff --git a/apps/cua-spaces-desktop/test/notch-model.test.ts b/apps/cua-spaces-desktop/test/notch-model.test.ts
index bfd755a239..e1ad41659f 100644
--- a/apps/cua-spaces-desktop/test/notch-model.test.ts
+++ b/apps/cua-spaces-desktop/test/notch-model.test.ts
@@ -2,7 +2,7 @@
// Copyright (c) 2026 Cua AI, Inc.
import { describe, expect, it, vi } from "vitest";
-import { NotchModel, settingsURL, type NotchActions, type NotchTeleport, type WindowDragEvent } from "../src/notch/model";
+import { NotchModel, settingsURL, type NotchActions, type NotchTeleport, type WindowDragEvent, type WindowTargets } from "../src/notch/model";
import type { ScreenFacts, StateMessage } from "../src/notch/protocol";
import { fakeCore, manualClock, MOTION, type FakeSpace } from "./fakeNotchCore";
@@ -36,7 +36,14 @@ function actions(): NotchActions & { calls: unknown[][] } {
};
}
-function setup(opts: { teleport?: NotchTeleport; thumbnail?: (id: string) => Promise<Uint8Array | null> } = {}) {
+function setup(
+ opts: {
+ teleport?: NotchTeleport;
+ thumbnail?: (id: string) => Promise<Uint8Array | null>;
+ windowTargets?: WindowTargets;
+ windowUnder?: (x: number, y: number, below: number | undefined) => Promise<number | null>;
+ } = {},
+) {
const fake = fakeCore();
const clock = manualClock();
const states: StateMessage[] = [];
@@ -45,9 +52,9 @@ function setup(opts: { teleport?: NotchTeleport; thumbnail?: (id: string) => Pro
const opened: string[] = [];
const acts = actions();
const model = new NotchModel(
- { core: fake.core, actions: acts, teleport: opts.teleport, thumbnail: opts.thumbnail },
+ { core: fake.core, actions: acts, teleport: opts.teleport, thumbnail: opts.thumbnail, windowTargets: opts.windowTargets },
{ state: (s) => states.push(s), thumbnail: (id, i) => thumbnails.push([id, i]), ghost: (g) => ghosts.push(g) },
- { clock, openURL: (u) => opened.push(u), log: () => {} },
+ { clock, openURL: (u) => opened.push(u), log: () => {}, windowUnder: opts.windowUnder },
);
model.setSpaces(SPACES);
const last = () => states[states.length - 1]!;
@@ -329,6 +336,102 @@ describe("notch window drags", () => {
expect(ghosts.at(-1)).toBeNull();
});
+ describe("onto the app's own Space tiles", () => {
+ // The main window (number 900) shows the tile "local:aurora" at 100..300 x 100..250.
+ const MAIN = 900;
+ function targets() {
+ const highlights: (string | null)[] = [];
+ const t: WindowTargets & { highlights: (string | null)[] } = {
+ highlights,
+ at: (x, y) => (x >= 100 && x < 300 && y >= 100 && y < 250 ? { spaceId: "local:aurora", window: MAIN } : null),
+ highlight: (id) => void highlights.push(id),
+ };
+ return t;
+ }
+ async function started(o: { kind?: number; under?: (x: number, y: number, below: number | undefined) => number | null } = {}) {
+ const teleport = fakeTeleport({ permitted: true });
+ const windowTargets = targets();
+ const asked: [number, number, number | undefined][] = [];
+ const under = o.under ?? (() => MAIN);
+ const s = setup({
+ teleport,
+ windowTargets,
+ windowUnder: async (x, y, below) => (asked.push([x, y, below]), under(x, y, below)),
+ });
+ s.model.screens(SCREEN, SCREEN);
+ s.model.recheckPermission();
+ await vi.waitFor(() => expect(teleport.listener).toBeDefined());
+ // The trigger: a move (or what `kind` says), never near the notch.
+ s.fake.script(() => ({ phase: 1, kind: o.kind ?? 1, overlay: [] }));
+ return { ...s, listener: teleport.listener!, windowTargets, asked };
+ }
+ const app = { name: "Notes", id: "com.apple.Notes" };
+ const frame = { x: 400, y: 300, width: 800, height: 600 };
+
+ it("highlights the tile under a moved window and commits a release there to its Teleport review", async () => {
+ const { listener, windowTargets, asked, acts, fake } = await started();
+ listener.onEvent({ phase: "start", x: 700, y: 500, window: { windowId: 7, appName: "Notes" }, app, startFrame: frame, frame });
+ expect(windowTargets.highlights).toEqual([]);
+ listener.onEvent({ phase: "move", x: 150, y: 120 });
+ // Covered or not: asked about the window under the dragged one (its number from the start; moves don't carry it).
+ await vi.waitFor(() => expect(windowTargets.highlights).toEqual(["local:aurora"]));
+ expect(asked.at(-1)).toEqual([150, 120, 7]);
+ listener.onEvent({ phase: "move", x: 600, y: 120 });
+ expect(windowTargets.highlights).toEqual(["local:aurora", null]);
+ listener.onEvent({ phase: "move", x: 160, y: 130 });
+ await vi.waitFor(() => expect(windowTargets.highlights.at(-1)).toBe("local:aurora"));
+ listener.onEvent({ phase: "end", x: 160, y: 130, window: { windowId: 7, appName: "Notes" } });
+ expect(windowTargets.highlights.at(-1)).toBeNull();
+ await vi.waitFor(() => expect(acts.calls).toEqual([["teleport", "local:aurora", app]]));
+ // The notch's own drag ends without a drop.
+ expect(fake.events.at(-1)).toEqual({ tag: "Drag", inner: { event: { tag: "Cancel" } } });
+ });
+
+ it("never targets a tile another window covers there", async () => {
+ const { listener, windowTargets, acts } = await started({ under: () => 1234 });
+ listener.onEvent({ phase: "start", x: 700, y: 500, window: { windowId: 7, appName: "Notes" }, app, startFrame: frame, frame });
+ listener.onEvent({ phase: "move", x: 150, y: 120 });
+ listener.onEvent({ phase: "end", x: 150, y: 120, window: { windowId: 7, appName: "Notes" } });
+ await new Promise((r) => setTimeout(r, 10));
+ expect(windowTargets.highlights.filter(Boolean)).toEqual([]);
+ expect(acts.calls).toEqual([]);
+ });
+
+ it("never targets a tile for a resize", async () => {
+ const { listener, windowTargets, asked, acts } = await started({ kind: 2 });
+ listener.onEvent({ phase: "start", x: 150, y: 120, window: { windowId: 7, appName: "Notes" }, app, startFrame: frame, frame });
+ listener.onEvent({ phase: "move", x: 150, y: 120 });
+ listener.onEvent({ phase: "end", x: 150, y: 120, window: { windowId: 7, appName: "Notes" } });
+ await new Promise((r) => setTimeout(r, 10));
+ expect(asked).toEqual([]);
+ expect(windowTargets.highlights.filter(Boolean)).toEqual([]);
+ expect(acts.calls).toEqual([]);
+ });
+
+ it("drops a late answer once the cursor moved on, and the highlight when the notch hides", async () => {
+ let release: (n: number) => void = () => {};
+ const teleport = fakeTeleport({ permitted: true });
+ const windowTargets = targets();
+ const s = setup({ teleport, windowTargets, windowUnder: () => new Promise((r) => (release = r)) });
+ s.model.recheckPermission();
+ await vi.waitFor(() => expect(teleport.listener).toBeDefined());
+ s.fake.script(() => ({ phase: 1, kind: 1, overlay: [] }));
+ const l = teleport.listener!;
+ l.onEvent({ phase: "start", x: 700, y: 500, window: { windowId: 7, appName: "Notes" }, app, startFrame: frame, frame });
+ l.onEvent({ phase: "move", x: 150, y: 120 });
+ const late = release;
+ l.onEvent({ phase: "move", x: 600, y: 120 });
+ late(MAIN);
+ await new Promise((r) => setTimeout(r, 10));
+ expect(windowTargets.highlights.filter(Boolean)).toEqual([]);
+ l.onEvent({ phase: "move", x: 150, y: 120 });
+ release(MAIN);
+ await vi.waitFor(() => expect(windowTargets.highlights.at(-1)).toBe("local:aurora"));
+ s.model.setShown(false);
+ expect(windowTargets.highlights.at(-1)).toBeNull();
+ });
+ });
+
it("drops window drags while hidden", async () => {
const teleport = fakeTeleport({ permitted: true });
const { model, fake } = setup({ teleport });
diff --git a/apps/cua-spaces-desktop/test/notch-protocol.test.ts b/apps/cua-spaces-desktop/test/notch-protocol.test.ts
index e6e7d4080d..a97b6c447d 100644
--- a/apps/cua-spaces-desktop/test/notch-protocol.test.ts
+++ b/apps/cua-spaces-desktop/test/notch-protocol.test.ts
@@ -121,6 +121,8 @@ describe("notch protocol", () => {
'{"type":"action","action":"drop","spaceId":"a","paths":[1]}',
'{"type":"screens","notch":{"frame":{}}}',
'{"type":"stage","open":"yes"}',
+ '{"type":"windowUnder"}',
+ '{"type":"windowUnder","id":1,"window":"900"}',
]) {
expect(parseHelperMessage(line), line).toBeNull();
}
diff --git a/apps/cua-spaces-desktop/test/notch.test.ts b/apps/cua-spaces-desktop/test/notch.test.ts
index 170e4e5aaa..ad1b7e68bd 100644
--- a/apps/cua-spaces-desktop/test/notch.test.ts
+++ b/apps/cua-spaces-desktop/test/notch.test.ts
@@ -7,7 +7,7 @@ import { createRequire } from "node:module";
import * as path from "node:path";
import { PassThrough } from "node:stream";
import { describe, expect, it, vi } from "vitest";
-import { helperPath, notchSupported, startNotch, type NotchActions } from "../src/notch";
+import { helperPath, notchSupported, startNotch, type NotchActions, type WindowDragEvent, type WindowTargets } from "../src/notch";
import { notchTeleport } from "../src/notch-feed";
import { fakeCore, manualClock, MOTION } from "./fakeNotchCore";
@@ -70,7 +70,7 @@ class FakeChild extends EventEmitter {
}
}
-function setup(trace?: (line: string) => void) {
+function setup(trace?: (line: string) => void, drags?: { windowTargets: WindowTargets; onListener(l: { onEvent(e: WindowDragEvent): void }): void }) {
const fake = fakeCore();
const clock = manualClock();
const children: FakeChild[] = [];
@@ -97,11 +97,12 @@ function setup(trace?: (line: string) => void) {
thumbnail: async () => new Uint8Array([0x89, 0x50, 0x4e, 0x47]),
teleport: {
windowDragSupported: () => true,
- windowDragPermitted: () => false,
+ windowDragPermitted: () => !!drags,
requestWindowDragPermission: () => (requested.push(1), true),
- startWindowDrag: () => ({ stop() {} }),
+ startWindowDrag: (l) => (drags?.onListener(l), { stop() {} }),
captureWindowThumbnail: () => null,
},
+ windowTargets: drags?.windowTargets,
},
{
path: "/helper",
@@ -109,6 +110,7 @@ function setup(trace?: (line: string) => void) {
clock,
openURL: (u) => opened.push(u),
log: () => {},
+ windowUnderTimeoutMs: 50,
process: {
spawn: () => {
const c = new FakeChild();
@@ -229,6 +231,35 @@ describe("the notch end to end (fake helper)", () => {
});
});
+describe("window drags onto the app's own Space tiles (fake helper)", () => {
+ it("asks the helper which window is under the dragged one, and highlights the tile only when it is the app's", async () => {
+ const highlights: (string | null)[] = [];
+ let listener: { onEvent(e: WindowDragEvent): void } | undefined;
+ const windowTargets: WindowTargets = {
+ at: (x) => (x < 300 ? { spaceId: "local:aurora", window: 900 } : null),
+ highlight: (id) => void highlights.push(id),
+ };
+ const { children, fake } = setup(undefined, { windowTargets, onListener: (l) => (listener = l) });
+ const c = children[0]!;
+ await vi.waitFor(() => expect(listener).toBeDefined());
+ fake.script(() => ({ phase: 1, kind: 1, overlay: [] }));
+ listener!.onEvent({ phase: "start", x: 700, y: 500, window: { windowId: 7, appName: "Notes" } });
+ listener!.onEvent({ phase: "move", x: 150, y: 120 });
+ await vi.waitFor(() => expect(c.received.at(-1)).toEqual({ type: "windowUnder", id: 1, x: 150, y: 120, below: 7 }));
+ c.say({ type: "windowUnder", id: 1, window: 900 });
+ await vi.waitFor(() => expect(highlights).toEqual(["local:aurora"]));
+ // Another window over the tile there: no highlight.
+ listener!.onEvent({ phase: "move", x: 160, y: 120 });
+ await vi.waitFor(() => expect(c.received.at(-1)).toMatchObject({ type: "windowUnder", id: 2 }));
+ c.say({ type: "windowUnder", id: 2, window: 1234 });
+ await vi.waitFor(() => expect(highlights).toEqual(["local:aurora", null]));
+ // A helper that never answers: none, after the wait.
+ listener!.onEvent({ phase: "move", x: 170, y: 120 });
+ await new Promise((r) => setTimeout(r, 80));
+ expect(highlights).toEqual(["local:aurora", null]);
+ });
+});
+
describe("window drags onto the notch", () => {
it("follows window drags with the SDK's teleport handle once there is one", async () => {
let handle: { windowDragSupported(): boolean; windowDragPermitted(): boolean; requestWindowDragPermission(): boolean; startWindowDrag: ReturnType<typeof vi.fn>; captureWindowThumbnail(): ArrayBuffer } | null = null;
diff --git a/apps/cua-spaces-desktop/test/window-drop.test.ts b/apps/cua-spaces-desktop/test/window-drop.test.ts
new file mode 100644
index 0000000000..85d7a7856b
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/window-drop.test.ts
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+import { dropTargetsOf, windowNumberOf, WindowDropTargets, type DropWindow, type Rect } from "../src/window-drop";
+
+function fakeWindow(o: { bounds: Rect; number?: number | null; zoom?: number }) {
+ const sent: [string, unknown][] = [];
+ const state = { gone: false, shown: true };
+ const w = {
+ sent,
+ get gone() {
+ return state.gone;
+ },
+ set gone(v: boolean) {
+ state.gone = v;
+ },
+ get shown() {
+ return state.shown;
+ },
+ set shown(v: boolean) {
+ state.shown = v;
+ },
+ destroyed: () => state.gone,
+ visible: () => state.shown,
+ contentBounds: () => o.bounds,
+ zoom: () => o.zoom ?? 1,
+ number: () => (o.number === undefined ? 900 : o.number),
+ send: (event: string, payload: unknown) => void sent.push([event, payload]),
+ } satisfies DropWindow & Record<string, unknown>;
+ return w;
+}
+
+// The main window's page at (200, 100) on screen; a tile at 20..252 x 60..240 in it.
+const TILES = [
+ { spaceId: "local:aurora", x: 20, y: 60, width: 232, height: 180 },
+ { spaceId: "cloud:build", x: 268, y: 60, width: 232, height: 180 },
+];
+
+describe("window drops onto the app's Space tiles", () => {
+ it("finds the tile under a global point, in the page's CSS pixels at its zoom, for Spaces that take a drop", () => {
+ const drops = new WindowDropTargets((id) => id !== "cloud:build");
+ const main = fakeWindow({ bounds: { x: 200, y: 100, width: 1000, height: 700 } });
+ drops.set(main, TILES);
+ expect(drops.at(200 + 30, 100 + 70)).toEqual({ spaceId: "local:aurora", window: 900 });
+ expect(drops.at(200 + 10, 100 + 70)).toBeNull();
+ // A Space that takes no drop (the core's rule) is no target.
+ expect(drops.at(200 + 300, 100 + 70)).toBeNull();
+ // Outside the window.
+ expect(drops.at(100, 100)).toBeNull();
+ // Zoomed to 125%: CSS pixel 30 is 37.5 points in.
+ const zoomed = new WindowDropTargets(() => true);
+ zoomed.set(fakeWindow({ bounds: { x: 0, y: 0, width: 1000, height: 700 }, zoom: 1.25 }), TILES);
+ expect(zoomed.at(20 * 1.25 + 1, 60 * 1.25 + 1)?.spaceId).toBe("local:aurora");
+ expect(zoomed.at(21, 61)).toBeNull();
+ });
+
+ it("ignores hidden, minimized and closed windows, and a page that shows no tiles", () => {
+ const drops = new WindowDropTargets(() => true);
+ const main = fakeWindow({ bounds: { x: 0, y: 0, width: 1000, height: 700 } });
+ drops.set(main, TILES);
+ main.shown = false;
+ expect(drops.at(30, 70)).toBeNull();
+ main.shown = true;
+ expect(drops.at(30, 70)?.spaceId).toBe("local:aurora");
+ drops.set(main, []);
+ expect(drops.at(30, 70)).toBeNull();
+ drops.set(main, TILES);
+ main.gone = true;
+ expect(drops.at(30, 70)).toBeNull();
+ // A window whose number is unknown can't be checked for cover: never a target.
+ const unknown = new WindowDropTargets(() => true);
+ unknown.set(fakeWindow({ bounds: { x: 0, y: 0, width: 1000, height: 700 }, number: null }), TILES);
+ expect(unknown.at(30, 70)).toBeNull();
+ });
+
+ it("highlights the tile in its page and clears it there", () => {
+ const drops = new WindowDropTargets(() => true);
+ const main = fakeWindow({ bounds: { x: 0, y: 0, width: 1000, height: 700 } });
+ drops.set(main, TILES);
+ drops.highlight("local:aurora");
+ drops.highlight("cloud:build");
+ drops.highlight(null);
+ expect(main.sent).toEqual([
+ ["window.dropTarget", { spaceId: "local:aurora" }],
+ ["window.dropTarget", { spaceId: null }],
+ ["window.dropTarget", { spaceId: "cloud:build" }],
+ ["window.dropTarget", { spaceId: null }],
+ ]);
+ });
+
+ it("checks a page's report and reads the window number", () => {
+ expect(dropTargetsOf([{ spaceId: "a", x: 1, y: 2, width: 3, height: 4, more: true }])).toEqual([{ spaceId: "a", x: 1, y: 2, width: 3, height: 4 }]);
+ expect(dropTargetsOf([{ spaceId: "a", x: 1, y: 2, width: 3 }])).toBeNull();
+ expect(dropTargetsOf([{ x: 1, y: 2, width: 3, height: 4 }])).toBeNull();
+ expect(dropTargetsOf("nope")).toBeNull();
+ expect(windowNumberOf("window:4242:0")).toBe(4242);
+ expect(windowNumberOf("screen:1:0")).toBeNull();
+ expect(windowNumberOf("window:0:0")).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index d7306e3467..f5e199f93e 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -145,6 +145,8 @@ public final class AppModel {
public private(set) var creates = AppCreatesState(pending: [], deleting: [], powering: [])
/// Sidebar rows as targets for a dragged real window.
public let dropTargets = SidebarDropTargets()
+ /// The New UI window's Space tiles, the same kind of target.
+ public let pageDropTargets = SidebarDropTargets()
public var settings: AppSettings
let settingsPath: String
/// The running app's version: with it, the New UI's default follows
@@ -269,6 +271,7 @@ public final class AppModel {
dropTargets.isDropTarget = { [weak self] id in
self?.spaces.first { $0.id == id }.map { appSpaceAcceptsDrop(space: $0) } ?? false
}
+ pageDropTargets.isDropTarget = dropTargets.isDropTarget
}
// MARK: - Launch
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SidebarDropTargets.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SidebarDropTargets.swift
index 943976d801..29ade6f909 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SidebarDropTargets.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SidebarDropTargets.swift
@@ -7,8 +7,9 @@ import CuaSpacesFFI
import Observation
import SwiftUI
-/// Space rows in the main window's sidebar as drop targets for a dragged
-/// real window (the notch's tiles are the other target). The drag itself is
+/// Space rows in the main window's sidebar (or Space tiles in the New UI
+/// window, whose page reports them) as drop targets for a dragged real
+/// window (the notch's tiles are the other target). The drag itself is
/// the SDK's window-drag monitor, which the notch controller already
/// follows; this hit-tests the global cursor against the rows. Which Spaces
/// take a drop is the core's decision (`appSpaceAcceptsDrop`, the notch
@@ -18,6 +19,8 @@ import SwiftUI
public final class SidebarDropTargets {
/// The row under a dragged window.
public private(set) var targetedId: String?
+ /// Told when the targeted row changes (the New UI window tells its page).
+ @ObservationIgnored var onTargeted: ((String?) -> Void)?
/// Row frames in the window's content, top-left origin (SwiftUI's
/// window space).
@ObservationIgnored private(set) var frames: [String: CGRect] = [:]
@@ -37,6 +40,8 @@ public final class SidebarDropTargets {
func setFrame(_ id: String, _ rect: CGRect) { frames[id] = rect }
func removeFrame(_ id: String) { frames[id] = nil }
+ /// Every row's frame at once (the New UI page reports all its tiles).
+ func setFrames(_ all: [String: CGRect]) { frames = all }
/// A global top-left point (the drag events' space: origin at the
/// primary display's top left, y down) in a window's content, top-left
@@ -71,17 +76,23 @@ public final class SidebarDropTargets {
func handle(phase: String, target: String?) -> String? {
switch phase {
case "start", "move":
- targetedId = target
+ setTargeted(target)
return nil
case "end":
let committed = target
- targetedId = nil
+ setTargeted(nil)
return committed
default:
- targetedId = nil
+ setTargeted(nil)
return nil
}
}
+
+ private func setTargeted(_ id: String?) {
+ guard id != targetedId else { return }
+ targetedId = id
+ onTargeted?(id)
+ }
}
/// Hands the hosting window to a closure (the drop targets need it to map
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift
index 6b2637d0d5..6498ceda02 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Notch/NotchController.swift
@@ -67,6 +67,12 @@ public final class NotchController {
@ObservationIgnored public var onDropURLs: ((String, [URL]) -> Void)?
/// The main window's Space rows, the other target for a window drag.
@ObservationIgnored public var sidebar: SidebarDropTargets?
+ /// The New UI window's Space tiles, a target the same way (the page
+ /// reports where they are).
+ @ObservationIgnored public var pageTiles: SidebarDropTargets?
+ /// The dragged window's number: `start` and `end` carry it, `move`
+ /// doesn't, and the rows' cover check needs it on every event.
+ @ObservationIgnored private var draggedWindowId: UInt32?
/// A Space's screenshot for its tile (the SDK's `Space.screenshot`).
@ObservationIgnored public var thumbnail: ((String) async -> NSImage?)?
/// Opens a URL (System Settings); tests capture it.
@@ -363,7 +369,10 @@ public final class NotchController {
guard isShown else { return }
let wasMove = trigger.kind == .move
let now = clock()
- if event.phase == "start" { draggedApp = event.app }
+ if event.phase == "start" {
+ draggedApp = event.app
+ draggedWindowId = event.window?.windowId
+ }
if event.phase != "start", let frame = event.frame { feed(.frame(frame: frame), event) }
switch event.phase {
case "start":
@@ -376,20 +385,23 @@ public final class NotchController {
default:
feed(.cancel, event)
}
- // A moved window released over a Space row in the main window
- // commits there; the notch drag then ends without a drop. A resize
- // never targets a row.
- guard let sidebar else { return }
+ // A moved window released over a Space row in the main window (or
+ // a Space tile in the New UI window) commits there; the notch drag
+ // then ends without a drop. A resize never targets a row.
+ let dragged = event.window?.windowId ?? draggedWindowId
+ if event.phase != "start", event.phase != "move" { draggedWindowId = nil }
let isMove = event.phase == "end" ? wasMove : trigger.kind == .move
- guard isMove else {
- sidebar.handle(phase: "cancel", target: nil)
- return
- }
- let target = sidebar.row(atGlobal: CGPoint(x: event.x, y: event.y), dragged: event.window?.windowId)
- if let spaceId = sidebar.handle(phase: event.phase, target: target) {
- model.send(.drag(event: .cancel))
- onTeleport?(spaceId, event.app ?? draggedApp)
- draggedApp = nil
+ for targets in [sidebar, pageTiles].compactMap({ $0 }) {
+ guard isMove else {
+ targets.handle(phase: "cancel", target: nil)
+ continue
+ }
+ let target = targets.row(atGlobal: CGPoint(x: event.x, y: event.y), dragged: dragged)
+ if let spaceId = targets.handle(phase: event.phase, target: target) {
+ model.send(.drag(event: .cancel))
+ onTeleport?(spaceId, event.app ?? draggedApp)
+ draggedApp = nil
+ }
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift
index f9117712c6..a48b0397c1 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift
@@ -294,6 +294,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
model.closeWebUI = { WebUIWindowController.closeShared() }
let controller = NotchController(model: model.notch)
controller.sidebar = model.dropTargets
+ controller.pageTiles = model.pageDropTargets
controller.showMain = { WebUIWindowController.actions?.openMain() }
// Each of these shows its result in the main window (the New UI
// window while its experiment is on): open it when it was closed
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 25d7be08d3..a45918bd65 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -45,6 +45,9 @@ public struct WebUIActions {
/// its New Space wizard (the app's New Space menu items, the notch).
/// `settings.openRequested` asks the page to open its Settings (the app
/// menu's Settings command, ⌘,, while the New UI window is in front).
+/// `window.dropTarget` (`{spaceId}`, null for none) names the Space tile a
+/// real window is being dragged over (`window.setDropTargets` said where the
+/// tiles are; the notch's drag monitor follows the drag).
///
/// Every method routes to the view models the SwiftUI windows use, so a
/// decision is the app core's either way. `spaces.cancelCreate`,
@@ -99,6 +102,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"keyvault.approve", "keyvault.deny", "keyvault.revokeGrant",
"keyvault.showItems", "keyvault.delete", "keyvault.run", "keyvault.dismiss",
"window.setBackgroundColor", "window.setDragRegions",
+ // Where the page's Space tiles are, for a real window dragged onto one.
+ "window.setDropTargets",
// The launch (WebUIBridge+Startup.swift).
"startup.get", "startup.act",
// The relay allowance this month (WebUIBridge+Pages.swift).
@@ -358,6 +363,9 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
guard let rects = args["rects"] as? [[String: Any]] else { throw Failure.badArgs("rects: [{x,y,width,height}]") }
host?.setDragRegions(rects.compactMap(Self.rect))
return NSNull()
+ case "window.setDropTargets":
+ host?.setDropTargets(try Self.dropTargets(args))
+ return NSNull()
default:
if let result = try routeStartup(method, args) { return result }
@@ -873,6 +881,19 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
return s
}
+ /// `{targets: [{spaceId, x, y, width, height}]}` as each tile's box by
+ /// Space id (CSS pixels from the page's top left).
+ static func dropTargets(_ args: [String: Any]) throws -> [String: CGRect] {
+ let bad = Failure.badArgs("targets: [{spaceId,x,y,width,height}]")
+ guard let targets = args["targets"] as? [[String: Any]] else { throw bad }
+ var frames: [String: CGRect] = [:]
+ for t in targets {
+ guard let id = t["spaceId"] as? String, let r = rect(t) else { throw bad }
+ frames[id] = r
+ }
+ return frames
+ }
+
static func rect(_ r: [String: Any]) -> CGRect? {
func n(_ k: String) -> CGFloat? { (r[k] as? NSNumber).map { CGFloat(truncating: $0) } }
guard let x = n("x"), let y = n("y"), let w = n("width"), let h = n("height") else { return nil }
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
index 2b4dab501b..f8d2d7b4b5 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
@@ -174,6 +174,12 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,
webView.uiDelegate = self
bridge.host = self
videoSurfaces?.emit = { [weak self] event, payload in self?.emit(event, payload: payload) }
+ // A real window dragged over a tile: the page highlights it.
+ dropTargets.window = window
+ dropTargets.setFrames([:])
+ dropTargets.onTargeted = { [weak self] id in
+ self?.emit("window.dropTarget", payload: ["spaceId": id.map { $0 as Any } ?? NSNull()])
+ }
setBackground(Self.storedBackground(for: window.effectiveAppearance), keep: false)
}
@@ -219,8 +225,9 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,
}
public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
- // A new page: the old one's video slots are gone with it.
+ // A new page: the old one's video slots and tiles are gone with it.
videoSurfaces?.removeAll()
+ dropTargets.setFrames([:])
}
public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
@@ -353,6 +360,21 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,
webView.dragRegions = rects
}
+ /// The page's Space tiles (CSS pixels from its top left) as targets for
+ /// a real window dragged onto one, in the window content's points (the
+ /// web view is the content view).
+ func setDropTargets(_ frames: [String: CGRect]) {
+ let zoom = webView.pageZoom * webView.magnification
+ dropTargets.window = window
+ dropTargets.setFrames(frames.mapValues {
+ CGRect(x: $0.minX * zoom, y: $0.minY * zoom, width: $0.width * zoom, height: $0.height * zoom)
+ })
+ }
+
+ /// The drop targets this window's page reports (the app model's, which
+ /// the notch's drag monitor hit-tests).
+ var dropTargets: SidebarDropTargets { bridge.model.pageDropTargets }
+
/// Tells the page something changed (`cua:event`).
func emit(_ event: String, payload: Any? = nil) {
onEmit?(event, payload)
@@ -429,6 +451,10 @@ public final class WebUIWindowController: NSWindowController, NSWindowDelegate,
window?.saveFrame(usingName: Self.frameName)
videoSurfaces?.removeAll()
webView.configuration.userContentController.removeAllScriptMessageHandlers()
+ if dropTargets.window === window {
+ dropTargets.setFrames([:])
+ dropTargets.onTargeted = nil
+ }
if Self.shared === self { Self.shared = nil }
}
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
index b3225ee3fc..fb0255d1e7 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -245,6 +245,7 @@ struct BridgeContractTests {
("teleport.remembered", ["providerId": "chrome", "spaceId": space]),
("window.setBackgroundColor", ["color": "#16181c"]),
("window.setDragRegions", ["rects": [["x": 78, "y": 0, "width": 400, "height": 38]]]),
+ ("window.setDropTargets", ["targets": [["spaceId": space, "x": 20, "y": 60, "width": 232, "height": 180]]]),
("startup.get", [:]),
]
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
index f22e7d80ea..4198883ed0 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
@@ -565,6 +565,39 @@ struct WebUIHostTests {
#expect(second.window?.frame.origin == frame.origin)
}
+ /// The page's Space tiles become the window-drag targets of its window
+ /// (CSS pixels at the page's zoom), and a targeted tile is named back to
+ /// the page; a new page starts with none.
+ @Test func thePagesTilesAreWindowDropTargets() async throws {
+ _ = NSApplication.shared
+ let (_, model) = bridge()
+ let c = WebUIWindowController(model: model)
+ defer { c.window?.close() }
+ var emitted: [(String, Any?)] = []
+ c.onEmit = { emitted.append(($0, $1)) }
+ _ = try await c.bridge.handle("window.setDropTargets",
+ ["targets": [["spaceId": "local:aurora", "x": 20, "y": 60, "width": 232, "height": 180]]])
+ let targets = model.pageDropTargets
+ #expect(targets.window === c.window)
+ #expect(targets.frames == ["local:aurora": CGRect(x: 20, y: 60, width: 232, height: 180)])
+ c.webView.pageZoom = 1.25
+ _ = try await c.bridge.handle("window.setDropTargets",
+ ["targets": [["spaceId": "local:aurora", "x": 20, "y": 60, "width": 232, "height": 180]]])
+ #expect(targets.frames["local:aurora"] == CGRect(x: 25, y: 75, width: 290, height: 225))
+ await #expect(throws: (any Error).self) {
+ _ = try await c.bridge.handle("window.setDropTargets", ["targets": [["x": 1]]])
+ }
+ targets.handle(phase: "move", target: "local:aurora")
+ targets.handle(phase: "move", target: "local:aurora")
+ targets.handle(phase: "end", target: "local:aurora")
+ let named = emitted.filter { $0.0 == "window.dropTarget" }.map { ($0.1 as? [String: Any])?["spaceId"] }
+ #expect(named.count == 2)
+ #expect(named.first as? String == "local:aurora")
+ #expect(named.last as? NSNull != nil)
+ c.window?.close()
+ #expect(targets.frames.isEmpty)
+ }
+
@Test func aboutIsTheUpdatesModelsInput() async throws {
let (bridge, model) = bridge()
model.updates = UpdatesModel(updater: FixtureUpdater(), channel: .stable)
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WindowDropTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WindowDropTests.swift
index f5f8370659..15622478c9 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WindowDropTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WindowDropTests.swift
@@ -105,4 +105,41 @@ struct WindowDropTests {
controller.handle(event("end"))
#expect(opened == nil)
}
+
+ /// The New UI window's tiles take a drop as the rows do. Only `start`
+ /// and `end` name the dragged window; the cover check on every `move`
+ /// still asks below it (the system hit test finds the dragged window
+ /// itself otherwise, so a tile would never highlight mid-drag).
+ @Test func aPageTileIsTargetedMidDragAndAReleaseOpensItsTeleport() {
+ let model = NotchModel()
+ let controller = NotchController(model: model)
+ let rows = SidebarDropTargets()
+ let tiles = SidebarDropTargets()
+ controller.sidebar = rows
+ controller.pageTiles = tiles
+ var opened: String?
+ controller.onTeleport = { id, _ in opened = id }
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
+ styleMask: [.borderless], backing: .buffered, defer: true)
+ window.isReleasedWhenClosed = false
+ tiles.window = window
+ tiles.visible = { _ in true }
+ tiles.isDropTarget = { _ in true }
+ // The system's answer: the page's window below the dragged one (7),
+ // the dragged window itself when asked for the frontmost.
+ tiles.windowUnder = { _, below in below == 7 ? window.windowNumber : 7 }
+ var named: [String?] = []
+ tiles.onTargeted = { named.append($0) }
+ tiles.setFrames(["local:aurora": CGRect(x: 10, y: 60, width: 200, height: 120)])
+ let primaryTop = NSScreen.screens.first?.frame.maxY ?? 0
+ let y = Double(primaryTop - (300 - 70))
+ let dragged = TeleportWindow(windowId: 7, pid: 1, appName: "Notes", title: "", bundlePath: nil)
+ controller.handle(TeleportWindowDragEvent(phase: "start", x: 500, y: y, window: dragged, app: nil))
+ controller.handle(TeleportWindowDragEvent(phase: "move", x: 50, y: y, window: nil, app: nil))
+ #expect(tiles.targetedId == "local:aurora")
+ #expect(rows.targetedId == nil)
+ controller.handle(TeleportWindowDragEvent(phase: "end", x: 50, y: y, window: dragged, app: nil))
+ #expect(opened == "local:aurora")
+ #expect(named == ["local:aurora", nil])
+ }
}
diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.md
index 5a5bb7df7e..5c4b6b0925 100644
--- a/apps/cua-spaces-web/src/bridge/README.md
+++ b/apps/cua-spaces-web/src/bridge/README.md
@@ -137,6 +137,16 @@ participants' cursors over the video it draws, `ops/presence.ts`; events
natively). Electron reads
drag regions from the CSS, so the adapter sends none there.
+Both hosts take the page's Space tiles (`window.setDropTargets`, sent by
+the adapter whenever the layout changes; `window-drop.ts`) as targets for a
+real window dragged onto one, as the classic Mac sidebar's rows are. The
+host follows the drag with the notch's window-drag monitor (macOS with the
+Accessibility permission, the notch shown), hit-tests the tiles, names the
+tile under the window with `window.dropTarget` (`{ spaceId }`, null for
+none) for the page to highlight, and opens that Space's Teleport review on
+release. Windows and Linux can't follow other apps' window drags, so they
+never send `window.dropTarget`.
+
### SwiftUI WKWebView: `webkit-protocol.ts`
The macOS app's `WebUIBridge.swift` defines this contract, and the adapter
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/window-drop.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/window-drop.test.ts
new file mode 100644
index 0000000000..982d085612
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/__tests__/window-drop.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { createWebkitAdapter } from "../adapters/webkit";
+import type { HostWindow } from "../detect";
+import type { Rect } from "../drag-regions";
+import type { WebkitRequest } from "../webkit-protocol";
+import { clip, measureDropTargets, setWindowDropTarget, syncDropTargets, useWindowDropTarget, windowDropTargetOf, type DropTargetRect } from "../window-drop";
+
+const r = (x: number, y: number, width: number, height: number): Rect => ({ x, y, width, height });
+const frame = () => new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+
+function place(el: Element, b: Rect) {
+ el.getBoundingClientRect = () => ({ left: b.x, top: b.y, width: b.width, height: b.height }) as DOMRect;
+}
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ setWindowDropTarget(null);
+});
+
+describe("window drop targets", () => {
+ it("clips a box", () => {
+ expect(clip(r(0, 0, 100, 100), r(50, 50, 100, 100))).toEqual(r(50, 50, 50, 50));
+ expect(clip(r(0, 0, 10, 10), r(20, 20, 5, 5))).toBeNull();
+ });
+
+ it("measures each tile's visible box with its Space id", () => {
+ document.body.innerHTML = `
+ <main style="overflow: auto">
+ <div data-window-drop="local:a"></div>
+ <div data-window-drop="local:b"></div>
+ <div data-window-drop="local:c"></div>
+ </main>`;
+ const [a, b, c] = [...document.querySelectorAll("[data-window-drop]")];
+ // The scrolling page below the 38 px top bar; b is half scrolled out, c entirely.
+ place(document.querySelector("main")!, r(0, 38, 1000, 600));
+ place(a!, r(20, 60, 232, 180));
+ place(b!, r(20, 560, 232, 180));
+ place(c!, r(20, 900, 232, 180));
+ expect(measureDropTargets(window)).toEqual<DropTargetRect[]>([
+ { spaceId: "local:a", ...r(20, 60, 232, 180) },
+ { spaceId: "local:b", ...r(20, 560, 232, 78) },
+ ]);
+ });
+
+ it("offers none while a dialog covers the page", () => {
+ document.body.innerHTML = `<div data-window-drop="local:a"></div><div role="dialog"></div>`;
+ place(document.querySelector("[data-window-drop]")!, r(0, 0, 100, 100));
+ expect(measureDropTargets(window)).toEqual([]);
+ });
+
+ it("sends them when they change, and only then", async () => {
+ document.body.innerHTML = `<div data-window-drop="local:a"></div>`;
+ place(document.querySelector("[data-window-drop]")!, r(10, 10, 100, 100));
+ const sent: DropTargetRect[][] = [];
+ const stop = syncDropTargets(window, (t) => sent.push(t));
+ await frame();
+ expect(sent).toEqual([[{ spaceId: "local:a", ...r(10, 10, 100, 100) }]]);
+ document.body.setAttribute("class", "x");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(sent).toHaveLength(1);
+ // The tiles left (another page): an empty list goes out.
+ document.body.innerHTML = "";
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(sent.at(-1)).toEqual([]);
+ stop();
+ });
+
+ it("highlights the tile the host names", () => {
+ const { result } = renderHook(() => useWindowDropTarget());
+ expect(result.current).toBeNull();
+ act(() => setWindowDropTarget(windowDropTargetOf({ spaceId: "local:a" })));
+ expect(result.current).toBe("local:a");
+ act(() => setWindowDropTarget(windowDropTargetOf({ spaceId: null })));
+ expect(result.current).toBeNull();
+ expect(windowDropTargetOf(null)).toBeNull();
+ expect(windowDropTargetOf({ spaceId: 4 })).toBeNull();
+ });
+
+ it("the webkit adapter sends the tiles and follows the host's highlight", async () => {
+ const sent: WebkitRequest[] = [];
+ const handler = {
+ postMessage: (m: unknown) => {
+ const req = m as WebkitRequest;
+ sent.push(req);
+ return Promise.resolve({ id: req.id, ok: true, result: null });
+ },
+ };
+ document.body.innerHTML = `<div data-window-drop="local:a"></div>`;
+ place(document.querySelector("[data-window-drop]")!, r(0, 50, 232, 180));
+ const w = window as unknown as HostWindow;
+ w.webkit = { messageHandlers: { cua: handler } };
+ const adapter = createWebkitAdapter(w);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ const req = sent.find((s) => s.method === "window.setDropTargets");
+ expect(req?.args).toEqual({ targets: [{ spaceId: "local:a", ...r(0, 50, 232, 180) }] });
+ const { result } = renderHook(() => useWindowDropTarget());
+ act(() => {
+ window.dispatchEvent(new CustomEvent("cua:event", { detail: { event: "window.dropTarget", payload: { spaceId: "local:a" } } }));
+ });
+ expect(result.current).toBe("local:a");
+ // Closing the bridge drops the highlight.
+ act(() => adapter.dispose?.());
+ expect(result.current).toBeNull();
+ delete (w as { webkit?: unknown }).webkit;
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index 6ae96f66b7..2f8ddc635b 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -23,7 +23,9 @@
* resolves without a call; the Electron shell's is this page's
* (`onboarding.get`, `onboarding.complete`). Appearance and the hotkey are page-side; an appearance change sets
* the window's background (`window.setBackgroundColor`). The page tells the
- * window where it drags (`window.setDragRegions`, `../drag-regions.ts`).
+ * window where it drags (`window.setDragRegions`, `../drag-regions.ts`), and
+ * where its Space tiles are for a real window dragged onto one
+ * (`window.setDropTargets`, `../window-drop.ts`).
*/
import { Emitter, HostError, type DataAdapter } from "../adapter";
@@ -45,6 +47,7 @@ import {
import type { KeyvaultOverview, KvGrant, KvPending } from "../contracts/keyvault";
import type { CreateProgress } from "../contracts/host";
import { syncDragRegions } from "../drag-regions";
+import { setWindowDropTarget, syncDropTargets, WINDOW_DROP_EVENT, windowDropTargetOf } from "../window-drop";
import { requestNewSpace } from "../new-space";
import { STOPPED_SHARING_ERROR, stoppedSharingLine, withNotSharing } from "../sharing";
import { teleportProgressFromWk, webkitPageOps } from "../ops/webkit-pages";
@@ -618,6 +621,11 @@ export function createWebkitAdapter(
events.emit({ type: "startup.changed", state: startupFromHost(detail.payload) });
return;
}
+ // A real window dragged over a Space tile (the host follows the drag).
+ if (detail?.event === WINDOW_DROP_EVENT) {
+ setWindowDropTarget(windowDropTargetOf(detail.payload));
+ return;
+ }
if (detail?.event === "teleport.progress") {
const ev = teleportProgressFromWk(detail.payload);
if (ev) events.emit(ev);
@@ -634,6 +642,12 @@ export function createWebkitAdapter(
!electron && dom.document && dom.requestAnimationFrame && typeof MutationObserver !== "undefined"
? syncDragRegions(dom as Window, (rects) => void request("window.setDragRegions", { rects }).catch(() => {}))
: null;
+ // Where the Space tiles are, for a real window dragged onto one (both
+ // hosts: neither sees such a drag in the page; `../window-drop.ts`).
+ const stopDropTargets =
+ dom.document && dom.requestAnimationFrame && typeof MutationObserver !== "undefined"
+ ? syncDropTargets(dom as Window, (targets) => void request("window.setDropTargets", { targets }).catch(() => {}))
+ : null;
return {
mode: electron ? "electron" : "webkit",
@@ -648,6 +662,8 @@ export function createWebkitAdapter(
events.clear();
stopEvents();
stopDragRegions?.();
+ stopDropTargets?.();
+ setWindowDropTarget(null);
},
};
}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index e5d4decebf..e1dafa5948 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -6388,6 +6388,9 @@
},
"window.setDragRegions": {
"type": "null"
+ },
+ "window.setDropTargets": {
+ "type": "null"
}
},
"webkitUnshaped": {}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 436d804a4d..78cefa421b 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -1140,6 +1140,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"keyvault.revokeGrant": num,
"window.setBackgroundColor": nul,
"window.setDragRegions": nul,
+ "window.setDropTargets": nul,
"startup.get": StartupShape,
"startup.act": StartupShape,
"relay.usage": OP_SHAPES["relay.usage"],
diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.ts
index d4707e65cc..b4a3cda997 100644
--- a/apps/cua-spaces-web/src/bridge/coverage.ts
+++ b/apps/cua-spaces-web/src/bridge/coverage.ts
@@ -169,4 +169,5 @@ export const HOST_COVERAGE = {
*/
export const WEBKIT_HOST_ONLY: Partial<Record<WebkitMethod, string>> = {
"window.setDragRegions": "the webkit adapter sends the page's drag regions itself whenever the layout changes (drag-regions.ts)",
+ "window.setDropTargets": "the webkit adapter sends the Space tiles' boxes itself whenever the layout changes, for a real window dragged onto one (window-drop.ts)",
};
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index 82cb971bb9..4b28edcdaa 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -98,6 +98,7 @@ export { createFailedText, emptyHome, type EmptyHome, type EmptyTile, type First
export type * from "./contracts/volume";
export * from "./volume";
export { ThumbnailStore, THUMBNAIL_CAP, THUMBNAIL_REFRESH_MS, thumbnailStore, useSpaceThumbnail } from "./thumbnails";
+export { useWindowDropTarget } from "./window-drop";
export { useSpaceFiles, parseDropped, dropSendingText, dropSentText, sendFiles, splitDrop, type DropStatus, type SpaceFilesHook } from "./space-files";
export { agentRunLines, useDesktopCover, useSpaceDetail, type AgentRunLine, type DetailFor, type DetailReadings, type PipOutcome, type SpaceDetailHook } from "./space-detail";
export type * from "./ops/space-detail";
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index b9278d7e98..c6e9df261f 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -142,6 +142,7 @@ export const WEBKIT_METHODS = [
"keyvault.revokeGrant",
"window.setBackgroundColor",
"window.setDragRegions",
+ "window.setDropTargets",
"startup.get",
"startup.act",
"relay.usage",
diff --git a/apps/cua-spaces-web/src/bridge/window-drop.ts b/apps/cua-spaces-web/src/bridge/window-drop.ts
new file mode 100644
index 0000000000..bdb476adcc
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/window-drop.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * A real window dragged onto a Space tile (the classic Mac sidebar's window
+ * drop on a row, `SidebarDropTargets.swift`).
+ *
+ * The page can't see such a drag: another app's window moving over this one
+ * sends the page no events. The host follows it with the SDK's window-drag
+ * monitor (the one the notch follows; macOS, with the Accessibility
+ * permission), so the page tells the host where its tiles are
+ * (`window.setDropTargets`: each `[data-window-drop]` element's Space id and
+ * visible box, in CSS pixels from the top left, again whenever the layout
+ * changes). The host hit-tests the cursor against them, decides which Space
+ * takes a drop (the core's rule, as for the notch's tiles), tells the page
+ * which tile to highlight (`window.dropTarget`, `{ spaceId }` or null) and,
+ * on release, opens that Space's Teleport review for the window's app.
+ *
+ * A host that can't follow window drags (Windows, Linux, the browser demo)
+ * never sends `window.dropTarget`, so nothing shows there.
+ */
+
+import { useSyncExternalStore } from "react";
+import type { Rect } from "./drag-regions";
+
+/** The attribute that makes an element a window-drop target; its value is the Space id. */
+export const WINDOW_DROP_ATTR = "data-window-drop";
+/** The host's event naming the targeted Space (or null). */
+export const WINDOW_DROP_EVENT = "window.dropTarget";
+
+export interface DropTargetRect extends Rect {
+ spaceId: string;
+}
+
+/** `a` clipped to `b`, or null when they don't overlap. */
+export function clip(a: Rect, b: Rect): Rect | null {
+ const left = Math.max(a.x, b.x);
+ const top = Math.max(a.y, b.y);
+ const right = Math.min(a.x + a.width, b.x + b.width);
+ const bottom = Math.min(a.y + a.height, b.y + b.height);
+ if (right <= left || bottom <= top) return null;
+ return { x: left, y: top, width: right - left, height: bottom - top };
+}
+
+const box = (el: Element): Rect => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+};
+
+const clips = (style: CSSStyleDeclaration) => [style.overflow, style.overflowX, style.overflowY].some((o) => o && o !== "visible");
+
+/**
+ * The page's drop targets now: each tile's box clipped to the viewport and
+ * to every scrolling ancestor (a tile scrolled half out of view takes a drop
+ * on its visible half only). None while a dialog or menu covers the page.
+ */
+export function measureDropTargets(win: Window): DropTargetRect[] {
+ const doc = win.document;
+ if (doc.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"]')) return [];
+ const viewport: Rect = { x: 0, y: 0, width: win.innerWidth, height: win.innerHeight };
+ const out: DropTargetRect[] = [];
+ for (const el of doc.querySelectorAll(`[${WINDOW_DROP_ATTR}]`)) {
+ const spaceId = el.getAttribute(WINDOW_DROP_ATTR);
+ if (!spaceId) continue;
+ let visible: Rect | null = clip(box(el), viewport);
+ for (let p = el.parentElement; visible && p && p !== doc.documentElement; p = p.parentElement) {
+ if (clips(win.getComputedStyle(p))) visible = clip(visible, box(p));
+ }
+ if (!visible) continue;
+ out.push({
+ spaceId,
+ x: Math.round(visible.x),
+ y: Math.round(visible.y),
+ width: Math.round(visible.width),
+ height: Math.round(visible.height),
+ });
+ }
+ return out;
+}
+
+/**
+ * Sends the drop targets now and after every layout change (resize, scroll,
+ * DOM and class changes, once per frame at most, only when they differ).
+ * Returns the stop function.
+ */
+export function syncDropTargets(win: Window, send: (targets: DropTargetRect[]) => void): () => void {
+ const doc = win.document;
+ let last = "";
+ let frame: number | null = null;
+ const flush = () => {
+ frame = null;
+ const targets = measureDropTargets(win);
+ const key = JSON.stringify(targets);
+ if (key === last) return;
+ last = key;
+ send(targets);
+ };
+ const schedule = () => {
+ if (frame === null) frame = win.requestAnimationFrame(flush);
+ };
+ const observer = new MutationObserver(schedule);
+ observer.observe(doc.documentElement, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ["class", "style", "hidden", "data-state", "open", "role", WINDOW_DROP_ATTR],
+ });
+ win.addEventListener("resize", schedule);
+ doc.addEventListener("scroll", schedule, true);
+ doc.addEventListener("transitionend", schedule, true);
+ schedule();
+ return () => {
+ observer.disconnect();
+ win.removeEventListener("resize", schedule);
+ doc.removeEventListener("scroll", schedule, true);
+ doc.removeEventListener("transitionend", schedule, true);
+ if (frame !== null) win.cancelAnimationFrame(frame);
+ };
+}
+
+/* ---- The targeted tile (the host's `window.dropTarget`) ------------------- */
+
+let targeted: string | null = null;
+const listeners = new Set<() => void>();
+
+/** The host says which tile a dragged window is over (null: none). */
+export function setWindowDropTarget(spaceId: string | null): void {
+ if (spaceId === targeted) return;
+ targeted = spaceId;
+ for (const l of listeners) l();
+}
+
+/** The host's `window.dropTarget` payload, checked. */
+export function windowDropTargetOf(payload: unknown): string | null {
+ const id = (payload as { spaceId?: unknown } | null)?.spaceId;
+ return typeof id === "string" && id ? id : null;
+}
+
+const subscribe = (l: () => void) => {
+ listeners.add(l);
+ return () => listeners.delete(l);
+};
+
+/** The Space a dragged window is over now, if any. */
+export function useWindowDropTarget(): string | null {
+ return useSyncExternalStore(subscribe, () => targeted, () => null);
+}
diff --git a/apps/cua-spaces-web/src/routes/spaces/index.tsx b/apps/cua-spaces-web/src/routes/spaces/index.tsx
index 92bca785b3..bc77469d99 100644
--- a/apps/cua-spaces-web/src/routes/spaces/index.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/index.tsx
@@ -5,7 +5,7 @@ import { createFileRoute, Link } from "@tanstack/react-router";
import { ArrowDownCircleIcon, KeyRoundIcon, LoaderCircleIcon, MonitorIcon, PlusIcon, PowerIcon } from "lucide-react";
import { useEffect, useRef, useState, type DragEvent } from "react";
-import { emptyHome, useBridge, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, type Space } from "@/bridge";
+import { emptyHome, useBridge, useFirstSpaceOffers, useMachines, useNewSpaceWizard, useSpaceAccess, useSpaceFiles, useSpaces, useSpaceThumbnail, useWindowDropTarget, type Space } from "@/bridge";
import { EmptyHome } from "@/components/empty-home";
import { GettingStarted } from "@/components/getting-started";
import { OsIcon } from "@/components/os-icon";
@@ -102,9 +102,18 @@ function SpacesPage() {
function SpaceTile({ space, machine, accessKey }: { space: Space; machine: string; accessKey?: string | null }) {
const drop = useTileDrop(space);
+ // A real window dragged over this tile (the host hit-tests the tiles' boxes and says which; macOS only).
+ const windowOver = useWindowDropTarget() === space.id;
return (
- <div className="group/tile relative" data-tile-drop={drop.over ?? undefined} data-drop-status={drop.status?.kind} {...drop.handlers}>
- <SpaceLink space={space} machine={machine} />
+ <div
+ className="group/tile relative"
+ data-tile-drop={drop.over ?? undefined}
+ data-drop-status={drop.status?.kind}
+ data-window-drop={space.id}
+ data-window-over={windowOver || undefined}
+ {...drop.handlers}
+ >
+ <SpaceLink space={space} machine={machine} windowOver={windowOver} />
{drop.over ? <DropOverlay space={space} accepts={drop.over === "accept"} /> : null}
{/* A drop on the tile still going in: the core's "Sending …" line. */}
{drop.status?.kind === "working" && !drop.over ? (
@@ -225,14 +234,17 @@ function TilePower({ space }: { space: Space }) {
);
}
-function SpaceLink({ space, machine }: { space: Space; machine: string }) {
+function SpaceLink({ space, machine, windowOver = false }: { space: Space; machine: string; windowOver?: boolean }) {
return (
<Link
to="/spaces/$spaceId"
params={{ spaceId: space.id }}
data-space-id={space.id}
data-state={spaceState(space)}
- className="group block w-full cursor-default rounded-xl border bg-card p-1.5 text-left shadow-xs outline-none transition-[box-shadow,border-color] hover:border-foreground/15 hover:shadow-sm focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/25"
+ className={cn(
+ "group block w-full cursor-default rounded-xl border bg-card p-1.5 text-left shadow-xs outline-none transition-[box-shadow,border-color] hover:border-foreground/15 hover:shadow-sm focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/25",
+ windowOver && "border-brand ring-3 ring-brand/25",
+ )}
>
<Thumbnail space={space} />
<div className="flex items-start gap-2.5 px-1.5 pt-2.5 pb-1">
diff --git a/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/HelperNotch.swift b/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/HelperNotch.swift
index df86acaf6f..44c58f7ef3 100644
--- a/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/HelperNotch.swift
+++ b/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/HelperNotch.swift
@@ -43,6 +43,14 @@ public final class HelperNotch: NotchSurface {
@ObservationIgnored private var observers: [NSObjectProtocol] = []
/// Tests and `--selftest` turn this off so nothing goes on screen.
@ObservationIgnored public var makesPanel = true
+ /// The window at a global top-left point under window `below` (any
+ /// app's; the system's hit test, as the SwiftUI app's
+ /// `SidebarDropTargets.windowUnder`). Tests set their own.
+ @ObservationIgnored public var windowUnder: (Double, Double, Int?) -> Int? = { x, y, below in
+ let primaryTop = NSScreen.screens.first?.frame.maxY ?? 0
+ let n = NSWindow.windowNumber(at: NSPoint(x: x, y: primaryTop - y), belowWindowWithWindowNumber: below ?? 0)
+ return n > 0 ? n : nil
+ }
public init(emit: @escaping (HelperMessage) -> Void) {
self.emit = emit
@@ -80,6 +88,8 @@ public final class HelperNotch: NotchSurface {
thumbnails[id] = image.flatMap(NSImage.init(data:))
case .ghost(let image):
ghost = image.flatMap(NSImage.init(data:))
+ case .windowUnder(let id, let x, let y, let below):
+ emit(.windowUnder(id: id, window: windowUnder(x, y, below)))
case .quit:
return false
}
diff --git a/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/NotchProtocol.swift b/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/NotchProtocol.swift
index 787a7ea410..37f891694e 100644
--- a/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/NotchProtocol.swift
+++ b/libs/spaces-notch-swift/Sources/CuaSpacesNotchHelper/NotchProtocol.swift
@@ -20,6 +20,9 @@ import Foundation
/// * `thumbnail` `{id, image?}`: a Space's latest thumbnail (base64 PNG or
/// JPEG; none clears it).
/// * `ghost` `{image?}`: the dragged window's image.
+/// * `windowUnder` `{id, x, y, below?}`: which window is at a global
+/// top-left point under the dragged window (a window dragged over a
+/// Space tile in the app's own window: is the tile covered there?).
/// * `quit`: exit now.
///
/// Helper to Electron:
@@ -35,6 +38,8 @@ import Foundation
/// * `stage` `{open}`: the panel finished opening or closing (Electron
/// keeps the tiles' thumbnails fresh while open).
/// * `error` `{message}`: why the helper is about to exit.
+/// * `windowUnder` `{id, window?}`: the answer, with the request's `id`
+/// (`kCGWindowNumber`; none when no window is there).
public enum NotchProtocol {
/// Bumped on any incompatible change; both sides refuse another.
public static let version = 1
@@ -50,6 +55,10 @@ public enum HostMessage: Equatable {
case state(HostState)
case thumbnail(spaceId: String, image: Data?)
case ghost(image: Data?)
+ /// Which window is at a global top-left point under the dragged window
+ /// `below` (a window drag over the app's own window: is it covered
+ /// there?). Answered with `HelperMessage.windowUnder` and the same `id`.
+ case windowUnder(id: Int, x: Double, y: Double, below: Int?)
case quit
}
@@ -89,7 +98,7 @@ public struct HostState: Equatable, Decodable {
}
extension HostMessage: Decodable {
- private enum Key: String, CodingKey { case type, v, motion, radii, id, image }
+ private enum Key: String, CodingKey { case type, v, motion, radii, id, image, x, y, below }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: Key.self)
@@ -105,6 +114,10 @@ extension HostMessage: Decodable {
image: try Self.image(c))
case "ghost":
self = .ghost(image: try Self.image(c))
+ case "windowUnder":
+ self = .windowUnder(id: try c.decode(Int.self, forKey: .id), x: try c.decode(Double.self, forKey: .x),
+ y: try c.decode(Double.self, forKey: .y),
+ below: try c.decodeIfPresent(Int.self, forKey: .below))
case "quit":
self = .quit
case let other:
@@ -145,10 +158,13 @@ public enum HelperMessage: Equatable {
case action(HelperAction)
case stage(open: Bool)
case error(message: String)
+ /// The answer to `HostMessage.windowUnder`: the window's number
+ /// (`kCGWindowNumber`), none when no window is there.
+ case windowUnder(id: Int, window: Int?)
}
extension HelperMessage: Encodable {
- private enum Key: String, CodingKey { case type, v, pid, notch, primary, event, action, spaceId, pane, paths, open, message }
+ private enum Key: String, CodingKey { case type, v, pid, notch, primary, event, action, spaceId, pane, paths, open, message, id, window }
public func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: Key.self)
@@ -188,6 +204,10 @@ extension HelperMessage: Encodable {
case .error(let message):
try c.encode("error", forKey: .type)
try c.encode(message, forKey: .message)
+ case .windowUnder(let id, let window):
+ try c.encode("windowUnder", forKey: .type)
+ try c.encode(id, forKey: .id)
+ try c.encodeIfPresent(window, forKey: .window)
}
}
diff --git a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/helper-messages.jsonl b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/helper-messages.jsonl
index f53fd856ea..96068cdf6f 100644
--- a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/helper-messages.jsonl
+++ b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/helper-messages.jsonl
@@ -16,3 +16,5 @@
{"action":"drop","paths":["/Applications/Notes.app","/Users/me/report.pdf"],"spaceId":"local:aurora","type":"action"}
{"open":true,"type":"stage"}
{"message":"Electron speaks notch protocol 2; this helper speaks 1","type":"error"}
+{"id":7,"type":"windowUnder","window":4242}
+{"id":8,"type":"windowUnder"}
diff --git a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/host-messages.jsonl b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/host-messages.jsonl
index 7ad2ffc815..4c5b216f8d 100644
--- a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/host-messages.jsonl
+++ b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/Fixtures/host-messages.jsonl
@@ -3,4 +3,5 @@
{"type":"thumbnail","id":"local:aurora","image":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="}
{"type":"thumbnail","id":"cloud:build"}
{"type":"ghost"}
+{"type":"windowUnder","id":7,"x":640.5,"y":412,"below":5120}
{"type":"quit"}
diff --git a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/HelperNotchTests.swift b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/HelperNotchTests.swift
index 3d1d712f06..99cc386fbe 100644
--- a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/HelperNotchTests.swift
+++ b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/HelperNotchTests.swift
@@ -207,6 +207,22 @@ struct HelperNotchTests {
#expect(n.query == "", "the core cleared it (the panel closed)")
}
+ /// A window dragged over the app's own window: the window under the
+ /// dragged one at that point goes back with the request's id.
+ @Test func windowUnderIsAnsweredWithTheRequestsId() throws {
+ let (n, sink) = try notch()
+ var asked: (Double, Double, Int?)?
+ n.windowUnder = { x, y, below in
+ asked = (x, y, below)
+ return x < 1000 ? 4242 : nil
+ }
+ sink.messages = []
+ #expect(n.receive(.windowUnder(id: 7, x: 640.5, y: 412, below: 5120)))
+ #expect(n.receive(.windowUnder(id: 8, x: 2000, y: 10, below: nil)))
+ #expect(sink.messages == [.windowUnder(id: 7, window: 4242), .windowUnder(id: 8, window: nil)])
+ #expect(asked?.0 == 2000 && asked?.2 == nil)
+ }
+
@Test func theSelftestPasses() {
#expect(NotchHelperRunner.selftest() == 0)
}
diff --git a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/ProtocolTests.swift b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/ProtocolTests.swift
index 9e348de6de..a636721eb5 100644
--- a/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/ProtocolTests.swift
+++ b/libs/spaces-notch-swift/Tests/CuaSpacesNotchTests/ProtocolTests.swift
@@ -21,7 +21,7 @@ enum Fixtures {
struct ProtocolTests {
@Test func everyHostMessageDecodes() throws {
let messages = try Fixtures.lines("host-messages.jsonl").map(HostMessage.decode)
- #expect(messages.count == 6)
+ #expect(messages.count == 7)
guard case .hello(let v, let motion, let radii) = messages[0] else { Issue.record("hello"); return }
#expect(v == 1)
#expect(motion.hoverDwellMs == 300 && motion.closeDamping == 1 && motion.contentScale == 0.96)
@@ -51,7 +51,8 @@ struct ProtocolTests {
#expect(id == "local:aurora" && image?.prefix(4) == Data([0x89, 0x50, 0x4E, 0x47]))
#expect(messages[3] == .thumbnail(spaceId: "cloud:build", image: nil))
#expect(messages[4] == .ghost(image: nil))
- #expect(messages[5] == .quit)
+ #expect(messages[5] == .windowUnder(id: 7, x: 640.5, y: 412, below: 5120))
+ #expect(messages[6] == .quit)
}
/// A state with only the view: the rest defaults (shown, nothing else).
@@ -89,6 +90,7 @@ struct ProtocolTests {
.action(.drop(spaceId: "local:aurora", paths: ["/Applications/Notes.app", "/Users/me/report.pdf"])),
.stage(open: true),
.error(message: "Electron speaks notch protocol 2; this helper speaks 1"),
+ .windowUnder(id: 7, window: 4242), .windowUnder(id: 8, window: nil),
]
let expected = try Fixtures.lines("helper-messages.jsonl")
#expect(messages.count == expected.count)