Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 125 additions & 71 deletions apps/server/src/computerUse/ComputerUse.test.ts

Large diffs are not rendered by default.

144 changes: 96 additions & 48 deletions apps/server/src/computerUse/ComputerUse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import { type Capture, captureToScreen } from "./pointerTarget.ts";
import { carryRefs } from "./snapshotTree.ts";
import {
ComputerUseError,
COORDINATE_ACTIONS,
ELEMENTLESS_ACTIONS,
type ComputerAction,
type ComputerStep,
type ElementTarget,
type NativeSnapshot,
type SnapshotOptions,
Expand Down Expand Up @@ -52,18 +51,10 @@ export type SnapshotInput = {
readonly limit?: number | undefined;
readonly includeOffscreen?: boolean | undefined;
};
/** Targets an element by ref, or by exact name (and role) from the latest snapshot. */
export type ActionStep = {
readonly ref?: number | undefined;
readonly name?: string | undefined;
readonly role?: string | undefined;
readonly action: ComputerAction;
};

/** The one snapshot element a step names; undefined when absent or ambiguous. */
export function resolveStepTarget(
elements: readonly ElementTarget[],
step: Pick<ActionStep, "ref" | "name" | "role">,
step: Pick<ComputerStep, "ref" | "name" | "role">,
): ElementTarget | undefined {
if (step.ref !== undefined) return elements.find((element) => element.ref === step.ref);
if (step.name === undefined) return undefined;
Expand All @@ -78,53 +69,110 @@ type ActionRequest = Extract<WorkerRequest, { kind: "action" }>;
export type PlannedStep = Pick<ActionRequest, "action" | "target" | "drop" | "screen">;

/**
* Checks one step against its snapshot and the latest capture, resolving
* element names and mapping capture pixels to screen points. Returns the
* error code that rejects the whole batch when the step cannot run.
* Checks one step against its snapshot and the latest capture, maps its verb to
* the worker action that performs it, resolves element names and maps capture
* pixels to screen points. Returns the error code that rejects the whole batch
* when the step cannot run.
*/
export function planStep(
elements: readonly ElementTarget[],
capture: Capture | undefined,
step: ActionStep,
step: ComputerStep,
): PlannedStep | ComputerUseError["code"] {
const { action } = step;
const named = step.ref !== undefined || step.name !== undefined;
const target = resolveStepTarget(elements, step);
const target = resolveStepTarget(elements, step) ?? null;
if (named && !target) return "invalid_ref";
if (named && COORDINATE_ACTIONS.has(action.kind)) return "invalid_input";
if (action.kind === "key" && !parseKeyChord(action.key)) return "invalid_key";
if (action.kind === "drag") {
// A drag starts from exactly one of the step's element or a capture pixel.
if (named && action.from) return "invalid_input";
if (!named && !action.from) return "invalid_ref";
} else if (!target && !ELEMENTLESS_ACTIONS.has(action.kind)) return "invalid_ref";
if ((step.x === undefined) !== (step.y === undefined)) return "invalid_input";
const point = step.x !== undefined && step.y !== undefined ? { x: step.x, y: step.y } : null;
// A step starts from exactly one of an element or a capture pixel.
if (named && point) return "invalid_input";
const toScreen = (pixel: { readonly x: number; readonly y: number }) =>
capture ? captureToScreen(capture, pixel) : undefined;
const planned = { action, target: target ?? null };
if (action.kind === "click_at" || action.kind === "move_at") {
const to = toScreen(action);
if (!to || !capture) return "invalid_point";
return { ...planned, screen: { window: capture.window, to } };
const foreground = step.foreground === undefined ? {} : { foreground: step.foreground };
const plan = (action: ComputerAction, more?: Pick<PlannedStep, "drop" | "screen">) => ({
action,
target,
...more,
});
switch (step.action) {
case "click":
case "hover": {
const click = { button: step.button ?? "left", count: step.clickCount ?? 1, ...foreground };
// The worker lands a single click on an element listing press (show_menu for
// right) through that accessibility action.
if (target)
return plan(
step.action === "click" ? { kind: "click", ...click } : { kind: "move", ...foreground },
);
if (!point) return "invalid_ref";
const to = toScreen(point);
if (!to || !capture) return "invalid_point";
return plan(
step.action === "click"
? { kind: "click_at", ...point, ...click }
: { kind: "move_at", ...point, ...foreground },
{ screen: { window: capture.window, to } },
);
}
case "drag": {
if (!step.target) return "invalid_input";
if (!target && !point) return "invalid_ref";
const from = point ? toScreen(point) : undefined;
if (point && !from) return "invalid_point";
let to: ReturnType<typeof toScreen>;
let drop: ElementTarget | undefined;
if ("x" in step.target) {
to = toScreen(step.target);
if (!to) return "invalid_point";
} else {
drop = resolveStepTarget(elements, step.target);
if (!drop) return "invalid_ref";
}
return plan(
{ kind: "drag", ...(point ? { from: point } : {}), to: step.target, ...foreground },
{
...(drop ? { drop } : {}),
...(capture && (from || to)
? {
screen: {
window: capture.window,
...(from ? { from } : {}),
...(to ? { to } : {}),
},
}
: {}),
},
);
}
}
if (point) return "invalid_input";
switch (step.action) {
case "press": {
if (step.key === undefined) return "invalid_input";
const key = [...(step.modifiers ?? []), step.key].join("+");
if (!parseKeyChord(key)) return "invalid_key";
return plan({ kind: "key", key, ...(step.repeat ? { repeat: step.repeat } : {}) });
}
case "menu":
return step.path ? plan({ kind: "menu", path: step.path }) : "invalid_input";
case "wait":
return step.ms === undefined ? "invalid_input" : plan({ kind: "wait", ms: step.ms });
}
if (action.kind !== "drag") return planned;
const from = action.from && toScreen(action.from);
if (action.from && !from) return "invalid_point";
let to: ReturnType<typeof toScreen>;
let drop: ElementTarget | undefined;
if ("x" in action.to) {
to = toScreen(action.to);
if (!to) return "invalid_point";
} else {
drop = resolveStepTarget(elements, action.to);
if (!drop) return "invalid_ref";
if (!target) return "invalid_ref";
switch (step.action) {
case "type":
return step.text === undefined
? "invalid_input"
: plan({ kind: "type", text: step.text, replace: step.clear ?? false });
case "scroll":
return step.deltaX === undefined && step.deltaY === undefined
? "invalid_input"
: plan({ kind: "scroll", dx: step.deltaX ?? 0, dy: step.deltaY ?? 0, ...foreground });
case "perform":
return step.perform === undefined
? "invalid_input"
: plan({ kind: "perform", action: step.perform });
}
return {
...planned,
...(drop ? { drop } : {}),
...(capture && (from || to)
? { screen: { window: capture.window, ...(from ? { from } : {}), ...(to ? { to } : {}) } }
: {}),
};
}
export type Observation = NativeSnapshot & {
readonly snapshotId: string;
Expand Down Expand Up @@ -169,7 +217,7 @@ export class ComputerUse extends Context.Service<
caller: string,
input: {
readonly snapshotId: string;
readonly steps: readonly ActionStep[];
readonly steps: readonly ComputerStep[];
readonly includeImage?: boolean | undefined;
},
) => Effect.Effect<ActResult, ComputerUseError>;
Expand Down
96 changes: 61 additions & 35 deletions apps/server/src/computerUse/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,69 @@ const PixelCoordinate = Schema.Number.check(
);
/** A pixel in the latest window capture of the app (includeImage=true). */
const ImagePoint = Schema.Struct({ x: PixelCoordinate, y: PixelCoordinate });
const ElementName = Schema.String.check(Schema.isMaxLength(500));
const ElementRole = Schema.String.check(Schema.isMaxLength(64));
/** An element of the same snapshot, by ref or exact name (plus role when names repeat). */
const ElementRef = Schema.Union([
Schema.Struct({ ref: Schema.Int }),
Schema.Struct({
name: Schema.String.check(Schema.isMaxLength(500)),
role: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(64))),
}),
Schema.Struct({ name: ElementName, role: Schema.optionalKey(ElementRole) }),
]);
const KeySpec = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64));
const KeyRepeat = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }));
const MenuPath = Schema.Array(
Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(200)),
).check(Schema.isMinLength(1), Schema.isMaxLength(6));
const WaitMs = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 5000 }));
/**
* Pointer steps reach the app in the background by default. `foreground: true`
* instead moves the user's real pointer, bringing the app forward first when
* the user is idle, for the rare control that ignores posted input.
*/
const Foreground = { foreground: Schema.optionalKey(Schema.Boolean) };

