Skip to content

Commit c931496

Browse files
authored
feat(computer-use): work in Mac app windows in the background (#6606)
* feat(computer-use): work in Mac app windows in the background Behind the new computerUseBackground feature (off by default), control sessions on This Mac work in their window where it is: the helper makes it the app's key window with WindowServer event records instead of raising it and activating the app, posts pointer and key events to the app's process, primes Chromium's user-gesture check before a click, and reads the window without bringing it forward. The person's front app, cursor and Space stay as they are, so they keep working and several chats work at once. Background sessions skip the per-computer turn queue, the focus lock and the typing-gap wait; keys are sent only while the window is the app's key window and the observed field still has focus. Blender and Unity keep the foreground path, as does any Mac without the private calls. Observations in background sessions read the accessibility tree first and skip the screenshot when it names at least eight controls; include_image true still asks for one. Every action receipt reports its delivery and whether the front app, cursor or Space changed, and the real-app check prints that per scenario. Signed-off-by: Jalil <reachjalil@gmail.com> * fix(computer-use): take the front for steps that need it in background sessions Menu shortcuts, modified clicks, hover, drags and keys to Chromium, Electron and Catalyst apps do nothing when sent to an app in the background, so those steps now take the front through the shared-desktop path; a step whose window had to come forward and that uses coordinates asks for a fresh look and sends nothing. Clicks send the app only the focus record; keys add the make-key pair and read the app's focused window back, retrying once, and a session whose app never focuses the window takes the front from then on. Hit tests in the background ask the app, not the screen, what is under the point, so a covered window can still be clicked. Background sessions launch apps without activating them, read a background app's focused window, flag a focused dialog, keep games and Qt, wxWidgets and Tk apps in front, and the Chromium primer press is no longer tracked or shown. Signed-off-by: Jalil <reachjalil@gmail.com> * fix(computer-use): one agent at a time changes an app's key window An app sends keys to its one key window. Background sessions in different windows of the same app ran at once, so one could make its window key between another's check and its keys, and that agent's text landed in the wrong window. Every control step that can change the key window (a background focus or make-key record, or bringing a window forward to open, look, act or continue) now holds a cross-process lock for the app until its input is sent. Sessions in different apps still work at the same time; the lock is taken after the keyboard focus lock, never before. Signed-off-by: Jalil <reachjalil@gmail.com> --------- Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent fb8f433 commit c931496

20 files changed

Lines changed: 710 additions & 78 deletions

File tree

‎apps/app/src/react-app/domains/session/computer/computer-store.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,16 +32,22 @@ export const useComputerRequest = (sessionId: string | null | undefined) =>
3232

3333
/**
3434
* Connects the desktop's computer broker to the app, once per window and on
35-
* every route, Settings included: reports the `computerUse` and
36-
* `remoteComputers` features and keeps in-chat requests current.
35+
* every route, Settings included: reports the `computerUse`,
36+
* `remoteComputers` and `computerUseBackground` features and keeps in-chat
37+
* requests current.
3738
*/
3839
export function ComputerBridge() {
3940
const enabled = useDesktopFeature("computerUse")
4041
const remote = useDesktopFeature("remoteComputers")
42+
const background = useDesktopFeature("computerUseBackground")
4143
useEffect(() => {
4244
void desktopBridge.computerSetRemoteEnabled(enabled && remote).catch(() => {})
4345
}, [enabled, remote])
4446

47+
useEffect(() => {
48+
void desktopBridge.computerSetBackgroundEnabled(enabled && background).catch(() => {})
49+
}, [enabled, background])
50+
4551
useEffect(() => {
4652
void desktopBridge.computerSetFeatureEnabled(enabled).catch(() => {})
4753
if (!enabled) return

‎apps/app/src/react-app/domains/session/status/use-desktop-feature.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { useAutomationsDenContext } from "@/react-app/domains/automations/use-au
88

99
const FEATURE_STALE_MS = 30_000
1010

11-
type DesktopFeatureKey = "computerUse" | "browserFloatingView" | "remoteComputers" | "mermaidZoom" | "providerCredentialStatus"
11+
type DesktopFeatureKey = "computerUse" | "computerUseBackground" | "browserFloatingView" | "remoteComputers" | "mermaidZoom" | "providerCredentialStatus"
1212

1313
/**
1414
* Reads one desktop feature from the registry. Signed in, it follows the

‎apps/desktop/electron/computer-control.test.mjs‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ function fixture(options = {}) {
3131
protocol: COMPUTER_PROTOCOL,
3232
setup: async () => ({ setupId: "setup" }),
3333
readiness: options.readiness ?? (async () => ({ readiness: "ready", detail: "Ready" })),
34-
connect: async ({ onClose, onUi }) => {
34+
connect: async ({ onClose, onUi, background }) => {
3535
calls.push("connect");
36+
options.connected?.push({ background: background === true });
3637
emit = onUi; disconnect = onClose;
3738
let paused = false;
3839
return {
@@ -545,14 +546,17 @@ test("Blender scripts reach the bridge with its token, and an open Blender witho
545546
function parallelFixture(options = {}) {
546547
const events = [];
547548
let connections = 0;
549+
/** The connect options each helper started with. */
550+
const started = [];
548551
const windows = { blender: 11, photoshop: 12, notes: 13 };
549552
/** @type {import("@openwork/computer-use/computer-control").ComputerAdapter} */
550553
const adapter = {
551554
id: "local", label: "This Mac", placement: "local", parallel: true, protocol: COMPUTER_PROTOCOL,
552555
setup: async () => ({ setupId: "setup" }),
553556
readiness: async () => ({ readiness: "ready", detail: "Ready" }),
554-
connect: async ({ onUi, onClose }) => {
557+
connect: async ({ onUi, onClose, background }) => {
555558
connections++;
559+
started.push({ background: background === true });
556560
let app = "";
557561
return {
558562
callTool: async (name, args) => {
@@ -562,19 +566,20 @@ function parallelFixture(options = {}) {
562566
events.push(`${app}:${name}:end`);
563567
if (name === "computer_open_session") {
564568
onUi({ kind: "state", id: `view-${app}`, phase: "working", appID: app, appName: app, windowTitle: app, mode: args.mode, task: args.purpose });
565-
return text({ ok: true, session_id: `native-${app}`, window_id: args.window_id ?? windows[app], state: "active" });
569+
return text({ ok: true, session_id: `native-${app}`, window_id: args.window_id ?? windows[app], state: "active",
570+
...(options.delivery ? { delivery: options.delivery(app) } : {}) });
566571
}
567572
if (name === "computer_session_status") return text({ ok: true, state: "active" });
568573
if (name === "computer_act") return text({ ok: true, status: "dispatched" });
569574
return text({ ok: true, ...(name === "computer_observe" ? { observation_id: `observation-${app}` } : {}) });
570575
},
571576
notifyUi: async (value) => { if (value.action === "takeover") onUi({ kind: "state", id: `view-${app}`, phase: "paused", canContinue: true }); },
572-
close: async () => { onClose(); },
577+
close: async () => { events.push(`${app}:close`); onClose(); },
573578
};
574579
},
575580
};
576581
const control = createComputerControl({ adapters: [adapter] });
577-
return { control, events, connections: () => connections };
582+
return { control, events, started, connections: () => connections };
578583
}
579584
const openApp = (control, sessionId, app, mode = "control", windowId) =>
580585
control.execute({ sessionId, name: "computer_open", args: { app_id: app, mode, purpose: `Work in ${app}`, ...(windowId ? { window_id: windowId } : {}) } });
@@ -690,3 +695,59 @@ test("chats on different computers no longer block each other", async (t) => {
690695
assert.equal(payload(await f.control.execute({ sessionId: "chat-other", name: "computer_open", args: { app_id: "editor", mode: "control", purpose: "Edit" } })).code, "computer_busy",
691696
"a computer that is not parallel still serves one chat");
692697
});
698+
699+
test("background sessions act at the same time instead of taking turns", async (t) => {
700+
const started = deferred(); const gate = deferred();
701+
const f = parallelFixture({ delivery: () => "background",
702+
beforeTool: async (name, app) => { if (name === "computer_act" && app === "blender") { started.resolve(); await gate.promise; } } });
703+
t.after(() => f.control.reset(true));
704+
await f.control.setFeatureEnabled(true);
705+
await f.control.setBackgroundEnabled(true);
706+
await openApp(f.control, "chat-blender", "blender");
707+
await openApp(f.control, "chat-photoshop", "photoshop");
708+
assert.deepEqual(f.started, [{ background: true }, { background: true }], "each helper starts with background delivery");
709+
const blender = click(f.control, "chat-blender");
710+
await started.promise;
711+
assert.equal(payload(await click(f.control, "chat-photoshop")).status, "dispatched", "the second chat acts while the first one's input is still running");
712+
gate.resolve();
713+
await blender;
714+
});
715+
716+
test("a session the helper keeps in front still takes turns, without holding up background ones", async (t) => {
717+
const started = deferred(); const gate = deferred();
718+
const f = parallelFixture({ delivery: (app) => app === "photoshop" ? "background" : "foreground",
719+
beforeTool: async (name, app) => { if (name === "computer_act" && app === "blender") { started.resolve(); await gate.promise; } } });
720+
t.after(() => f.control.reset(true));
721+
await f.control.setFeatureEnabled(true);
722+
await f.control.setBackgroundEnabled(true);
723+
for (const app of ["blender", "photoshop", "notes"]) await openApp(f.control, `chat-${app}`, app);
724+
const blender = click(f.control, "chat-blender");
725+
await started.promise;
726+
const notes = click(f.control, "chat-notes");
727+
assert.equal(payload(await click(f.control, "chat-photoshop")).status, "dispatched");
728+
await settle();
729+
assert.ok(!f.events.includes("notes:computer_act:start"), "another foreground session waits for its turn");
730+
gate.resolve();
731+
await Promise.all([blender, notes]);
732+
assert.ok(f.events.indexOf("blender:computer_act:end") < f.events.indexOf("notes:computer_act:start"));
733+
});
734+
735+
test("turning background off hands idle sessions back so the next call starts in front", async (t) => {
736+
const f = parallelFixture({ delivery: () => "background" }); t.after(() => f.control.reset(true));
737+
await f.control.setFeatureEnabled(true);
738+
await f.control.setBackgroundEnabled(true);
739+
await openApp(f.control, "chat-notes", "notes");
740+
await f.control.setBackgroundEnabled(false);
741+
assert.ok(f.events.includes("notes:close"), "the idle background session was handed back");
742+
assert.equal(payload(await f.control.execute({ sessionId: "chat-notes", name: "computer_observe", args: {} })).ok, true);
743+
assert.deepEqual(f.started.at(-1), { background: false });
744+
});
745+
746+
test("background stays off on a computer that is not parallel", async (t) => {
747+
const connected = [];
748+
const f = fixture({ connected }); t.after(() => f.control.reset(true));
749+
await f.control.setFeatureEnabled(true);
750+
await f.control.setBackgroundEnabled(true);
751+
assert.equal(payload(await f.control.execute({ sessionId: "chat", name: "computer_open", args: { app_id: "editor", mode: "control", purpose: "Edit" } })).ok, true);
752+
assert.deepEqual(connected, [{ background: false }]);
753+
});

‎apps/desktop/electron/computer-local.mjs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -387,11 +387,12 @@ export function createLocalComputerAdapter({
387387
* @param {{
388388
* signal?: AbortSignal,
389389
* presence?: { name?: string, color?: string },
390+
* background?: boolean,
390391
* onUi?: (params: unknown) => void,
391392
* onClose?: () => void,
392393
* }} [options]
393394
*/
394-
async connect({ signal, onUi = () => {}, onClose = () => {}, presence } = {}) {
395+
async connect({ signal, onUi = () => {}, onClose = () => {}, presence, background = false } = {}) {
395396
signal?.throwIfAborted();
396397
await dismissSetup();
397398
const state = await inspect();
@@ -404,7 +405,9 @@ export function createLocalComputerAdapter({
404405
const hex = (value) => typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value);
405406
const shown = typeof presence?.name === "string" && presence.name.trim() && hex(presence.color)
406407
? { OPENWORK_COMPUTER_USE_PRESENCE: JSON.stringify({ name: presence.name.trim().slice(0, 32), color: presence.color }) } : {};
407-
const transport = new StdioClientTransport({ command: state.binary, args: ["mcp-embedded"], env: { ...env, ...shown }, stderr: "ignore" });
408+
// Set only while `computerUseBackground` is on: the helper then works behind other windows.
409+
const delivery = background ? { OPENWORK_COMPUTER_USE_DELIVERY: "background" } : {};
410+
const transport = new StdioClientTransport({ command: state.binary, args: ["mcp-embedded"], env: { ...env, ...shown, ...delivery }, stderr: "ignore" });
408411
let closed = false;
409412
let terminationConfirmed = false;
410413
let busy = false;

‎apps/desktop/electron/main.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2074,6 +2074,10 @@ const desktopCommandHandlers = {
20742074
assertComputerSender(event);
20752075
return computerControl.setRemoteEnabled(enabled === true);
20762076
},
2077+
"computerSetBackgroundEnabled": async (event, enabled) => {
2078+
assertComputerSender(event);
2079+
return computerControl.setBackgroundEnabled(enabled === true);
2080+
},
20772081
"computerResetPermission": async (event, permission) => {
20782082
assertComputerSender(event);
20792083
if (permission !== "accessibility" && permission !== "screenRecording") throw new Error("Choose Accessibility or Screen Recording.");
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Computer use in the background
2+
3+
- **Feature key:** `computerUseBackground`
4+
- **Deployments:** cloud and self-hosted
5+
- **Author:** reachjalil
6+
- **Default:** off. Needs `computerUse`.
7+
8+
## What people get
9+
10+
On a Mac, an agent with control of an app window works in that window where
11+
it is. The window is not brought to the front, the person's cursor does not
12+
move and their Space does not change, so they keep working in their own apps.
13+
Several chats can each work in their own window at the same time.
14+
15+
Agents also read the window's accessibility tree first. An observation skips
16+
the screenshot when the tree names at least eight controls to act on, and the
17+
agent asks for an image (`include_image: true`) when it needs coordinates.
18+
19+
Some apps and steps still need the front, and get it the way they did before
20+
(the window comes forward, then is handed back):
21+
22+
- whole sessions in Blender, Unity, Unreal, games, and apps built with Qt,
23+
wxWidgets or Tk, which read only real pointer input;
24+
- single steps in any app: menu shortcuts (⌘ keys), clicks with modifier
25+
keys, hover, drags, and typing in Chromium, Electron and Catalyst apps.
26+
When such a step needs the window brought forward and uses coordinates,
27+
nothing is sent and the agent is asked to look again.
28+
29+
## How it works
30+
31+
- Desktop reports the feature to the computer broker
32+
(`computerSetBackgroundEnabled`). New sessions on This Mac start the helper
33+
with background delivery; turning it off hands idle sessions back and the
34+
next call reopens them in the foreground.
35+
- The helper decides per session (`InputDelivery.decide`): background for
36+
control sessions, foreground for the apps above or when the private calls
37+
below are missing on that macOS. Background sessions launch apps without
38+
activating them. Per step, `InputDelivery.stepNeedsFront` picks the steps
39+
that take the front anyway. The open result carries the session's
40+
`delivery`; every action receipt carries the step's.
41+
- Background input never raises the window or activates the app, and never
42+
sends the person's front app anything. Before a click it sends the app one
43+
WindowServer focus record for the window (`SLPSPostEventRecordTo`); before
44+
keys it also sends the make-key pair and reads the app's focused window back.
45+
Pointer events go to the app's process (`SLEventPostToPid` for Chromium,
46+
Electron and Catalyst apps, `postToPid` for others), with a discarded press
47+
outside every window first for Chromium's user-gesture check. Hit tests ask
48+
the app, not the screen, what is under the point.
49+
- Keys are sent only when the app reports the target window as focused and the
50+
observed field still has focus. If the app never focuses it, nothing is typed
51+
(`background_keys_unavailable`) and the session's later steps take the front.
52+
- Background steps skip the per-computer turn queue, the focus lock and the
53+
typing-gap wait. The person's own clicks and typing stop a background step
54+
only when they are in the agent's app. Steps that take the front use the
55+
existing shared-desktop path and the cross-process focus lock.
56+
- An app sends keys to its one key window, so sessions in different windows
57+
of the same app take turns: every control step that can change that window
58+
(a background focus or make-key record, or bringing a window forward) holds
59+
the app's cross-process lock until its input is sent. Sessions in different
60+
apps still work at the same time.
61+
62+
## How to try it
63+
64+
1. Turn on `computerUse` and `computerUseBackground` for your organization.
65+
2. Ask an agent to work in TextEdit or Notes while you keep using another app.
66+
3. Run the real-app check with the desktop open:
67+
`pnpm --filter @openwork/computer-use prove:mac-apps`. Each action receipt
68+
includes `desktop.front_app_changed`, `desktop.cursor_moved` and
69+
`desktop.space_changed`; in background sessions all three should stay
70+
`false` unless the person moved something themselves.
71+
72+
## Turning it off
73+
74+
The kill switch or turning the feature off hands idle sessions back at once;
75+
a call already running finishes as it started. The next call opens a
76+
foreground session, the behavior before this feature. Nothing is stored.
77+
78+
## What to watch
79+
80+
- Receipts with `delivery: "background"` and `settled: false` or
81+
`background_keys_unavailable`: the app ignored background input. Add its
82+
bundle id to `InputDelivery.foregroundBundlePrefixes`.
83+
- The private SkyLight calls can change with a macOS release. When a symbol is
84+
missing, sessions fall back to the foreground on their own; check the
85+
real-app run on each new macOS.

0 commit comments

Comments
 (0)