Skip to content

The agent that turns websites into APIs!

fix: set process title at module level instead of in main()

kalil032194f9e3198855
diff --git a/src/reverse_api/browser.py b/src/reverse_api/browser.py
index a72937a..af04dbe 100644
--- a/src/reverse_api/browser.py
+++ b/src/reverse_api/browser.py
@@ -210,11 +210,11 @@ class ManualBrowser:
self.output_dir = output_dir
self.use_real_chrome = use_real_chrome
self.enable_action_recording = enable_action_recording
-
+
self.har_dir = get_har_dir(run_id, output_dir)
self.har_path = self.har_dir / "recording.har"
self.metadata_path = self.har_dir / "metadata.json"
-
+
self._playwright = None
self._browser: Browser | None = None
self._context: BrowserContext | None = None
@@ -226,15 +226,15 @@ class ManualBrowser:
def _inject_action_recorder(self, page: Page) -> None:
"""Inject action recording script into page.
-
+
Uses console.log + page.on('console') for reliable capture.
Works best with stealth Chromium mode (not real Chrome).
"""
if not self.enable_action_recording:
return
-
+
# Simple JS that logs actions to console with a special prefix
- recorder_js = '''
+ recorder_js = """
window.__recordedActions = [];
window.__lastUrl = null;
@@ -378,34 +378,35 @@ class ManualBrowser:
}
}
}
- '''
-
+ """
+
# Listen to console for actions
import json
+
last_url = [None] # Mutable to track last URL
-
+
def on_console(msg):
text = msg.text
- if text.startswith('__ACTION__'):
+ if text.startswith("__ACTION__"):
try:
action_json = text[10:] # Remove '__ACTION__' prefix
action_data = json.loads(action_json)
-
+
# Filter duplicate navigations
- if action_data.get('type') == 'navigate':
- url = action_data.get('url', '')
+ if action_data.get("type") == "navigate":
+ url = action_data.get("url", "")
if url == last_url[0]:
return # Skip duplicate
last_url[0] = url
-
+
if self.action_recorder:
self.action_recorder.add_action(RecordedAction(**action_data))
except Exception as e:
console.print(f" [dim]action parse error: {e}[/dim]")
-
+
page.on("console", on_console)
page.add_init_script(recorder_js)
-
+
console.print(" [dim]action recording enabled[/dim]")
def _save_metadata(self, end_time: str) -> None:
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.py
index 41e3ca3..3db0006 100644
--- a/src/reverse_api/cli.py
+++ b/src/reverse_api/cli.py
@@ -50,6 +50,9 @@ from .utils import (
parse_record_only_tag,
)
+setproctitle.setproctitle("reverse-api-engineer")
+setproctitle.setthreadtitle("reverse-api-engineer")
+
console = Console()
config_manager = ConfigManager(get_config_path())
session_manager = SessionManager(get_history_path())
@@ -375,8 +378,6 @@ def main(ctx: click.Context):
Run without a subcommand to start the interactive REPL; use agent, manual,
or engineer for CLI mode.
"""
- setproctitle.setproctitle("reverse-api-engineer")
- setproctitle.setthreadtitle("reverse-api-engineer")
if ctx.invoked_subcommand is None:
repl_loop()
diff --git a/src/reverse_api/playwright_codegen.py b/src/reverse_api/playwright_codegen.py
index f6a36ca..3e1d63c 100644
--- a/src/reverse_api/playwright_codegen.py
+++ b/src/reverse_api/playwright_codegen.py
@@ -16,32 +16,33 @@ class PlaywrightCodeGenerator:
def _clean_actions(self, actions: List[RecordedAction]) -> List[RecordedAction]:
"""Clean up actions (deduplicate fills, remove redundant events)."""
cleaned = []
-
+
for i, action in enumerate(actions):
# For 'fill' actions on the same selector, only keep the last one
if action.type == "fill":
# Look ahead to see if there's another fill for this selector
is_last_fill = True
- for next_action in actions[i + 1:]:
+ for next_action in actions[i + 1 :]:
if next_action.type == "fill" and next_action.selector == action.selector:
is_last_fill = False
break
if next_action.type != "fill":
# If interaction changes (e.g. click), we must keep the current fill
break
-
+
if is_last_fill:
cleaned.append(action)
else:
cleaned.append(action)
-
+
return cleaned
-
+
def _get_base_url(self, url: str | None) -> str | None:
"""Extract base URL (without query params) for comparison."""
if not url:
return None
from urllib.parse import urlparse
+
parsed = urlparse(url)
return f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
@@ -64,7 +65,7 @@ class PlaywrightCodeGenerator:
' "--disable-extensions",',
' "--no-first-run",',
' "--no-default-browser-check",',
- ']',
+ "]",
"",
"",
"def main():",
@@ -83,8 +84,8 @@ class PlaywrightCodeGenerator:
]
if self.start_url:
- lines.append(f' # Start URL')
- lines.append(f' page.goto({json.dumps(self.start_url)})')
+ lines.append(f" # Start URL")
+ lines.append(f" page.goto({json.dumps(self.start_url)})")
lines.append("")
current_url = self.start_url
@@ -93,14 +94,14 @@ class PlaywrightCodeGenerator:
for action in self.actions:
if action.type == "click" and action.selector:
lines.append(f" page.click({json.dumps(action.selector)})")
-
+
elif action.type == "fill" and action.selector and action.value is not None:
# Use json.dumps to safely escape newlines, quotes, and backslashes
lines.append(f" page.fill({json.dumps(action.selector)}, {json.dumps(action.value)})")
-
+
elif action.type == "press" and action.selector and action.value is not None:
lines.append(f" page.press({json.dumps(action.selector)}, {json.dumps(action.value)})")
-
+
elif action.type == "navigate":
# Skip if same as start URL or very similar (just different query params)
nav_base = self._get_base_url(action.url)
@@ -113,18 +114,20 @@ class PlaywrightCodeGenerator:
# Add a small delay between actions as requested
lines.append(" page.wait_for_timeout(1000)")
- lines.extend([
- "",
- " # Keep browser open for a moment",
- " page.wait_for_timeout(2000)",
- "",
- " context.close()",
- " browser.close()",
- "",
- "",
- "if __name__ == '__main__':",
- " main()",
- ""
- ])
+ lines.extend(
+ [
+ "",
+ " # Keep browser open for a moment",
+ " page.wait_for_timeout(2000)",
+ "",
+ " context.close()",
+ " browser.close()",
+ "",
+ "",
+ "if __name__ == '__main__':",
+ " main()",
+ "",
+ ]
+ )
return "\n".join(lines)