-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1950 lines (1733 loc) · 86.8 KB
/
Copy pathmain.py
File metadata and controls
1950 lines (1733 loc) · 86.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import re
import json
import subprocess
import platform
from pathlib import Path
from typing import Dict, List, Optional, Set
from collections import defaultdict
from dotenv import load_dotenv
from playwright.sync_api import sync_playwright, Page, TimeoutError as PlaywrightTimeoutError
from agent.task_parser import TaskParser
from agent.browser_controller import BrowserController
from agent.state_detector import StateDetector
from utils.session_manager import SessionManager
# from utils.state_documentation import StateDocumentation
# from utils.documentation_generator import DocumentationGenerator
from utils.dom_inspector import DOMInspector
# from config.prompts import DocumentationPrompts
load_dotenv()
def get_screen_size():
system = platform.system()
if system == "Darwin":
try:
r = subprocess.run(["system_profiler", "SPDisplaysDataType"], capture_output=True, text=True, timeout=10)
for line in r.stdout.split("\n"):
if "Resolution:" in line:
m = re.search(r"Resolution:\s*(\d+)\s*x\s*(\d+)", line)
if m:
return int(m.group(1)), int(m.group(2))
r = subprocess.run(
["osascript", "-e", "tell application \"Finder\" to get bounds of window of desktop"],
capture_output=True, text=True, timeout=5
)
b = r.stdout.strip().split(", ")
if len(b) == 4:
return int(b[2]), int(b[3])
except Exception:
pass
elif system == "Linux":
try:
r = subprocess.run(["xrandr", "--current"], capture_output=True, text=True, timeout=10)
for line in r.stdout.split("\n"):
if " connected " in line and "+" in line:
m = re.search(r"(\d+)x(\d+)\+", line)
if m:
return int(m.group(1)), int(m.group(2))
except Exception:
pass
elif system == "Windows":
try:
r = subprocess.run(
["powershell", "-Command",
"Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::PrimaryScreen.Bounds"],
capture_output=True, text=True, timeout=10
)
out = r.stdout.strip()
wm = re.search(r"Width=(\d+)", out)
hm = re.search(r"Height=(\d+)", out)
if wm and hm:
return int(wm.group(1)), int(hm.group(2))
except Exception:
pass
return 1920, 1080
def manual_login_handoff(page, state_detector, app_url, task_dir: Path):
print("\n⚠️ Login required. Please complete login in the browser.")
input("Press Enter here after you finish logging in...")
# Verify login completed - simple LLM check
retries = 0
while retries < 3:
time.sleep(4)
verify = task_dir / f"post_login_{retries+1}.png"
page.screenshot(path=str(verify), full_page=True)
login_check_prompt = """
Is the user now logged in to this application?
Return ONLY valid JSON:
{
"is_logged_in": true/false,
"reason": "brief explanation"
}
"""
try:
login_response = state_detector.analyze_screenshot(verify, login_check_prompt)
# Wait 7 seconds after LLM call
time.sleep(7)
cleaned = state_detector._clean_json_like(login_response)
login_data = json.loads(cleaned)
is_logged_in = login_data.get("is_logged_in", False)
if is_logged_in:
print("✅ Login confirmed.")
return True
except Exception:
pass
retries += 1
print("Login not verified yet. If SSO or 2FA is in progress, finish it, then press Enter...")
input()
print("Proceeding even though login could not be verified automatically.")
return True
def ensure_navigate(controller: BrowserController, page, url: str, task_dir: Path, app_name: str) -> bool:
"""
Robust navigation with retries and manual fallback. Returns True when on target domain or any non-empty page.
Hard-stops the run if nothing works.
"""
# Try a few strategies: different wait states and longer timeouts
attempts = [
("domcontentloaded", 30000),
("load", 45000),
("networkidle", 60000),
]
for i, (wait_state, timeout) in enumerate(attempts, 1):
res = controller.navigate(url, wait_until=wait_state, timeout=timeout)
if res.get("success"):
return True
time.sleep(1.0)
# If still failing, try a few alternate landing URLs for common apps
alt_urls = [url]
if "linear.app" in url:
alt_urls = ["https://linear.app", "https://linear.app/login", "https://linear.app/launch"]
elif "notion.so" in url:
alt_urls = ["https://www.notion.so/login", "https://www.notion.so"]
for alt in alt_urls:
for wait_state, timeout in attempts:
res = controller.navigate(alt, wait_until=wait_state, timeout=timeout)
if res.get("success"):
return True
time.sleep(0.8)
# Manual fallback: let user drive to any working page
print("\nNavigation is timing out. Please use the open browser window to reach the app manually.")
print(f"Try opening the homepage or workspace for {app_name}. When the page looks ready, press Enter here...")
input("> ")
# Small grace period to let the page settle, then sanity check
time.sleep(3)
snap = task_dir / "manual_nav_check.png"
page.screenshot(path=str(snap), full_page=True)
cur_url = page.url or ""
if cur_url and "about:blank" not in cur_url:
return True
# Hard stop: do not continue to step loop when not reachable
print("\nCould not reach the application. Stopping the run to avoid acting on an empty page.")
return False
def click_text_anywhere(page: Page, text: str, timeout_ms: int = 6000, prefer_exact: bool = True) -> Dict:
"""
Attempt to click visible text across all frames using trusted Playwright input.
Returns dict with success status and details about what was clicked.
"""
target_text = (text or "").strip()
if not target_text:
return {"success": False, "reason": "empty text"}
def normalize_text_for_matching(text: str) -> str:
"""Normalize text by removing special chars and normalizing whitespace."""
if not text:
return ""
# Remove special characters, keep only letters, numbers, spaces
normalized = re.sub(r'[^a-zA-Z0-9\s]', '', text)
# Normalize whitespace
normalized = re.sub(r'\s+', ' ', normalized)
return normalized.strip().lower()
def try_locator(loc, description: str = "") -> Dict:
try:
count = loc.count()
if count > 0:
target_normalized = normalize_text_for_matching(target_text)
# If multiple matches, prefer exact normalized text match
if count > 1 and prefer_exact:
# Try to find exact normalized match first
for i in range(count):
try:
el = loc.nth(i)
el_text = el.inner_text(timeout=500).strip()
el_normalized = normalize_text_for_matching(el_text)
if el_normalized == target_normalized:
el.scroll_into_view_if_needed(timeout=timeout_ms)
el.click(timeout=timeout_ms)
return {"success": True, "method": description, "matched_text": el_text, "index": i, "total": count}
except Exception:
continue
# Fallback to first match
locator = loc.first
matched_text = ""
try:
matched_text = locator.inner_text(timeout=500).strip()
except Exception:
pass
locator.scroll_into_view_if_needed(timeout=timeout_ms)
locator.click(timeout=timeout_ms)
return {"success": True, "method": description, "matched_text": matched_text, "index": 0, "total": count}
except PlaywrightTimeoutError:
return {"success": False, "reason": "timeout"}
except Exception as e:
return {"success": False, "reason": str(e)[:50]}
return {"success": False, "reason": "no matches"}
# Normalize target text for matching (remove special chars, normalize spaces)
normalized_target = re.sub(r'[^a-zA-Z0-9\s]', '', target_text)
normalized_target = re.sub(r'\s+', ' ', normalized_target).strip()
# Try exact match first, then partial
pattern_factories = [
(lambda f: f.get_by_text(normalized_target, exact=True), "exact_text"),
(lambda f: f.get_by_role("button", name=re.compile(re.escape(normalized_target), re.I)), "button_role"),
(lambda f: f.get_by_role("link", name=re.compile(re.escape(normalized_target), re.I)), "link_role"),
(lambda f: f.get_by_text(normalized_target, exact=False), "partial_text"),
]
for frame in page.frames:
for factory, desc in pattern_factories:
try:
locator = factory(frame)
result = try_locator(locator, desc)
if result.get("success"):
return result
except Exception:
continue
fallback_script = """
(t) => {
const withinViewport = (r) =>
r.width > 0 && r.height > 0 &&
r.top < innerHeight && r.bottom > 0 && r.left < innerWidth && r.right > 0;
// Normalize text: remove special chars, normalize whitespace
const normalize = (str) => {
if (!str) return '';
return str.replace(/[^a-zA-Z0-9\\s]/g, '') // Remove special chars
.replace(/\\s+/g, ' ') // Normalize whitespace
.trim()
.toLowerCase();
};
const targetNormalized = normalize(t);
const els = [...document.querySelectorAll('*')].filter(el => {
if (!el || !el.innerText) return false;
const elNormalized = normalize(el.innerText);
// Check if normalized text includes target (flexible matching)
return elNormalized.includes(targetNormalized) || targetNormalized.includes(elNormalized);
});
if (!els.length) return null;
const rank = el => {
const tag = el.tagName.toLowerCase();
let score = 0;
if (['button','a','input'].includes(tag)) score += 10;
if (getComputedStyle(el).cursor === 'pointer') score += 5;
if (el.hasAttribute('role')) score += 2;
// Prefer exact normalized matches
const elNormalized = normalize(el.innerText);
if (elNormalized === targetNormalized) score += 20;
// Prefer starts with match
else if (elNormalized.startsWith(targetNormalized)) score += 15;
// Prefer contains match
else if (elNormalized.includes(targetNormalized)) score += 10;
return score - (el.innerText.length || 0) * 0.01;
};
els.sort((a,b) => rank(b) - rank(a));
const el = els[0];
const matchedText = (el.innerText || "").trim();
el.scrollIntoView({ block: 'center', inline: 'center' });
const rect = el.getBoundingClientRect();
const finalRect = withinViewport(rect) ? rect : el.getBoundingClientRect();
return {
x: finalRect.left + finalRect.width / 2,
y: finalRect.top + finalRect.height / 2,
text: matchedText,
tag: el.tagName
};
}
"""
for frame in page.frames:
try:
coords_data = frame.evaluate(fallback_script, target_text)
except Exception:
continue
if not coords_data:
continue
offset_x = 0.0
offset_y = 0.0
try:
owner = frame.frame_element()
if owner:
box = owner.bounding_box()
if box:
offset_x += box.get("x", 0.0)
offset_y += box.get("y", 0.0)
except Exception:
pass
try:
absolute_x = offset_x + coords_data["x"]
absolute_y = offset_y + coords_data["y"]
page.mouse.move(absolute_x, absolute_y, steps=2)
page.mouse.click(absolute_x, absolute_y)
return {
"success": True,
"method": "fallback_mouse",
"matched_text": coords_data.get("text", target_text),
"tag": coords_data.get("tag", "unknown")
}
except Exception:
continue
return {"success": False, "reason": "no elements found"}
def main():
task_description = input("Enter task: ").strip()
if not task_description:
print("No task provided.")
return
print(f"\nTask: {task_description}")
print("=" * 60)
parser = TaskParser()
parsed = parser.parse(task_description)
app_name = "WorkflowDoc"
app_url = parsed["app_url"]
action_goal = parsed["action"]
task_name_slug = parsed["task_name"]
task_parameters = parsed.get("task_parameters", {})
if "name" not in task_parameters:
name_match = re.search(r"name(?:d)?\s+(?:it\s+)?['\"]?([A-Za-z0-9\s\-\_]+)['\"]?", task_description, flags=re.IGNORECASE)
if name_match:
task_parameters["name"] = name_match.group(1).strip(" '\"")
elif "test" in task_description.lower():
task_parameters["name"] = "test"
base_dir = Path("captures")
task_dir = base_dir / task_name_slug
task_dir.mkdir(parents=True, exist_ok=True)
# doc_recorder = StateDocumentation(
# task_name=task_name_slug,
# task_description=task_description,
# parsed_task=parsed
# )
# Keep a stable viewport to avoid DPI/layout surprises across runs
w, h = 1280, 1080
session = SessionManager()
profile_path = session.get_profile_path(app_name.lower())
headless = os.getenv("HEADLESS", "false").lower() == "true"
with sync_playwright() as p:
context = p.firefox.launch_persistent_context(
user_data_dir=str(profile_path),
headless=headless,
viewport={"width": w, "height": h}
)
page = context.pages[0] if context.pages else context.new_page()
controller = BrowserController(page)
detector = StateDetector(page)
print(f"\nNavigating to {app_url} ...")
if not ensure_navigate(controller, page, app_url, task_dir, app_name):
# Abort early, do not proceed to steps
try:
print("\nClosing browser in 10 seconds...")
time.sleep(10)
context.close()
except Exception:
pass
return
# WAIT FOR PAGE TO FULLY LOAD BEFORE LOGIN CHECK
print(f"\n{'='*80}")
print(f"⏳ Waiting for page to fully load...")
print(f"{'='*80}")
# Wait for network idle and DOM content
try:
page.wait_for_load_state("networkidle", timeout=5000)
except Exception:
pass
# Additional wait to ensure dynamic content loads
time.sleep(3)
# NOW TAKE SCREENSHOT AND CHECK LOGIN
print(f"\n{'='*80}")
print(f"🔐 LOGIN CHECK:")
print(f"{'='*80}")
login_screenshot = task_dir / "login_check_initial.png"
page.screenshot(path=str(login_screenshot), full_page=True)
print(f" 📸 Screenshot taken: {login_screenshot.name}")
logged_in_indicators = []
login_required_indicators = []
# METHOD 1: Check URL for login-related paths (MOST RELIABLE)
try:
current_url = page.url.lower()
login_paths = ["/login", "/signin", "/sign-in", "/auth", "/signup", "/register", "/welcome"]
if any(path in current_url for path in login_paths):
print(f" ⚠️ URL suggests login page: {current_url[:80]}")
login_required_indicators.append(f"Login URL detected")
else:
print(f" ✅ URL looks like main app: {current_url[:80]}")
logged_in_indicators.append("Main app URL")
except Exception as e:
print(f" ⚠️ URL check failed: {e}")
# METHOD 2: Check DOM for login forms vs user indicators
try:
login_form_check = page.evaluate("""
() => {
// Check for login form elements
const passwordInputs = document.querySelectorAll('input[type="password"]');
const emailInputs = document.querySelectorAll('input[type="email"], input[name*="email"], input[id*="email"]');
const loginButtons = Array.from(document.querySelectorAll('button, a, [role="button"]')).filter(el => {
const text = (el.innerText || el.textContent || '').toLowerCase().trim();
return text === 'log in' || text === 'sign in' || text === 'login' || text === 'sign up';
});
// Check for user profile/dashboard indicators
const userIndicators = Array.from(document.querySelectorAll('*')).filter(el => {
const text = (el.innerText || '').toLowerCase();
const attrs = (el.className + ' ' + el.id).toLowerCase();
return text.includes('my workspace') || text.includes('my projects') ||
attrs.includes('avatar') || attrs.includes('user-menu') ||
text.includes('logout') || text.includes('sign out');
});
const hasLoginForm = passwordInputs.length > 0 && emailInputs.length > 0;
return {
hasPasswordField: passwordInputs.length > 0,
hasEmailField: emailInputs.length > 0,
hasLoginForm: hasLoginForm,
hasLoginButton: loginButtons.length > 0,
hasUserIndicators: userIndicators.length > 0,
loginButtonsCount: loginButtons.length,
userIndicatorsCount: userIndicators.length
};
}
""")
print(f" 📋 DOM Analysis:")
print(f" Password fields: {login_form_check.get('hasPasswordField')}")
print(f" Email fields: {login_form_check.get('hasEmailField')}")
print(f" Login buttons: {login_form_check.get('loginButtonsCount', 0)}")
print(f" User indicators: {login_form_check.get('userIndicatorsCount', 0)}")
# FIXED LOGIC: Login buttons are a STRONG signal of NOT being logged in
# If login buttons exist, user is NOT logged in (regardless of user indicators)
has_login_button = login_form_check.get("hasLoginButton", False)
has_user_indicators = login_form_check.get("hasUserIndicators", False)
has_login_form = login_form_check.get("hasLoginForm", False)
if has_login_button:
# Login buttons = NOT LOGGED IN (this is the strongest signal)
print(f" ⚠️ DOM shows login button(s) - NOT LOGGED IN")
login_required_indicators.append(f"Login button(s) present ({login_form_check.get('loginButtonsCount', 0)} found)")
elif has_login_form:
# Login form = NOT LOGGED IN
print(f" ⚠️ DOM shows login form present - NOT LOGGED IN")
login_required_indicators.append("Login form in DOM")
elif has_user_indicators:
# User indicators without login buttons = LOGGED IN
print(f" ✅ DOM shows user indicators (logged in)")
logged_in_indicators.append("User indicators in DOM")
else:
print(f" 📋 DOM check inconclusive")
except Exception as e:
print(f" ⚠️ DOM check failed: {e}")
# METHOD 3: Check cookies (LEAST RELIABLE - some apps work without auth cookies)
try:
cookies = page.context.cookies()
if len(cookies) > 0:
print(f" 📋 Cookies found: {len(cookies)} cookies")
else:
print(f" ⚠️ No cookies found")
except Exception as e:
print(f" ⚠️ Cookie check failed: {e}")
# DECISION LOGIC: Require BOTH indicators for logged in, OR use screenshot
needs_login = False
login_reason = ""
# Strong indicators of login page
if login_required_indicators:
needs_login = True
login_reason = "; ".join(login_required_indicators)
print(f" ⚠️ Login required indicators: {', '.join(login_required_indicators)}")
# Strong indicators of being logged in
elif logged_in_indicators:
needs_login = False
print(f" ✅ Logged in indicators found: {', '.join(logged_in_indicators)}")
else:
# Inconclusive - ALWAYS use screenshot as final check
print(f" 📋 Checks inconclusive - using screenshot as final check...")
try:
login_prompt = """
Look at this screenshot carefully. Is this a LOGIN PAGE, SIGNUP PAGE, or WELCOME/ONBOARDING page?
Signs of login page:
- Password input field
- Email input field
- "Log in" or "Sign in" button
- "Sign up" or "Create account" option
- "Forgot password" link
Signs of logged in:
- User name or profile visible
- "Logout" or "Sign out" option
- Dashboard/workspace content
- Project/task lists
- Settings or account menu
Answer ONLY with JSON:
{
"is_login_page": true/false,
"reason": "one sentence explaining what you see"
}
"""
login_response = detector.analyze_screenshot(login_screenshot, login_prompt)
# Wait 7 seconds after LLM call
time.sleep(7)
cleaned = detector._clean_json_like(login_response)
screenshot_data = json.loads(cleaned)
is_login_page = screenshot_data.get("is_login_page", False)
if is_login_page:
print(f" ⚠️ Screenshot confirms login page")
needs_login = True
login_reason = screenshot_data.get("reason", "Screenshot shows login page")
else:
print(f" ✅ Screenshot confirms logged in")
needs_login = False
except Exception as e:
print(f" ⚠️ Screenshot check failed: {e}")
import traceback
traceback.print_exc()
# When screenshot fails, assume login needed to be safe
needs_login = True
login_reason = "Screenshot check failed - defaulting to login required"
print(f" {'='*80}")
print(f" FINAL VERDICT: {'⚠️ LOGIN REQUIRED' if needs_login else '✅ LOGGED IN'}")
if login_reason:
print(f" Reason: {login_reason}")
print(f"{'='*80}\n")
if needs_login:
print("⚠️ Login required. Handing control to user...")
manual_login_handoff(page, detector, app_url, task_dir)
time.sleep(1)
post_login_shot = task_dir / "post_login_handoff.png"
page.screenshot(path=str(post_login_shot), full_page=True)
print("✅ Login handoff complete. Continuing with task...\n")
else:
print("✅ User is logged in. Proceeding with task...\n")
time.sleep(1)
previous_actions = []
attempted_targets = defaultdict(int)
seen_texts: Set[str] = set()
step_count = 0
max_steps = 20
default_click_keywords = [
"new",
"create",
"add",
"blank",
"project",
"task",
"next",
"continue",
"start",
"begin",
"submit",
"done",
"finish",
"save",
"confirm"
]
goal_tokens = [
token for token in re.findall(
r"[A-Za-z0-9\+\#][A-Za-z0-9\-\+]*",
f"{action_goal} {task_description}".replace("_", " ").lower()
)
if len(token) >= 3
]
default_keyword_pool = list(dict.fromkeys(default_click_keywords + goal_tokens))
def capture_state(tag: str) -> Path:
"""Capture a full-page screenshot after giving the DOM a moment to settle."""
try:
page.wait_for_load_state("domcontentloaded", timeout=5000)
except Exception:
pass
time.sleep(0.4)
shot_path = task_dir / f"state_{tag}.png"
page.screenshot(path=str(shot_path), full_page=True)
return shot_path
def normalize_text(value: str) -> str:
return (value or "").strip().lower()
def llm_decide_action(
screenshot_path: Path,
current_state_description: str,
ocr_data: List[Dict],
candidate_keywords: List[str],
recent_actions: List[Dict],
new_texts: List[str],
attempted_map: Dict[str, int],
new_dom_elements_text: str = ""
) -> Optional[Dict]:
context_items = []
for entry in (ocr_data or [])[:25]:
if not isinstance(entry, dict):
continue
text = (entry.get("text") or "").strip()
if not text:
continue
bbox = entry.get("bounding_box") or {}
context_items.append({
"text": text,
"bounding_box": {
"x": int(bbox.get("x", 0)),
"y": int(bbox.get("y", 0)),
"width": int(bbox.get("width", 0)),
"height": int(bbox.get("height", 0))
}
})
prompt = f"""
Goal: {task_description}
What do I do next?
{new_dom_elements_text if new_dom_elements_text else "No new popup elements."}
Return ONLY valid JSON:
{{
"event": "click|fill|done",
"text": "exact text to click or label to fill"
}}
"""
try:
raw = detector.analyze_screenshot(screenshot_path, prompt)
# Wait 7 seconds after LLM call
time.sleep(7)
cleaned = detector._clean_json_like(raw)
data = json.loads(cleaned)
return data
except Exception:
return None
def find_ocr_match(ocr_data: List[Dict], candidates: List[str]) -> (Optional[Dict], Optional[str]):
if not ocr_data or not candidates:
return None, None
normalized_candidates = [normalize_text(c) for c in candidates if c]
for candidate in normalized_candidates:
for entry in ocr_data:
text = entry.get("text") if isinstance(entry, dict) else None
if not text:
continue
if candidate in normalize_text(text):
return entry, candidate
return None, None
def register_attempt(target: str):
normalized_target = normalize_text(target)
if normalized_target:
attempted_targets[normalized_target] += 1
# def generate_step_summary(
# step_number: int,
# action_type: str,
# action_target: str,
# source_label: str,
# doc_step_text: str,
# pre_state_description: str,
# post_state_description: str
# ):
# fallback_summary = f"{action_type.title()} {action_target}".strip() or action_type.title()
# fallback_notes = ""
#
# try:
# model = detector.model
# except Exception:
# return fallback_summary, fallback_notes
#
# if not model:
# return fallback_summary, fallback_notes
#
# prompt = DocumentationPrompts.step_narration(
# task_description=task_description,
# app_name=app_name,
# step_number=step_number,
# action_type=action_type,
# action_target=action_target,
# action_source=source_label,
# doc_step_text=doc_step_text,
# pre_state_description=pre_state_description,
# post_state_description=post_state_description
# )
#
# try:
# response = model.generate_content(prompt)
# raw_text = response.text.strip()
# cleaned = detector._clean_json_like(raw_text)
# data = json.loads(cleaned)
# summary = (data.get("summary") or "").strip()
# notes = (data.get("notes") or "").strip()
# if not summary:
# summary = fallback_summary
# return summary, notes
# except Exception:
# return fallback_summary, fallback_notes
# def record_step(
# step_number: int,
# action_type: str,
# action_target: str,
# source_label: str,
# doc_step_text: str,
# pre_state_description: str,
# post_shot: Path = None,
# post_state_description: str = ""
# ):
# if post_shot is None:
# post_tag = f"step_{step_number}_{source_label}_{action_type}".replace(" ", "_").lower()
# post_shot = capture_state(post_tag)
# if not post_state_description:
# post_state_description = detector.get_page_description(post_shot)
#
# summary, extra_note = generate_step_summary(
# step_number=step_number,
# action_type=action_type,
# action_target=action_target,
# source_label=source_label,
# doc_step_text=doc_step_text,
# pre_state_description=pre_state_description,
# post_state_description=post_state_description
# )
#
# note_parts = []
# if doc_step_text:
# note_parts.append(f"Reference: {doc_step_text}")
# if extra_note:
# note_parts.append(extra_note)
# notes = " | ".join(part for part in note_parts if part) or None
#
# doc_recorder.add_step(
# step_number=step_number,
# action_type=action_type,
# action_description=summary,
# state_description=post_state_description,
# url=page.url,
# screenshot_filename=post_shot.name,
# page_title=page.title(),
# notes=notes
# )
#
# print(f" ✅ {source_label} {action_type.upper()} → {summary}")
goal_reached = False
dom_snapshot_before = None
action_history = [] # Track previous actions for context
previous_screenshot_path = None # Track previous screenshot for duplicate detection
last_llm_suggestion: Optional[Dict[str, str]] = None
while step_count < max_steps:
step_count += 1
print(f"\nStep {step_count}")
try:
page.evaluate("() => { window.beforeClickSnapshot = null; window.capturedChanges = []; }")
except Exception:
pass
# Capture DOM snapshot BEFORE action (if we have a previous snapshot, we'll diff)
if dom_snapshot_before is None:
dom_snapshot_before = DOMInspector.capture_snapshot(page)
shot = task_dir / f"screenshot_step_{step_count}.png"
page.screenshot(path=str(shot), full_page=True)
# Check goal completion FIRST to inform whether to reuse instruction
goal_check = detector.check_goal_completion(shot, task_goal=action_goal, current_state="")
# Wait 7 seconds after LLM call
time.sleep(7)
goal_completed = goal_check.get("goal_completed", False)
goal_reasoning = goal_check.get("reasoning", "")
next_steps = goal_check.get("next_steps_needed", [])
# If goal is completed, break
if goal_completed:
print("🎉 Goal achieved!")
goal_reached = True
break
duplicate_screenshot = False
if previous_screenshot_path and previous_screenshot_path.exists():
try:
import filecmp
if filecmp.cmp(previous_screenshot_path, shot, shallow=False):
duplicate_screenshot = True
print("⚠️ Screenshot is identical to previous step")
# Don't reuse if goal check suggests a different action
if goal_reasoning and last_llm_suggestion:
# Check if reasoning suggests clicking (not filling)
reasoning_lower = goal_reasoning.lower()
last_action = last_llm_suggestion.get("event", "").lower()
# If reasoning says "click" but last action was "fill", don't reuse
if ("click" in reasoning_lower or "select" in reasoning_lower) and last_action == "fill":
print(f" ⚠️ Goal check suggests different action (click), not reusing fill instruction")
reuse_previous_instruction = False
elif last_llm_suggestion:
reused_event = (last_llm_suggestion.get("event") or "").upper()
reused_text = last_llm_suggestion.get("text") or ""
print(f" ↻ Reusing previous instruction: {reused_event} → '{reused_text}'")
reuse_previous_instruction = True
else:
reuse_previous_instruction = False
elif last_llm_suggestion:
reused_event = (last_llm_suggestion.get("event") or "").upper()
reused_text = last_llm_suggestion.get("text") or ""
print(f" ↻ Reusing previous instruction: {reused_event} → '{reused_text}'")
reuse_previous_instruction = True
else:
print(" ⚠️ No previous instruction to reuse; requesting a new one.")
reuse_previous_instruction = False
except Exception as cmp_err:
print(f" ⚠️ Screenshot comparison failed: {cmp_err}")
previous_screenshot_path = shot
if not duplicate_screenshot:
reuse_previous_instruction = False
# LOOP: Keep going until goal is met
# NO PAGE DESCRIPTION - just ask what to do next
# Build context from previous actions - be more descriptive
context_parts = []
if action_history:
context_parts.append("What I did in previous steps:")
for action in action_history[-10:]: # Last 10 actions
step_num = action.get("step", "?")
action_type = action.get("action", "unknown")
target = action.get("target", "")
value = action.get("value", "")
result = action.get("result", "")
if action_type == "fill" and value:
context_parts.append(f" Step {step_num}: Filled '{target}' with '{value}' → {result}")
elif action_type == "click":
context_parts.append(f" Step {step_num}: Clicked '{target}' → {result}")
else:
context_parts.append(f" Step {step_num}: {action_type.upper()} '{target}' → {result}")
# Add summary of workflow state
recent_actions_summary = []
for action in action_history[-5:]:
action_type = action.get("action", "")
if action_type == "click":
recent_actions_summary.append(f"clicked {action.get('target', '')}")
elif action_type == "fill":
recent_actions_summary.append(f"filled {action.get('target', '')}")
if recent_actions_summary:
context_parts.append(f"\nRecent workflow: {' → '.join(recent_actions_summary)}")
context_parts.append("IMPORTANT: If you see a form/modal, you need to FILL it and SUBMIT it. The goal is not complete until the item is actually created and visible.")
else:
context_parts.append("Starting fresh.")
context_str = "\n".join(context_parts) if context_parts else ""
# Summarize context if too long (to avoid rate limits)
if len(context_str) > 2000:
recent_actions = action_history[-5:] # Keep only last 5 if too long
context_parts = ["What I did in previous steps:"]
for action in recent_actions:
step_num = action.get("step", "?")
action_type = action.get("action", "unknown")
target = action.get("target", "")
result = action.get("result", "")
context_parts.append(f" Step {step_num}: {action_type.upper()} '{target}' → {result}")
context_parts.append(f"(Summary: Completed {len(action_history)} total actions)")
context_str = "\n".join(context_parts)
# Ask LLM what to do next - SIMPLE, NO ANALYSIS
# Add context about recent clicks to help avoid loops
recent_clicks_context = ""
if action_history:
recent_clicks = [a for a in action_history[-3:] if a.get("action") == "click"]
if recent_clicks:
clicked_texts = [a.get("target") for a in recent_clicks]
recent_clicks_context = f"\n⚠️ Recently clicked: {', '.join(clicked_texts)}"
recent_clicks_context += "\nIf the UI hasn't changed, try a DIFFERENT element or more specific text."
# Add goal check context if available
goal_context = ""
if goal_reasoning and not goal_completed:
goal_context = f"\n📋 Goal status: Not completed yet. {goal_reasoning}"
if next_steps:
goal_context += f"\nSuggested next steps: {', '.join(next_steps[:2])}"
prompt = f"""
Goal: {task_description}
{context_str}{recent_clicks_context}{goal_context}
What do I do next?
REMEMBER: The goal is ONLY complete when the item is ACTUALLY CREATED and visible (e.g., task appears in list, project shows in dashboard).
If you see a form/modal, you must FILL required fields and SUBMIT/CREATE to complete the goal.
Just seeing the word "{action_goal.split('_')[0]}" in the UI doesn't mean it's created - you need to see the actual item in a list or confirmation message.
IMPORTANT RULES:
1. If there are multiple similar elements (e.g., multiple "New" buttons), be VERY SPECIFIC.
2. Use the FULL visible text or unique identifier to avoid clicking the wrong one.
3. The "text" field should contain ONLY letters (a-z, A-Z) and numbers (0-9). NO special characters, symbols, or punctuation.
4. Remove all special characters like: +, -, _, @, #, $, %, &, *, (, ), [, ], {{, }}, |, \\, /, <, >, =, !, ?, ., ,, ;, :, ', ", etc.
5. Replace spaces with single spaces and trim whitespace.
6. Examples:
- "Blank + Project" → "Blank Project"
- "New-Project" → "New Project"
- "Create_Task!" → "Create Task"
- "Save & Continue" → "Save Continue"
CRITICAL: Return ONLY the JSON object. Do NOT include any reasoning, explanation, or text before or after the JSON.
Do NOT write sentences like "The user is currently viewing..." or "They must select..."
ONLY return the JSON object, nothing else.
Return ONLY this JSON (no other text):
{{
"event": "click|fill|done",
"text": "clean text with only letters numbers and single spaces"
}}
"""
event = ""
text = ""
if reuse_previous_instruction:
event = (last_llm_suggestion.get("event") or "").lower()
text = (last_llm_suggestion.get("text") or "").strip()
if not event or not text:
print("⚠️ Previous instruction incomplete; requesting fresh guidance.")
reuse_previous_instruction = False
else:
print(f"\n🔁 Action (reused): {event.upper()} → '{text}'")
if not reuse_previous_instruction:
llm_response = detector.analyze_screenshot(shot, prompt)
# Wait 7 seconds after LLM call
time.sleep(7)
# Parse response - extract JSON even if LLM added reasoning
try:
cleaned = detector._clean_json_like(llm_response)
if not cleaned:
print(f"❌ No JSON found in LLM response")
print(f" Raw response: {llm_response[:200]}...")