/**
* One computer_action step, in the flat shape and field names of upstream's
* preview_act, so agents drive apps and tabs with the same verbs. A step
* targets an element (ref, or name plus role) or a capture pixel (x, y);
* planStep checks the fields its action needs and maps it to a worker action.
*/
export const ComputerStep = Schema.Struct({
action: Schema.Literals([
"click",
"hover",
"type",
"press",
"scroll",
"drag",
"perform",
"menu",
"wait",
]),
ref: Schema.optionalKey(Schema.Int),
name: Schema.optionalKey(ElementName),
role: Schema.optionalKey(ElementRole),
x: Schema.optionalKey(PixelCoordinate),
y: Schema.optionalKey(PixelCoordinate),
button: Schema.optionalKey(Schema.Literals(["left", "right"])),
clickCount: Schema.optionalKey(Schema.Literals([1, 2])),
text: Schema.optionalKey(BoundedText),
clear: Schema.optionalKey(Schema.Boolean),
key: Schema.optionalKey(KeySpec),
modifiers: Schema.optionalKey(Schema.Array(Schema.Literals(["Alt", "Control", "Meta", "Shift"]))),
repeat: Schema.optionalKey(KeyRepeat),
deltaX: Schema.optionalKey(ScrollDelta),
deltaY: Schema.optionalKey(ScrollDelta),
/** Where a drag drops. */
target: Schema.optionalKey(Schema.Union([ImagePoint, ElementRef])),
/** An accessibility action the element lists, such as expand or raise. */
perform: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(128))),
path: Schema.optionalKey(MenuPath),
ms: Schema.optionalKey(WaitMs),
...Foreground,
});
export type ComputerStep = typeof ComputerStep.Type;

