XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

New Grok provider

ee26d847
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

8 个文件 +896 -271
Modified .gitignore +2 -1
@@ -17,4 +17,5 @@ playground
17 17 .vscode
18 18 .gradle
19 19 windows
20 build
20 build
21 assets
Modified android/README.md +13 -0
@@ -56,3 +56,16 @@ WebView polls /chat/ until 200, then loads it (2-thread executor: server + polle
56 56 native JS bridge (`window.AndroidClipboard` → `ClipboardManager`), so copy/paste works
57 57 reliably inside the WebView
58 58 - **Text selection**: long-press works natively; WebView text selection menu is enabled by default
59
60 ## Provider browser automation (CDP)
61
62 Providers that need a browser (e.g. Cloudflare) use `CDPSession`. On Android there is no
63 installable Chrome, so `CDPSession` attaches to the app's own **WebView**:
64
65 - `MainActivity` enables `WebView.setWebContentsDebuggingEnabled(true)`, which exposes the
66 DevTools abstract socket `@webview_devtools_remote_<pid>`
67 - `CDPSession` (mode `webview`, auto-detected on Android or forced with `G4F_BROWSER_MODE=webview`)
68 connects to that socket with an aiohttp `UnixConnector` and speaks plain CDP
69 - On close, the session navigates the WebView back to the page it showed before automation
70 - Limitation: there is only one WebView, so sessions cannot run in parallel tabs and
71 automation navigation is visible in the app UI
Modified android/app/src/main/java/dev/g4f/android/MainActivity.java +131 -5
@@ -15,13 +15,19 @@ import android.webkit.WebChromeClient;
15 15 import android.webkit.WebView;
16 16 import android.webkit.WebViewClient;
17 17 import android.webkit.WebSettings;
18 import android.view.Gravity;
18 19 import android.view.KeyEvent;
20 import android.view.ViewGroup;
21 import android.widget.Button;
22 import android.widget.FrameLayout;
19 23
20 24 import java.io.File;
21 25 import java.io.FileOutputStream;
22 26 import java.io.IOException;
23 27 import java.io.InputStream;
24 28 import java.io.OutputStream;
29 import java.util.LinkedHashMap;
30 import java.util.Map;
25 31 import java.util.concurrent.ExecutorService;
26 32 import java.util.concurrent.Executors;
27 33
@@ -31,10 +37,11 @@ import com.chaquo.python.android.AndroidPlatform;
31 37 public class MainActivity extends Activity {
32 38
33 39 private WebView webView;
40 private FrameLayout rootLayout;
34 41 private ExecutorService executor;
35 42 public static final int PORT = 1337;
36 43 private static final String APP_DIR = "app";
37 private static final String EXTRACTION_VERSION = "3"; // bump to force re-extraction
44 private static final String EXTRACTION_VERSION = "5"; // bump to force re-extraction
38 45
39 46 // File chooser (image / file upload from the chat UI)
40 47 private static final int FILE_CHOOSER_REQUEST = 1001;
@@ -47,6 +54,16 @@ public class MainActivity extends Activity {
47 54 Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA
48 55 };
49 56
57 // ── Automation WebViews (CDP targets) ─────────────────────────────
58 // Dedicated WebViews created on demand for provider browser automation.
59 // Each one shows up as its own "page" target on the app's WebView
60 // DevTools socket, so CDPSession can attach to it without hijacking the
61 // chat UI. It is shown in front of the chat UI (with a close button) and
62 // WebView debugging is enabled while at least one automation target
63 // exists — and disabled again when the last one is closed.
64 private final Map<String, WebView> automationWebViews = new LinkedHashMap<>();
65 private int automationRefCount = 0;
66
50 67 @Override
51 68 protected void onCreate(Bundle savedInstanceState) {
52 69 super.onCreate(savedInstanceState);
@@ -58,6 +75,10 @@ public class MainActivity extends Activity {
58 75 }
59 76
60 77 webView = new WebView(this);
78 // WebView remote debugging is enabled only while automation targets
79 // exist (see createAutomationWebView) and disabled again when the
80 // last one is closed. The DevTools socket (@webview_devtools_remote_)
81 // is exposed on demand for the embedded Python CDPSession.
61 82 WebSettings ws = webView.getSettings();
62 83 ws.setJavaScriptEnabled(true);
63 84 ws.setDomStorageEnabled(true);
@@ -70,6 +91,7 @@ public class MainActivity extends Activity {
70 91 ws.setUserAgentString("Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36");
71 92
72 93 webView.addJavascriptInterface(new ClipboardBridge(), "AndroidClipboard");
94 webView.addJavascriptInterface(new AutomationBridge(), "G4FAutomation");
73 95 webView.setWebViewClient(new WebViewClient() {
74 96 @Override
75 97 public void onPageFinished(WebView view, String url) {
@@ -105,7 +127,10 @@ public class MainActivity extends Activity {
105 127 }
106 128 });
107 129
108 setContentView(webView);
130 rootLayout = new FrameLayout(this);
131 rootLayout.addView(webView, new FrameLayout.LayoutParams(
132 FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
133 setContentView(rootLayout);
109 134
110 135 startServer();
111 136 }
@@ -153,6 +178,92 @@ public class MainActivity extends Activity {
153 178 return new File(getFilesDir(), APP_DIR);
154 179 }
155 180
181 // ── Automation WebView management (called from the JS bridge) ──────
182
183 /** Create a visible automation WebView in front of the chat UI and start
184 * loading {@code url}. It appears as its own CDP target on the app's
185 * DevTools socket. A close button lets the user dismiss it; WebView
186 * debugging is enabled while any automation target exists. Runs on the
187 * UI thread. */
188 private void createAutomationWebView(final String targetId, final String url) {
189 runOnUiThread(() -> {
190 if (automationWebViews.containsKey(targetId)) return;
191 WebView aw = new WebView(this);
192 WebSettings s = aw.getSettings();
193 s.setJavaScriptEnabled(true);
194 s.setDomStorageEnabled(true);
195 s.setUserAgentString(webView.getSettings().getUserAgentString());
196 aw.setWebViewClient(new WebViewClient());
197 aw.setWebChromeClient(new WebChromeClient());
198
199 // Container: the automation WebView plus a close button on top,
200 // layered in front of the chat UI.
201 FrameLayout container = new FrameLayout(this);
202 container.addView(aw, new FrameLayout.LayoutParams(
203 FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
204 Button closeBtn = new Button(this);
205 closeBtn.setText("✕ Close");
206 closeBtn.setOnClickListener(v -> destroyAutomationWebView(targetId));
207 FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(
208 FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT,
209 Gravity.TOP | Gravity.END);
210 btnParams.setMargins(0, 48, 24, 0);
211 container.addView(closeBtn, btnParams);
212
213 automationWebViews.put(targetId, aw);
214 if (automationRefCount == 0) {
215 WebView.setWebContentsDebuggingEnabled(true);
216 }
217 automationRefCount++;
218 rootLayout.addView(container, new FrameLayout.LayoutParams(
219 FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
220 container.bringToFront();
221 aw.loadUrl(url);
222 android.util.Log.i("g4f-automation", "created target " + targetId + " -> " + url);
223 });
224 }
225
226 /** Destroy the automation WebView for {@code targetId} (via close button
227 * or the Python bridge). When the last one is gone, WebView debugging is
228 * disabled again. Runs on the UI thread. */
229 private void destroyAutomationWebView(final String targetId) {
230 runOnUiThread(() -> {
231 WebView aw = automationWebViews.remove(targetId);
232 if (aw != null) {
233 automationRefCount = Math.max(0, automationRefCount - 1);
234 if (automationRefCount == 0) {
235 WebView.setWebContentsDebuggingEnabled(false);
236 }
237 ViewGroup container = (ViewGroup) aw.getParent();
238 if (container != null && container.getParent() instanceof ViewGroup) {
239 ((ViewGroup) container.getParent()).removeView(container);
240 }
241 aw.destroy();
242 android.util.Log.i("g4f-automation", "destroyed target " + targetId
243 + " (" + automationRefCount + " remaining)");
244 }
245 });
246 }
247
248 /** JS bridge: lets the embedded Python server create/close automation
249 * WebViews from the chat UI (window.G4FAutomation.*). */
250 class AutomationBridge {
251 /** Create a new offscreen automation WebView (a new CDP target).
252 * Returns a unique target id used later for closing. */
253 @JavascriptInterface
254 public String createTarget(final String url) {
255 final String targetId = "auto-" + System.nanoTime();
256 createAutomationWebView(targetId, url != null && url.length() > 0 ? url : "about:blank");
257 return targetId;
258 }
259
260 /** Close a previously created automation WebView by target id. */
261 @JavascriptInterface
262 public void closeTarget(final String targetId) {
263 if (targetId != null) destroyAutomationWebView(targetId);
264 }
265 }
266
156 267 /** Recursively copy APK assets under assetPath into target. */
157 268 private void extractAssets(String assetPath, File target) throws IOException {
158 269 String[] entries = getAssets().list(assetPath);
@@ -286,14 +397,29 @@ public class MainActivity extends Activity {
286 397 @Override
287 398 protected void onDestroy() {
288 399 if (executor != null) executor.shutdown();
400 // Tear down any leftover automation WebViews
401 for (WebView aw : automationWebViews.values()) {
402 aw.destroy();
403 }
404 automationWebViews.clear();
405 automationRefCount = 0;
289 406 super.onDestroy();
290 407 }
291 408
292 409 @Override
293 410 public boolean onKeyDown(int keyCode, KeyEvent event) {
294 if (keyCode == KeyEvent.KEYCODE_BACK && webView != null && webView.canGoBack()) {
295 webView.goBack();
296 return true;
411 if (keyCode == KeyEvent.KEYCODE_BACK) {
412 // Back closes the most recently opened automation WebView first
413 if (!automationWebViews.isEmpty()) {
414 String lastId = null;
415 for (String id : automationWebViews.keySet()) lastId = id;
416 destroyAutomationWebView(lastId);
417 return true;
418 }
419 if (webView != null && webView.canGoBack()) {
420 webView.goBack();
421 return true;
422 }
297 423 }
298 424 return super.onKeyDown(keyCode, event);
299 425 }
Modified g4f-android-debug.apk +0 -0
二进制文件已变更,无法进行逐行预览。
Modified g4f/cookies.py +2 -0
@@ -80,6 +80,8 @@ class BrowserConfig:
80 80 headless: bool = True
81 81 # "extension": route CDP through the g4f browser extension relay
82 82 # (see g4f/api/cdp_relay.py) instead of a local Chrome CDP port.
83 # "webview": attach to the Android app's WebView via its DevTools socket
84 # (auto-detected on Android when no CDP port is configured).
83 85 browser_mode: str = None
84 86
85 87 @staticmethod
Modified g4f/requests/cdp.py +367 -6
@@ -24,6 +24,10 @@ Common features:
24 24 • Auto-detects Chrome/Chromium/Edge path via BrowserConfig or system PATH.
25 25 • Stores browser profiles in g4f cookies directory (no project root pollution).
26 26 • Offscreen windowed mode (--window-position=-2000,-2000) bypasses Turnstile.
27 • Android app: creates dedicated automation WebViews through its DevTools
28 socket (browser_mode="webview", auto-detected — no Chrome needed). Each
29 target is shown in front of the app UI with a close button; WebView
30 debugging is disabled again when the last target is closed.
27 31 """
28 32
29 33 import asyncio
@@ -38,7 +42,7 @@ import time
38 42 import urllib.request
39 43 from typing import Optional, Dict, Any, List, AsyncIterator
40 44 import hashlib
41 from urllib.parse import quote_plus
45 from urllib.parse import quote_plus, urlparse
42 46 import datetime
43 47
44 48 try:
@@ -401,6 +405,133 @@ def get_shared_browser(
401 405 + (f": {stderr_output}" if stderr_output else "")
402 406 )
403 407
408 # ──────────────────────────────────────────────────────────────────────
409 # Android WebView support — drive the app's own WebView via CDP.
410 # ──────────────────────────────────────────────────────────────────────
411
412 def _is_android() -> bool:
413 """Return True when running under Android (e.g. the Chaquopy app)."""
414 if os.path.exists("/system/build.prop"):
415 return True
416 try:
417 import java # Chaquopy java bridge # noqa: F401
418 return True
419 except ImportError:
420 return False
421
422 def _enable_webview_debugging() -> bool:
423 """Enable remote debugging for all WebViews in this app (process-wide)."""
424 try:
425 from java import jclass
426
427 WebView = jclass("android.webkit.WebView")
428 WebView.setWebContentsDebuggingEnabled(True)
429 return True
430 except Exception as e:
431 debug.log(f"CDP: failed to enable WebView debugging: {e}")
432 return False
433
434 def _disable_webview_debugging() -> bool:
435 """Disable remote debugging for all WebViews in this app (process-wide).
436
437 Called when the last automation target has been closed, so the DevTools
438 socket is not exposed while no automation is running.
439 """
440 try:
441 from java import jclass
442
443 WebView = jclass("android.webkit.WebView")
444 WebView.setWebContentsDebuggingEnabled(False)
445 debug.log("CDP: WebView debugging disabled (no targets left)")
446 return True
447 except Exception as e:
448 debug.log(f"CDP: failed to disable WebView debugging: {e}")
449 return False
450
451 def _find_webview_devtools_socket() -> str:
452 """
453 Find the abstract Unix socket name of the WebView DevTools server.
454
455 The WebView listens on ``@webview_devtools_remote_<pid>`` in the app's
456 own process. Since Android 10 apps can no longer read /proc/net/unix,
457 so the pid based name is preferred and the scan is only a fallback.
458 """
459 own = f"webview_devtools_remote_{os.getpid()}"
460 candidates = []
461 try:
462 with open("/proc/net/unix") as fp:
463 for line in fp:
464 name = line.split()[-1].lstrip("@")
465 if name.startswith("webview_devtools_remote_"):
466 candidates.append(name)
467 except Exception:
468 pass
469 if own in candidates:
470 return own
471 if candidates:
472 return candidates[0]
473 return own
474
475 def _webview_devtools_request(socket_name: str, path: str, timeout: float = 5.0):
476 """HTTP GET against the WebView DevTools server over its abstract Unix socket."""
477 import http.client
478 import socket as _socket
479
480 sock = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
481 sock.settimeout(timeout)
482 try:
483 sock.connect("\0" + socket_name)
484 conn = http.client.HTTPConnection("localhost")
485 conn.sock = sock # reuse the abstract socket connection
486 conn.request("GET", path, headers={"Host": "localhost", "Connection": "close"})
487 body = conn.getresponse().read()
488 return json.loads(body.decode("utf-8", errors="replace"))
489 finally:
490 try:
491 sock.close()
492 except Exception:
493 pass
494
495 # DevTools target ids claimed by active webview-mode sessions, so parallel
496 # sessions don't attach to the same freshly created automation WebView.
497 _webview_claimed_targets = set()
498
499 async def _webview_bridge_call(socket_name: str, target: dict, expression: str, timeout: float = 10.0):
500 """Evaluate a JS expression on a WebView target and return its value.
501
502 Used to reach the app's automation bridge (window.G4FAutomation) on the
503 chat UI page, which creates and closes dedicated automation WebViews.
504 """
505 import aiohttp
506
507 ws_path = urlparse(target.get("webSocketDebuggerUrl", "")).path
508 if not ws_path:
509 ws_path = f"/devtools/page/{target.get('id')}"
510 connector = aiohttp.UnixConnector(path="\0" + socket_name)
511 async with aiohttp.ClientSession(connector=connector) as session:
512 ws = await session.ws_connect(f"ws://localhost{ws_path}")
513 try:
514 await ws.send_str(json.dumps({
515 "id": 1,
516 "method": "Runtime.evaluate",
517 "params": {"expression": expression, "returnByValue": True},
518 }))
519 deadline = time.time() + timeout
520 while time.time() < deadline:
521 msg = await asyncio.wait_for(ws.receive(), timeout=deadline - time.time())
522 if msg.type != aiohttp.WSMsgType.TEXT:
523 if msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):
524 break
525 continue
526 data = json.loads(msg.data)
527 if data.get("id") == 1:
528 if "error" in data:
529 raise RuntimeError(f"WebView bridge error: {data['error']}")
530 return data.get("result", {}).get("result", {}).get("value")
531 finally:
532 await ws.close()
533 raise TimeoutError("WebView bridge call timed out")
534
404 535
405 536 class CDPSession:
406 537 def __init__(
@@ -442,6 +573,17 @@ class CDPSession:
442 573 # True when this session runs through the browser-extension relay
443 574 # (g4f/api/cdp_relay.py) instead of a local Chrome CDP port.
444 575 self._via_extension = False
576 # True when this session is attached to the Android app's WebView
577 # (browser_mode="webview") instead of a local Chrome CDP port.
578 self._via_webview = False
579 self._webview_initial_url: Optional[str] = None
580 # WebView automation target bookkeeping: the DevTools socket name, the
581 # bridge id of the dedicated automation WebView created for this
582 # session (None when falling back to the chat UI page) and the target
583 # id of the chat UI page used for bridge calls.
584 self._webview_socket: Optional[str] = None
585 self._webview_automation_id: Optional[str] = None
586 self._webview_control_id: Optional[str] = None
445 587
446 588 # Network event loggers
447 589 self.network_requests: List[dict] = []
@@ -453,12 +595,22 @@ class CDPSession:
453 595 return not self._closing and not self._connection_lost and self.ws is not None and not self.ws.closed
454 596
455 597 async def start(self):
456 """Launch/get shared Chrome and connect via CDP targeting a new tab."""
598 """Connect a CDP target: Android WebView, extension relay or shared Chrome."""
599 browser_mode = getattr(BrowserConfig, "browser_mode", None)
457 600 # Extension mode: route through the g4f browser extension relay
458 601 # (g4f/api/cdp_relay.py) instead of a local Chrome CDP port.
459 if getattr(BrowserConfig, "browser_mode", None) == "extension":
602 if browser_mode == "extension":
460 603 return await self._start_via_extension()
461 604
605 # WebView mode: attach to the Android app's own WebView through its
606 # DevTools socket — there is no installable Chrome on Android. Forced
607 # with G4F_BROWSER_MODE=webview, auto-detected on Android when no
608 # explicit CDP port is configured.
609 if browser_mode == "webview" or (
610 browser_mode is None and self.port is None and _is_android()
611 ):
612 return await self._start_via_webview()
613
462 614 if self.port is None:
463 615 self.port = get_shared_browser(
464 616 self.host, self.port, self.headless, self.proxy, self.browser_args
@@ -585,6 +737,205 @@ class CDPSession:
585 737 await self.call("Runtime.enable")
586 738 await self.call("Network.enable")
587 739
740 async def _start_via_webview(self):
741 """
742 Run automation in a dedicated WebView of the Android app.
743
744 The app's chat UI WebView exposes a JS bridge (window.G4FAutomation)
745 that creates additional WebViews on demand. Each one appears as its
746 own "page" target on the app's DevTools socket
747 ``@webview_devtools_remote_<pid>``, is shown in front of the chat UI
748 (with a close button) and can be attached via a WebSocket (aiohttp
749 UnixConnector). Everything else (call/evaluate/events) works
750 unchanged, because the WebView speaks plain CDP.
751
752 Without the bridge (older app builds) this falls back to attaching to
753 the chat UI page itself.
754 """
755 import aiohttp
756
757 if not _enable_webview_debugging():
758 raise RuntimeError(
759 "CDP: could not enable WebView debugging — not running inside the Android app?"
760 )
761
762 socket_name = _find_webview_devtools_socket()
763 # The DevTools socket appears shortly after debugging is enabled.
764 targets = None
765 deadline = time.time() + 10
766 while time.time() < deadline:
767 try:
768 targets = _webview_devtools_request(socket_name, "/json/list")
769 if isinstance(targets, list) and targets:
770 break
771 except Exception:
772 pass
773 await asyncio.sleep(0.5)
774 if not targets or not isinstance(targets, list):
775 raise RuntimeError(
776 f"CDP: no WebView DevTools targets on socket @{socket_name}"
777 )
778 self._webview_socket = socket_name
779
780 pages = [t for t in targets if t.get("type") == "page"]
781 if not pages:
782 raise RuntimeError(f"CDP: no page target in WebView DevTools: {targets}")
783 # The app's chat UI acts as the control page for the automation bridge.
784 control = next((t for t in pages if "127.0.0.1" in t.get("url", "")), None)
785
786 # Prefer a dedicated automation WebView (a new CDP target) created via
787 # the app's JS bridge: it is shown in front of the chat UI and keeps
788 # the chat UI itself untouched. Parallel sessions each get their own.
789 target = None
790 if control is not None:
791 target = await self._create_webview_target(socket_name, control, targets)
792
793 if target is None:
794 # Fallback: attach to the app's chat UI page directly.
795 target = control if control is not None else pages[0]
796 debug.log("CDP: no automation bridge — attaching to the chat UI page")
797
798 ws_path = urlparse(target.get("webSocketDebuggerUrl", "")).path
799 if not ws_path:
800 ws_path = f"/devtools/page/{target.get('id')}"
801 self.target_id = target.get("id")
802 self._webview_initial_url = target.get("url")
803 self._via_webview = True
804 debug.log(
805 f"CDP: attached to Android WebView target {self.target_id} "
806 f"({self._webview_initial_url}) via @{socket_name}"
807 )
808
809 connector = aiohttp.UnixConnector(path="\0" + socket_name)
810 self.session = aiohttp.ClientSession(connector=connector)
811 self.ws = await self.session.ws_connect(f"ws://localhost{ws_path}")
812 self._closing = False
813 self._receive_task = asyncio.create_task(self._receiver_loop())
814
815 # Enable essential domains (no viewport/UA overrides — the WebView is
816 # a real, visible browser and the app already configured it).
817 await self.call("Page.enable")
818 await self.call("DOM.enable")
819 await self.call("Runtime.enable")
820 await self.call("Network.enable")
821
822 async def _create_webview_target(
823 self, socket_name: str, control: dict, known_targets: list
824 ) -> Optional[dict]:
825 """Create a dedicated automation WebView (new CDP target) via the app's
826 JS bridge and return its DevTools target. Returns None when the bridge
827 is unavailable or the target never shows up."""
828 known_ids = {t.get("id") for t in known_targets}
829 try:
830 automation_id = await _webview_bridge_call(
831 socket_name, control,
832 "(window.G4FAutomation && window.G4FAutomation.createTarget('about:blank')) || null",
833 )
834 except Exception as e:
835 debug.log(f"CDP: WebView bridge createTarget failed: {e}")
836 return None
837 if not isinstance(automation_id, str) or not automation_id:
838 return None
839
840 # Wait for the new WebView to appear as a page target on the socket.
841 deadline = time.time() + 10
842 while time.time() < deadline:
843 try:
844 fresh = _webview_devtools_request(socket_name, "/json/list")
845 new_pages = [
846 t for t in (fresh or [])
847 if isinstance(t, dict)
848 and t.get("type") == "page"
849 and t.get("id") not in known_ids
850 and t.get("id") not in _webview_claimed_targets
851 ]
852 if new_pages:
853 target = new_pages[0]
854 _webview_claimed_targets.add(target.get("id"))
855 self._webview_automation_id = automation_id
856 self._webview_control_id = control.get("id")
857 debug.log(
858 f"CDP: created automation WebView target {target.get('id')} "
859 f"(bridge id {automation_id})"
860 )
861 return target
862 except Exception:
863 pass
864 await asyncio.sleep(0.25)
865
866 # Target never showed up — destroy the stray WebView again.
867 debug.log("CDP: automation WebView target did not appear — cleaning up")
868 try:
869 await _webview_bridge_call(
870 socket_name, control,
871 "window.G4FAutomation && window.G4FAutomation.closeTarget(%s)"
872 % json.dumps(automation_id),
873 )
874 except Exception:
875 pass
876 return None
877
878 async def _close_webview_target(self):
879 """Tear down this webview-mode session.
880
881 Dedicated automation WebViews (created through the app's JS bridge)
882 are destroyed via the bridge — the app removes them from the UI and
883 disables WebView debugging when the last one is closed. Fallback
884 sessions attached to the chat UI only navigate back, and debugging is
885 disabled when no other page target is left.
886 """
887 if self._webview_automation_id:
888 _webview_claimed_targets.discard(self.target_id)
889 control = None
890 try:
891 targets = _webview_devtools_request(self._webview_socket, "/json/list")
892 pages = [
893 t for t in (targets or [])
894 if isinstance(t, dict) and t.get("type") == "page"
895 ]
896 control = next(
897 (t for t in pages if t.get("id") == self._webview_control_id),
898 next((t for t in pages if "127.0.0.1" in t.get("url", "")), None),
899 )
900 except Exception:
901 pass # Socket gone — debugging already disabled (last target closed)
902 if control is not None:
903 try:
904 await _webview_bridge_call(
905 self._webview_socket, control,
906 "window.G4FAutomation && window.G4FAutomation.closeTarget(%s)"
907 % json.dumps(self._webview_automation_id),
908 )
909 except Exception as e:
910 debug.log(f"CDP: WebView bridge closeTarget failed: {e}")
911 else:
912 # Fallback: the target is the app's chat UI — never close it.
913 # Navigate back to the page the WebView showed before automation.
914 if (
915 self._webview_initial_url
916 and self.ws
917 and not self.ws.closed
918 and not self._connection_lost
919 ):
920 try:
921 await asyncio.wait_for(
922 self.call("Page.navigate", url=self._webview_initial_url),
923 timeout=3.0,
924 )
925 except Exception:
926 pass
927 # Disable WebView debugging when this was the only page left.
928 try:
929 targets = _webview_devtools_request(self._webview_socket, "/json/list")
930 pages = [
931 t for t in (targets or [])
932 if isinstance(t, dict) and t.get("type") == "page"
933 ]
934 if len(pages) <= 1:
935 _disable_webview_debugging()
936 except Exception:
937 pass # Socket gone — debugging already disabled
938
588 939 async def _receiver_loop(self):
589 940 """Listen for WebSocket messages."""
590 941 try:
@@ -1223,9 +1574,17 @@ if (deepseekSendButton) {
1223 1574 The shared browser process is kept alive as long as other CDP sessions
1224 1575 (tabs) are active. When the last session releases its reference the
1225 1576 browser is terminated automatically.
1577
1578 In webview mode a dedicated automation WebView is destroyed through
1579 the app's bridge — WebView debugging is disabled again when the last
1580 automation target is closed. Fallback sessions (attached to the chat
1581 UI) only navigate the WebView back to its initial URL.
1226 1582 """
1227 1583 self._closing = True
1228 1584
1585 if self._via_webview:
1586 await self._close_webview_target()
1587
1229 1588 if self._receive_task:
1230 1589 self._receive_task.cancel()
1231 1590
@@ -1241,7 +1600,9 @@ if (deepseekSendButton) {
1241 1600 self.session = None
1242 1601
1243 1602 if self.target_id:
1244 if self._via_extension:
1603 if self._via_webview:
1604 pass # Automation WebView already destroyed via the app bridge.
1605 elif self._via_extension:
1245 1606 # Extension mode: ask the relay to close the automation tab
1246 1607 # in the extension's browser (agent executes close_tab).
1247 1608 try:
@@ -1264,6 +1625,6 @@ if (deepseekSendButton) {
1264 1625 self.target_id = None
1265 1626
1266 1627 # Release our tab; browser stays alive for reuse by other tabs.
1267 # Extension mode never acquired a shared-browser reference.
1268 if not self._via_extension:
1628 # Extension/webview mode never acquired a shared-browser reference.
1629 if not self._via_extension and not self._via_webview:
1269 1630 release_shared_browser_ref()
Modified g4f/requests/curl_cffi.py +88 -11
@@ -33,6 +33,7 @@ else:
33 33 has_curl_ws = False
34 34 from typing import AsyncGenerator, Any
35 35 from functools import partialmethod
36 import asyncio
36 37 import json
37 38 from ..cookies import BrowserConfig
38 39
@@ -168,34 +169,110 @@ else:
168 169 if has_curl_cffi and has_curl_ws:
169 170
170 171 class WebSocket:
172 """WebSocket wrapper compatible with curl_cffi >= 0.16 (and older).
173
174 curl_cffi 0.16 replaced the old recv()/send() API with AsyncWebSocket
175 (recv_str/send_str, keyword-only timeout, ``closed`` attribute). The
176 wrapper is awaitable directly and also usable as async context manager.
177 """
178
171 179 def __init__(self, session, url, **kwargs) -> None:
172 180 self.session: StreamSession = session
173 181 self.url: str = url
174 182 if "autoping" in kwargs:
175 183 del kwargs["autoping"]
176 184 self.options: dict = kwargs
185 self.inner = None
186 self._closed: bool = False
177 187
178 async def __aenter__(self):
179 self.inner = await self.session._ws_connect(self.url, **self.options)
188 def __await__(self):
189 return self._connect().__await__()
190
191 async def _connect(self):
192 if self.inner is None:
193 self.inner = await self.session._ws_connect(self.url, **self.options)
180 194 return self
181 195
196 async def __aenter__(self):
197 return await self._connect()
198
182 199 async def __aexit__(self, *args):
183 await self.inner.aclose() if hasattr(
184 self.inner, "aclose"
185 ) else await self.inner.close()
200 await self.close()
201
202 @property
203 def closed(self) -> bool:
204 if self._closed:
205 return True
206 if self.inner is None:
207 return False
208 closed = getattr(self.inner, "closed", None)
209 if callable(closed):
210 return closed()
211 return bool(closed)
212
213 async def close(self):
214 self._closed = True
215 if self.inner is not None:
216 inner_close = getattr(self.inner, "close", None)
217 if inner_close is not None:
218 result = inner_close()
219 if asyncio.iscoroutine(result):
220 await result
221 self.inner = None
186 222
187 223 async def receive_str(self, **kwargs) -> str:
224 await self._connect()
225 timeout = kwargs.get("timeout")
226 if hasattr(self.inner, "recv_str"):
227 # curl_cffi >= 0.16: recv_str(*, timeout=None) -> str
228 if timeout:
229 return await self.inner.recv_str(timeout=timeout)
230 return await self.inner.recv_str()
188 231 method = (
189 232 self.inner.arecv if hasattr(self.inner, "arecv") else self.inner.recv
190 233 )
191 bytes, _ = await method()
192 return bytes.decode(errors="ignore")
234 data = await method()
235 if isinstance(data, tuple):
236 data = data[0]
237 return data.decode(errors="ignore") if isinstance(data, bytes) else data
238
239 async def recv(self, **kwargs):
240 """Return (data, flags) like the legacy curl_cffi recv API."""
241 await self._connect()
242 timeout = kwargs.get("timeout")
243 if hasattr(self.inner, "recv"):
244 if timeout:
245 return await self.inner.recv(timeout=timeout)
246 return await self.inner.recv()
247 data = await self.receive_str(**kwargs)
248 return data, 0
193 249
194 250 async def send_str(self, data: str):
195 method = (
196 self.inner.asend if hasattr(self.inner, "asend") else self.inner.send
197 )
198 await method(data.encode(), CurlWsFlag.TEXT)
251 await self._connect()
252 if hasattr(self.inner, "send_str"):
253 # curl_cffi >= 0.16
254 await self.inner.send_str(data)
255 else:
256 method = (
257 self.inner.asend if hasattr(self.inner, "asend") else self.inner.send
258 )
259 await method(data.encode(), CurlWsFlag.TEXT)
260
261 async def send(self, data):
262 await self._connect()
263 if hasattr(self.inner, "send_str"):
264 # curl_cffi >= 0.16
265 if isinstance(data, str):
266 await self.inner.send_str(data)
267 else:
268 await self.inner.send(data)
269 else:
270 method = (
271 self.inner.asend if hasattr(self.inner, "asend") else self.inner.send
272 )
273 await method(
274 data if isinstance(data, bytes) else data.encode(), CurlWsFlag.TEXT
275 )
199 276
200 277 else:
201 278