Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

release-app add ability to scroll in operator

Louis Beaumontbaff60ad1fce
diff --git a/pipes/hello-world-computer-use/bun.lockb b/pipes/hello-world-computer-use/bun.lockb
index eb7925ad0..18747c88b 100755
Binary files a/pipes/hello-world-computer-use/bun.lockb and b/pipes/hello-world-computer-use/bun.lockb differ
diff --git a/pipes/hello-world-computer-use/components/chat.tsx b/pipes/hello-world-computer-use/components/chat.tsx
index 793cf2482..a7880492a 100644
--- a/pipes/hello-world-computer-use/components/chat.tsx
+++ b/pipes/hello-world-computer-use/components/chat.tsx
@@ -141,50 +141,40 @@ export const Chat = () => {
Be as specific as possible when selecting elements by role. If a role does not work, try a different role.
`,
- onChunk: (chunk) => {
- console.log(chunk);
- },
+ // onChunk: (chunk) => {
+ // console.log(chunk);
+ // },
onError: (error) => {
console.log(JSON.stringify(error, null, 2));
},
tools: {
- // click: {
- // description: "Click an element in an application",
- // parameters: z.object({
- // app: z.string().describe("The name of the application"),
- // window: z.string().optional().describe("Optional window name"),
- // text: z
- // .string()
- // .optional()
- // .describe("Text content of the element to click"),
- // role: z.string().optional().describe("Role of the element"),
- // label: z
- // .string()
- // .optional()
- // .describe("Accessibility label of the element"),
- // }),
- // execute: async ({ app, window, text, role, label }) => {
- // console.log("[tool:click] params:", {
- // app,
- // window,
- // text,
- // role,
- // label,
- // });
- // try {
- // const result = await pipe.operator.click({
- // app,
- // window,
- // role,
- // });
- // console.log("[tool:click] result:", result);
- // return `Successfully clicked element using ${result.method}`;
- // } catch (error) {
- // console.error("[tool:click] error:", error);
- // throw new Error(`Failed to click element: ${error}`);
- // }
- // },
- // },
+ click: {
+ description: "Click an element in an application",
+ parameters: z.object({
+ app: z.string().describe("The name of the application"),
+ id: z.string().optional().describe("Id of the element"),
+ }),
+ execute: async ({ app, id }) => {
+ console.log("[tool:click] params:", {
+ app,
+ id,
+ });
+ try {
+ const result = await pipe.operator
+ .getById(id, {
+ app,
+ activateApp: true,
+ useBackgroundApps: true,
+ })
+ .click();
+ console.log("[tool:click] result:", result);
+ return `Successfully clicked element using ${result.method}`;
+ } catch (error) {
+ console.error("[tool:click] error:", error);
+ throw new Error(`Failed to click element: ${error}`);
+ }
+ },
+ },
fill: {
description: "Fill text in a form field",
@@ -201,14 +191,12 @@ export const Chat = () => {
});
try {
const success = await pipe.operator
- .fill({
- value,
+ .getById(id, {
app,
- id,
- });
- // const success = await pipe.operator
- // .getById(id, { app })
- // .fill(value);
+ activateApp: true,
+ useBackgroundApps: true,
+ })
+ .fill(value);
console.log("[tool:fill] result:", success);
return success
? `Successfully entered text`
@@ -227,6 +215,9 @@ export const Chat = () => {
}),
execute: async ({ appName }) => {
try {
+ console.log("[tool:open_application] params:", {
+ appName,
+ });
const success = await pipe.operator.openApplication(appName);
return success
? `Successfully opened application '${appName}'`
@@ -258,17 +249,14 @@ export const Chat = () => {
},
find_by_role: {
- description:
- "Find elements with a specific role",
+ description: "Find elements with a specific role",
parameters: z.object({
app: z
.string()
.describe(
"The application name (e.g., 'Chrome', 'Firefox', 'Arc')"
),
- role: z
- .string()
- .describe("The role to search for"),
+ role: z.string().describe("The role to search for"),
maxResults: z
.number()
.optional()
@@ -282,10 +270,13 @@ export const Chat = () => {
});
try {
const elements = await pipe.operator
- .getByRole(role, { app })
+ .getByRole(role, {
+ app,
+ activateApp: true,
+ useBackgroundApps: true,
+ })
.all(maxResults);
console.log("[tool:find_by_role] found elements:", elements);
- currentSelectedElement = elements[0];
return JSON.stringify(elements);
} catch (error) {
console.error("[tool:find_by_role] error:", error);
@@ -293,9 +284,45 @@ export const Chat = () => {
}
},
},
+
+ scroll: {
+ description: "Scroll an element in a specific direction",
+ parameters: z.object({
+ app: z.string().describe("The name of the application"),
+ id: z.string().optional().describe("Id of the element"),
+ direction: z
+ .enum(["up", "down", "left", "right"])
+ .describe("Direction to scroll"),
+ amount: z.number().describe("Amount to scroll in pixels"),
+ }),
+ execute: async ({ app, id, direction, amount }) => {
+ console.log("[tool:scroll] params:", {
+ app,
+ id,
+ direction,
+ amount,
+ });
+ try {
+ const success = await pipe.operator
+ .getById(id, {
+ app,
+ activateApp: true,
+ useBackgroundApps: true,
+ })
+ .scroll(direction, amount);
+ console.log("[tool:scroll] result:", success);
+ return success
+ ? `Successfully scrolled element ${direction} by ${amount}px`
+ : "Failed to scroll element";
+ } catch (error) {
+ console.error("[tool:scroll] error:", error);
+ throw new Error(`Failed to scroll element: ${error}`);
+ }
+ },
+ },
},
toolCallStreaming: true,
- maxSteps: 5,
+ maxSteps: 10,
});
for await (const chunk of result.textStream) {
diff --git a/pipes/hello-world-computer-use/package.json b/pipes/hello-world-computer-use/package.json
index 98eb28290..a98c03977 100644
--- a/pipes/hello-world-computer-use/package.json
+++ b/pipes/hello-world-computer-use/package.json
@@ -29,7 +29,7 @@
"@radix-ui/react-tabs": "^1.1.3",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-tooltip": "^1.1.8",
- "@screenpipe/browser": "^0.1.38-beta.7",
+ "@screenpipe/browser": "^0.1.38-beta.10",
"@screenpipe/js": "^1.0.19-beta.8",
"@types/express": "^5.0.1",
"@types/lodash": "^4.17.16",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index cb48a83d2..10170f761 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.43.5"
+version = "0.43.6"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index b99b7b2b0..713989436 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -69,4 +69,4 @@ objc = "0.2.7"
objc-foundation = "0.1.1"
core-foundation = "=0.10.0"
-core-graphics = "=0.24.0"
+core-graphics = { version = "0.24.0", features = ["highsierra"] }
diff --git a/screenpipe-core/src/operator/element.rs b/screenpipe-core/src/operator/element.rs
index fb05ffe58..eb6fabd65 100644
--- a/screenpipe-core/src/operator/element.rs
+++ b/screenpipe-core/src/operator/element.rs
@@ -45,6 +45,7 @@ pub(crate) trait UIElementImpl: Send + Sync + Debug {
fn perform_action(&self, action: &str) -> Result<(), AutomationError>;
fn as_any(&self) -> &dyn std::any::Any;
fn create_locator(&self, selector: Selector) -> Result<Locator, AutomationError>;
+ fn scroll(&self, direction: &str, amount: f64) -> Result<(), AutomationError>;
// Add a method to clone the box
fn clone_box(&self) -> Box<dyn UIElementImpl>;
@@ -161,6 +162,11 @@ impl UIElement {
let selector = selector.into();
self.inner.create_locator(selector)
}
+
+ /// Scroll the element in a given direction
+ pub fn scroll(&self, direction: &str, amount: f64) -> Result<(), AutomationError> {
+ self.inner.scroll(direction, amount)
+ }
}
impl PartialEq for UIElement {
diff --git a/screenpipe-core/src/operator/platforms/linux.rs b/screenpipe-core/src/operator/platforms/linux.rs
index fd33d5124..7739a7106 100644
--- a/screenpipe-core/src/operator/platforms/linux.rs
+++ b/screenpipe-core/src/operator/platforms/linux.rs
@@ -211,4 +211,10 @@ impl UIElementImpl for LinuxUIElement {
fn clone_box(&self) -> Box<dyn UIElementImpl> {
Box::new(LinuxUIElement)
}
+
+ fn scroll(&self, _direction: &str, _amount: f64) -> Result<(), AutomationError> {
+ Err(AutomationError::UnsupportedPlatform(
+ "Linux implementation is not yet available".to_string(),
+ ))
+ }
}
diff --git a/screenpipe-core/src/operator/platforms/macos.rs b/screenpipe-core/src/operator/platforms/macos.rs
index 0b249f3c9..5632c6770 100644
--- a/screenpipe-core/src/operator/platforms/macos.rs
+++ b/screenpipe-core/src/operator/platforms/macos.rs
@@ -965,20 +965,35 @@ impl std::fmt::Debug for MacOSUIElement {
impl MacOSUIElement {
// Helper function to get the containing application
fn get_application(&self) -> Option<MacOSUIElement> {
- let attr = AXAttribute::new(&CFString::new("AXTopLevelUIElement"));
- match self.element.0.attribute(&attr) {
- Ok(value) => {
- if let Some(app) = value.downcast::<AXUIElement>() {
- Some(MacOSUIElement {
- element: ThreadSafeAXUIElement::new(app),
+ // inefficient but works
+ // Start with current element
+ let mut current = self.element.clone();
+
+ // Keep traversing up until we find an application or hit the top
+ loop {
+ // Check if current element is an application
+ if let Ok(role) = current.0.role() {
+ if role.to_string() == "AXApplication" {
+ return Some(MacOSUIElement {
+ element: current,
use_background_apps: self.use_background_apps,
activate_app: self.activate_app,
- })
- } else {
- None
+ });
}
}
- Err(_) => None,
+
+ // Try to get parent
+ let parent_attr = AXAttribute::new(&CFString::new("AXParent"));
+ match current.0.attribute(&parent_attr) {
+ Ok(value) => {
+ if let Some(parent) = value.downcast::<AXUIElement>() {
+ current = ThreadSafeAXUIElement::new(parent);
+ } else {
+ return None;
+ }
+ }
+ Err(_) => return None,
+ }
}
}
@@ -996,6 +1011,27 @@ impl MacOSUIElement {
// Add these methods to the MacOSUIElement impl block
fn click_auto(&self) -> Result<ClickResult, AutomationError> {
+ // only mouse simulation works on web and it seems function don't fail on web so let's try to detect if we are on web based on app
+ // eg chrome, arc, safari, etc
+ let app_name = self.get_application();
+
+ if let Some(app) = app_name {
+ // kind of dirty and hacky but it works
+ let app_name = app.get_text(1).unwrap_or_default().to_lowercase();
+ if app_name.contains("chrome")
+ || app_name.contains("safari")
+ || app_name.contains("arc")
+ || app_name.contains("firefox")
+ || app_name.contains("edge")
+ || app_name.contains("brave")
+ || app_name.contains("opera")
+ || app_name.contains("vivaldi")
+ || app_name.contains("microsoft edge")
+ {
+ return self.click_mouse_simulation();
+ }
+ }
+
// 1. Try AXPress action first
match self.click_press() {
Ok(result) => return Ok(result),
@@ -1228,7 +1264,7 @@ impl MacOSUIElement {
.unwrap_or_default();
// Get position if available (as integers to be more stable)
- let (x, y, w, h) = self
+ let (_, _, w, h) = self
.bounds()
.map(|(x, y, w, h)| {
(
@@ -1240,15 +1276,18 @@ impl MacOSUIElement {
})
.unwrap_or((0, 0, 0, 0));
+ let count_of_children = self.children().unwrap_or_default().len();
+
// Hash combination of stable attributes
role.hash(&mut hasher);
title.hash(&mut hasher);
desc.hash(&mut hasher);
- x.hash(&mut hasher);
- y.hash(&mut hasher);
+ // not using position because things more likely move than change size
+ // x.hash(&mut hasher);
+ // y.hash(&mut hasher);
w.hash(&mut hasher);
h.hash(&mut hasher);
-
+ count_of_children.hash(&mut hasher);
// Get parent info if available to make ID more unique
if let Ok(Some(parent)) = self.parent() {
if let Some(parent_role) = parent.attributes().label {
@@ -1959,6 +1998,57 @@ impl UIElementImpl for MacOSUIElement {
activate_app: self.activate_app,
})
}
+
+ fn scroll(&self, direction: &str, amount: f64) -> Result<(), AutomationError> {
+ // First try to focus the element to ensure it can receive scroll events
+ let _ = self.focus();
+
+ // Get element bounds to determine where to scroll
+ let (x, y, width, height) = self.bounds()?;
+ let center_x = x + width / 2.0;
+ let center_y = y + height / 2.0;
+
+ // Create event source
+ let source =
+ CGEventSource::new(core_graphics::event_source::CGEventSourceStateID::HIDSystemState)
+ .map_err(|_| {
+ AutomationError::PlatformError("Failed to create event source".to_string())
+ })?;
+
+ // Convert amount to scroll units (typically lines)
+ let scroll_amount = amount as i32;
+
+ // Create scroll event based on direction
+ let (scroll_x, scroll_y) = match direction.to_lowercase().as_str() {
+ "up" => (0, -scroll_amount),
+ "down" => (0, scroll_amount),
+ "left" => (-scroll_amount, 0),
+ "right" => (scroll_amount, 0),
+ _ => {
+ return Err(AutomationError::InvalidArgument(format!(
+ "Invalid scroll direction: {}. Must be up, down, left, or right",
+ direction
+ )))
+ }
+ };
+
+ // Create scroll wheel event
+ let scroll_event = CGEvent::new_scroll_event(
+ source, 0, 1, // number of wheels (1 for standard mouse wheel)
+ scroll_y, scroll_x, 0, // z scroll amount (unused)
+ )
+ .map_err(|_| AutomationError::PlatformError("Failed to create scroll event".to_string()))?;
+
+ // Post the event at the center point location
+ scroll_event.post(core_graphics::event::CGEventTapLocation::HID);
+
+ debug!(
+ "Scrolled {} by {} lines at position ({}, {})",
+ direction, amount, center_x, center_y
+ );
+
+ Ok(())
+ }
}
// Helper function to parse AXUIElement attribute values into appropriate types
diff --git a/screenpipe-core/src/operator/platforms/windows.rs b/screenpipe-core/src/operator/platforms/windows.rs
index 6ef6a31d3..f9898adc8 100644
--- a/screenpipe-core/src/operator/platforms/windows.rs
+++ b/screenpipe-core/src/operator/platforms/windows.rs
@@ -1,8 +1,8 @@
use crate::operator::element::UIElementImpl;
use crate::operator::platforms::AccessibilityEngine;
+use crate::operator::ClickResult;
use crate::operator::{AutomationError, Locator, Selector, UIElement, UIElementAttributes};
use std::fmt::Debug;
-use crate::operator::ClickResult;
pub struct WindowsEngine;
@@ -217,4 +217,10 @@ impl UIElementImpl for WindowsUIElement {
fn clone_box(&self) -> Box<dyn UIElementImpl> {
Box::new(WindowsUIElement)
}
+
+ fn scroll(&self, _direction: &str, _amount: f64) -> Result<(), AutomationError> {
+ Err(AutomationError::UnsupportedPlatform(
+ "Windows implementation is not yet available".to_string(),
+ ))
+ }
}
diff --git a/screenpipe-core/src/operator/tests.rs b/screenpipe-core/src/operator/tests.rs
index 483758a4c..524ca5b32 100644
--- a/screenpipe-core/src/operator/tests.rs
+++ b/screenpipe-core/src/operator/tests.rs
@@ -177,6 +177,23 @@ mod tests {
);
}
+ #[test]
+ #[ignore]
+ fn test_scroll_wheel() {
+ setup_tracing();
+
+ let desktop = Desktop::new(true, true).unwrap();
+ let app = desktop.application("Cursor").unwrap();
+ let stuff = app.locator("AXGroup").unwrap().all().unwrap();
+ for s in stuff.iter().take(10) {
+ println!("s: {:?}", s.role());
+ println!("s: {:?}", s.attributes().value);
+ println!("s: {:?}", s.attributes().properties);
+ println!("s: {:?}", s.text(10).unwrap());
+ s.scroll("down", 10000.0).unwrap();
+ }
+ }
+
#[test]
#[ignore]
fn test_find_and_fill_text_inputs() {
@@ -204,38 +221,16 @@ mod tests {
println!("App child #{}: {:?}", i, child.role());
}
- let inputs = app
- .locator("AXTextField")
- .unwrap()
- .all()
- .unwrap_or_default();
+ let inputs = app.locator("AXButton").unwrap().all().unwrap_or_default();
for input in inputs.clone() {
println!("input: {:?}", input.id());
println!("input: {:?}", input.text(10).unwrap());
- println!("input: {:?}", input.type_text("foo").unwrap());
+ println!("input: {:?}", input.attributes().label);
+ // println!("input: {:?}", input.type_text("foo").unwrap());
println!("input: {:?}", input.role());
}
- let specific_input = app
- .locator("AXTextField")
- .unwrap()
- .first()
- .unwrap()
- .unwrap()
- .locator(&*format!("#{}", inputs[0].id().unwrap()))
- .unwrap()
- .first()
- .unwrap()
- .unwrap();
-
- println!("specific_input: {:?}", specific_input.text(10).unwrap());
- println!(
- "specific_input: {:?}",
- specific_input.type_text("foobar").unwrap()
- );
- println!("specific_input: {:?}", specific_input.role());
-
let specific_input = app
.locator(&*format!("#{}", inputs[0].id().unwrap()))
.unwrap()
@@ -246,7 +241,7 @@ mod tests {
println!("specific_input: {:?}", specific_input.text(10).unwrap());
println!(
"specific_input: {:?}",
- specific_input.type_text("foobarbaz").unwrap()
+ specific_input.click().unwrap().details
);
println!("specific_input: {:?}", specific_input.role());
diff --git a/screenpipe-js/browser-sdk/package.json b/screenpipe-js/browser-sdk/package.json
index c0680e712..0f84f01ef 100644
--- a/screenpipe-js/browser-sdk/package.json
+++ b/screenpipe-js/browser-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@screenpipe/browser",
- "version": "0.1.38-beta.7",
+ "version": "0.1.38-beta.10",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
diff --git a/screenpipe-js/common/Operator.ts b/screenpipe-js/common/Operator.ts
index f60867711..91f2352c0 100644
--- a/screenpipe-js/common/Operator.ts
+++ b/screenpipe-js/common/Operator.ts
@@ -268,12 +268,19 @@ export class Operator {
*/
getByRole(
role: string,
- options?: { app?: string; window?: string }
+ options?: {
+ app?: string;
+ window?: string;
+ useBackgroundApps?: boolean;
+ activateApp?: boolean;
+ }
): ElementLocator {
return this.locator({
app: options?.app || "",
window: options?.window,
role,
+ useBackgroundApps: options?.useBackgroundApps,
+ activateApp: options?.activateApp,
});
}
@@ -286,11 +293,19 @@ export class Operator {
*/
getById(
id: string,
- options?: { app?: string; window?: string }
+ options?: {
+ app?: string;
+ window?: string;
+ useBackgroundApps?: boolean;
+ activateApp?: boolean;
+ }
): ElementLocator {
return this.locator({
app: options?.app || "",
window: options?.window,
+ id,
+ useBackgroundApps: options?.useBackgroundApps,
+ activateApp: options?.activateApp,
});
}
@@ -747,6 +762,70 @@ export class Operator {
return data.success;
}
+
+ /**
+ * Scroll an element in the specified direction
+ *
+ * @example
+ * // Scroll down in a scrollable element
+ * await pipe.operator.scroll({
+ * app: "Chrome",
+ * id: "content-area",
+ * direction: "down",
+ * amount: 100
+ * });
+ */
+ async scroll(options: {
+ app: string;
+ id?: string;
+ window?: string;
+ useBackgroundApps?: boolean;
+ activateApp?: boolean;
+ direction: "up" | "down" | "left" | "right";
+ amount: number;
+ }): Promise<boolean> {
+ const selector: ElementSelector = {
+ app_name: options.app,
+ window_name: options.window,
+ locator: options.id ? `#${options.id}` : "",
+ use_background_apps: options.useBackgroundApps,
+ activate_app: options.activateApp !== false,
+ };
+
+ const response = await fetch(
+ `${this.baseUrl}/experimental/operator/scroll`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ selector,
+ direction: options.direction,
+ amount: options.amount,
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ const responseText = await response.text();
+ console.log("error response:", responseText);
+
+ try {
+ const errorData = JSON.parse(responseText);
+ throw new Error(
+ `failed to scroll element: ${errorData.error || response.statusText}`
+ );
+ } catch (parseError) {
+ throw new Error(
+ `failed to scroll element (status ${response.status}): ${
+ responseText || response.statusText
+ }`
+ );
+ }
+ }
+
+ const data = await response.json();
+ return data.success;
+ }
}
class ElementLocator {
@@ -994,4 +1073,53 @@ class ElementLocator {
const result = await response.json();
return result.success;
}
+
+ /**
+ * Scroll the first element matching the selector
+ *
+ * @param direction The direction to scroll: "up", "down", "left", or "right"
+ * @param amount The amount to scroll in pixels
+ * @returns Whether the scroll operation was successful
+ */
+ async scroll(
+ direction: "up" | "down" | "left" | "right",
+ amount: number
+ ): Promise<boolean> {
+ const response = await fetch(
+ `${this.baseUrl}/experimental/operator/scroll`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ selector: {
+ ...this.selector,
+ activate_app: this.selector.activate_app !== false,
+ },
+ direction,
+ amount,
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ const responseText = await response.text();
+ console.log("error response:", responseText);
+
+ try {
+ const errorData = JSON.parse(responseText);
+ throw new Error(
+ `failed to scroll element: ${errorData.error || response.statusText}`
+ );
+ } catch (parseError) {
+ throw new Error(
+ `failed to scroll element (status ${response.status}): ${
+ responseText || response.statusText
+ }`
+ );
+ }
+ }
+
+ const result = await response.json();
+ return result.success;
+ }
}
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index d16ba3022..175a1bc08 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1154,9 +1154,9 @@ impl SCServer {
.post("/experimental/frames/merge", merge_frames_handler)
.get("/experimental/validate/media", validate_media_handler)
.post("/experimental/operator", find_elements_handler)
+ .post("/experimental/operator/scroll", scroll_element_handler)
.post("/experimental/operator/click", click_element_handler)
.post("/experimental/operator/type", type_text_handler)
-
.post("/experimental/operator/press-key", press_key_handler)
.post("/experimental/operator/get_text", get_text_handler)
.post(
@@ -1180,9 +1180,7 @@ impl SCServer {
open_application_handler,
)
.post("/experimental/operator/open-url", open_url_handler)
-
.post("/experimental/input_control", input_control_handler)
-
.post("/audio/start", start_audio)
.post("/audio/stop", stop_audio)
.get("/semantic-search", semantic_search_handler)
@@ -3214,7 +3212,11 @@ async fn find_elements_handler(
if request.max_results.unwrap_or(1) > 1 {
// Get all matching elements if 'all' is true
match locator.all() {
- Ok(elements) => elements,
+ Ok(elements) => elements
+ .into_iter()
+ // inefficient but works
+ .take(request.max_results.unwrap_or(1))
+ .collect(),
Err(_) => {
error!("No matching elements found");
return Err((
@@ -4290,3 +4292,94 @@ async fn open_url_handler(
)),
}
}
+
+#[derive(Debug, OaSchema, Deserialize, Serialize)]
+pub struct ScrollElementRequest {
+ selector: ElementSelector,
+ direction: String,
+ amount: f64,
+}
+
+#[derive(Debug, OaSchema, Serialize)]
+pub struct ScrollElementResponse {
+ success: bool,
+ message: String,
+}
+
+// Add the handler function
+#[oasgen]
+async fn scroll_element_handler(
+ State(_): State<Arc<AppState>>,
+ Json(request): Json<ScrollElementRequest>,
+) -> Result<JsonResponse<ScrollElementResponse>, (StatusCode, JsonResponse<Value>)> {
+ let desktop = match Desktop::new(
+ request.selector.use_background_apps.unwrap_or(false),
+ request.selector.activate_app.unwrap_or(false),
+ ) {
+ Ok(d) => d,
+ Err(e) => {
+ error!("Failed to initialize desktop automation: {}", e);
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "error": format!("Failed to initialize desktop automation: {}", e)
+ })),
+ ));
+ }
+ };
+
+ // app
+ let app = match desktop.application(&request.selector.app_name) {
+ Ok(app) => app,
+ Err(e) => {
+ error!("Failed to find application: {}", e);
+ return Err((
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({"error": format!("Failed to find application: {}", e)})),
+ ));
+ }
+ };
+
+ let element = match app.locator(request.selector.locator.as_str()) {
+ Ok(locator) => locator.first(),
+ Err(e) => {
+ error!("Failed to find element: {}", e);
+ return Err((
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({"error": format!("Failed to find element: {}", e)})),
+ ));
+ }
+ }
+ .map_err(|e| {
+ error!("Failed to find element: {}", e);
+ (
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({"error": format!("Failed to find element: {}", e)})),
+ )
+ })?;
+
+ match element {
+ Some(element) => {
+ // Perform scroll
+ match element.scroll(&request.direction, request.amount) {
+ Ok(_) => Ok(JsonResponse(ScrollElementResponse {
+ success: true,
+ message: format!(
+ "Successfully scrolled {} by {}",
+ request.direction, request.amount
+ ),
+ })),
+ Err(e) => Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({
+ "error": format!("Failed to scroll element: {}", e)
+ })),
+ )),
+ }
+ }
+ None => Err((
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({"error": "No element found"})),
+ )),
+ }
+}