/** What the native worker runs for one planned step. */
export const ComputerAction = Schema.Union([
Schema.Struct({ kind: Schema.Literal("press") }),
Schema.Struct({ kind: Schema.Literal("move"), ...Foreground }),
Expand All @@ -48,21 +97,12 @@ export const ComputerAction = Schema.Union([
// A key or shortcut such as "Return", "Escape", "Down" or "cmd+shift+t".
Schema.Struct({
kind: Schema.Literal("key"),
key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)),
repeat: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),
key: KeySpec,
repeat: Schema.optionalKey(KeyRepeat),
}),
// A menu bar command by titles, such as ["File", "New Window"].
Schema.Struct({
kind: Schema.Literal("menu"),
path: Schema.Array(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(200))).check(
Schema.isMinLength(1),
Schema.isMaxLength(6),
),
}),
Schema.Struct({
kind: Schema.Literal("wait"),
ms: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 5000 })),
}),
Schema.Struct({ kind: Schema.Literal("menu"), path: MenuPath }),
Schema.Struct({ kind: Schema.Literal("wait"), ms: WaitMs }),
// Pointer input at a pixel of the latest window capture, for content
// without usable accessibility controls (canvases, games, custom views).
Schema.Struct({
Expand All @@ -81,20 +121,6 @@ export const ComputerAction = Schema.Union([
...Foreground,
}),
]);
/** Actions that need no element target. A key may optionally focus one first. Drag needs one
* unless it starts from a capture pixel. */
export const ELEMENTLESS_ACTIONS: ReadonlySet<ComputerAction["kind"]> = new Set([
"key",
"menu",
"wait",
"click_at",
"move_at",
]);
/** Actions positioned by capture pixels, which never take an element target. */
export const COORDINATE_ACTIONS: ReadonlySet<ComputerAction["kind"]> = new Set([
"click_at",
"move_at",
]);
export type ComputerAction = typeof ComputerAction.Type;

const Bounds = Schema.Struct({
Expand Down Expand Up @@ -320,19 +346,19 @@ export class ComputerUseError extends Schema.TaggedError<ComputerUseError>()("Co
return "macOS has not granted Accessibility permission to the process running the T3 native helper. Ask the user to grant it to the T3 host on that machine.";
return "The environment needs operating-system Accessibility or Screen Recording permission. Ask the user to grant it on that machine.";
case "target_changed":
return "The app, element or captured window changed. Take a fresh computer_snapshot before acting (with includeImage=true for click_at, move_at or drag coordinates).";
return "The app, element or captured window changed. Take a fresh computer_snapshot before acting (with includeImage=true for steps at x, y).";
case "app_not_running":
return "That app is not running on the environment machine. Open it with computer_open.";
case "unsupported_action":
return "This element does not support that accessibility action. Use an action listed in a fresh snapshot.";
case "capture_requires_foreground":
return "The app has no visible window to capture. Open or unminimize one, or use includeImage=false.";
case "input_requires_foreground":
return "This step needs the user's real pointer (foreground: true), and the target was not reachable: the app has no window there, or it is in the background and pointer takeover is off, or another window still covers the target. Prefer press, type, key, menu, an action listed for the element, or the same pointer step without foreground; those run in the background. Otherwise ask the user to bring the app forward or turn on pointer takeover in Settings > Integrations > Computer use, then take a fresh snapshot.";
return "This step needs the user's real pointer (foreground: true), and the target was not reachable: the app has no window there, or it is in the background and pointer takeover is off, or another window still covers the target. Prefer a click on an element listing press, type, press, menu, perform, or the same pointer step without foreground; those run in the background. Otherwise ask the user to bring the app forward or turn on pointer takeover in Settings > Integrations > Computer use, then take a fresh snapshot.";
case "user_active":
return "The user is using this machine right now, so the agent did not take over the pointer for this foreground step. Prefer press, type, key, menu, an action listed for the element, or the same pointer step without foreground; those run in the background. Otherwise ask the user to leave the mouse and keyboard alone for a few seconds, or to bring the app forward, and retry later.";
return "The user is using this machine right now, so the agent did not take over the pointer for this foreground step. Prefer a click on an element listing press, type, press, menu, perform, or the same pointer step without foreground; those run in the background. Otherwise ask the user to leave the mouse and keyboard alone for a few seconds, or to bring the app forward, and retry later.";
case "invalid_point":
return "click_at, move_at and drag coordinates are pixels of the app's latest window image and must lie inside it. Take computer_snapshot with includeImage=true and read coordinates from that image.";
return "A step's x, y and a drag target's x, y are pixels of the app's latest window image and must lie inside it. Take computer_snapshot with includeImage=true and read coordinates from that image.";
case "menu_not_found":
return `No enabled menu item matched that path.${this.available?.length ? ` Available here: ${this.available.join(", ")}.` : ""}`;
case "invalid_key":
Expand Down
Loading
Loading