Trisha Tomy commited on
Commit
5f7e666
·
1 Parent(s): 6f61f21

roll back app

Browse files
Files changed (1) hide show
  1. app.py +30 -37
app.py CHANGED
@@ -27,11 +27,10 @@ async def initialize_runner():
27
  config = RunnerConfig.from_dict({
28
  "environment": {
29
  "name": "webbrowser",
30
- # Set homepage to Salesforce's generic login URL to avoid premature waits for target page elements.
31
- "homepage": "https://login.salesforce.com/",
32
- "headless": True, # Keep this False for local testing
33
  "launch_args": ["--no-sandbox", "--disable-setuid-sandbox"],
34
- "screenshot_delay": 0.5, # Reduced for faster debugging cycles
35
  "include_html": True,
36
  "include_poi_text": True,
37
  },
@@ -61,9 +60,20 @@ async def initialize_runner():
61
  logger.info("Proxy-lite Runner initialized successfully.")
62
  return _runner
63
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  @app.route('/run_proxy_task', methods=['POST'])
66
- async def run_proxy_task_endpoint():
67
  data = request.json
68
  request_task_instruction = data.get('task')
69
 
@@ -80,40 +90,27 @@ async def run_proxy_task_endpoint():
80
  logger.error("Salesforce credentials (SALESFORCE_USERNAME, SALESFORCE_PASSWORD) environment variables not set.")
81
  return jsonify({"error": "Salesforce credentials not configured. Please set SALESFORCE_USERNAME and SALESFORCE_PASSWORD as Space secrets."}), 500
82
 
83
- # Define the specific Account Forecast Settings URL
84
- account_forecast_url = "https://dwd000006jia1mae.lightning.force.com/lightning/setup/AccountForecastSettings/home"
85
-
86
- # Define the tool code block to open a new tab and navigate after login
87
- # Using a raw f-string for multiline tool code block
88
- tool_code_block_new_tab = fr"""
89
- <tool_code>
90
- await browser.open_new_tab_and_go_to(url='{account_forecast_url}')
91
- </tool_code>
92
- """
93
-
94
- # Refined agent_task instruction to be sequential and robust to Salesforce redirects
95
- agent_task = f"""
96
- **Task Instructions for Proxy Lite Agent:**
97
- 1. **Start on Login Page:** Navigate to the Salesforce login page.
98
- 2. **Perform Login:** Log in to Salesforce using the provided username '{salesforce_username}' and password '{salesforce_password}'. Ensure all login fields are filled and the 'Log In' button is clicked.
99
- 3. **Handle Post-Login Redirect:** After clicking the 'Log In' button:
100
- * Observe the current URL. If the URL has changed from the initial login domain (e.g., from `login.salesforce.com` or `my.salesforce.com`) **immediately execute the following tool code block to open a new tab and navigate directly to the Account Forecast Settings page (`{account_forecast_url}`) to bypass any persistent loading issues or internal redirects:**
101
- {tool_code_block_new_tab.strip()}
102
- 4. **Confirm Target Page Load:** After successfully navigating to '{account_forecast_url}' (either directly after login or via the new tab strategy), ensure the page is fully loaded and stable. This means no loading spinners should be visible, and the main content for 'Account Forecast Settings' (like a clear heading, relevant toggles, or data tables) should be present and interactive.
103
- 5. **Execute Main Task:** Once the Account Forecast Settings page is confirmed loaded and stable, proceed with the original user request: {request_task_instruction}.
104
- 6. **Report Final Status:** Report the final status of the requested action, confirming both successful login and complete page load of the Account Forecast Settings.
105
- """
106
 
107
- logger.info(f"Executing agent task (truncated for log): '{agent_task[:500]}...'")
108
 
109
  try:
 
110
  runner = await initialize_runner()
111
- result = await runner.run(agent_task)
112
 
113
- logger.info(f"Proxy-lite task completed. Output (truncated for log): {result[:500]}...")
114
  return jsonify({"output": result})
115
  except Exception as e:
116
  logger.exception(f"Error processing Salesforce task: {e}")
 
 
117
  return jsonify({"error": f"An error occurred: {str(e)}. Check logs for details."}), 500
118
 
119
  @app.route('/')
@@ -122,12 +119,8 @@ def root():
122
  return "Proxy-lite API is running. Send POST requests to /run_proxy_task with a 'task' in JSON body."
123
 
124
  if __name__ == '__main__':
125
- # It is crucial to set HF_API_TOKEN as an environment variable (e.g., in a .env file or directly)
126
- # for local testing as well, otherwise initialize_runner will fail.
127
  if not os.environ.get("HF_API_TOKEN"):
128
  logger.error("HF_API_TOKEN environment variable is not set. Please set it for local testing.")
129
- # Removed exit(1) to allow the Flask app to start for basic connectivity checks,
130
- # but runner initialization will still fail if token is missing.
131
- # For full functionality, the token is essential.
132
  logger.info("Starting Flask development server on 0.0.0.0:7860...")
133
- app.run(host='0.0.0.0', port=7860, debug=True)
 
27
  config = RunnerConfig.from_dict({
28
  "environment": {
29
  "name": "webbrowser",
30
+ "homepage": "https://dwd000006jia1mae.lightning.force.com/lightning/setup/AccountForecastSettings/home",
31
+ "headless": True,
 
32
  "launch_args": ["--no-sandbox", "--disable-setuid-sandbox"],
33
+ "screenshot_delay": 3.0,
34
  "include_html": True,
35
  "include_poi_text": True,
36
  },
 
60
  logger.info("Proxy-lite Runner initialized successfully.")
61
  return _runner
62
 
63
+ # --- MODIFIED run_async_task FUNCTION (SIMPLIFIED) ---
64
+ # This function is no longer needed in most cases with gevent.monkey.patch_all(asyncio=True)
65
+ # but if you must call async functions from sync context, you simply await them.
66
+ # However, you are already in an async function context within Flask routes when using Gunicorn/gevent.
67
+ # The Gunicorn worker itself implicitly runs an event loop.
68
+ # Let's remove the run_until_complete part.
69
+
70
+ # DELETED: def run_async_task(coro): ...
71
+
72
+ # --- END MODIFIED run_async_task FUNCTION ---
73
+
74
 
75
  @app.route('/run_proxy_task', methods=['POST'])
76
+ async def run_proxy_task_endpoint(): # <--- MAKE THIS FUNCTION ASYNC
77
  data = request.json
78
  request_task_instruction = data.get('task')
79
 
 
90
  logger.error("Salesforce credentials (SALESFORCE_USERNAME, SALESFORCE_PASSWORD) environment variables not set.")
91
  return jsonify({"error": "Salesforce credentials not configured. Please set SALESFORCE_USERNAME and SALESFORCE_PASSWORD as Space secrets."}), 500
92
 
93
+ agent_task = (
94
+ f"Log in to Salesforce. The username is '{salesforce_username}' and the password is '{salesforce_password}'. "
95
+ f"After attempting to log in, observe the page carefully. "
96
+ f"If the login was successful, the URL should change from the login page, and you should see elements indicating a logged-in state (e.g., a Salesforce navigation menu, a home screen, or a profile icon), rather than a login form or an error message. "
97
+ f"If the login is successful, {request_task_instruction}. "
98
+ f"Report the final status of the requested action and confirmation of successful login."
99
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ logger.info(f"Executing agent task: '{agent_task[:200]}...'")
102
 
103
  try:
104
+ # Since run_proxy_task_endpoint is now async, you can directly await
105
  runner = await initialize_runner()
106
+ result = await runner.run(agent_task) # <--- AWAIT DIRECTLY
107
 
108
+ logger.info(f"Proxy-lite task completed. Output: {result[:200]}...")
109
  return jsonify({"output": result})
110
  except Exception as e:
111
  logger.exception(f"Error processing Salesforce task: {e}")
112
+ # The RuntimeWarning: coroutine 'initialize_runner' was never awaited will disappear
113
+ # because initialize_runner is now awaited.
114
  return jsonify({"error": f"An error occurred: {str(e)}. Check logs for details."}), 500
115
 
116
  @app.route('/')
 
119
  return "Proxy-lite API is running. Send POST requests to /run_proxy_task with a 'task' in JSON body."
120
 
121
  if __name__ == '__main__':
 
 
122
  if not os.environ.get("HF_API_TOKEN"):
123
  logger.error("HF_API_TOKEN environment variable is not set. Please set it for local testing.")
124
+ exit(1)
 
 
125
  logger.info("Starting Flask development server on 0.0.0.0:7860...")
126
+ app.run(host='0.0.0.0', port=7860, debug=True)