RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Refactor: delete agent browser (#21599)
Wang Qid717d0c97522
diff --git a/.gitignore b/.gitignoreindex 11a7336d2d..585abe5a47 100644--- a/.gitignore+++ b/.gitignore@@ -53,7 +53,6 @@ nltk_data/uv-x86_64*.tar.gzoffice_oxide*.tar.gzpdf_oxide*.tar.gz-stagehand-server*# Exclude hash-like temporary files like 9b5ad71b2ce5302211f9c61530b329a4922fc6a4*[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*diff --git a/AGENTS.md b/AGENTS.mdindex dc284eca91..84a72316c3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -53,7 +53,7 @@ Use this file as the local operating guide for the current codebase. Prefer the- `web/`: frontend application.- `docker/`: local and production compose files.- `sdk/python/`: legacy Python client SDK pending deletion.-- `tools/scripts/download_dev_deps.py` and `deps/download_deps.py`: Python downloaders for the Go build's dependencies. `download_dev_deps.py` pulls the native static libraries (pdfium, pdf_oxide, office_oxide, onnxruntime) that `build.sh` links; `download_deps.py` pulls the runtime resources (cl100k BPE table, DeepDoc models, embedding tokenizer assets) and installs the stagehand server into the SDK cache. Versions and URLs are defined inline in each downloader (`tools/scripts/download_dev_deps.py` for native static libraries, `deps/download_deps.py` for runtime resources); the tokenizer assets are inlined as `TOKENIZER_ASSETS` in each downloader. Replace these with non-Python preparation before removing Python dependencies.+- `tools/scripts/download_dev_deps.py` and `deps/download_deps.py`: Python downloaders for the Go build's dependencies. `download_dev_deps.py` pulls the native static libraries (pdfium, pdf_oxide, office_oxide, onnxruntime) that `build.sh` links; `download_deps.py` pulls the runtime resources (cl100k BPE table, DeepDoc models, embedding tokenizer assets). Versions and URLs are defined inline in each downloader (`tools/scripts/download_dev_deps.py` for native static libraries, `deps/download_deps.py` for runtime resources); the tokenizer assets are inlined as `TOKENIZER_ASSETS` in each downloader. Replace these with non-Python preparation before removing Python dependencies.- `test/`: contains Python tests, including tests that import the legacy Python implementation directly. Migrate needed coverage to Go tests or frontend tests, then remove the Python tests; keep only tests for supported code.## Go-Specific Rulesdiff --git a/Dockerfile b/Dockerfileindex bea057a0fb..0d15c07785 100644--- a/Dockerfile+++ b/Dockerfile@@ -110,29 +110,6 @@ RUN --mount=type=cache,id=ragflow_apt,target=/var/cache/apt,sharing=locked \fc-cache -f && \rm -rf /var/lib/apt/lists/* && apt-get clean-# Stagehand launches Chrome over CDP; its server binary does not bundle a browser.-ARG CHROME_VERSION=156.0.8078.47-ENV CHROME_PATH=/opt/chrome/chrome-RUN --mount=type=cache,id=ragflow_apt,target=/var/cache/apt,sharing=locked \- apt-get update && \- apt-get install -y --no-install-recommends \- libnss3 libatk-bridge2.0-0 libx11-xcb1 libxcomposite1 libxdamage1 libxfixes3 \- libxrandr2 libgbm1 libasound2t64 libxkbcommon0 libpango-1.0-0 libcairo2 libcups2t64 && \- case "$(dpkg --print-architecture)" in \- amd64) chrome_platform=linux64 ;; \- arm64) chrome_platform=linux-arm64 ;; \- *) echo "Unsupported Chrome architecture" >&2; exit 1 ;; \- esac && \- curl --retry 5 --retry-all-errors -fsSL \- "https://storage.googleapis.com/chrome-for-testing-public/${CHROME_VERSION}/${chrome_platform}/chrome-${chrome_platform}.zip" \- -o /tmp/chrome.zip && \- unzip -q /tmp/chrome.zip -d /opt && \- mv "/opt/chrome-${chrome_platform}" /opt/chrome && \- "$CHROME_PATH" --version && \- "$CHROME_PATH" --headless --no-sandbox --disable-dev-shm-usage --dump-dom about:blank | grep -q '<html>' && \- rm /tmp/chrome.zip && \- rm -rf /var/lib/apt/lists/* && apt-get clean-# Download resource from GitHub to /usr/share/infinity# Ship only the directories required by the runtime tokenizer:# rag - base analyzer dictionaries (mandatory)diff --git a/Dockerfile_base b/Dockerfile_baseindex a84ad82a55..3be671261a 100644--- a/Dockerfile_base+++ b/Dockerfile_base@@ -122,49 +122,6 @@ RUN --mount=type=cache,id=ragflow_apt,target=/var/cache/apt,sharing=locked \apt-get install -y nodejs && \node -v && npm -v-# stagehand-server-v3 (Node.js SEA binary used by Browser component-# in local mode).-#-# The `v3.21.0` value below is the `stagehand-go/v3` Go module-# version pinned in `go.mod`. It is used here only to compute the-# `go_<ver>/` subdirectory that `local.go:cacheDir()` will look in-# for the binary at runtime — that subdirectory name is keyed by-# the Go module's own `internal.PackageVersion`, NOT by the server-# binary's release tag.-#-# The server binary itself is fetched separately by `download_deps.py`-# from the browserbase/stagehand GitHub releases. The two are-# LOOSELY MATCHED — both stay on the v3.x line and remain protocol--# compatible, but the version numbers do NOT track each other (Go-# SDK is at v3.21.0, server binary is at v3.7.2 today). On every-# go.mod bump, refresh the server binary pin in `download_deps.py`-# to the current latest server release; no version correspondence-# is required to maintain.-#-# Drift on the Go SDK pin (this ARG vs go.mod) forces a fresh-# GitHub download at process boot — a hard failure in air-gapped-# deployments. CI cross-checks the two values.-#-# The binary is pre-fetched by `download_deps.py` and shipped via-# the deps image, then written directly to the stagehand-go-# cache path that `local.go:cacheDir()` constructs at runtime —-# `/root/.cache/stagehand/lib/go_<ver>/stagehand-server-v3-<arch>`.-ARG STAGEHAND_GO_VERSION=v3.21.0-RUN --mount=type=bind,from=infiniflow/ragflow_deps:latest,source=/,target=/deps \- set -eux; \- arch="$(uname -m)"; \- case "$arch" in \- x86_64) stagehand_arch=x64 ;; \- aarch64|arm64) stagehand_arch=arm64 ;; \- *) echo "Unsupported architecture: $arch" >&2; exit 1 ;; \- esac; \- stagehand_version="${STAGEHAND_GO_VERSION#v}"; \- stagehand_cache_dir="/root/.cache/stagehand/lib/go_${stagehand_version}"; \- mkdir -p "${stagehand_cache_dir}"; \- cp "/deps/stagehand-server-v3-linux-${stagehand_arch}" \- "${stagehand_cache_dir}/stagehand-server-v3-linux-${stagehand_arch}"; \- chmod +x "${stagehand_cache_dir}/stagehand-server-v3-linux-${stagehand_arch}"-# Add msssql ODBC driver# macOS ARM64 environment, install msodbcsql18.# general x86_64 environment, install msodbcsql17.diff --git a/README.md b/README.mdindex fc8a1ea00a..fba9e6a51b 100644--- a/README.md+++ b/README.md@@ -262,7 +262,7 @@ For document-engine changes, configuration updates, restarting services, and retuv run tools/scripts/download_dev_deps.py```- This is the local-dev one-stop: after one run the environment is ready, and already-present files are skipped so re-running never re-downloads. The image-facing counterpart `deps/download_deps.py` fetches the same runtime resources PLUS the stagehand server binary (used by the Browser component) and skips the native `.a` files — run it only when building the dependency image or in CI, not for local development.+ This is the local-dev one-stop: after one run the environment is ready, and already-present files are skipped so re-running never re-downloads. The image-facing counterpart `deps/download_deps.py` fetches the same runtime resources and skips the native `.a` files — run it only when building the dependency image or in CI, not for local development.`download_dev_deps.py` pulls and unpacks pdfium, pdf_oxide, office_oxide, and onnxruntime under `~/ragflow-native-libs`, and writes the cl100k vocabulary, DeepDoc models, and embedding tokenizer assets under `deps/`. It is a Python script; `uv run` installs its declared dependencies (`requests` and `huggingface-hub`) automatically. Skip this step if you have prepared the same resources by other means. When started from the repository root, Go services automatically find `internal/rag/res/deepdoc`; to start from another directory, set `DEEPDOC_MODEL_DIR` to its absolute path.diff --git a/deps/Dockerfile b/deps/Dockerfileindex e45e64158e..2f189bf3cd 100644--- a/deps/Dockerfile+++ b/deps/Dockerfile@@ -2,6 +2,6 @@# docker build -f Dockerfile -t infiniflow/ragflow_deps:latest .FROM scratch-COPY cl100k_base.tiktoken stagehand-server-v3-linux-x64 stagehand-server-v3-linux-arm64 NotoSansCJKsc-VF.ttf /+COPY cl100k_base.tiktoken NotoSansCJKsc-VF.ttf /COPY huggingface.co /huggingface.codiff --git a/deps/download_deps.py b/deps/download_deps.pyindex 2cfbe621de..62df360fff 100755--- a/deps/download_deps.py+++ b/deps/download_deps.py@@ -10,14 +10,13 @@# ///# This script prepares the runtime / image resources that the dependency image-# ships on Linux x86_64: the cl100k BPE table, the stagehand-server binaries-# (installed into the Go SDK's cache), the Go DeepDoc `.ort` weights+# ships on Linux x86_64: the cl100k BPE table, the Go DeepDoc `.ort` weights# (det/layout/tsr/rec.ort + ocr.res), and the embedding tokenizer assets the Go# counters load.#-# This is the CI / image-build one-stop. It fetches the runtime resources PLUS-# the stagehand server binary, and deliberately does NOT fetch the native static-# libraries the Go build links — those come from tools/scripts/download_dev_deps.py+# This is the CI / image-build one-stop. It fetches the runtime resources+# and deliberately does NOT fetch the native static libraries the Go build links+# — those come from tools/scripts/download_dev_deps.py# and are baked into the server binary by the build stage. Run this once to ready# a dependency image; for local development, run the dev downloader instead.# All version numbers and URLs are defined in the block below; bump a version@@ -47,8 +46,6 @@import argparseimport hashlibimport os-import platform-import reimport shutilimport sysimport tempfile@@ -64,14 +61,6 @@ REPO_ROOT = os.path.dirname(SCRIPT_DIR)# keep the `NAME = "value"` form greppable for consistency with# tools/scripts/download_dev_deps.py.-# stagehand-server release binaries (used by the Browser component in local-# mode). They are LOOSELY matched to the stagehand-go Go module: both stay on-# the v3.x line and remain protocol-compatible, but the two version numbers do-# NOT track each other, so there is no cross-reference to keep in sync here.-# Kept with the "v" prefix because it is used verbatim in the release tag path.-STAGEHAND_SERVER_VERSION = "v3.7.2"--# Noto Sans CJK SC variable TTF, rendered into PDFs by the Go backend# (internal/agent/component/io/pdf_writer.go). When non-empty, it is the pinned# SHA-256 every downloaded/kept font must match. When empty, the hash recorded in@@ -87,31 +76,12 @@ def gh_proxy() -> str:return os.environ.get("GH_PROXY") or ""-def go_module_version(module: str, repo_root: str) -> str:- """Read a Go module's pinned version (the "vX.Y.Z" after its require line)- from `repo_root`/go.mod. Raises RuntimeError when go.mod or the module is- missing — the caller cannot link the right library without it."""- go_mod = os.path.join(repo_root, "go.mod")- if not os.path.isfile(go_mod):- raise RuntimeError(f"go.mod not found at {go_mod}")- with open(go_mod, encoding="utf-8") as file:- match = re.search(rf"{re.escape(module)}\s+v([^\s]+)", file.read())- if match is None:- raise RuntimeError(f"{module} version not found in {go_mod}")- return match.group(1)--def cl100k_url() -> str:"""cl100k BPE table. Hosted on Azure blob storage (NOT a GitHub release),so the GitHub mirror prefix does not apply and is deliberately omitted."""return "https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken"-def stagehand_url(arch: str) -> str:- """stagehand-server release binary: stagehand_url("x64" | "arm64")."""- return f"{gh_proxy()}https://github.com/browserbase/stagehand/releases/download/stagehand-server-v3/{STAGEHAND_SERVER_VERSION}/stagehand-server-v3-linux-{arch}"--def noto_cjk_font_url() -> str:"""Noto Sans CJK SC variable TTF, rendered into PDFs by the Go backend(internal/agent/component/io/pdf_writer.go). It is a GitHub raw URL, so the@@ -177,14 +147,6 @@ def download_with_progress(url, filename):print()-def _valid_stagehand_binary(path):- """True when PATH is a non-empty ELF executable (the stagehand-server SEA)."""- if not os.path.isfile(path) or os.path.getsize(path) == 0:- return False- with open(path, "rb") as file:- return file.read(4) == b"\x7fELF"--def _valid_font(path):"""True when PATH is a TrueType font with the sfnt signature b"\\x00\\x01\\x00\\x00".@@ -259,27 +221,6 @@ def load_tokenizer_assets(assets=None):return result-def _install_stagehand():- if platform.system() != "Linux":- raise RuntimeError("The downloaded native dependencies support Linux only")- architecture = {"x86_64": "x64", "aarch64": "arm64"}.get(platform.machine())- if architecture is None:- raise RuntimeError(f"Unsupported stagehand architecture: {platform.machine()}")- version = go_module_version("github.com/browserbase/stagehand-go/v3", REPO_ROOT)- cache_root = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")- target_dir = os.path.join(cache_root, "stagehand", "lib", f"go_{version}")- os.makedirs(target_dir, exist_ok=True)- filename = f"stagehand-server-v3-linux-{architecture}"- source = os.path.join(SCRIPT_DIR, filename)- target = os.path.join(target_dir, filename)- with tempfile.TemporaryDirectory(dir=target_dir) as staging:- prepared = os.path.join(staging, filename)- shutil.copyfile(source, prepared)- os.chmod(prepared, 0o755)- os.replace(prepared, target)- print(f" ✓ stagehand installed to {target}")--def download_go_models(use_china_mirrors=False):"""Download the Go DeepDoc `.ort` weights so a Go dev can run the in-processbackend with no further setup.@@ -417,21 +358,6 @@ def main():print(f"Downloading cl100k_base.tiktoken from {cl100k_url()}...")download_with_progress(cl100k_url(), cl100k)- # ── stagehand-server binaries (image root + local cache) ────────────────- print("== stagehand-server ==")- for arch in ("x64", "arm64"):- filename = f"stagehand-server-v3-linux-{arch}"- target = os.path.join(SCRIPT_DIR, filename)- if os.path.isfile(target) and os.path.getsize(target) > 0:- print(f" ✓ {filename} already present")- continue- print(f"Downloading {filename} from {stagehand_url(arch)}...")- download_with_progress(stagehand_url(arch), target)- if not _valid_stagehand_binary(target):- os.unlink(target)- raise RuntimeError(f"Invalid downloaded dependency: {filename}")- _install_stagehand()-# ── Noto Sans CJK SC font (rendered into PDFs by the Go backend) ─────────# Verified by a font magic-number check (only the sfnt signature# b"\x00\x01\x00\x00" that gopdf's AddTTFFont accepts) plus a SHA-256 checkdiff --git a/docs/develop/launch_ragflow_from_source.md b/docs/develop/launch_ragflow_from_source.mdindex 7ea948d9ba..fec5dcfe84 100644--- a/docs/develop/launch_ragflow_from_source.md+++ b/docs/develop/launch_ragflow_from_source.md@@ -60,7 +60,7 @@ Download the native static libraries and the runtime model / tokenizer resourcesuv run tools/scripts/download_dev_deps.py # local-dev one-stop: native .a + cl100k, DeepDoc .ort, tokenizer assets```-`download_dev_deps.py` is the local-dev one-stop: it fetches the static libraries needed by `build.sh` (pdfium / pdf_oxide / office_oxide / onnxruntime → `~/ragflow-native-libs`) AND the runtime resources the backend loads at runtime — `det.ort`, `layout.ort`, `tsr.ort`, `rec.ort`, `ocr.res` into `internal/rag/res/deepdoc/` (required by the in-process Go DeepDoc backend) and `deps/cl100k_base.tiktoken` and the embedding tokenizer assets under `deps/huggingface.co/`. Run it once and the local environment is ready; already-present files are skipped on re-run. The image-facing `deps/download_deps.py` fetches the same runtime resources PLUS the stagehand server (installed into `${XDG_CACHE_HOME:-$HOME/.cache}/stagehand/lib/go_<SDK version>/`) and skips the native `.a`; run it only when building the dependency image or in CI. Native archives support Linux x86_64. Keep the server's working directory at the repository root so it can find the DeepDoc models automatically; if you launch it elsewhere, set `DEEPDOC_MODEL_DIR` to the absolute path of `internal/rag/res/deepdoc`.+`download_dev_deps.py` is the local-dev one-stop: it fetches the static libraries needed by `build.sh` (pdfium / pdf_oxide / office_oxide / onnxruntime → `~/ragflow-native-libs`) AND the runtime resources the backend loads at runtime — `det.ort`, `layout.ort`, `tsr.ort`, `rec.ort`, `ocr.res` into `internal/rag/res/deepdoc/` (required by the in-process Go DeepDoc backend) and `deps/cl100k_base.tiktoken` and the embedding tokenizer assets under `deps/huggingface.co/`. Run it once and the local environment is ready; already-present files are skipped on re-run. The image-facing `deps/download_deps.py` fetches the same runtime resources and skips the native `.a`; run it only when building the dependency image or in CI. Native archives support Linux x86_64. Keep the server's working directory at the repository root so it can find the DeepDoc models automatically; if you launch it elsewhere, set `DEEPDOC_MODEL_DIR` to the absolute path of `internal/rag/res/deepdoc`.Skip either script if you have prepared the same resources by other means.diff --git a/docs/guides/agent/agent_workflow/tool_components.md b/docs/guides/agent/agent_workflow/tool_components.mdindex 04f6230ad2..e33185cca3 100644--- a/docs/guides/agent/agent_workflow/tool_components.md+++ b/docs/guides/agent/agent_workflow/tool_components.md@@ -22,7 +22,6 @@ In the tables below, **No** means manual input is optional; keep any default sho| Academic search | Google Scholar, ArXiv, PubMed, BGPT | Retrieve papers, medical literature, and research materials. || Data and financial queries | Execute SQL, Yahoo Finance, WenCai | Query databases, market data, or financial screening results. || Content output | Email, Document Generator | Send emails or generate downloadable documents. |-| Web content extraction | Browser | Extract page content using natural-language instructions. |## Web Page and Information Retrieval@@ -785,29 +784,3 @@ Use `download` to display the generated file in a Message. The other outputs ide2. In Document Generator, set **Content** to `# Sample report`, **Output Format** to **PDF**, and **Filename** to `sample-report.pdf`. Keep the other settings at their defaults.3. In Message, open the variable selector and insert Document Generator's `download` output.4. Save and click **Run**. The conversation should show a downloadable file named `sample-report.pdf`; open it to check that it contains the heading Sample report.--### Browser (Browser)--Browser uses a configured chat model and a natural-language instruction to extract web page content.--#### Parameter Description--| Field | Type | Required | Default Value | Description |-| --- | --- | --- | --- | --- |-| Model | Selection | Yes | None | Select a configured chat model from the dropdown. |-| prompts | string | Yes | `{sys.query}` | Extraction instruction. Canvas variables are supported. |-| headless | boolean | No | true | Whether to run the browser without a visible window. |--#### Configuration Example--| Configuration Item | Example Value |-| --- | --- |-| Model | Select an available chat model |-| Prompt | Extract the main navigation labels from https://www.ragflow.io and return a concise bullet list. |-| Headless | true |--#### Output Result--`content` contains the extracted text. Insert this field into a downstream Agent prompt or Message.--Test a small extraction task and check the returned content before connecting downstream components.diff --git a/docs/release_notes.md b/docs/release_notes.mdindex f42ad426fc..9ef9557c54 100644--- a/docs/release_notes.md+++ b/docs/release_notes.md@@ -346,7 +346,6 @@ Released on May 26, 2026.### New features-- Agent: Adds a **Browser** component that enables AI to autonomously navigate and interact with web pages. [#14888](https://github.com/infiniflow/ragflow/pull/14888)### Improvementsdiff --git a/go.mod b/go.modindex e742c2eb5a..f992f21050 100644--- a/go.mod+++ b/go.mod@@ -25,7 +25,6 @@ require (github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3github.com/aws/aws-sdk-go-v2/service/sts v1.41.8github.com/aws/smithy-go v1.24.2- github.com/browserbase/stagehand-go/v3 v3.21.0github.com/bytedance/sonic v1.15.4github.com/cenkalti/backoff/v5 v5.0.3github.com/cespare/xxhash/v2 v2.3.0@@ -224,10 +223,6 @@ require (github.com/spf13/pflag v1.0.5 // indirectgithub.com/spiffe/go-spiffe/v2 v2.8.1 // indirectgithub.com/subosito/gotenv v1.6.0 // indirect- github.com/tidwall/gjson v1.18.0 // indirect- github.com/tidwall/match v1.1.1 // indirect- github.com/tidwall/pretty v1.2.1 // indirect- github.com/tidwall/sjson v1.2.5 // indirectgithub.com/tiendc/go-deepcopy v1.7.2 // indirectgithub.com/tinylib/msgp v1.6.1 // indirectgithub.com/tjfoc/gmsm v1.4.1 // indirectdiff --git a/go.sum b/go.sumindex e59cfbb211..a5e1ab748f 100644--- a/go.sum+++ b/go.sum@@ -169,8 +169,6 @@ github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFgithub.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs=github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=-github.com/browserbase/stagehand-go/v3 v3.21.0 h1:4DMtqcibQSobwLvuODla8SdkF0sk3BzsbEqG3eG+KI4=-github.com/browserbase/stagehand-go/v3 v3.21.0/go.mod h1:2w/HwHce4GmhHWsKamELt/TLLtDJFXmCUHbYqPCH62k=github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=@@ -582,16 +580,6 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKugithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=-github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=-github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=-github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=-github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=-github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=-github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=-github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=-github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=-github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=-github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=diff --git a/internal/agent/canvas/variable_test.go b/internal/agent/canvas/variable_test.goindex 4e404b31ac..8f4735590d 100644--- a/internal/agent/canvas/variable_test.go+++ b/internal/agent/canvas/variable_test.go@@ -252,7 +252,6 @@ func TestVarRefPattern_MatchesColonBearingComponentIDs(t *testing.T) {{"{UserFillUp:LoopInput@value}", "UserFillUp:LoopInput@value"},{"{Retrieval:KBSearch@formalized_content}", "Retrieval:KBSearch@formalized_content"},{"{CodeExec:Double@result}", "CodeExec:Double@result"},- {"{Browser:BusyHatsSink@content}", "Browser:BusyHatsSink@content"},}for _, c := range cases {diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.goindex 18dddb3bb4..bb93f450df 100644--- a/internal/agent/component/agent.go+++ b/internal/agent/component/agent.go@@ -43,14 +43,6 @@ import (const maxSubAgentDepth = 8const defaultAgentDeferredTimeout = 10 * time.Minute-// agentPatternless matches `<model>@<provider>` and-// `<model>@<instance>@<provider>` (the trailing `@<provider>` is-// always the last segment — the segment just before the last `@`-// is treated as the bare model name for upstream API calls). The-// browser component has the same idea at browser.go:88-92, but-// keeps the regex greedy for its 2-part fixture; we keep both-// behaviors here via the in-function split below.-// agentProviderLastSegmentSplit takes a composite llm_id and// returns (bareModelName, providerName, true) — or ("", "", false)// when no `@<provider>` suffix exists. The bare model name isdiff --git a/internal/agent/component/browser.go b/internal/agent/component/browser.godeleted file mode 100644index 5fab1fab65..0000000000--- a/internal/agent/component/browser.go+++ /dev/null@@ -1,340 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--// Browser runs natural-language browser tasks through Stagehand in local mode.-// StagehandInvoker.RunTask navigates and interacts with pages before returning-// the agent's final result. The runtime owns the server and session lifecycle.-// File upload/download and persistent sessions are not supported.-package component--import (- "context"- "errors"- "fmt"- "net/url"-- "strings"-- "ragflow/internal/agent/runtime"- "ragflow/internal/entity/models"-- "gorm.io/gorm"-)--const componentNameBrowser = "Browser"--var browserModelFactory func(context.Context, string, string) (*models.ChatModel, error)--// SetBrowserModelFactory binds Browser to the shared tenant-scoped model factory.-func SetBrowserModelFactory(factory func(context.Context, string, string) (*models.ChatModel, error)) {- browserModelFactory = factory-}--// browserParam is the static DSL param surface for the Browser-// component. Mirrors Python `browser.py:LLMParam + browser knobs`:-//-// llm_id, model_id (alias), prompts, prompt (alias),-// max_steps, headless, enable_default_extensions,-// chromium_sandbox, persist_session, upload_sources.-//-// Go-only fields kept for backward compat with the existing test-// file and the optional-URL form some operators still wire up:-//-// url, timeout.-//-// v1 does not act on the v1-deferred params; Update accepts them so-// the v1 fixture loads.-type browserParam struct {- LLMID string `json:"llm_id"`- ModelID string `json:"model_id"` // alias for llm_id- Prompts string `json:"prompts"`- Prompt string `json:"prompt"` // alias for prompts- MaxSteps int `json:"max_steps"`- Headless *bool `json:"headless"`- EnableDefaultExt *bool `json:"enable_default_extensions"`- ChromiumSandbox *bool `json:"chromium_sandbox"`- PersistSession *bool `json:"persist_session"`-- // Go-only fields (kept for backward compat with the existing- // test file; not used by the stagehand path).- URL string `json:"url"`- Timeout int `json:"timeout"`-}--// Update copies a fresh param map into the receiver. The-// `llm_id`/`model_id` and `prompts`/`prompt` alias pairs collapse-// onto the same field; the first non-empty value wins.-func (p *browserParam) Update(conf map[string]any) error {- if conf == nil {- conf = map[string]any{}- }- if v, ok := stringFrom(conf, "llm_id"); ok && v != "" {- p.LLMID = v- }- if v, ok := stringFrom(conf, "model_id"); ok && v != "" && p.LLMID == "" {- p.LLMID = v- }- if v, ok := stringFrom(conf, "prompts"); ok && v != "" {- p.Prompts = v- }- if v, ok := stringFrom(conf, "prompt"); ok && v != "" && p.Prompts == "" {- p.Prompts = v- }- if v, ok := intFrom(conf, "max_steps"); ok {- p.MaxSteps = v- } else {- p.MaxSteps = 0- }- if v, ok := boolFrom(conf, "headless"); ok {- p.Headless = &v- }- if v, ok := boolFrom(conf, "enable_default_extensions"); ok {- p.EnableDefaultExt = &v- }- if v, ok := boolFrom(conf, "chromium_sandbox"); ok {- p.ChromiumSandbox = &v- }- if v, ok := boolFrom(conf, "persist_session"); ok {- p.PersistSession = &v- }- if v, ok := stringFrom(conf, "url"); ok {- p.URL = v- }- if v, ok := intFrom(conf, "timeout"); ok {- p.Timeout = v- } else {- p.Timeout = 0- }- return nil-}--// Check validates the param. The accepted-but-ignored Python-// fields are NOT validated here — the v1 fixture is allowed to set-// them; we only reject structurally invalid values for fields we-// actually use (`llm_id`, `prompts`).-func (p *browserParam) Check() error {- if p.LLMID == "" {- return &ParamError{Field: "llm_id", Reason: "required (or model_id alias)"}- }- if p.Prompts == "" {- return &ParamError{Field: "prompts", Reason: "required (or prompt alias)"}- }- if p.MaxSteps < 0 {- return &ParamError{Field: "max_steps", Reason: "must be non-negative"}- }- if p.Timeout < 0 {- return &ParamError{Field: "timeout", Reason: "must be non-negative"}- }- return nil-}--// AsDict returns the param as a plain map (for serialization / debug).-func (p *browserParam) AsDict() map[string]any {- out := map[string]any{- "llm_id": p.LLMID,- "model_id": p.LLMID, // alias echoed- "prompts": p.Prompts,- "prompt": p.Prompts, // alias echoed- "max_steps": p.MaxSteps,- "url": p.URL,- "timeout": p.Timeout,- }- if p.Headless != nil {- out["headless"] = *p.Headless- }- if p.EnableDefaultExt != nil {- out["enable_default_extensions"] = *p.EnableDefaultExt- }- if p.ChromiumSandbox != nil {- out["chromium_sandbox"] = *p.ChromiumSandbox- }- if p.PersistSession != nil {- out["persist_session"] = *p.PersistSession- }- return out-}--// BrowserComponent is the canvas Browser node. Owns its static-// param; delegates the multistep agent run to StagehandInvoker.-type BrowserComponent struct {- name string- param browserParam-}--// NewBrowserComponent constructs a Browser from the DSL param map.-func NewBrowserComponent(params map[string]any) (Component, error) {- p := &browserParam{}- if err := p.Update(params); err != nil {- return nil, fmt.Errorf("browser: param update: %w", err)- }- if err := p.Check(); err != nil {- return nil, fmt.Errorf("browser: param check: %w", err)- }- return &BrowserComponent{- name: componentNameBrowser,- param: *p,- }, nil-}--// Name returns the registered component name.-func (b *BrowserComponent) Name() string { return b.name }--// Invoke runs the resolved browser instruction through Stagehand's agent so-// navigation and interaction happen before the final result is returned.-func (b *BrowserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[string]any) (map[string]any, error) {- state, err := runtime.GetStateFromContext(ctx)- if err != nil {- return nil, fmt.Errorf("browser: %w", err)- }- if state == nil {- return nil, errors.New("browser: nil canvas state")- }-- tenantID, _ := state.GetSysString("tenant_id")- if tenantID == "" {- return nil, errors.New("browser: tenant_id missing from canvas state (state.Sys[\"tenant_id\"])")- }-- // 1. Resolve prompts template.- prompts := b.param.Prompts- if v, ok := inputs["prompts"].(string); ok && strings.TrimSpace(v) != "" {- prompts = v- }- resolvedPrompts, err := runtime.ResolveTemplate(prompts, state)- if err != nil {- return nil, fmt.Errorf("browser: resolve prompts template: %w", err)- }-- if browserModelFactory == nil {- return nil, errors.New("browser: model factory is not configured")- }- chatModel, err := browserModelFactory(ctx, tenantID, b.param.LLMID)- if err != nil {- return nil, fmt.Errorf("browser: resolve model (%q): %w", b.param.LLMID, err)- }- if chatModel == nil {- return nil, errors.New("browser: model factory returned nil model")- }- req := RunTaskRequest{- TenantID: tenantID,- LLMID: b.param.LLMID,- ChatModel: chatModel,- Headless: b.param.Headless,- ChromiumSandbox: b.param.ChromiumSandbox != nil && *b.param.ChromiumSandbox,- Instruction: resolvedPrompts,- MaxSteps: b.param.MaxSteps,- }- if chatModel.ModelName != nil {- req.ModelName = *chatModel.ModelName- }- if chatModel.APIConfig != nil {- if chatModel.APIConfig.ApiKey != nil {- req.APIKey = *chatModel.APIConfig.ApiKey- }- if chatModel.APIConfig.BaseURL != nil {- req.BaseURL = *chatModel.APIConfig.BaseURL- }- }-- invoker := getDefaultStagehandInvoker()- content, err := invoker.RunTask(ctx, req)- if err != nil {- return nil, fmt.Errorf("browser: stagehand task (model=%q, base_url=%s): %w",- req.ModelName, browserBaseURLForLog(req.BaseURL), err)- }-- // 4. Build the output map.- out := map[string]any{- "content": content,- "downloaded_files": []map[string]any{},- "url": "",- "status": 0,- "size": len(content),- "model_id": b.param.LLMID,- "prompt": prompts,- }- return out, nil-}--func browserBaseURLForLog(raw string) string {- raw = strings.TrimSpace(raw)- if raw == "" {- return "<provider default>"- }- u, err := url.Parse(raw)- if err != nil {- return "<invalid>"- }- u.User = nil- return u.String()-}--// Stream emits the final result after the browser task completes.-func (b *BrowserComponent) Stream(ctx context.Context, db *gorm.DB, inputs map[string]any) (<-chan map[string]any, error) {- out, err := b.Invoke(ctx, db, inputs)- if err != nil {- return nil, err- }- ch := make(chan map[string]any, 1)- ch <- out- close(ch)- return ch, nil-}--// Inputs returns the parameter metadata for tooling.-func (b *BrowserComponent) Inputs() map[string]string {- return map[string]string{- "llm_id": "Required: tenant model id, e.g. \"deepseek-v4-pro@DeepSeek\". model_id accepted as alias.",- "prompts": "Required: natural-language browser task. {sys.query} and other canvas refs are resolved. prompt accepted as alias.",- "max_steps": "Maximum browser agent steps (default 30).",- "headless": "Browser launch mode (default true).",- "enable_default_extensions": "Accepted for fixture compat; ignored at Invoke.",- "chromium_sandbox": "Whether to enable Chromium's sandbox (default false).",- "persist_session": "Accepted for fixture compat; ignored at Invoke.",- "url": "Go-only; not used (kept for backward compat).",- "timeout": "Go-only; not used (kept for backward compat).",- }-}--func (b *BrowserComponent) GetInputForm() map[string]any {- return map[string]any{- "prompts": map[string]any{- "type": "paragraph",- "name": "Prompts",- },- "upload_sources": map[string]any{- "type": "line",- "name": "Upload sources",- },- }-}--// Outputs returns the response surface.-func (b *BrowserComponent) Outputs() map[string]string {- return map[string]string{- "content": "Browser agent final result.",- "downloaded_files": "Always [] (file download not supported).",- "url": "Go-native compat key; always \"\".",- "status": "Go-native compat key; always 0.",- "size": "Bytes in content.",- "model_id": "Resolved llm_id (echoed back).",- "prompt": "Resolved prompts (echoed back).",- }-}--func init() {- Register(componentNameBrowser, NewBrowserComponent)-}diff --git a/internal/agent/component/browser_test.go b/internal/agent/component/browser_test.godeleted file mode 100644index f89cc27182..0000000000--- a/internal/agent/component/browser_test.go+++ /dev/null@@ -1,494 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package component--import (- "context"- "errors"- "strings"- "sync"- "testing"-- "ragflow/internal/agent/canvas"- "ragflow/internal/agent/runtime"- "ragflow/internal/entity/models"-)--// mockStagehandInvoker captures RunTask requests and returns a-// canned final message. Used by every test in this file; the Browser-// component depends on `DefaultRuntime` which is swapped via-// `SetDefaultStagehandInvoker` and restored at test cleanup.-type mockStagehandInvoker struct {- mu sync.Mutex- requests []RunTaskRequest- message string- err error-}--func (m *mockStagehandInvoker) RunExtract(_ context.Context, _ RunExtractRequest) (string, error) {- return "", errors.New("Browser must execute the task before extracting page content")-}--func (m *mockStagehandInvoker) RunTask(_ context.Context, req RunTaskRequest) (string, error) {- m.mu.Lock()- defer m.mu.Unlock()- m.requests = append(m.requests, req)- if m.err != nil {- return "", m.err- }- return m.message, nil-}--func (m *mockStagehandInvoker) lastRequest(t *testing.T) RunTaskRequest {- t.Helper()- m.mu.Lock()- defer m.mu.Unlock()- if len(m.requests) == 0 {- t.Fatal("no RunTask call recorded")- }- return m.requests[len(m.requests)-1]-}--// withMockRuntime swaps DefaultRuntime for a mock for the duration-// of t, restoring the production runtime on cleanup.-func withMockRuntime(t *testing.T, mock StagehandInvoker) {- t.Helper()- prev := DefaultRuntime- SetDefaultStagehandInvoker(mock)-- t.Cleanup(func() {- SetDefaultStagehandInvoker(prev)- })-}--// stateWith seeds a CanvasState with a tenant_id and the supplied-// sys map. The state is attached to ctx so the Browser component-// can read it.-func stateWith(t *testing.T, sys map[string]any) context.Context {- t.Helper()- state := canvas.NewCanvasState("run-1", "task-1")- state.Sys = sys- return canvas.WithState(t.Context(), state)-}--// TestBrowser_AcceptsPythonSchema: the v1 fixture's param surface-// (llm_id / prompts / max_steps / headless / enable_default_extensions-// / chromium_sandbox / persist_session) parses into-// browserParam without error.-func TestBrowser_AcceptsPythonSchema(t *testing.T) {- _, err := NewBrowserComponent(map[string]any{- "llm_id": "deepseek-v4-pro@DeepSeek",- "prompts": "search for AI trends",- "max_steps": 30,- "headless": true,- "enable_default_extensions": false,- "chromium_sandbox": false,- "persist_session": true,- })- if err != nil {- t.Fatalf("NewBrowserComponent: %v", err)- }-}--// TestBrowser_AcceptsAliases: model_id / prompt are accepted as-// aliases for llm_id / prompts.-func TestBrowser_AcceptsAliases(t *testing.T) {- c, err := NewBrowserComponent(map[string]any{- "model_id": "gpt-4o@OpenAI",- "prompt": "summarize the page",- })- if err != nil {- t.Fatalf("NewBrowserComponent: %v", err)- }- got := c.(*BrowserComponent).param- if got.LLMID != "gpt-4o@OpenAI" {- t.Errorf("LLMID: got %q, want %q (from model_id alias)", got.LLMID, "gpt-4o@OpenAI")- }- if got.Prompts != "summarize the page" {- t.Errorf("Prompts: got %q, want %q (from prompt alias)", got.Prompts, "summarize the page")- }-}--// TestBrowser_LLMIDAndPromptsRequired: both fields are required.-func TestBrowser_LLMIDAndPromptsRequired(t *testing.T) {- _, err := NewBrowserComponent(map[string]any{"prompts": "hi"})- if err == nil || !strings.Contains(err.Error(), "llm_id") {- t.Errorf("expected llm_id required error, got %v", err)- }- _, err = NewBrowserComponent(map[string]any{"llm_id": "gpt-4o"})- if err == nil || !strings.Contains(err.Error(), "prompts") {- t.Errorf("expected prompts required error, got %v", err)- }-}--// TestBrowser_ResolvesSysQueryTemplate: {sys.query} in prompts is-// resolved against canvas state before dispatch to the runtime.-func TestBrowser_ResolvesSysQueryTemplate(t *testing.T) {- mock := &mockStagehandInvoker{message: "ok"}- withMockRuntime(t, mock)-- c, _ := NewBrowserComponent(map[string]any{- "llm_id": "deepseek-v4-pro@DeepSeek",- "prompts": "{sys.query}打开百度,搜索'2026年最新AI技术趋势'",- })- ctx := stateWith(t, map[string]any{- "tenant_id": "tenant-1",- "query": "what's the latest",- })-- // LLM lookup will fail (no DB seeded in test), so we can't- // exercise the full Invoke path. Instead, verify the template- // resolution independently via runtime.ResolveTemplate.- resolved, err := runtime.ResolveTemplate(c.(*BrowserComponent).param.Prompts, mustState(t, ctx))- if err != nil {- t.Fatalf("ResolveTemplate: %v", err)- }- if !strings.Contains(resolved, "what's the latest") {- t.Errorf("resolved prompts should contain sys.query value; got %q", resolved)- }- if strings.Contains(resolved, "{sys.query}") {- t.Errorf("sys.query ref not substituted: %q", resolved)- }-}--// mustState pulls the CanvasState out of ctx; used by helpers that-// need to test template resolution without going through Invoke.-func mustState(t *testing.T, ctx context.Context) *runtime.CanvasState {- t.Helper()- state, err := runtime.GetStateFromContext(ctx)- if err != nil {- t.Fatalf("get state from context: %v", err)- }- return state-}--// A model resolution error must stop before the browser runtime is invoked.-func TestBrowser_DispatchesToRuntime(t *testing.T) {- mock := &mockStagehandInvoker{message: "agent result text"}- withMockRuntime(t, mock)- factoryErr := errors.New("tenant model unavailable")- withBrowserModelFactory(t, func(ctx context.Context, tenantID, modelRef string) (*models.ChatModel, error) {- if tenantID != "tenant-1" || modelRef != "selected-model" {- t.Errorf("factory scope: tenant=%q model=%q", tenantID, modelRef)- }- return nil, factoryErr- })- c, _ := NewBrowserComponent(map[string]any{"llm_id": "selected-model", "prompts": "do something"})- _, err := c.Invoke(stateWith(t, map[string]any{"tenant_id": "tenant-1"}), nil, nil)- if !errors.Is(err, factoryErr) {- t.Fatalf("expected factory error, got %v", err)- }- if len(mock.requests) != 0 {- t.Fatal("runtime called after model factory failed")- }-}--func withBrowserModelFactory(t *testing.T, factory func(context.Context, string, string) (*models.ChatModel, error)) {- t.Helper()- previous := browserModelFactory- SetBrowserModelFactory(factory)- t.Cleanup(func() { SetBrowserModelFactory(previous) })-}--func withBrowserTestModel(t *testing.T) {- t.Helper()- model := models.NewChatModel(nil, new("gpt-4o"), &models.APIConfig{- ApiKey: new("sk-test"), BaseURL: new("https://api.openai.com/v1"),- })- withBrowserModelFactory(t, func(context.Context, string, string) (*models.ChatModel, error) { return model, nil })-}--// TestBrowser_MissingTenant: state.Sys["tenant_id"] is required.-// Missing tenant_id must error.-func TestBrowser_MissingTenant(t *testing.T) {- mock := &mockStagehandInvoker{message: "ok"}- withMockRuntime(t, mock)-- c, _ := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "x",- })- // state with no tenant_id- state := canvas.NewCanvasState("run-1", "task-1")- ctx := canvas.WithState(t.Context(), state)-- _, err := c.Invoke(ctx, nil, nil)- if err == nil || !strings.Contains(err.Error(), "tenant_id") {- t.Errorf("expected tenant_id error, got %v", err)- }-}--// TestBrowser_PropagatesRuntimeError verifies runtime errors retain model context.-func TestBrowser_PropagatesRuntimeError(t *testing.T) {- mock := &mockStagehandInvoker{message: "x", err: errors.New("boom")}- withMockRuntime(t, mock)-- withBrowserTestModel(t)-- c, _ := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "x",- })- ctx := stateWith(t, map[string]any{"tenant_id": "tenant-1"})-- _, err := c.Invoke(ctx, nil, nil)- if err == nil {- t.Fatal("expected runtime error, got nil")- }- if !strings.Contains(err.Error(), "stagehand task") {- t.Errorf("error should mention stagehand task; got %v", err)- }- if !strings.Contains(err.Error(), `model="gpt-4o"`) {- t.Errorf("error should include model context; got %v", err)- }- if !strings.Contains(err.Error(), "base_url=https://api.openai.com/v1") {- t.Errorf("error should include base_url context; got %v", err)- }- if !strings.Contains(err.Error(), "boom") {- t.Errorf("error should include underlying message; got %v", err)- }-}--func TestBrowserBaseURLForLog(t *testing.T) {- cases := []struct {- name string- in string- want string- }{- {name: "empty", in: "", want: "<provider default>"},- {name: "blank", in: " \t\n ", want: "<provider default>"},- {name: "redacts_userinfo", in: "https://user:[email protected]/v1", want: "https://example.com/v1"},- {name: "invalid", in: "://bad", want: "<invalid>"},- }- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- if got := browserBaseURLForLog(tc.in); got != tc.want {- t.Fatalf("browserBaseURLForLog(%q) = %q, want %q", tc.in, got, tc.want)- }- })- }-}--// TestBrowser_RunTaskRequestShape verifies model settings, task instructions,-// and the step limit are forwarded to the navigation-capable runtime.-func TestBrowser_RunTaskRequestShape(t *testing.T) {- mock := &mockStagehandInvoker{message: "ok"}- withMockRuntime(t, mock)-- withBrowserTestModel(t)-- c, _ := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "{sys.query}",- "max_steps": 17,- })- instruction := "extract the title of the pr in https://github.com/infiniflow/ragflow/pull/21460"- ctx := stateWith(t, map[string]any{"tenant_id": "tenant-1", "query": instruction})-- if _, err := c.Invoke(ctx, nil, nil); err != nil {- t.Fatalf("Invoke: %v", err)- }- req := mock.lastRequest(t)- if req.ModelName != "gpt-4o" {- t.Errorf("ModelName: got %q, want gpt-4o", req.ModelName)- }- if req.TenantID != "tenant-1" {- t.Errorf("TenantID: got %q, want tenant-1", req.TenantID)- }- if req.APIKey != "sk-test" {- t.Errorf("APIKey: got %q, want sk-test", req.APIKey)- }- if req.BaseURL != "https://api.openai.com/v1" {- t.Errorf("BaseURL: got %q", req.BaseURL)- }- if req.ChatModel == nil {- t.Fatal("shared chat model missing from runtime request")- }- if req.Instruction != instruction {- t.Errorf("Instruction: got %q, want %q", req.Instruction, instruction)- }- if req.MaxSteps != 17 {- t.Errorf("MaxSteps: got %d, want 17", req.MaxSteps)- }-}--// TestBrowser_HeadlessPropagates: the param's headless bool is-// forwarded to the runtime verbatim.-func TestBrowser_HeadlessPropagates(t *testing.T) {- mock := &mockStagehandInvoker{message: "ok"}- withMockRuntime(t, mock)-- withBrowserTestModel(t)-- c, _ := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "x",- "headless": false,- })- ctx := stateWith(t, map[string]any{"tenant_id": "tenant-1"})-- if _, err := c.Invoke(ctx, nil, nil); err != nil {- t.Fatalf("Invoke: %v", err)- }- req := mock.lastRequest(t)- if req.Headless == nil {- t.Fatal("Headless: got nil, want pointer to false")- }- if *req.Headless != false {- t.Errorf("Headless: got %v, want false", *req.Headless)- }-}--func TestBrowser_ChromiumSandboxPropagates(t *testing.T) {- for _, tc := range []struct {- name string- set *bool- want bool- }{- {name: "default_disabled"},- {name: "disabled", set: new(false)},- {name: "enabled", set: new(true), want: true},- } {- t.Run(tc.name, func(t *testing.T) {- mock := &mockStagehandInvoker{message: "ok"}- withMockRuntime(t, mock)-- withBrowserTestModel(t)-- conf := map[string]any{"llm_id": "gpt-4o@OpenAI", "prompts": "x"}- if tc.set != nil {- conf["chromium_sandbox"] = *tc.set- }- c, err := NewBrowserComponent(conf)- if err != nil {- t.Fatalf("NewBrowserComponent: %v", err)- }- ctx := stateWith(t, map[string]any{"tenant_id": "tenant-1"})- if _, err := c.Invoke(ctx, nil, nil); err != nil {- t.Fatalf("Invoke: %v", err)- }- if got := mock.lastRequest(t).ChromiumSandbox; got != tc.want {- t.Errorf("ChromiumSandbox = %v, want %v", got, tc.want)- }- })- }-}--// TestBrowser_OutputsShape: the output map contains the Python keys-// (content, downloaded_files) and the Go-native compat keys (url,-// status, size, model_id, prompt).-func TestBrowser_OutputsShape(t *testing.T) {- mock := &mockStagehandInvoker{message: "the agent's final message"}- withMockRuntime(t, mock)-- withBrowserTestModel(t)-- c, _ := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "x",- })- ctx := stateWith(t, map[string]any{"tenant_id": "tenant-1"})-- out, err := c.Invoke(ctx, nil, nil)- if err != nil {- t.Fatalf("Invoke: %v", err)- }- if got, want := out["content"], "the agent's final message"; got != want {- t.Errorf("content: got %v, want %v", got, want)- }- df, ok := out["downloaded_files"].([]map[string]any)- if !ok {- t.Fatalf("downloaded_files: got %T, want []map[string]any", out["downloaded_files"])- }- if len(df) != 0 {- t.Errorf("downloaded_files: got %d entries, want 0 (v1 always empty)", len(df))- }- if got, want := out["model_id"], "gpt-4o@OpenAI"; got != want {- t.Errorf("model_id: got %v, want %v", got, want)- }- if got, want := out["prompt"], "x"; got != want {- t.Errorf("prompt: got %v, want %v", got, want)- }-}--// TestBrowser_Registered: factory lookup works.-func TestBrowser_Registered(t *testing.T) {- c, err := New("browser", map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "x",- })- if err != nil {- t.Fatalf("registry lookup: %v", err)- }- if c.Name() != "Browser" {- t.Errorf("Name()=%q, want Browser", c.Name())- }-}--// TestBrowser_ParamCheck_NegativeMaxSteps: negative max_steps is-// rejected at construction.-func TestBrowser_ParamCheck_NegativeMaxSteps(t *testing.T) {- _, err := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "x",- "max_steps": -1,- })- if err == nil || !strings.Contains(err.Error(), "max_steps") {- t.Errorf("expected max_steps error, got %v", err)- }-}--// Provider catalog coverage verifies delegation, without making provider calls.-func TestBrowser_ForwardsConfiguredProviderModels(t *testing.T) {- if err := models.InitProviderManager("../../../conf/models"); err != nil {- t.Fatal(err)- }- providers := models.GetProviderManager().Providers- if len(providers) == 0 {- t.Fatal("provider catalog is empty")- }- t.Logf("verifying Browser delegates %d configured provider drivers", len(providers))- for _, provider := range providers {- if provider.ModelDriver == nil {- t.Fatalf("provider %q has no configured driver", provider.Name)- }- t.Run(provider.Name, func(t *testing.T) {- mock := &mockStagehandInvoker{message: "ok"}- withMockRuntime(t, mock)- model := models.NewChatModel(provider.ModelDriver, new("configured-browser-model"), nil)- withBrowserModelFactory(t, func(context.Context, string, string) (*models.ChatModel, error) { return model, nil })- c, _ := NewBrowserComponent(map[string]any{"llm_id": "configured-model", "prompts": "browse"})- if _, err := c.Invoke(stateWith(t, map[string]any{"tenant_id": "tenant-1"}), nil, nil); err != nil {- t.Fatal(err)- }- req := mock.lastRequest(t)- if req.ChatModel != model || req.ChatModel.ModelDriver != provider.ModelDriver || req.ModelName != *model.ModelName {- t.Errorf("configured provider model was replaced: name=%q model=%p", req.ModelName, req.ChatModel)- }- })- }-}--func TestBrowser_ModelFactoryUnavailable(t *testing.T) {- for _, factory := range []func(context.Context, string, string) (*models.ChatModel, error){nil, func(context.Context, string, string) (*models.ChatModel, error) { return nil, nil }} {- withBrowserModelFactory(t, factory)- c, _ := NewBrowserComponent(map[string]any{"llm_id": "configured-model", "prompts": "browse"})- if _, err := c.Invoke(stateWith(t, map[string]any{"tenant_id": "tenant-1"}), nil, nil); err == nil {- t.Fatal("expected unavailable model error")- }- }-}diff --git a/internal/agent/component/integer_params.go b/internal/agent/component/integer_params.goindex 236604f50a..e8a6b9b666 100644--- a/internal/agent/component/integer_params.go+++ b/internal/agent/component/integer_params.go@@ -32,13 +32,6 @@ var integerParams = map[string]map[string]struct{}{"message_history_window_size": {},"optimize_history_window": {},},- "browser": {- "max_retries": {},- "max_steps": {},- "max_tokens": {},- "message_history_window_size": {},- "timeout": {},- },"categorize": {"max_retries": {},"max_tokens": {},diff --git a/internal/agent/component/stagehand_model.go b/internal/agent/component/stagehand_model.godeleted file mode 100644index 4433938f45..0000000000--- a/internal/agent/component/stagehand_model.go+++ /dev/null@@ -1,166 +0,0 @@-package component--import (- "context"- "crypto/hmac"- "crypto/rand"- "encoding/json/v2"- "fmt"- "net"- "net/http"- "time"-- "ragflow/internal/entity/models"-)--// Stagehand speaks OpenAI on this private connection; the selected Go driver-// owns the actual provider protocol, credentials, endpoints and response parsing.-func startStagehandModelServer(ctx context.Context, model *models.ChatModel) (baseURL, token string, closeServer func(), err error) {- if model == nil || model.ModelDriver == nil {- return "", "", nil, fmt.Errorf("stagehand model: resolved chat model is required")- }- listener, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- return "", "", nil, fmt.Errorf("stagehand model: listen: %w", err)- }- token = rand.Text()- mux := http.NewServeMux()- mux.HandleFunc("POST /v1/chat/completions", func(w http.ResponseWriter, request *http.Request) {- w.Header().Set("Content-Type", "application/json")- fail := func(status int, err error) {- w.WriteHeader(status)- _ = json.MarshalWrite(w, map[string]any{"error": map[string]any{"message": err.Error(), "type": "model_error"}})- }- if !hmac.Equal([]byte(request.Header.Get("Authorization")), []byte("Bearer "+token)) {- fail(http.StatusUnauthorized, fmt.Errorf("invalid Stagehand model token"))- return- }- var input struct {- Messages []models.Message `json:"messages"`- Stream bool `json:"stream"`- Temperature *float64 `json:"temperature"`- TopP *float64 `json:"top_p"`- MaxTokens *int `json:"max_tokens"`- MaxCompletionTokens *int `json:"max_completion_tokens"`- Stop any `json:"stop"`- Tools []map[string]any `json:"tools"`- ToolChoice any `json:"tool_choice"`- ResponseFormat *struct {- Type string `json:"type"`- JSONSchema struct {- Schema map[string]any `json:"schema"`- } `json:"json_schema"`- } `json:"response_format"`- }- if err := json.UnmarshalRead(http.MaxBytesReader(w, request.Body, 64<<20), &input); err != nil {- fail(http.StatusBadRequest, err)- return- }- if input.Stream || len(input.Messages) == 0 {- fail(http.StatusBadRequest, fmt.Errorf("Stagehand model requires non-streaming messages"))- return- }- config := &models.ChatConfig{Temperature: input.Temperature, TopP: input.TopP, MaxTokens: input.MaxTokens}- if config.MaxTokens == nil {- config.MaxTokens = input.MaxCompletionTokens- }- if len(input.Tools) > 0 {- config.Tools = input.Tools- }- if choice, ok := input.ToolChoice.(string); ok {- config.ToolChoice = &choice- } else if input.ToolChoice != nil {- config.ToolChoice = new("required")- config.ToolChoiceValue = input.ToolChoice- }- if input.Stop != nil {- var stop []string- switch value := input.Stop.(type) {- case string:- stop = []string{value}- case []any:- for _, item := range value {- text, ok := item.(string)- if !ok {- fail(http.StatusBadRequest, fmt.Errorf("invalid stop sequence"))- return- }- stop = append(stop, text)- }- default:- fail(http.StatusBadRequest, fmt.Errorf("invalid stop sequence"))- return- }- config.Stop = &stop- }- structured := false- if format := input.ResponseFormat; format != nil && format.Type != "text" {- if len(input.Tools) > 0 {- fail(http.StatusBadRequest, fmt.Errorf("combined structured output and tools are unsupported"))- return- }- schema := format.JSONSchema.Schema- switch format.Type {- case "json_object":- schema = map[string]any{"type": "object"}- case "json_schema":- if len(schema) == 0 {- fail(http.StatusBadRequest, fmt.Errorf("structured output schema is required"))- return- }- default:- fail(http.StatusBadRequest, fmt.Errorf("unsupported response format %q", format.Type))- return- }- // Function tools are the shared provider contract for structured output.- config.Tools = []map[string]any{{"type": "function", "function": map[string]any{"name": "ragflow_structured_output", "description": "Return the requested structured result.", "parameters": schema}}}- config.ToolChoice = new("required")- config.ToolChoiceValue = map[string]any{"type": "function", "function": map[string]any{"name": "ragflow_structured_output"}}- structured = true- }- result, err := model.ChatWithMessages(request.Context(), input.Messages, config, nil)- if err != nil {- fail(http.StatusBadGateway, err)- return- }- if result == nil {- fail(http.StatusBadGateway, fmt.Errorf("provider returned no response"))- return- }- content := result.Answer- calls := result.ToolCalls- if structured {- if len(calls) != 1 {- fail(http.StatusBadGateway, fmt.Errorf("provider did not return the structured output tool"))- return- }- function, _ := calls[0]["function"].(map[string]any)- arguments, ok := function["arguments"].(string)- var value any- if !ok || function["name"] != "ragflow_structured_output" || json.Unmarshal([]byte(arguments), &value) != nil {- fail(http.StatusBadGateway, fmt.Errorf("provider returned invalid structured output"))- return- }- content = &arguments- calls = nil- }- message := map[string]any{"role": "assistant", "content": content}- finishReason := "stop"- if len(calls) > 0 {- message["tool_calls"] = calls- finishReason = "tool_calls"- }- if result.ReasonContent != nil {- message["reasoning_content"] = *result.ReasonContent- }- response := map[string]any{"id": "chatcmpl-stagehand", "object": "chat.completion", "created": time.Now().Unix(), "model": "ragflow", "choices": []any{map[string]any{"index": 0, "message": message, "finish_reason": finishReason}}}- if result.Usage != nil {- response["usage"] = result.Usage- }- _ = json.MarshalWrite(w, response)- })- server := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second, BaseContext: func(net.Listener) context.Context { return ctx }}- go func() { _ = server.Serve(listener) }()- stop := context.AfterFunc(ctx, func() { _ = server.Close() })- return "http://" + listener.Addr().String() + "/v1", token, func() { stop(); _ = server.Close() }, nil-}diff --git a/internal/agent/component/stagehand_runtime.go b/internal/agent/component/stagehand_runtime.godeleted file mode 100644index fbc44a05d5..0000000000--- a/internal/agent/component/stagehand_runtime.go+++ /dev/null@@ -1,761 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--// Package component — StagehandInvoker runtime (T3 sub-package).-//-// StagehandInvoker is the abstraction the Browser component uses to-// dispatch a multi-step web automation task via-// `github.com/browserbase/stagehand-go/v3` in local mode.-//-// # Multi-tenant client cache-//-// The production runtime (stagehandRuntime) maintains a cache of-// stagehand.Client instances keyed by-// `(apiKey, baseURL, modelName)`. Each cached client owns its own-// stagehand-server-v3 subprocess. The cache is bounded by:-// - TTL (default 30 min): idle entries are evicted by a-// background sweeper goroutine.-// - LRU cap (default 64): when the cache exceeds `cap`, the-// least-recently-used entry is evicted.-//-// This replaces the v1 "single-client, recycle on key change"-// model. The recycle model paid a 1–3 s subprocess rebuild on every-// tenant/model switch under mixed-tenant load; the cache model-// pays it once per tenant (cold start) and serves subsequent calls-// in O(1).-//-// # Configuration-//-// Tunable via env (read at DefaultRuntime construction time):-// - STAGEHAND_CACHE_TTL: entry idle-TTL (Go duration syntax, default 30m)-// - STAGEHAND_CACHE_CAP: max concurrent entries (default 64, 0 = unlimited)-// - STAGEHAND_CACHE_SWEEP: sweeper interval (default ttl/6, clamped to ≥ 30s)-//-// # Concurrency-//-// The cache is a sync.Map; a runtime mutex serializes acquisitions and-// eviction so an entry cannot close while a caller is acquiring a lease.-//-// # Dependency-//-// The runtime depends on a working `stagehand-server-v3-<platform>-<arch>`-// binary on the host (Docker: see `docker/Dockerfile`; local dev:-// `ResolveBinaryPath` in `lib/local/local.go` downloads from GitHub-// on first use).-package component--import (- "context"- "encoding/json"- "errors"- "fmt"- "math"- "ragflow/internal/common"- "ragflow/internal/entity/models"- "sort"- "strconv"- "strings"- "sync"- "sync/atomic"- "time"-- stagehand "github.com/browserbase/stagehand-go/v3"- "github.com/browserbase/stagehand-go/v3/option"-)--// RunTaskRequest is the input to StagehandInvoker.RunTask.-//-// Fields are the per-call model config + task instruction. The-// runtime owns the stagehand-server process and the session-// lifecycle; the caller is responsible for resolving these from-// the tenant model config and the canvas state.-type RunTaskRequest struct {- ChatModel *models.ChatModel- // TenantID is the RAGFlow tenant identifier (used for logging /- // error context; not currently passed to stagehand).- TenantID string- // LLMID is the original `llm_id` from the canvas (e.g.- // "deepseek-v4-pro@DeepSeek"). Echoed back in error context.- LLMID string- // ModelName is the stagehand `modelName` value (e.g.- // "openai/gpt-4o"). Must be in `<provider>/<model>` form.- ModelName string- // BaseURL is the OpenAI-compatible LLM endpoint. When non-empty,- // passed via the per-call Model.BaseURL field; when empty, the- // stagehand server's default (api.openai.com) is used.- BaseURL string- // OpenAIChatCompletions selects Chat Completions for compatible providers.- OpenAIChatCompletions bool- // APIKey is the LLM provider key. Required by the stagehand- // server in local mode (MODEL_API_KEY env).- APIKey string- // Instruction is the natural-language task description that- // `Sessions.Execute` consumes.- Instruction string- // MaxSteps caps the agent's step count. Zero defaults to 30- // (matches Python `browser.py:max_steps`).- MaxSteps int- // Headless controls `Sessions.Start.Browser.LaunchOptions.Headless`.- // Nil = server default (true).- Headless *bool- ChromiumSandbox bool-- // DownloadsPath is forwarded to- // `Sessions.Start.Browser.LaunchOptions.DownloadsPath`. When- // non-empty, the stagehand browser writes downloads to this- // directory. Used by OQ-22a.- DownloadsPath string- // UserDataDir is forwarded to- // `Sessions.Start.Browser.LaunchOptions.UserDataDir`. When- // non-empty, the stagehand browser uses it as the persistent- // profile dir. Used by OQ-22c.- UserDataDir string- // PreserveUserDataDir is forwarded to- // `Sessions.Start.Browser.LaunchOptions.PreserveUserDataDir`.- // Set when persist_session=true so cookies / local storage- // survive across sessions. Used by OQ-22c.- PreserveUserDataDir bool-}--// StagehandInvoker is the abstraction BrowserComponent depends on.-// Tests substitute a fake; production uses `DefaultRuntime`.-type StagehandInvoker interface {- RunTask(ctx context.Context, req RunTaskRequest) (message string, err error)- RunExtract(ctx context.Context, req RunExtractRequest) (rawJSON string, err error)-}--// Default cache parameters. Override via env at process start;-// DefaultRuntime reads these via envDuration / envInt at init.-const (- defaultStagehandCacheTTL = 30 * time.Minute- defaultStagehandCacheCap = 64- defaultStagehandCacheSweep = 5 * time.Minute- minStagehandCacheSweep = 30 * time.Second-)--// DefaultRuntime is the package-level production invoker. Replaced-// in tests via `SetDefaultStagehandInvoker`.-var (- DefaultRuntime StagehandInvoker = newStagehandRuntimeFromEnv()-- defaultRuntimeMu sync.RWMutex-)--// SetDefaultStagehandInvoker swaps the package-level invoker (test-// helper). Production code should not call this; the runtime is-// process-singleton.-func SetDefaultStagehandInvoker(inv StagehandInvoker) {- defaultRuntimeMu.Lock()- defer defaultRuntimeMu.Unlock()- if inv == nil {- DefaultRuntime = newStagehandRuntimeFromEnv()- return- }- DefaultRuntime = inv-}--// getDefaultStagehandInvoker returns the current invoker under a-// read-lock so concurrent swaps during a test are race-free.-func getDefaultStagehandInvoker() StagehandInvoker {- defaultRuntimeMu.RLock()- defer defaultRuntimeMu.RUnlock()- if DefaultRuntime == nil {- return newStagehandRuntimeFromEnv()- }- return DefaultRuntime-}--// envDuration reads a Go-duration env var, falling back to def on-// missing / parse failure.-func envDuration(key string, def time.Duration) time.Duration {- v := common.GetEnv(key)- if v == "" {- return def- }- d, err := time.ParseDuration(v)- if err != nil || d <= 0 {- return def- }- return d-}--// envInt reads a non-negative int env var, falling back to def.-func envInt(key string, def int) int {- v := common.GetEnv(key)- if v == "" {- return def- }- n, err := strconv.Atoi(v)- if err != nil || n < 0 {- return def- }- return n-}--// newStagehandRuntimeFromEnv builds a stagehandRuntime with config-// from env (or library defaults). Used as the production DefaultRuntime.-func newStagehandRuntimeFromEnv() *stagehandRuntime {- ttl := envDuration("STAGEHAND_CACHE_TTL", defaultStagehandCacheTTL)- cap := envInt("STAGEHAND_CACHE_CAP", defaultStagehandCacheCap)- sweep := envDuration("STAGEHAND_CACHE_SWEEP", defaultStagehandCacheSweep)- return newStagehandRuntime(ttl, cap, sweep)-}--// stagehandClientEntry is one cached stagehand.Client. lastUsedAt-// is touched on every cache hit; the sweeper uses it to decide-// eviction. A retired entry closes once its last operation releases it.-type stagehandClientEntry struct {- client stagehand.Client- lastUsedAt atomic.Int64 // unix nano- closeOnce sync.Once- users int // guarded by stagehandRuntime.mu- retired bool-}--// Close shuts down the client (kills the stagehand-server-// subprocess). Idempotent.-func (e *stagehandClientEntry) Close() {- e.closeOnce.Do(func() {- _ = e.client.Close()- })-}--// stagehandRuntime is the production StagehandInvoker. It maintains-// a sync.Map cache of stagehand.Client instances keyed by-// `(apiKey, baseURL, modelName)`. See the package doc for the-// multi-tenant model rationale.-type stagehandRuntime struct {- cache sync.Map // map[string]*stagehandClientEntry- mu sync.Mutex- closed bool- stopOnce sync.Once- ttl time.Duration- cap int // 0 = unlimited- sweepStop chan struct{}- sweepDone chan struct{}-}--// newStagehandRuntime constructs a runtime with explicit config and-// starts the sweeper goroutine. Tests that want full control over-// timing should use this constructor (e.g., with very short TTL +-// short sweep interval) rather than newStagehandRuntimeFromEnv.-//-// sweepInterval is clamped to at least minStagehandCacheSweep to-// avoid sweeper-storm when ttl is small.-func newStagehandRuntime(ttl time.Duration, cap int, sweepInterval time.Duration) *stagehandRuntime {- r := &stagehandRuntime{- ttl: ttl,- cap: cap,- sweepStop: make(chan struct{}),- sweepDone: make(chan struct{}),- }- if ttl > 0 && sweepInterval < minStagehandCacheSweep {- sweepInterval = minStagehandCacheSweep- }- r.startSweeper(sweepInterval)- return r-}--// startSweeper runs the TTL eviction loop in a background-// goroutine. It exits cleanly when sweepStop is closed; Close()-// drains via sweepDone.-func (r *stagehandRuntime) startSweeper(interval time.Duration) {- if r.ttl <= 0 {- // No TTL → no sweeper. Drain immediately so Close() doesn't- // block.- close(r.sweepDone)- return- }- go func() {- ticker := time.NewTicker(interval)- defer ticker.Stop()- defer close(r.sweepDone)- for {- select {- case <-r.sweepStop:- return- case <-ticker.C:- r.evictExpired()- }- }- }()-}--// evictExpired retires entries whose lastUsedAt is older than ttl.-// Active operations hold a lease until their session cleanup finishes.-func (r *stagehandRuntime) evictExpired() {- cutoff := time.Now().Add(-r.ttl).UnixNano()- removed := r.retireExpired(cutoff)- for _, e := range removed {- e.Close()- }-}--func (r *stagehandRuntime) retireExpired(cutoff int64) []*stagehandClientEntry {- r.mu.Lock()- defer r.mu.Unlock()- var removed []*stagehandClientEntry- var keys []string- r.cache.Range(func(k, v any) bool {- keys = append(keys, k.(string))- return true- })- sort.Strings(keys)- for _, k := range keys {- v, ok := r.cache.Load(k)- if !ok {- continue- }- e := v.(*stagehandClientEntry)- if e.lastUsedAt.Load() >= cutoff {- continue // still fresh- }- if cur, loaded := r.cache.LoadAndDelete(k); loaded {- e = cur.(*stagehandClientEntry)- e.retired = true- if e.users == 0 {- removed = append(removed, e)- }- }- }- return removed-}--// enforceLRUCap evicts the least-recently-used entry when the cache-// exceeds `cap`. Called by leaseClient after a successful insert.-func (r *stagehandRuntime) enforceLRUCap() {- if r.cap <= 0 {- return- }- r.mu.Lock()- count := 0- r.cache.Range(func(_, _ any) bool { count++; return true })- if count <= r.cap {- r.mu.Unlock()- return- }- var (- oldestKey string- oldestTS int64 = math.MaxInt64- )- r.cache.Range(func(k, v any) bool {- t := v.(*stagehandClientEntry).lastUsedAt.Load()- if t < oldestTS {- oldestTS, oldestKey = t, k.(string)- }- return true- })- if oldestKey == "" {- r.mu.Unlock()- return- }- var closeEntry *stagehandClientEntry- if cur, loaded := r.cache.LoadAndDelete(oldestKey); loaded {- e := cur.(*stagehandClientEntry)- e.retired = true- if e.users == 0 {- closeEntry = e- }- }- r.mu.Unlock()- if closeEntry != nil {- closeEntry.Close()- }-}--// RunTask implements StagehandInvoker.-//-// Lifecycle per call:-// 1. Look up (or build + cache) the stagehand.Client for this-// request's key.-// 2. Sessions.Start (browser, model, launch options).-// 3. defer Sessions.End.-// 4. Sessions.Execute (instruction, max-steps).-// 5. Return the agent's final message text.-//-// Multi-tenant isolation: a request with key K hits only the-// cached client for K (or builds one). Other tenants' clients are-// unaffected.-func (r *stagehandRuntime) RunTask(ctx context.Context, req RunTaskRequest) (string, error) {- if req.Instruction == "" {- return "", errors.New("stagehand runtime: Instruction is required")- }- cacheReq := req- if req.ChatModel != nil {- baseURL, token, closeServer, err := startStagehandModelServer(ctx, req.ChatModel)- if err != nil {- return "", err- }- defer closeServer()- // Cache subprocesses by tenant/model, not by ephemeral bridge credentials.- cacheReq.ModelName, cacheReq.APIKey, cacheReq.BaseURL = "openai/ragflow", "ragflow", ""- req.ModelName, req.APIKey, req.BaseURL = "openai/ragflow", token, baseURL- req.OpenAIChatCompletions = true- }- if req.ModelName == "" {- return "", errors.New("stagehand runtime: ModelName is required")- }- if req.APIKey == "" {- return "", errors.New("stagehand runtime: APIKey is required (stagehand local mode requires MODEL_API_KEY)")- }-- client, release, err := r.leaseClient(cacheReq)- if err != nil {- return "", fmt.Errorf("stagehand runtime: client: %w", err)- }- defer release()-- headless := true- if req.Headless != nil {- headless = *req.Headless- }-- // Sessions.Start opens a local browser session. Browser.Type =- // "local" tells the stagehand server to use its bundled CDP- // driver (not Browserbase). The ModelName is the session-wide- // LLM; per-call Model.BaseURL/APIKey are passed on Execute.- //- // LaunchOptions are populated only when the caller provided- // non-zero values; the SDK's param.Opt[T] omits zero-valued- // pointers from the JSON payload, so an unset DownloadsPath /- // UserDataDir produces byte-identical wire output to v1.- launchOpts := stagehand.SessionStartParamsBrowserLaunchOptions{- Headless: stagehand.Bool(headless),- }- if !req.ChromiumSandbox {- launchOpts.Args = []string{"--no-sandbox"}- }- if req.DownloadsPath != "" {- launchOpts.DownloadsPath = stagehand.String(req.DownloadsPath)- }- if req.UserDataDir != "" {- launchOpts.UserDataDir = stagehand.String(req.UserDataDir)- if req.PreserveUserDataDir {- launchOpts.PreserveUserDataDir = stagehand.Bool(true)- }- }- startResp, err := client.Sessions.Start(ctx, stagehand.SessionStartParams{- ModelName: req.ModelName,- Browser: stagehand.SessionStartParamsBrowser{- Type: "local",- LaunchOptions: launchOpts,- },- })- if err != nil {- return "", fmt.Errorf("stagehand runtime: Sessions.Start: %w", err)- }- sessionID := startResp.Data.SessionID- defer func() {- // Best-effort End. The deferred call's error is intentionally- // dropped — the agent result has already been returned; the- // End failure is logged by the stagehand server.- cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)- defer cancel()- _, _ = client.Sessions.End(cleanupCtx, sessionID, stagehand.SessionEndParams{})- }()-- // Sessions.Execute runs the multi-step agent. MaxSteps defaults- // to 30 when zero (matches Python browser.py).- maxSteps := req.MaxSteps- if maxSteps <= 0 {- maxSteps = 30- }-- agentConfig := stagehand.SessionExecuteParamsAgentConfig{- // GenericModelConfigObject carries ModelName + APIKey +- // BaseURL on a per-call basis; the "openai/" prefix in- // ModelName tells the stagehand server to dispatch via- // its OpenAI-compatible provider (CHANGELOG #1025 added- // custom BaseURL support). The union's- // OfSessionExecutesAgentConfigModelGenericModelConfigObject- // variant is the only path that exposes BaseURL.- Model: stagehand.SessionExecuteParamsAgentConfigModelUnion{- OfSessionExecutesAgentConfigModelGenericModelConfigObject: stagehandExecuteModelConfig(req),- },- }- if req.ChatModel != nil {- agentConfig.Mode = "dom"- }- execResp, err := client.Sessions.Execute(ctx, sessionID, stagehand.SessionExecuteParams{- AgentConfig: agentConfig,- ExecuteOptions: stagehand.SessionExecuteParamsExecuteOptions{- Instruction: req.Instruction,- MaxSteps: stagehand.Float(float64(maxSteps)),- },- })- if err != nil {- return "", fmt.Errorf("stagehand runtime: Sessions.Execute: %w", err)- }-- if !execResp.Success || !execResp.Data.Result.Success {- // Surface a clear error so the canvas engine can branch on- // the failure. The agent's own `Message` is included for- // debugging.- return "", fmt.Errorf("stagehand runtime: agent did not succeed (success=%v, completed=%v, message=%q)",- execResp.Data.Result.Success, execResp.Data.Result.Completed, execResp.Data.Result.Message)- }-- return execResp.Data.Result.Message, nil-}--func stagehandExecuteModelConfig(req RunTaskRequest) *stagehand.SessionExecuteParamsAgentConfigModelGenericModelConfigObject {- provider, _, _ := strings.Cut(req.ModelName, "/")- model := &stagehand.SessionExecuteParamsAgentConfigModelGenericModelConfigObject{- ModelName: req.ModelName,- APIKey: stagehand.String(req.APIKey),- Provider: provider,- }- if provider == "openai" && req.OpenAIChatCompletions {- // Compatible providers implement Chat Completions, not necessarily Responses.- model.SetExtraFields(map[string]any{"openaiEndpointFormat": "chat"})- }- if baseURL := strings.TrimSpace(req.BaseURL); baseURL != "" {- model.BaseURL = stagehand.String(baseURL)- }- return model-}--// RunExtractRequest is the input to stagehandRuntime.RunExtract.-//-// RunExtract is the "structured single-shot" sibling of RunTask:-// it opens a session, optionally navigates to a URL, calls-// Sessions.Extract with a JSON schema, and returns the extracted-// data as a JSON string. The schema's structure is the result-// shape (e.g. `{"headlines": [...]}`); the response field-// `Data.Result` (any) is marshaled as JSON for the caller.-//-// RunExtract is the right API when:-// - the URL is known up front-// - the output shape is well-known (zod-style JSON schema)-// - the caller wants deterministic structured data, not a-// free-form agent summary-//-// Use RunTask (Sessions.Execute) instead when the agent must-// discover the URL, navigate multiple pages, or chain actions.-type RunExtractRequest struct {- TenantID string- LLMID string- ModelName string // "openai/<model>"- BaseURL string- OpenAIChatCompletions bool- APIKey string- Headless *bool- // ChromiumSandbox controls whether Chromium's sandbox is enabled.- // False (the zero value) adds --no-sandbox to support root containers.- ChromiumSandbox bool- URL string // optional: when set, Sessions.Navigate to this URL first- Instruction string // natural-language extraction prompt- Schema map[string]any // JSON schema; Data.Result is the structured data-}--// RunExtract implements the "structured single-shot" path against-// stagehand-go. Returns the extracted data as a JSON string.-//-// Lifecycle per call:-// 1. Look up (or build + cache) the stagehand.Client for this-// request's key (same cache as RunTask).-// 2. Sessions.Start (browser, model, launch options).-// 3. defer Sessions.End.-// 4. If URL != "", Sessions.Navigate({URL: req.URL}).-// 5. Sessions.Extract({Instruction, Schema, Options.Model}). The-// response `Data.Result` field is the structured data matching-// Schema; we marshal it as JSON and return.-//-// RunExtract reuses the same `stagehandRuntime` cache as RunTask-// (per `(apiKey, baseURL, modelName)` key), so cold-start cost is-// amortized across Task and Extract calls for the same tenant.-func (r *stagehandRuntime) RunExtract(ctx context.Context, req RunExtractRequest) (string, error) {- if req.Instruction == "" {- return "", errors.New("stagehand runtime: RunExtract: Instruction is required")- }- if req.ModelName == "" {- return "", errors.New("stagehand runtime: RunExtract: ModelName is required")- }- if req.Schema == nil {- return "", errors.New("stagehand runtime: RunExtract: Schema is required")- }- if req.APIKey == "" {- return "", errors.New("stagehand runtime: RunExtract: APIKey is required (stagehand local mode requires MODEL_API_KEY)")- }-- client, release, err := r.leaseClient(RunTaskRequest{- BaseURL: req.BaseURL,- APIKey: req.APIKey,- ModelName: req.ModelName,- })- if err != nil {- return "", fmt.Errorf("stagehand runtime: RunExtract: client: %w", err)- }- defer release()-- headless := true- if req.Headless != nil {- headless = *req.Headless- }-- launchOpts := stagehand.SessionStartParamsBrowserLaunchOptions{- Headless: stagehand.Bool(headless),- }- if !req.ChromiumSandbox {- launchOpts.Args = []string{"--no-sandbox"}- }- if req.URL != "" {- // Note: BrowserLaunchOptions doesn't carry DownloadsPath /- // UserDataDir here; RunExtract is single-shot extraction- // without browser automation, so we skip those.- _ = req.URL- }-- startResp, err := client.Sessions.Start(ctx, stagehand.SessionStartParams{- ModelName: req.ModelName,- Browser: stagehand.SessionStartParamsBrowser{- Type: "local",- LaunchOptions: launchOpts,- },- })- if err != nil {- return "", fmt.Errorf("stagehand runtime: RunExtract: Sessions.Start: %w", err)- }- sessionID := startResp.Data.SessionID- defer func() {- cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)- defer cancel()- _, _ = client.Sessions.End(cleanupCtx, sessionID, stagehand.SessionEndParams{})- }()-- // Optional: navigate to the target URL before extracting.- if req.URL != "" {- if _, err := client.Sessions.Navigate(ctx, sessionID, stagehand.SessionNavigateParams{- URL: req.URL,- }); err != nil {- return "", fmt.Errorf("stagehand runtime: RunExtract: Sessions.Navigate: %w", err)- }- }-- extractResp, err := client.Sessions.Extract(ctx, sessionID, stagehand.SessionExtractParams{- Instruction: stagehand.String(req.Instruction),- Options: stagehand.SessionExtractParamsOptions{- Model: stagehandExtractModelConfig(req),- },- Schema: req.Schema,- })- if err != nil {- return "", fmt.Errorf("stagehand runtime: RunExtract: Sessions.Extract: %w", err)- }- if !extractResp.Success {- return "", fmt.Errorf("stagehand runtime: RunExtract: agent did not succeed (success=%v, data=%+v)",- extractResp.Success, extractResp.Data)- }-- // Data.Result is `any` (decoded from stagehand server's JSON).- // Re-marshal as a stable JSON string for the caller.- out, err := json.Marshal(extractResp.Data.Result)- if err != nil {- return "", fmt.Errorf("stagehand runtime: RunExtract: marshal result: %w", err)- }- return string(out), nil-}--func stagehandExtractModelConfig(req RunExtractRequest) stagehand.SessionExtractParamsOptionsModelUnion {- provider, _, _ := strings.Cut(req.ModelName, "/")- model := &stagehand.SessionExtractParamsOptionsModelGenericModelConfigObject{- ModelName: req.ModelName,- APIKey: stagehand.String(req.APIKey),- Provider: provider,- }- if provider == "openai" && req.OpenAIChatCompletions {- // The server supports this field; the pinned Go SDK has no typed field yet.- model.SetExtraFields(map[string]any{"openaiEndpointFormat": "chat"})- }- if baseURL := strings.TrimSpace(req.BaseURL); baseURL != "" {- model.BaseURL = stagehand.String(baseURL)- }- return stagehand.SessionExtractParamsOptionsModelUnion{- OfSessionExtractsOptionsModelGenericModelConfigObject: model,- }-}--// Close drains the sweeper goroutine and closes every cached-// client (each Close kills its stagehand-server subprocess).-// Safe to call multiple times.-func (r *stagehandRuntime) Close() error {- if r.sweepStop != nil {- r.stopOnce.Do(func() { close(r.sweepStop) })- if r.sweepDone != nil {- <-r.sweepDone- }- }- r.mu.Lock()- r.closed = true- var removed []*stagehandClientEntry- r.cache.Range(func(k, v any) bool {- e := v.(*stagehandClientEntry)- r.cache.Delete(k)- e.retired = true- if e.users == 0 {- removed = append(removed, e)- }- return true- })- r.mu.Unlock()- for _, e := range removed {- e.Close()- }- return nil-}--func (r *stagehandRuntime) leaseClient(req RunTaskRequest) (stagehand.Client, func(), error) {- if req.APIKey == "" {- return stagehand.Client{}, nil, errors.New("stagehand runtime: APIKey is required")- }- key := req.BaseURL + "|" + req.APIKey + "|" + req.ModelName- if req.ChatModel != nil {- key = fmt.Sprintf("resolved:%q:%q", req.TenantID, req.LLMID)- }- r.mu.Lock()- if r.closed {- r.mu.Unlock()- return stagehand.Client{}, nil, errors.New("stagehand runtime: closed")- }- var e *stagehandClientEntry- inserted := false- if v, ok := r.cache.Load(key); ok {- e = v.(*stagehandClientEntry)- } else {- e = &stagehandClientEntry{client: stagehand.NewClient(- option.WithServer("local"),- option.WithModelAPIKey(req.APIKey),- )}- r.cache.Store(key, e)- inserted = true- }- e.lastUsedAt.Store(time.Now().UnixNano())- e.users++- r.mu.Unlock()-- if inserted {- r.enforceLRUCap()- }- return e.client, func() {- r.mu.Lock()- e.users--- closeEntry := e.users == 0 && e.retired- r.mu.Unlock()- if closeEntry {- e.Close()- }- }, nil-}diff --git a/internal/agent/component/stagehand_runtime_integration_test.go b/internal/agent/component/stagehand_runtime_integration_test.godeleted file mode 100644index 71b33c0fda..0000000000--- a/internal/agent/component/stagehand_runtime_integration_test.go+++ /dev/null@@ -1,258 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--// Integration test for stagehand-runtime happy path.-//-// Gated by OPENAI_API_KEY + OPENAI_BASE_URL + OPENAI_MODEL. Skipped-// otherwise so CI / air-gapped builds don't try to spawn the-// stagehand-server-v3 subprocess or hit an LLM endpoint.-//-// Credentials are read from env at test time — never hardcoded:-//-// OPENAI_API_KEY LLM provider key-// OPENAI_BASE_URL OpenAI-compatible endpoint (default https://api.openai.com/v1)-// OPENAI_MODEL model id passed as `openai/<model>` to stagehand-//-// Optional:-//-// STAGEHAND_EXTRACT_SCHEMA_JSON zod-style JSON schema (default: {"type":"string"})-// STAGEHAND_EXTRACT_RESULT_FILE path to dump the extraction result-//-// Run:-//-// export OPENAI_API_KEY=sk-...-// export OPENAI_BASE_URL=https://...-// export OPENAI_MODEL=...-// rtk go test ./internal/agent/component/ -count=1 \-// -run TestStagehandRuntime_Extract -v -timeout 3m--//go:build integration--package component--import (- "context"- "encoding/json"- "fmt"- "net/http"- "net/http/httptest"- "os"- "path/filepath"- "ragflow/internal/common"- "ragflow/internal/entity/models"- "strings"- "testing"- "time"-- "ragflow/internal/agent/canvas"- "ragflow/internal/agent/runtime"-)--// TestStagehandRuntime_Extract is the single happy-path integration-// test. It calls stagehandRuntime.RunExtract (Sessions.Navigate +-// Sessions.Extract) against BBC News's international section with-// the **default single-string schema** and asserts the LLM returns-// a non-empty result. The test exists to prove the full RAGFlow +-// stagehand-go pipeline works end-to-end:-//-// - stagehand-server-v3 binary spawn (or GitHub download on cold start)-// - HTTP routing on localhost (Sessions.Start / Extract / End)-// - LLM dispatch through the OpenAI-compat provider with a custom-// BaseURL and API key-// - Real headless Chromium loading the page-// - RunExtractRequest caching by (apiKey, baseURL, modelName)-//-// The default schema is intentionally minimal ({"type": "string"}):-// a single-string response is the cheapest LLM call that still-// exercises the extract path. Callers wanting structured output-// pass their own schema via RunExtractRequest.Schema, or override-// the test's default via STAGEHAND_EXTRACT_SCHEMA_JSON. We-// deliberately do NOT assert specific content here — the goal is-// to prove the pipeline, not pin a particular model output.-//-// End-to-end verified against api.zetatechs.com/v1 + gpt-4o label-// against https://www.bbc.com/news/world — returns a non-empty-// summary string in ~10s.-func TestStagehandRuntime_Extract(t *testing.T) {- apiKey := common.GetEnv(common.EnvOpenAIAPIKey)- baseURL := common.GetEnv(common.EnvOpenAIBaseURL)- model := common.GetEnv(common.EnvOpenAIModel)- if apiKey == "" || baseURL == "" || model == "" {- t.Skipf("missing required env (OPENAI_API_KEY/OPENAI_BASE_URL/OPENAI_MODEL); skipping")- }-- // Default schema: single string. Optional override via env:- // STAGEHAND_EXTRACT_SCHEMA_JSON='{"type":"object",...}'.- var schema map[string]any- if raw := common.GetEnv(common.EnvStageHandExtractSchemaJSON); raw != "" {- if err := json.Unmarshal([]byte(raw), &schema); err != nil {- t.Fatalf("STAGEHAND_EXTRACT_SCHEMA_JSON is not valid JSON: %v", err)- }- } else {- schema = map[string]any{"type": "string"}- }-- // Sanity-check the binary is at least resolvable. The runtime- // itself downloads from GitHub on first use when missing, so- // we don't fail here — we just log a hint.- if _, err := os.Stat(filepath.Join(cacheDirGuess(), "stagehand-server-v3-linux-x64")); err != nil {- t.Logf("stagehand-server-v3 binary not pre-cached at %s; will attempt download on first call",- filepath.Join(cacheDirGuess(), "stagehand-server-v3-linux-x64"))- }-- r := newStagehandRuntime(time.Hour, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- headless := true- req := RunExtractRequest{- TenantID: "integration-test",- LLMID: model,- ModelName: "openai/" + model, // provider/model form required by stagehand allowlist- BaseURL: baseURL,- APIKey: apiKey,- Headless: &headless,- URL: "https://www.bbc.com/news/world",- Instruction: "Provide a one-paragraph summary of the current top international news on this page.",- Schema: schema,- }-- ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)- defer cancel()-- t.Logf("starting stagehand RunExtract (timeout 3m); spawns subprocess, calls LLM once with schema=%s",- truncateSchema(schema))- start := time.Now()- resultJSON, err := r.RunExtract(ctx, req)- elapsed := time.Since(start)- if err != nil {- t.Fatalf("RunExtract failed after %v: %v", elapsed, err)- }- if resultJSON == "" {- t.Fatalf("RunExtract returned empty result after %v", elapsed)- }-- t.Logf("RunExtract returned in %v (result length=%d bytes)", elapsed, len(resultJSON))- t.Logf("extraction result:\n%s", resultJSON)-- // Dump for external observers.- dumpPath := common.GetEnv(common.EnvStageHandExtractResultFile)- if dumpPath == "" {- dumpPath = "/tmp/stagehand_extract_result.txt"- }- _ = os.WriteFile(dumpPath, []byte(resultJSON), 0o644)- t.Logf("extraction result dumped to %s", dumpPath)-}--// truncateSchema renders a small summary of the schema for test-// log lines (avoids dumping long JSON).-func truncateSchema(s map[string]any) string {- b, _ := json.Marshal(s)- if len(b) > 120 {- return string(b[:120]) + "..."- }- return string(b)-}--// cacheDirGuess returns the most likely location of the-// stagehand-server-v3 binary on this host. Mirrors-// `local.go:cacheDir()` so the test can log a hint when the-// binary is missing. We don't fail on miss because the runtime-// falls back to a GitHub download.-func cacheDirGuess() string {- if v := common.GetEnv(common.EnvXDGCacheHome); v != "" {- return filepath.Join(v, "stagehand", "lib")- }- home, err := os.UserHomeDir()- if err != nil || home == "" {- return "/tmp/stagehand/lib"- }- return filepath.Join(home, ".cache", "stagehand", "lib")-}--// TestBrowser_E2E_Extract exercises Browser's agent through the shared model-// driver against a local page. Requires OPENAI_* credentials and Chrome.-func TestBrowser_E2E_Extract(t *testing.T) {- apiKey := common.GetEnv(common.EnvOpenAIAPIKey)- baseURL := common.GetEnv(common.EnvOpenAIBaseURL)- model := common.GetEnv(common.EnvOpenAIModel)- if apiKey == "" || baseURL == "" || model == "" {- t.Skipf("missing required env (OPENAI_API_KEY/OPENAI_BASE_URL/OPENAI_MODEL); skipping")- }-- // --- local test server: a simple page with text content ---- mux := http.NewServeMux()- mux.HandleFunc("/page.html", func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "text/html; charset=utf-8")- fmt.Fprintf(w, `<!DOCTYPE html>-<html><body>-<h1>Test Page</h1>-<p>Hello, this is a test page for RunExtract integration testing.</p>-</body></html>`)- })- srv := httptest.NewServer(mux)- t.Cleanup(srv.Close)-- driver := models.NewOpenAIAPICompatibleModel(map[string]string{"default": strings.TrimRight(baseURL, "/")}, models.URLSuffix{Chat: "chat/completions"})- chatModel := models.NewChatModel(driver, &model, &models.APIConfig{ApiKey: &apiKey, BaseURL: &baseURL})- previousFactory := browserModelFactory- SetBrowserModelFactory(func(_ context.Context, tenantID, modelRef string) (*models.ChatModel, error) {- if tenantID != "tenant-1" {- return nil, fmt.Errorf("unexpected tenant %q", tenantID)- }- return chatModel, nil- })- t.Cleanup(func() { SetBrowserModelFactory(previousFactory) })-- // --- use production stagehand runtime ---- r := newStagehandRuntimeFromEnv()- SetDefaultStagehandInvoker(r)- t.Cleanup(func() {- _ = r.Close()- SetDefaultStagehandInvoker(nil)- })-- // --- browser: extract page content ---- headless := true- prompt := fmt.Sprintf(- "请打开 %s/page.html,提取页面上的标题(h1)和段落(p)的文本内容,用一句话总结。只访问 %s/ 开头的URL。",- srv.URL, srv.URL,- )- c, err := NewBrowserComponent(map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": prompt,- "headless": &headless,- })- if err != nil {- t.Fatalf("NewBrowserComponent: %v", err)- }-- ctx := canvas.WithState(t.Context(), canvas.NewCanvasState("run-1", "task-1"))- state, _ := runtime.GetStateFromContext(ctx)- state.Sys["tenant_id"] = "tenant-1"-- invokeCtx, cancel := context.WithTimeout(ctx, 3*time.Minute)- defer cancel()- t.Logf("starting browser.Invoke (RunTask) against %s (timeout 3m)", srv.URL)- out, err := c.Invoke(invokeCtx, nil, nil)- if err != nil {- t.Fatalf("Invoke: %v", err)- }- content, ok := out["content"].(string)- if !ok || strings.TrimSpace(content) == "" || content == "null" {- t.Fatalf("missing browser result: %#v", out)- }- t.Logf("extracted content: %s", content)-}diff --git a/internal/agent/component/stagehand_runtime_test.go b/internal/agent/component/stagehand_runtime_test.godeleted file mode 100644index 2178938714..0000000000--- a/internal/agent/component/stagehand_runtime_test.go+++ /dev/null@@ -1,716 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package component--import (- "context"- "errors"- "fmt"- "net/http"- "net/http/httptest"- "strings"- "sync"- "sync/atomic"- "testing"- "time"-- stagehand "github.com/browserbase/stagehand-go/v3"- "github.com/browserbase/stagehand-go/v3/option"-)--// cacheKey is the key formula used by clientFor. Exposed so tests-// can derive the same key without re-implementing the formula.-func cacheKey(req RunTaskRequest) string {- return req.BaseURL + "|" + req.APIKey + "|" + req.ModelName-}--// cacheSize returns the current entry count of r.cache.-func cacheSize(r *stagehandRuntime) int {- n := 0- r.cache.Range(func(_, _ any) bool { n++; return true })- return n-}--// clientFor populates the cache without retaining an operation lease.-func (r *stagehandRuntime) clientFor(req RunTaskRequest) (stagehand.Client, error) {- client, release, err := r.leaseClient(req)- if err == nil {- release()- }- return client, err-}--// ----------------------------------------------------------------------------// Validation (unchanged)-// -----------------------------------------------------------------------------func TestStagehandRuntime_ValidatesRequiredFields(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0, time.Minute) // TTL large → no sweeper interference- t.Cleanup(func() { _ = r.Close() })- ctx := t.Context()-- cases := []struct {- name string- req RunTaskRequest- want string- }{- {"empty_instruction", RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: "k"}, "Instruction"},- {"empty_model", RunTaskRequest{Instruction: "x", APIKey: "k"}, "ModelName"},- {"empty_api_key", RunTaskRequest{Instruction: "x", ModelName: "openai/gpt-4o"}, "APIKey"},- }- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- _, err := r.RunTask(ctx, tc.req)- if err == nil {- t.Fatalf("expected error for %s, got nil", tc.name)- }- if !strings.Contains(err.Error(), tc.want) {- t.Errorf("error %q should mention %q", err.Error(), tc.want)- }- })- }-}--func TestStagehandRuntime_RunExtractModelConfig(t *testing.T) {- model := stagehandExtractModelConfig(RunExtractRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://example.test/v1",- APIKey: "sk-test",- })-- if got := model.GetModelName(); got == nil || *got != "openai/gpt-4o" {- t.Fatalf("modelName = %v, want openai/gpt-4o", got)- }- if got := model.GetAPIKey(); got == nil || *got != "sk-test" {- t.Fatalf("apiKey = %v, want sk-test", got)- }- if got := model.GetBaseURL(); got == nil || *got != "https://example.test/v1" {- t.Fatalf("baseURL = %v, want https://example.test/v1", got)- }- if got := model.GetProvider(); got == nil || *got != "openai" {- t.Fatalf("provider = %v, want openai", got)- }-}--func TestStagehandRuntime_RunExtractModelConfigOmitsEmptyBaseURL(t *testing.T) {- model := stagehandExtractModelConfig(RunExtractRequest{- ModelName: "openai/gpt-4o",- BaseURL: " \t\n ",- APIKey: "sk-test",- })-- if got := model.GetBaseURL(); got != nil {- t.Fatalf("baseURL = %q, want omitted", *got)- }-}--// ----------------------------------------------------------------------------// Cache hit / miss / key formula-// -----------------------------------------------------------------------------func TestStagehandRuntime_Cache_HitMiss(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- // First call: miss → build → cache has 1 entry.- if _, err := r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-a",- }); err != nil {- t.Fatalf("clientFor(a): %v", err)- }- if got := cacheSize(r); got != 1 {- t.Errorf("after first clientFor: cache size = %d, want 1", got)- }-- // Same key: hit → still 1 entry.- if _, err := r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-a",- }); err != nil {- t.Fatalf("clientFor(b): %v", err)- }- if got := cacheSize(r); got != 1 {- t.Errorf("after same-key clientFor: cache size = %d, want 1", got)- }-- // Different apiKey → miss → 2 entries.- if _, err := r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-b",- }); err != nil {- t.Fatalf("clientFor(c): %v", err)- }- if got := cacheSize(r); got != 2 {- t.Errorf("after different-apiKey clientFor: cache size = %d, want 2", got)- }-- // Different modelName → 3 entries.- if _, err := r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o-mini",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-b",- }); err != nil {- t.Fatalf("clientFor(d): %v", err)- }- if got := cacheSize(r); got != 3 {- t.Errorf("after different-modelName clientFor: cache size = %d, want 3", got)- }-- // Different baseURL → 4 entries.- if _, err := r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o-mini",- BaseURL: "https://api.deepseek.com/v1",- APIKey: "sk-b",- }); err != nil {- t.Fatalf("clientFor(e): %v", err)- }- if got := cacheSize(r); got != 4 {- t.Errorf("after different-baseURL clientFor: cache size = %d, want 4", got)- }-}--func TestStagehandRuntime_Cache_LastUsedTouched(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- req := RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-a",- }- if _, err := r.clientFor(req); err != nil {- t.Fatalf("clientFor: %v", err)- }- key := cacheKey(req)- v1, ok := r.cache.Load(key)- if !ok {- t.Fatal("entry missing after clientFor")- }- e1 := v1.(*stagehandClientEntry)- t1 := e1.lastUsedAt.Load()-- // Sleep so the timestamp would advance if touched.- time.Sleep(2 * time.Millisecond)-- if _, err := r.clientFor(req); err != nil {- t.Fatalf("clientFor (second): %v", err)- }- v2, _ := r.cache.Load(key)- e2 := v2.(*stagehandClientEntry)- t2 := e2.lastUsedAt.Load()-- if t2 <= t1 {- t.Errorf("lastUsedAt not advanced: t1=%d, t2=%d", t1, t2)- }-}--// ----------------------------------------------------------------------------// Concurrent dedup-// -----------------------------------------------------------------------------func TestStagehandRuntime_Cache_ConcurrentSameKey_NoDuplicateBuild(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- req := RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-conc",- }- const N = 64-- var wg sync.WaitGroup- var calls atomic.Int32- for i := 0; i < N; i++ {- wg.Go(func() {- _, _ = r.clientFor(req)- calls.Add(1)- })- }- wg.Wait()- if calls.Load() != N {- t.Errorf("calls = %d, want %d", calls.Load(), N)- }- // Even with race conditions, the cache must end up with exactly- // 1 entry — sync.Map.LoadOrStore guarantees deduplication.- if got := cacheSize(r); got != 1 {- t.Errorf("after %d concurrent same-key clientFor: cache size = %d, want 1", N, got)- }-}--func TestStagehandRuntime_Cache_ConcurrentDifferentKeys(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- const N = 32- var wg sync.WaitGroup- for i := 0; i < N; i++ {- i := i- wg.Go(func() {- _, _ = r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-" + string(rune('a'+i%26)) + string(rune('A'+(i/26)%26)),- })- })- }- wg.Wait()- // 32 goroutines, but the apiKey pattern has 26*2 = 52 unique- // values. With N=32 < 52 collisions, expect exactly 32 entries.- if got := cacheSize(r); got != N {- t.Errorf("cache size = %d, want %d (one per distinct key)", got, N)- }-}--// ----------------------------------------------------------------------------// TTL eviction-// -----------------------------------------------------------------------------func TestStagehandRuntime_Cache_TTLEviction(t *testing.T) {- r := newStagehandRuntime(50*time.Millisecond, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- req := RunTaskRequest{- ModelName: "openai/gpt-4o",- BaseURL: "https://api.openai.com/v1",- APIKey: "sk-ttl",- }- if _, err := r.clientFor(req); err != nil {- t.Fatalf("clientFor: %v", err)- }- if got := cacheSize(r); got != 1 {- t.Fatalf("after clientFor: cache size = %d, want 1", got)- }-- // Backdate the entry past TTL and trigger eviction directly- // (we don't want to wait for the sweeper in a unit test).- key := cacheKey(req)- v, _ := r.cache.Load(key)- v.(*stagehandClientEntry).lastUsedAt.Store(time.Now().Add(-time.Hour).UnixNano())-- r.evictExpired()-- if got := cacheSize(r); got != 0 {- t.Errorf("after evictExpired: cache size = %d, want 0", got)- }-}--func TestStagehandRuntime_Cache_TTL_FreshEntriesSurvive(t *testing.T) {- r := newStagehandRuntime(50*time.Millisecond, 0, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- if _, err := r.clientFor(RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: "sk-fresh"}); err != nil {- t.Fatalf("clientFor: %v", err)- }- // Don't backdate → entry is fresh → should survive eviction.- r.evictExpired()- if got := cacheSize(r); got != 1 {- t.Errorf("fresh entry evicted: cache size = %d, want 1", got)- }-}--// ----------------------------------------------------------------------------// LRU eviction-// -----------------------------------------------------------------------------func TestStagehandRuntime_Cache_LRUEviction(t *testing.T) {- r := newStagehandRuntime(time.Hour, 2 /*cap=2*/, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- // Insert 3 entries with distinct, ordered lastUsedAt values.- // enforceLRUCap fires inline after each insert, so after the- // 3rd insert the cache is already at cap=2 with the oldest- // (sk-1) evicted.- mk := func(apiKey string) RunTaskRequest {- return RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: apiKey}- }- if _, err := r.clientFor(mk("sk-1")); err != nil {- t.Fatalf("clientFor 1: %v", err)- }- time.Sleep(time.Millisecond)- if _, err := r.clientFor(mk("sk-2")); err != nil {- t.Fatalf("clientFor 2: %v", err)- }- time.Sleep(time.Millisecond)- if _, err := r.clientFor(mk("sk-3")); err != nil {- t.Fatalf("clientFor 3: %v", err)- }-- if got := cacheSize(r); got != 2 {- t.Errorf("after 3 inserts with cap=2: cache size = %d, want 2 (oldest evicted inline)", got)- }- if _, ok := r.cache.Load(cacheKey(mk("sk-1"))); ok {- t.Errorf("oldest entry (sk-1) should be evicted; still present")- }- if _, ok := r.cache.Load(cacheKey(mk("sk-2"))); !ok {- t.Errorf("second entry (sk-2) should still be present")- }- if _, ok := r.cache.Load(cacheKey(mk("sk-3"))); !ok {- t.Errorf("newest entry (sk-3) should still be present")- }-}--func TestStagehandRuntime_Cache_LRUEviction_TouchesLastUsed(t *testing.T) {- r := newStagehandRuntime(time.Hour, 2 /*cap=2*/, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- mk := func(apiKey string) RunTaskRequest {- return RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: apiKey}- }- if _, err := r.clientFor(mk("sk-1")); err != nil {- t.Fatal(err)- }- time.Sleep(time.Millisecond)- if _, err := r.clientFor(mk("sk-2")); err != nil {- t.Fatal(err)- }-- // Touch sk-1 so it becomes the most-recently-used.- time.Sleep(time.Millisecond)- if _, err := r.clientFor(mk("sk-1")); err != nil {- t.Fatal(err)- }-- // Insert sk-3 → cap exceeded → oldest by lastUsedAt (sk-2)- // should be evicted, sk-1 should survive.- if _, err := r.clientFor(mk("sk-3")); err != nil {- t.Fatal(err)- }- if _, ok := r.cache.Load(cacheKey(mk("sk-1"))); !ok {- t.Errorf("touched sk-1 should survive LRU eviction")- }- if _, ok := r.cache.Load(cacheKey(mk("sk-2"))); ok {- t.Errorf("sk-2 should be evicted (was oldest after touch)")- }- if _, ok := r.cache.Load(cacheKey(mk("sk-3"))); !ok {- t.Errorf("sk-3 should survive (newly inserted)")- }-}--func TestStagehandRuntime_Cache_LRUCapZero_Unlimited(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0 /*unlimited*/, time.Minute)- t.Cleanup(func() { _ = r.Close() })-- for i := 0; i < 100; i++ {- _, _ = r.clientFor(RunTaskRequest{- ModelName: "openai/gpt-4o",- APIKey: "sk-" + itoa(i),- })- }- if got := cacheSize(r); got != 100 {- t.Errorf("cap=0 should mean unlimited; cache size = %d, want 100", got)- }-}--// itoa is a tiny helper to avoid pulling in strconv just for these tests.-func itoa(i int) string {- if i == 0 {- return "0"- }- var b []byte- for i > 0 {- b = append([]byte{byte('0' + i%10)}, b...)- i /= 10- }- return string(b)-}--// ----------------------------------------------------------------------------// Close-// -----------------------------------------------------------------------------func TestStagehandRuntime_Close_DrainsSweeperAndClosesAllEntries(t *testing.T) {- r := newStagehandRuntime(50*time.Millisecond, 0, 10*time.Millisecond)- for i := 0; i < 5; i++ {- _, _ = r.clientFor(RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: "sk-" + itoa(i)})- }- if got := cacheSize(r); got != 5 {- t.Fatalf("precondition: cache size = %d, want 5", got)- }-- done := make(chan struct{})- go func() {- _ = r.Close()- close(done)- }()- select {- case <-done:- // good- case <-time.After(2 * time.Second):- t.Fatal("Close did not return within 2s (sweeper did not drain)")- }-- if got := cacheSize(r); got != 0 {- t.Errorf("after Close: cache size = %d, want 0", got)- }-- // Calling Close again is a safe no-op.- if err := r.Close(); err != nil {- t.Errorf("second Close: got %v, want nil", err)- }-}--func TestStagehandRuntime_Close_TTLZero_NoSweeper(t *testing.T) {- // ttl=0 disables the sweeper entirely; sweepDone must be- // pre-closed so Close() doesn't block.- r := newStagehandRuntime(0, 0, time.Second)- _, _ = r.clientFor(RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: "sk-z"})- done := make(chan struct{})- go func() {- _ = r.Close()- close(done)- }()- select {- case <-done:- case <-time.After(time.Second):- t.Fatal("Close hung with ttl=0 (sweeper not pre-closed)")- }-}--type countedStagehandOption struct {- option.RequestOption- closes atomic.Int32-}--func (o *countedStagehandOption) Close() error {- o.closes.Add(1)- return nil-}--func TestStagehandRuntime_EvictionWaitsForSessionEnd(t *testing.T) {- for _, operation := range []string{"task", "extract"} {- for _, eviction := range []string{"ttl", "lru", "close"} {- t.Run(operation+"/"+eviction, func(t *testing.T) {- endStarted := make(chan struct{})- finishEnd := make(chan struct{})- releaseEnd := sync.OnceFunc(func() { close(finishEnd) })- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {- w.Header().Set("Content-Type", "application/json")- switch {- case strings.HasSuffix(req.URL.Path, "/start"):- _, _ = fmt.Fprint(w, `{"success":true,"data":{"sessionId":"s"}}`)- case strings.HasSuffix(req.URL.Path, "/end"):- close(endStarted)- <-finishEnd- _, _ = fmt.Fprint(w, `{"success":true}`)- case strings.HasSuffix(req.URL.Path, "/agentExecute"):- _, _ = fmt.Fprint(w, `{"success":true,"data":{"result":{"success":true,"message":"ok"}}}`)- case strings.HasSuffix(req.URL.Path, "/extract"):- _, _ = fmt.Fprint(w, `{"success":true,"data":{"result":"ok"}}`)- default:- http.Error(w, "unexpected path: "+req.URL.Path, http.StatusNotFound)- }- }))- defer server.Close()- defer releaseEnd()-- r := newStagehandRuntime(time.Hour, 1, time.Minute)- defer r.Close()- req := RunTaskRequest{Instruction: "do it", ModelName: "openai/gpt-4o", APIKey: "key"}- counted := &countedStagehandOption{RequestOption: option.WithBaseURL(server.URL)}- entry := &stagehandClientEntry{- client: stagehand.NewClient(counted, option.WithMaxRetries(0)),- }- entry.lastUsedAt.Store(time.Now().UnixNano())- r.cache.Store(cacheKey(req), entry)- done := make(chan error, 1)- go func() {- if operation == "task" {- _, err := r.RunTask(t.Context(), req)- done <- err- } else {- _, err := r.RunExtract(t.Context(), RunExtractRequest{- Instruction: req.Instruction, ModelName: req.ModelName, APIKey: req.APIKey,- Schema: map[string]any{"type": "string"},- })- done <- err- }- }()- select {- case <-endStarted:- case err := <-done:- t.Fatalf("operation completed before End: %v", err)- case <-time.After(3 * time.Second):- t.Fatal("Sessions.End did not start")- }- if eviction == "ttl" {- entry.lastUsedAt.Store(time.Now().Add(-2 * time.Hour).UnixNano())- r.evictExpired()- } else if eviction == "lru" {- _, _ = r.clientFor(RunTaskRequest{ModelName: req.ModelName, APIKey: "other"})- } else {- _ = r.Close()- }- if _, ok := r.cache.Load(cacheKey(req)); ok {- t.Fatal("entry was not evicted")- }- if got := counted.closes.Load(); got != 0 {- t.Fatalf("client closed before Sessions.End completed: %d", got)- }- releaseEnd()- select {- case err := <-done:- if err != nil {- t.Fatalf("operation: %v", err)- }- case <-time.After(3 * time.Second):- t.Fatal("operation did not finish")- }- r.Close()- if got := counted.closes.Load(); got != 1 {- t.Fatalf("client Close calls = %d, want 1", got)- }- })- }- }-}--func TestStagehandRuntime_RetiredClientWaitsForLastLease(t *testing.T) {- r := newStagehandRuntime(time.Hour, 0, time.Minute)- defer r.Close()- req := RunTaskRequest{ModelName: "openai/gpt-4o", APIKey: "key"}- counted := &countedStagehandOption{RequestOption: option.WithBaseURL("http://unused.test")}- entry := &stagehandClientEntry{client: stagehand.NewClient(counted)}- r.cache.Store(cacheKey(req), entry)-- _, releaseFirst, err := r.leaseClient(req)- if err != nil {- t.Fatal(err)- }- _, releaseLast, err := r.leaseClient(req)- if err != nil {- t.Fatal(err)- }- entry.lastUsedAt.Store(time.Now().Add(-2 * time.Hour).UnixNano())- r.evictExpired()- _, releaseNew, err := r.leaseClient(req)- if err != nil {- t.Fatal(err)- }- releaseNew()- if v, _ := r.cache.Load(cacheKey(req)); v == entry {- t.Fatal("new acquisition reused a retired entry")- }- releaseFirst()- if got := counted.closes.Load(); got != 0 {- t.Fatalf("client closed with a remaining lease: %d", got)- }- var wg sync.WaitGroup- wg.Go(releaseLast)- for range 8 {- wg.Go(func() { _ = r.Close() })- }- wg.Wait()- if got := counted.closes.Load(); got != 1 {- t.Fatalf("Close calls = %d, want 1", got)- }- if _, _, err := r.leaseClient(req); err == nil {- t.Fatal("acquisition succeeded after runtime Close")- }-}--// ----------------------------------------------------------------------------// Env-driven config-// -----------------------------------------------------------------------------func TestStagehandRuntime_EnvConfig_Defaults(t *testing.T) {- // Clear env so we get the library defaults.- t.Setenv("STAGEHAND_CACHE_TTL", "")- t.Setenv("STAGEHAND_CACHE_CAP", "")- t.Setenv("STAGEHAND_CACHE_SWEEP", "")- r := newStagehandRuntimeFromEnv()- t.Cleanup(func() { _ = r.Close() })- if r.ttl != defaultStagehandCacheTTL {- t.Errorf("default ttl: got %v, want %v", r.ttl, defaultStagehandCacheTTL)- }- if r.cap != defaultStagehandCacheCap {- t.Errorf("default cap: got %d, want %d", r.cap, defaultStagehandCacheCap)- }-}--func TestStagehandRuntime_EnvConfig_Overrides(t *testing.T) {- t.Setenv("STAGEHAND_CACHE_TTL", "5m")- t.Setenv("STAGEHAND_CACHE_CAP", "8")- r := newStagehandRuntimeFromEnv()- t.Cleanup(func() { _ = r.Close() })- if r.ttl != 5*time.Minute {- t.Errorf("override ttl: got %v, want 5m", r.ttl)- }- if r.cap != 8 {- t.Errorf("override cap: got %d, want 8", r.cap)- }-}--func TestStagehandRuntime_EnvConfig_InvalidFallsBack(t *testing.T) {- t.Setenv("STAGEHAND_CACHE_TTL", "not-a-duration")- t.Setenv("STAGEHAND_CACHE_CAP", "not-a-number")- r := newStagehandRuntimeFromEnv()- t.Cleanup(func() { _ = r.Close() })- if r.ttl != defaultStagehandCacheTTL {- t.Errorf("invalid ttl env should fall back to default: got %v, want %v",- r.ttl, defaultStagehandCacheTTL)- }- if r.cap != defaultStagehandCacheCap {- t.Errorf("invalid cap env should fall back to default: got %d, want %d",- r.cap, defaultStagehandCacheCap)- }-}--// ----------------------------------------------------------------------------// SetDefaultStagehandInvoker (unchanged)-// -----------------------------------------------------------------------------func TestStagehandRuntime_SetDefaultStagehandInvoker(t *testing.T) {- prev := DefaultRuntime- t.Cleanup(func() { SetDefaultStagehandInvoker(prev) })-- called := false- mock := StagehandInvokerFunc(func(_ context.Context, _ RunTaskRequest) (string, error) {- called = true- return "ok", nil- })- var invoker StagehandInvoker = mock- SetDefaultStagehandInvoker(invoker)- got := getDefaultStagehandInvoker()- if got == nil {- t.Fatal("getDefaultStagehandInvoker returned nil after swap")- }- ctx := t.Context()- out, err := got.RunTask(ctx, RunTaskRequest{Instruction: "x", ModelName: "m", APIKey: "k"})- if err != nil {- t.Fatalf("RunTask: %v", err)- }- if out != "ok" || !called {- t.Errorf("mock not invoked: out=%q, called=%v", out, called)- }-}--// StagehandInvokerFunc is an adapter for the StagehandInvoker-// interface, useful in tests.-type StagehandInvokerFunc func(ctx context.Context, req RunTaskRequest) (string, error)--func (f StagehandInvokerFunc) RunTask(ctx context.Context, req RunTaskRequest) (string, error) {- return f(ctx, req)-}--func (f StagehandInvokerFunc) RunExtract(_ context.Context, _ RunExtractRequest) (string, error) {- return "", errors.New("RunExtract not implemented in StagehandInvokerFunc adapter")-}diff --git a/internal/common/environments.go b/internal/common/environments.goindex d6323efc67..c7308fed95 100644--- a/internal/common/environments.go+++ b/internal/common/environments.go@@ -115,10 +115,6 @@ const (EnvDBType = "DB_TYPE"EnvDevice = "DEVICE"EnvStorageImpl = "STORAGE_IMPL"- EnvStageHandCacheCap = "STAGEHAND_CACHE_CAP"- EnvStageHandCacheTTLSeconds = "STAGEHAND_CACHE_TTL_SECONDS"- EnvStageHandCacheSweepInterval = "STAGEHAND_CACHE_SWEEP_INTERVAL"- EnvStageHandExtractResultFile = "STAGEHAND_EXTRACT_RESULT_FILE"EnvAgentRunAccessKeyID = "AGENTRUN_ACCESS_KEY_ID"EnvAgentRunAccessKeySecret = "AGENTRUN_ACCESS_KEY_SECRET"EnvAgentRunAccountID = "AGENTRUN_ACCOUNT_ID"@@ -169,7 +165,6 @@ const (EnvOpenAIBaseURL = "OPENAI_BASE_URL"EnvOpenAIModel = "OPENAI_MODEL"EnvLLMDebug = "LLM_DEBUG"- EnvStageHandExtractSchemaJSON = "STAGEHAND_EXTRACT_SCHEMA_JSON"EnvSandboxProviderType = "SANDBOX_PROVIDER_TYPE"EnvSandboxExecutorManagerURL = "SANDBOX_EXECUTOR_MANAGER_URL"EnvSandboxExecutorManagerTimeout = "SANDBOX_EXECUTOR_MANAGER_TIMEOUT"diff --git a/internal/development.md b/internal/development.mdindex ca98f0c913..808182e422 100644--- a/internal/development.md+++ b/internal/development.md@@ -72,7 +72,7 @@ uv run tools/scripts/download_dev_deps.py # local-dev one-stop: native .a + clInstall `uv` before running the downloaders; it installs each script's declared Python dependencies.-`download_dev_deps.py` is the local-dev one-stop: it provisions the Go native libraries under `~/ragflow-native-libs` AND the `.ort` weights, embedding tokenizer assets, and `cl100k_base.tiktoken` into `internal/rag/res/deepdoc/` and `deps/huggingface.co/`. Run it once and the local environment is ready. The image-facing `deps/download_deps.py` provisions the same runtime resources plus the stagehand driver (installed into the SDK's cache, using the SDK version from `go.mod`) and skips the native `.a`; run it only when building the dependency image or in CI. Native archives are fetched per target platform (linux/darwin on amd64/arm64; override with `RAGFLOW_TARGET_OS` / `RAGFLOW_TARGET_ARCH`).+`download_dev_deps.py` is the local-dev one-stop: it provisions the Go native libraries under `~/ragflow-native-libs` AND the `.ort` weights, embedding tokenizer assets, and `cl100k_base.tiktoken` into `internal/rag/res/deepdoc/` and `deps/huggingface.co/`. Run it once and the local environment is ready. The image-facing `deps/download_deps.py` provisions the same runtime resources and skips the native `.a`; run it only when building the dependency image or in CI. Native archives are fetched per target platform (linux/darwin on amd64/arm64; override with `RAGFLOW_TARGET_OS` / `RAGFLOW_TARGET_ARCH`).Build the Go resource image from `deps/` after preparing these files:@@ -82,7 +82,7 @@ docker build -f Dockerfile -t infiniflow/ragflow_deps:latest .cd ..```-The image contains Go DeepDoc weights, tokenizer assets, the BPE table, and stagehand binaries. DeepDoc weights are prepared under `deps/huggingface.co/InfiniFlow/deepdoc/` for packaging and under `internal/rag/res/deepdoc/` for local use.+The image contains Go DeepDoc weights, tokenizer assets, and the BPE table. DeepDoc weights are prepared under `deps/huggingface.co/InfiniFlow/deepdoc/` for packaging and under `internal/rag/res/deepdoc/` for local use.> **Note**: If you use IDEs like GoLand to run/debug directly (via Run/Debug buttons), or run `go build` / `go run` from command line, set these CGO environment variables:>> ```bashdiff --git a/internal/handler/agent_component_test.go b/internal/handler/agent_component_test.goindex 58ffb220f0..eefd6dc4fb 100644--- a/internal/handler/agent_component_test.go+++ b/internal/handler/agent_component_test.go@@ -159,67 +159,6 @@ func TestGetComponentInputForm_ExeSQLDynamicInputForm(t *testing.T) {}}-func TestGetComponentInputForm_BrowserDynamicInputForm(t *testing.T) {- cv := &entity.UserCanvas{- ID: "c1",- DSL: map[string]any{- "components": map[string]any{- "Browser:FlatWolvesTry": map[string]any{- "obj": map[string]any{- "component_name": "Browser",- "params": map[string]any{- "llm_id": "gpt-4o@OpenAI",- "prompts": "{sys.query}",- },- },- },- },- },- }- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}-- c, w := componentCtx(t, "GET", "/api/v1/agents/c1/components/Browser:FlatWolvesTry/input-form", "")- c.Params = gin.Params{- {Key: "canvas_id", Value: "c1"},- {Key: "component_id", Value: "Browser:FlatWolvesTry"},- }- h.GetComponentInputForm(c)-- if w.Code != 200 {- t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())- }- var env struct {- Code int `json:"code"`- Data map[string]interface{} `json:"data"`- }- if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {- t.Fatalf("decode: %v (body=%s)", err, w.Body.String())- }- if env.Code != 0 {- t.Fatalf("code = %d, want 0; body=%s", env.Code, w.Body.String())- }- prompts, ok := env.Data["prompts"].(map[string]interface{})- if !ok {- t.Fatalf("data.prompts = %v, want a map", env.Data["prompts"])- }- if prompts["name"] != "Prompts" {- t.Errorf("data.prompts.name = %v, want Prompts", prompts["name"])- }- if prompts["type"] != "paragraph" {- t.Errorf("data.prompts.type = %v, want paragraph", prompts["type"])- }- uploadSources, ok := env.Data["upload_sources"].(map[string]interface{})- if !ok {- t.Fatalf("data.upload_sources = %v, want a map", env.Data["upload_sources"])- }- if uploadSources["name"] != "Upload sources" {- t.Errorf("data.upload_sources.name = %v, want Upload sources", uploadSources["name"])- }- if uploadSources["type"] != "line" {- t.Errorf("data.upload_sources.type = %v, want line", uploadSources["type"])- }-}-func TestGetComponentInputForm_CanvasNotFound(t *testing.T) {h := &AgentHandler{loader: &fakeCanvasLoader{err: dao.ErrUserCanvasNotFound}}diff --git a/internal/server/api/server.go b/internal/server/api/server.goindex e102ca68e0..a851b67e41 100644--- a/internal/server/api/server.go+++ b/internal/server/api/server.go@@ -126,9 +126,6 @@ func startServer(ctx context.Context, serverName string, arguments *bootstrap.SemcpService := service.NewMCPService()modelProviderService := service.NewModelProviderService()modelFactory := service.NewModelFactory()- component.SetBrowserModelFactory(func(ctx context.Context, tenantID, modelRef string) (*modelModule.ChatModel, error) {- return modelFactory.NewChatModel(ctx, service.ModelAccess{TenantID: tenantID}, modelRef)- })modelCallService := service.NewModelCallServiceWithProviderService(modelProviderService, modelFactory)// Wire the real MemorySaver so the Message component can persistdiff --git a/tools/scripts/download_dev_deps.py b/tools/scripts/download_dev_deps.pyindex 2781bae7c4..35f4557956 100755--- a/tools/scripts/download_dev_deps.py+++ b/tools/scripts/download_dev_deps.py@@ -20,8 +20,7 @@# ready — you do NOT also need download_deps.py for local development.## The image-facing counterpart deps/download_deps.py fetches the same-# runtime resources PLUS the stagehand server binary (used by the Browser-# component) and skips the native `.a` files, because the build stage bakes+# runtime resources and skips the native `.a` files, because the build stage bakes# those into the server binary. Both scripts land the shared runtime resources# at the SAME paths, so running one after the other never re-downloads an# already-present asset.@@ -499,8 +498,7 @@ def _download_ort_archive(archive_path, goos, goarch):# RUN, parse documents and count tokens. Fetched here too so a developer runs# THIS script once and the environment is ready. Landing paths match# deps/download_deps.py, so re-running that image script never-# re-downloads an already-present asset. stagehand is deliberately NOT fetched-# here (Browser component only) — that is download_deps.py's job for images.+# re-downloads an already-present asset.# cl100k BPE table. Hosted on Azure blob storage (NOT a GitHub release), so the@@ -671,11 +669,7 @@ def main():resources (cl100k BPE table, DeepDoc .ort weights, embedding tokenizer assets)the local Go dev server needs to run, parse and count tokens.- This is the local-dev one-stop: one invocation readies the environment. The- Browser component's server binary is intentionally NOT fetched here — that- is the image script's job. Run `uv run deps/download_deps.py` for the- full image resources (it adds that binary and skips the native .a, which the- build stage bakes into the binary)."""+ This is the local-dev one-stop: one invocation readies the environment."""parser = argparse.ArgumentParser(description="Download the native static libraries and runtime resources the local Go dev server needs")parser.add_argument("--china-mirrors", action="store_true", help="Use China-accessible mirrors for downloads")parser.add_argument(@@ -773,8 +767,7 @@ def main():# DeepDoc .ort weights for in-process PDF/table parsing, the embedding# tokenizer assets for token counting) to actually RUN and ingest — not# just link. Fetch them here too so a local developer runs THIS script- # once and the environment is ready. The Browser component's server binary- # is fetched by the image script, not here.+ # once and the environment is ready.print("== cl100k_base.tiktoken ==")download_cl100k()print("== DeepDoc models ==")diff --git a/tools/scripts/test_download_dev_deps.py b/tools/scripts/test_download_dev_deps.pyindex 3cd2a6800f..9d635f22be 100644--- a/tools/scripts/test_download_dev_deps.py+++ b/tools/scripts/test_download_dev_deps.py@@ -311,8 +311,7 @@ def test_native_archive_rejects_unsafe_members(tmp_path, kind):# ── Local-dev one-stop: the dev downloader must also fetch the runtime# resources (cl100k / DeepDoc .ort / tokenizer assets) so a developer runs THIS-# script ONCE and the Go server is ready to build, run, parse and count — but it-# must NOT fetch stagehand (that is the image script's job). ──────────────────+# script ONCE and the Go server is ready to build, run, parse and count. ─────@pytest.fixture@@ -468,14 +467,6 @@ def test_load_tokenizer_assets_rejects_malformed_repo():native.load_tokenizer_assets([("nobadrepo", "f.bin", "runtime")])-def test_native_script_does_not_fetch_stagehand():- # Partition contract: the local-dev one-stop must not pull the Browser- # component's stagehand binary — that is download_deps.py's job for images.- assert not hasattr(native, "stagehand_url")- assert not hasattr(native, "_install_stagehand")- assert "stagehand" not in native.main.__doc__.lower()--# ── Image script (download_deps.py) must stay runtime-resources only: it must# NOT handle the native .a archives (the build stage bakes those into the# binary). Imported by path inside the test so the import lives next to thediff --git a/web/src/components/operator-icon.tsx b/web/src/components/operator-icon.tsxindex 98245ae5dc..51877bece2 100644--- a/web/src/components/operator-icon.tsx+++ b/web/src/components/operator-icon.tsx@@ -23,7 +23,6 @@ import {Columns3Cog,FileCode,FileText,- Globe,HousePlus,Infinity as InfinityIcon,LogOut,@@ -91,7 +90,6 @@ export const LucideIconMap = {[Operator.Loop]: InfinityIcon,[Operator.ExitLoop]: LogOut,[Operator.DocGenerator]: FileText,- [Operator.Browser]: Globe,[Operator.Compiler]: Columns3Cog,[Operator.File]: LucideFile,[Operator.Parser]: LucideFilePlay,diff --git a/web/src/constants/agent.tsx b/web/src/constants/agent.tsxindex 235df89365..addfeb7616 100644--- a/web/src/constants/agent.tsx+++ b/web/src/constants/agent.tsx@@ -123,7 +123,6 @@ export enum Operator {Search1APISearch = 'Search1APISearch',Search1APICrawl = 'Search1APICrawl',DocGenerator = 'DocGenerator',- Browser = 'Browser',Placeholder = 'Placeholder',DataOperations = 'DataOperations',ListOperations = 'ListOperations',diff --git a/web/src/locales/az.ts b/web/src/locales/az.tsindex feec577255..c92497acb8 100644--- a/web/src/locales/az.ts+++ b/web/src/locales/az.ts@@ -2817,20 +2817,6 @@ Nümunə: Virtual host üslubu`,toolTimeout: 'Alət üçün vaxt limiti',toolTimeoutTip:'Tək alət çağırışı üçün saniyə ilə vaxt limiti (MCP alətləri daxil olmaqla). Uzun müddət işləyən alətlər üçün bu dəyəri artırın.',- maxSteps: 'Maksimum addım sayı',- headless: 'Qrafik interfeyssiz',- enableDefaultExtensions: 'Standart genişlənmələri aktivləşdir',- enableDefaultExtensionsTip:- 'browser-use-un standart genişlənmələrini (uBlock, kukilərin idarə olunması, ClearURLs) aktivləşdirir. İcra zamanı genişlənmələrin endirilməməsi üçün bunu söndürün.',- chromiumSandbox: 'Chromium-un təcrid mühiti',- chromiumSandboxTip:- 'Chromium-un təcrid mühitinin aktivləşdirilib-aktivləşdirilməyəcəyini müəyyən edir. Docker-in root mühitlərində bu, adətən söndürülür; adi kompüterlərdə aktivləşdirilməsi tövsiyə olunur.',- persistSession: 'Sessiyanı saxla',- persistSessionTip:- 'Aktivləşdirildikdə bu brauzer düyünü təkrar girişlərin qarşısını almaq üçün öz brauzer sessiyasından yenidən istifadə edir.',- uploadSources: 'Mənbələri yüklə',- uploadSourcesTip:- 'Fayl ID-lərini, fayl URL-lərini və ya dəyişənləri dəstəkləyir. Bir neçə dəyəri vergüllə ayıra və ya JSON massivi formatından istifadə edə bilərsiniz (məsələn, ["id1","https://example.com/a.pdf"]).',advancedSettings: 'Genişləndirilmiş parametrlər',addTools: 'Alətlər əlavə et',sysPromptDefaultValue: `@@ -2976,9 +2962,6 @@ Nümunə: Virtual host üslubu`,sofyaApiKeyTip: 'Tələb olunur. sofya.co saytında API açarı yaradın.',docGenerator: 'Sənəd yaradıcısı',docGeneratorDescription: 'Markdown məzmunundan fayl yaradın.',- browser: 'Brauzer',- browserDescription:- 'Brauzer tapşırıqlarını avtomatlaşdırın. Model konfiqurasiyasını və təlimatla idarə olunan əməliyyatları dəstəkləyir. Yükləmə mənbələri fayl ID-lərini və URL-ləri dəstəkləyir, endirilmiş fayllar isə hədəf qovluqda saxlanıla bilər.',subtitle: 'Alt başlıq',logoImage: 'Loqo şəkli',logoPosition: 'Loqonun mövqeyi',diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex a068e95518..97ee52f08f 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -2845,20 +2845,6 @@ Best for: Documents with flowing, contextually connected content — such as bootoolTimeout: 'Tool timeout',toolTimeoutTip:'Timeout in seconds for a single tool call (including MCP tools). Increase it for long-running tools.',- maxSteps: 'Max steps',- headless: 'Headless',- enableDefaultExtensions: 'Enable default extensions',- enableDefaultExtensionsTip:- 'Enable browser-use default extensions (uBlock, cookie handling, ClearURLs). Disable this to avoid runtime extension downloads.',- chromiumSandbox: 'Chromium sandbox',- chromiumSandboxTip:- 'Whether to enable Chromium sandbox. In Docker root environments this is usually disabled; on regular hosts it is recommended to enable.',- persistSession: 'Persist session',- persistSessionTip:- 'When enabled, this Browser node reuses its browser session to avoid repeated logins.',- uploadSources: 'Upload sources',- uploadSourcesTip:- 'Supports file IDs, file URLs, or variables. You can separate multiple values with commas or use a JSON array format (for example ["id1","https://example.com/a.pdf"]).',advancedSettings: 'Advanced settings',addTools: 'Add tools',sysPromptDefaultValue: `@@ -3009,9 +2995,6 @@ Best for: Documents with flowing, contextually connected content — such as boo'The absolute HTTP or HTTPS URL of the page to read. As an agent tool, the agent supplies the URL.',docGenerator: 'Doc Generator',docGeneratorDescription: `Generate a file from Markdown content.`,- browser: 'Browser',- browserDescription:- 'Automate browser tasks. Supports model configuration and prompt-driven actions. Upload sources support file IDs and URLs, and downloaded files can be saved to a target folder.',subtitle: 'Subtitle',logoImage: 'Logo Image',logoPosition: 'Logo Position',diff --git a/web/src/locales/fr.ts b/web/src/locales/fr.tsindex 94d86a0c22..5e8a022cc2 100644--- a/web/src/locales/fr.ts+++ b/web/src/locales/fr.ts@@ -2576,20 +2576,6 @@ Idéal pour : les documents avec un contenu fluide et contextuellement lié —maxRounds: 'Nombre maximum de cycles de réflexion',delayAfterError: 'Délai après une erreur',maxRetries: 'Nombre maximum de tentatives',- maxSteps: "Nombre maximum d'étapes",- headless: 'Mode sans interface',- enableDefaultExtensions: 'Activer les extensions par défaut',- enableDefaultExtensionsTip:- "Active les extensions par défaut de browser-use (uBlock, gestion des cookies, ClearURLs). Désactivez cette option pour éviter les téléchargements d'extensions au moment de l'exécution.",- chromiumSandbox: 'Bac à sable Chromium',- chromiumSandboxTip:- "Indique si le bac à sable Chromium doit être activé. Dans les environnements Docker root, il est généralement désactivé ; sur les hôtes normaux, il est recommandé de l'activer.",- persistSession: 'Conserver la session',- persistSessionTip:- 'Lorsque cette option est activée, ce nœud Browser réutilise sa session de navigateur pour éviter les connexions répétées.',- uploadSources: 'Sources de téléversement',- uploadSourcesTip:- 'Prend en charge les IDs de fichiers, les URLs de fichiers ou des variables. Vous pouvez séparer plusieurs valeurs par des virgules ou utiliser un tableau JSON (par exemple ["id1","https://example.com/a.pdf"]).',advancedSettings: 'Paramètres avancés',addTools: 'Ajouter des outils',sysPromptDefaultValue: `@@ -2924,9 +2910,6 @@ Les informations structurées importantes peuvent inclure : noms, dates, lieux,variableAggregatorDescription: `Ce processus agrège des variables de plusieurs branches en une seule variable pour obtenir une configuration unifiée pour les nœuds en aval.`,userFillUpDescription: `Met en pause le workflow et attend le message de l'utilisateur avant de continuer.`,- browser: 'Navigateur',- browserDescription:- 'Automatise les tâches de navigation. Prend en charge la configuration du modèle et les actions pilotées par invite. Les sources de téléversement acceptent les IDs de fichiers et les URLs, et les fichiers téléchargés peuvent être enregistrés dans un dossier cible.',channel: 'Canal',channelTip:"Effectuer une recherche textuelle ou une recherche d'actualités sur l'entrée du composant",diff --git a/web/src/locales/it.ts b/web/src/locales/it.tsindex 5e1444ae37..247d48e8d4 100644--- a/web/src/locales/it.ts+++ b/web/src/locales/it.ts@@ -1948,20 +1948,6 @@ Ideale per: documenti con contenuto fluente e contestualmente connesso — comemaxRounds: 'Round massimi di riflessione',delayAfterError: 'Ritardo dopo errore',maxRetries: 'Round massimi di ritentativo',- maxSteps: 'Passi massimi',- headless: 'Headless',- enableDefaultExtensions: 'Abilita estensioni predefinite',- enableDefaultExtensionsTip:- 'Abilita le estensioni predefinite di browser-use (uBlock, gestione cookie, ClearURLs). Disabilita questo per evitare download di estensioni in runtime.',- chromiumSandbox: 'Sandbox Chromium',- chromiumSandboxTip:- 'Se abilitare la sandbox Chromium. Negli ambienti Docker root questo è solitamente disabilitato; su host normali è consigliato abilitarlo.',- persistSession: 'Mantieni sessione',- persistSessionTip:- 'Quando abilitato, questo nodo Browser riutilizza la sua sessione del browser per evitare accessi ripetuti.',- uploadSources: 'Carica sorgenti',- uploadSourcesTip:- 'Supporta ID di file, URL di file o variabili. Puoi separare più valori con virgole o usare un formato array JSON (ad esempio ["id1","https://example.com/a.pdf"]).',advancedSettings: 'Impostazioni avanzate',addTools: 'Aggiungi strumenti',sysPromptDefaultValue: `@@ -2065,9 +2051,6 @@ Ideale per: documenti con contenuto fluente e contestualmente connesso — come"Un componente che cerca tramite l'URL dell'istanza SearXNG fornita. Specifica TopN e l'URL dell'istanza.",docGenerator: 'Generatore Documenti',docGeneratorDescription: `Genera un file da contenuto Markdown.`,- browser: 'Browser',- browserDescription:- 'Automatizza attività del browser. Supporta la configurazione del modello e azioni guidate da prompt. Le sorgenti di caricamento supportano ID di file e URL, e i file scaricati possono essere salvati in una cartella di destinazione.',subtitle: 'Sottotitolo',logoImage: 'Immagine Logo',logoPosition: 'Posizione Logo',diff --git a/web/src/locales/ja.ts b/web/src/locales/ja.tsindex 52867a2e1b..a4b0640708 100644--- a/web/src/locales/ja.ts+++ b/web/src/locales/ja.ts@@ -2506,20 +2506,6 @@ export default {maxRounds: '最大リフレクション回数',delayAfterError: 'エラー後の遅延',maxRetries: '最大リトライ回数',- maxSteps: '最大ステップ数',- headless: 'ヘッドレス',- enableDefaultExtensions: 'デフォルト拡張機能を有効化',- enableDefaultExtensionsTip:- 'browser-useのデフォルト拡張機能(uBlock、Cookie処理、ClearURLs)を有効にします。実行時の拡張機能ダウンロードを避けたい場合は無効にしてください。',- chromiumSandbox: 'Chromiumサンドボックス',- chromiumSandboxTip:- 'Chromiumサンドボックスを有効にするかどうかです。Dockerのroot環境では通常無効化されており、通常のホストでは有効化することを推奨します。',- persistSession: 'セッションを永続化',- persistSessionTip:- '有効にすると、このBrowserノードはブラウザセッションを再利用し、ログインの繰り返しを回避します。',- uploadSources: 'アップロードソース',- uploadSourcesTip:- 'ファイルID、ファイルURL、または変数に対応しています。複数の値はカンマで区切るか、JSON配列形式(例: ["id1","https://example.com/a.pdf"])で指定できます。',advancedSettings: '詳細設定',addTools: 'ツールを追加',sysPromptDefaultValue:@@ -2555,9 +2541,6 @@ export default {keenableSite: 'サイト',keenableApiKeyTip:'任意項目です。キー不要の無料プランを使用する場合は空欄のままにしてください。',- browser: 'ブラウザ',- browserDescription:- 'ブラウザ操作を自動化します。モデル設定とプロンプト駆動のアクションに対応しています。アップロードソースはファイルIDとURLに対応しており、ダウンロードしたファイルは指定フォルダに保存できます。',channel: 'チャンネル',channelTip:'コンポーネントの入力に対してテキスト検索またはニュース検索を実行します',diff --git a/web/src/locales/ko.ts b/web/src/locales/ko.tsindex 2ba38b8174..30d75dc2bd 100644--- a/web/src/locales/ko.ts+++ b/web/src/locales/ko.ts@@ -1950,20 +1950,6 @@ export default {maxRounds: '최대 반성 횟수',delayAfterError: '오류 후 지연',maxRetries: '최대 재시도 횟수',- maxSteps: '최대 단계 수',- headless: '헤드리스',- enableDefaultExtensions: '기본 확장 기능 활성화',- enableDefaultExtensionsTip:- 'browser-use 기본 확장 기능(uBlock, 쿠키 처리, ClearURLs)을 활성화합니다. 런타임 확장 다운로드를 피하려면 비활성화하세요.',- chromiumSandbox: 'Chromium 샌드박스',- chromiumSandboxTip:- 'Chromium 샌드박스 활성화 여부입니다. Docker root 환경에서는 일반적으로 비활성화되며, 일반 호스트에서는 활성화를 권장합니다.',- persistSession: '세션 유지',- persistSessionTip:- '활성화하면 이 Browser 노드가 브라우저 세션을 재사용하여 반복 로그인을 방지합니다.',- uploadSources: '업로드 소스',- uploadSourcesTip:- '파일 ID, 파일 URL 또는 변수를 지원합니다. 쉼표로 여러 값을 구분하거나 JSON 배열 형식(예: ["id1","https://example.com/a.pdf"])을 사용할 수 있습니다.',advancedSettings: '고급 설정',addTools: '도구 추가',sysPromptDefaultValue: `@@ -2067,9 +2053,6 @@ export default {'제공된 SearXNG 인스턴스 URL을 통해 검색하는 구성 요소입니다. TopN과 인스턴스 URL을 지정하세요.',docGenerator: 'Doc Generator',docGeneratorDescription: `Markdown 내용에서 파일을 생성합니다.`,- browser: '브라우저',- browserDescription:- '브라우저 작업을 자동화합니다. 모델 설정 및 프롬프트 기반 작업을 지원합니다. 업로드 소스는 파일 ID와 URL을 지원하며, 다운로드된 파일은 대상 폴더에 저장할 수 있습니다.',subtitle: '자막',logoImage: '로고 이미지',logoPosition: '로고 위치',diff --git a/web/src/locales/tr.ts b/web/src/locales/tr.tsindex 4710a353fd..c6a7839998 100644--- a/web/src/locales/tr.ts+++ b/web/src/locales/tr.ts@@ -2819,20 +2819,6 @@ En uygun olduğu durumlar: Anlatı bütünlüğünün bitişik paragrafları birtoolTimeout: 'Araç zaman aşımı',toolTimeoutTip:'Tek bir araç çağrısı (MCP araçları dahil) için saniye cinsinden zaman aşımı. Uzun süren araçlar için artırın.',- maxSteps: 'Maksimum adım',- headless: 'Başsız',- enableDefaultExtensions: 'Varsayılan uzantıları etkinleştir',- enableDefaultExtensionsTip:- 'browser-use varsayılan uzantılarını (uBlock, çerez işleme, ClearURLs) etkinleştirir. Çalışma anında uzantı indirmelerinden kaçınmak için devre dışı bırakın.',- chromiumSandbox: 'Chromium korumalı alanı',- chromiumSandboxTip:- 'Chromium korumalı alanının etkinleştirilip etkinleştirilmeyeceği. Docker root ortamlarında genellikle devre dışı bırakılır; normal ana bilgisayarlarda etkinleştirilmesi önerilir.',- persistSession: 'Oturumu koru',- persistSessionTip:- 'Etkinleştirildiğinde bu Tarayıcı düğümü, yinelenen oturum açmalardan kaçınmak için tarayıcı oturumunu yeniden kullanır.',- uploadSources: 'Kaynakları yükle',- uploadSourcesTip:- 'Dosya kimliklerini, dosya URL\'lerini veya değişkenleri destekler. Birden fazla değeri virgülle ayırabilir ya da JSON dizisi biçimi kullanabilirsiniz (örneğin ["id1","https://example.com/a.pdf"]).',advancedSettings: 'Gelişmiş ayarlar',addTools: 'Araç ekle',sysPromptDefaultValue: `@@ -2990,9 +2976,6 @@ En uygun olduğu durumlar: Anlatı bütünlüğünün bitişik paragrafları bir"Okunacak sayfanın mutlak HTTP veya HTTPS URL'si. Ajan aracı olarak kullanıldığında URL'yi ajan sağlar.",docGenerator: 'Belge Oluşturucu',docGeneratorDescription: `Markdown içeriğinden bir dosya oluşturur.`,- browser: 'Tarayıcı',- browserDescription:- "Tarayıcı görevlerini otomatikleştirir. Model yapılandırmasını ve istem güdümlü eylemleri destekler. Yüklenen kaynaklar dosya kimliklerini ve URL'leri destekler, indirilen dosyalar bir hedef klasöre kaydedilebilir.",subtitle: 'Alt başlık',logoImage: 'Logo Görüntüsü',logoPosition: 'Logo Konumu',diff --git a/web/src/locales/uz.ts b/web/src/locales/uz.tsindex d1e5770e19..13fd9dd5bf 100644--- a/web/src/locales/uz.ts+++ b/web/src/locales/uz.ts@@ -2719,20 +2719,6 @@ export default {toolTimeout: 'Vosita timeouti',toolTimeoutTip:'Bitta vosita chaqiruvi (MCP vositalari ham) uchun soniyadagi timeout. Uzoq ishlaydigan vositalar uchun oshiring.',- maxSteps: 'Maksimal qadamlar',- headless: 'Headless',- enableDefaultExtensions: 'Standart kengaytmalarni yoqish',- enableDefaultExtensionsTip:- 'browser-use standart kengaytmalarini (uBlock, cookie ishlov berish, ClearURLs) yoqing. Ish vaqti kengaytma yuklanishlaridan qochish uchun o‘chiring.',- chromiumSandbox: 'Chromium sandbox',- chromiumSandboxTip:- 'Chromium sandbox yoqilsinmi. Docker root muhitlarida odatda o‘chiriladi; oddiy hostlarda yoqish tavsiya etiladi.',- persistSession: 'Sessiyani saqlash',- persistSessionTip:- 'Yoqilganda, bu Brauzer tuguni takroriy kirishlardan qochish uchun brauzer sessiyasini qayta ishlatadi.',- uploadSources: 'Manbalarni yuklash',- uploadSourcesTip:- 'Fayl ID’lari, fayl URL’lari yoki o‘zgaruvchilar qo‘llab-quvvatlanadi. Bir nechta qiymatni vergul bilan ajratishingiz yoki JSON massiv formatidan foydalanishingiz mumkin (masalan ["id1","https://example.com/a.pdf"]).',advancedSettings: 'Qo‘shimcha sozlamalar',addTools: 'Vositalar qo‘shish',sysPromptDefaultValue:@@ -2868,9 +2854,6 @@ export default {sofyaApiKeyTip: 'Talab qilinadi. sofya.co’da API Key yarating.',docGenerator: 'Doc Generator',docGeneratorDescription: 'Markdown kontentidan fayl generatsiya qilish.',- browser: 'Brauzer',- browserDescription:- 'Brauzer vazifalarini avtomatlashtiring. Model sozlamasi va prompt asosidagi amallar qo‘llab-quvvatlanadi. Yuklash manbalari fayl ID’lari va URL’larni qo‘llaydi, yuklab olingan fayllar maqsadli papkaga saqlanishi mumkin.',subtitle: 'Subtitr',logoImage: 'Logo rasmi',logoPosition: 'Logo joylashuvi',diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex 51c88e4b06..ac6c0a3341 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -2424,20 +2424,6 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 RtoolTimeout: '工具调用超时',toolTimeoutTip:'单次工具调用(含 MCP 工具)的超时秒数。长时间运行的工具请调大该值。',- maxSteps: '最大步数',- headless: '无头模式',- enableDefaultExtensions: '启用默认扩展',- enableDefaultExtensionsTip:- '启用 browser-use 默认扩展(uBlock、Cookie 处理、ClearURLs)。关闭后可避免运行时下载扩展。',- chromiumSandbox: 'Chromium 沙箱',- chromiumSandboxTip:- '是否启用 Chromium 沙箱。Docker root 环境通常需要关闭,普通宿主机环境建议开启。',- persistSession: '持久化登录态',- persistSessionTip:- '开启后将复用该 Browser 节点的浏览器会话,避免重复登录。',- uploadSources: '上传来源',- uploadSourcesTip:- '支持文件 ID、文件 URL 或变量。可用逗号分隔多个值,也支持 JSON 数组格式(如 ["id1","https://example.com/a.pdf"])。',advancedSettings: '高级设置',addTools: '添加工具',sysPromptDefultValue: `@@ -2607,9 +2593,6 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R'要读取页面的完整 HTTP 或 HTTPS 地址。作为智能体工具时,由智能体提供地址。',docGenerator: '文档生成器',docGeneratorDescription: `从 Markdown 内容生成文件。`,- browser: 'Browser',- browserDescription:- '使用 Browser 自动执行浏览器任务。支持模型与提示词配置,上传来源支持文件 ID 与 URL,并可将下载文件保存到指定目录。',subtitle: '副标题',logoImage: '标志图片',logoPosition: '标志位置',diff --git a/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx b/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsxindex f1f5f4c299..c5598cfd9d 100644--- a/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx+++ b/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx@@ -94,7 +94,6 @@ export function AccordionOperators({Operator.Search1APISearch,Operator.Search1APICrawl,Operator.DocGenerator,- Operator.Browser,]);return (diff --git a/web/src/pages/agent/constant/index.tsx b/web/src/pages/agent/constant/index.tsxindex 11fcf93e4e..59ca2c7d18 100644--- a/web/src/pages/agent/constant/index.tsx+++ b/web/src/pages/agent/constant/index.tsx@@ -892,7 +892,6 @@ export const RestrictedUpstreamMap = {[Operator.LoopStart]: [Operator.Begin],[Operator.ExitLoop]: [Operator.Begin],[Operator.DocGenerator]: [Operator.Begin],- [Operator.Browser]: [Operator.Begin],};export const NodeMap = {@@ -954,7 +953,6 @@ export const NodeMap = {[Operator.ExitLoop]: 'exitLoopNode',[Operator.ExcelProcessor]: 'ragNode',[Operator.DocGenerator]: 'ragNode',- [Operator.Browser]: 'ragNode',};export enum BeginQueryType {@@ -1195,21 +1193,6 @@ export const initialDocGeneratorValues = {},};-export const initialBrowserValues = {- ...initialLlmBaseValues,- prompts: `{${AgentGlobals.SysQuery}}`,- max_steps: 30,- headless: true,- enable_default_extensions: false,- chromium_sandbox: false,- persist_session: true,- upload_sources: '',- outputs: {- content: { type: 'string', value: '' },- downloaded_files: { type: 'Array<Object>', value: [] },- },-};-export enum WebhookMethod {Post = 'POST',Get = 'GET',diff --git a/web/src/pages/agent/form-sheet/form-config-map.tsx b/web/src/pages/agent/form-sheet/form-config-map.tsxindex 1572518eac..413b0f9e6b 100644--- a/web/src/pages/agent/form-sheet/form-config-map.tsx+++ b/web/src/pages/agent/form-sheet/form-config-map.tsx@@ -4,7 +4,6 @@ import AgentForm from '../form/agent-form';import ArXivForm from '../form/arxiv-form';import BeginForm from '../form/begin-form';import BingForm from '../form/bing-form';-import BrowserForm from '../form/browser-use-form';import CompilationForm from '../form/compilation-form';import CategorizeForm from '../form/categorize-form';import CodeForm from '../form/code-form';@@ -146,9 +145,6 @@ export const FormConfigMap: Partial<Record<Operator, OperatorFormConfig>> = {[Operator.DocGenerator]: {component: DocGeneratorForm,},- [Operator.Browser]: {- component: BrowserForm,- },[Operator.Note]: {component: () => <></>,},diff --git a/web/src/pages/agent/form/browser-use-form/index.tsx b/web/src/pages/agent/form/browser-use-form/index.tsxdeleted file mode 100644index 56d7f242b9..0000000000--- a/web/src/pages/agent/form/browser-use-form/index.tsx+++ /dev/null@@ -1,120 +0,0 @@-import { NextLLMSelect } from '@/components/llm-select/next';-import { RAGFlowFormItem } from '@/components/ragflow-form';-import { Form } from '@/components/ui/form';-import { NumberInput } from '@/components/ui/input';-import { Switch } from '@/components/ui/switch';-import { zodResolver } from '@hookform/resolvers/zod';-import { memo } from 'react';-import { useForm } from 'react-hook-form';-import { useTranslation } from 'react-i18next';-import { z } from 'zod';-import { initialBrowserValues } from '../../constant';-import { useOwnerTenantId } from '../../context';-import { useFormValues } from '../../hooks/use-form-values';-import { useWatchFormChange } from '../../hooks/use-watch-form-change';-import { INextOperatorForm } from '../../interface';-import { FormWrapper } from '../components/form-wrapper';-import { PromptEditor } from '../components/prompt-editor';--const FormSchema = z.object({- llm_id: z.string(),- prompts: z.string(),- max_steps: z.coerce.number().min(1),- headless: z.boolean(),- enable_default_extensions: z.boolean(),- chromium_sandbox: z.boolean(),- persist_session: z.boolean(),- upload_sources: z.string().optional(),-});--type FormSchemaType = z.infer<typeof FormSchema>;--function BrowserForm({ node }: INextOperatorForm) {- const { t } = useTranslation();- const defaultValues = useFormValues(initialBrowserValues, node);- const form = useForm<FormSchemaType>({- defaultValues,- resolver: zodResolver(FormSchema),- mode: 'onChange',- });-- useWatchFormChange(node?.id, form);-- const ownerTenantId = useOwnerTenantId();-- return (- <Form {...form}>- <FormWrapper>- <RAGFlowFormItem label={t('chat.model')} name="llm_id">- <NextLLMSelect ownerTenantId={ownerTenantId}></NextLLMSelect>- </RAGFlowFormItem>- <RAGFlowFormItem label={t('flow.userPrompt')} name="prompts">- <PromptEditor showToolbar={true}></PromptEditor>- </RAGFlowFormItem>- <RAGFlowFormItem label={t('flow.maxSteps')} name="max_steps">- {(field) => <NumberInput min={1} {...field}></NumberInput>}- </RAGFlowFormItem>- <RAGFlowFormItem label={t('flow.headless')} name="headless">- {(field) => (- <Switch- checked={field.value}- onCheckedChange={field.onChange}- ></Switch>- )}- </RAGFlowFormItem>- <RAGFlowFormItem- label={t('flow.enableDefaultExtensions')}- tooltip={t('flow.enableDefaultExtensionsTip')}- name="enable_default_extensions"- >- {(field) => (- <Switch- checked={field.value}- onCheckedChange={field.onChange}- ></Switch>- )}- </RAGFlowFormItem>- <RAGFlowFormItem- label={t('flow.chromiumSandbox')}- tooltip={t('flow.chromiumSandboxTip')}- name="chromium_sandbox"- >- {(field) => (- <Switch- checked={field.value}- onCheckedChange={field.onChange}- ></Switch>- )}- </RAGFlowFormItem>- <RAGFlowFormItem- label={t('flow.persistSession')}- tooltip={t('flow.persistSessionTip')}- name="persist_session"- >- {(field) => (- <Switch- checked={field.value}- onCheckedChange={field.onChange}- ></Switch>- )}- </RAGFlowFormItem>- <RAGFlowFormItem- label={t('flow.uploadSources')}- tooltip={t('flow.uploadSourcesTip')}- name="upload_sources"- >- {(field) => (- <PromptEditor- {...field}- showToolbar- multiLine={false}- placeholder="file_id,https://example.com/a.pdf,{[email protected]}"- ></PromptEditor>- )}- </RAGFlowFormItem>- </FormWrapper>- </Form>- );-}--export default memo(BrowserForm);diff --git a/web/src/pages/agent/hooks/use-add-node.ts b/web/src/pages/agent/hooks/use-add-node.tsindex 387146f57e..7b29793cc7 100644--- a/web/src/pages/agent/hooks/use-add-node.ts+++ b/web/src/pages/agent/hooks/use-add-node.ts@@ -13,7 +13,6 @@ import {initialArXivValues,initialBeginValues,initialBingValues,- initialBrowserValues,initialCategorizeValues,initialCodeValues,initialCompilationValues,@@ -227,7 +226,6 @@ export const useInitializeOperatorParams = () => {[Operator.LoopStart]: {},[Operator.ExitLoop]: {},[Operator.DocGenerator]: initialDocGeneratorValues,- [Operator.Browser]: { ...initialBrowserValues, llm_id: llmId },[Operator.ExcelProcessor]: {},} satisfies Record<Operator, unknown>;}, [defaultModelDictionary, llmId]);diff --git a/web/src/pages/agent/utils/__tests__/dsl-bridge.test.ts b/web/src/pages/agent/utils/__tests__/dsl-bridge.test.tsindex 2d2d32a797..e393a33701 100644--- a/web/src/pages/agent/utils/__tests__/dsl-bridge.test.ts+++ b/web/src/pages/agent/utils/__tests__/dsl-bridge.test.ts@@ -157,10 +157,9 @@ const roundTrip = (bridge: any, input: any): any => {};describe('dsl-bridge round-trip stability', () => {- // Realistic v2 fixture with React-Flow-internal fields. Mirrors- // the structure of internal/agent/dsl/testdata/browser.json- // but inlined here so the test is self-contained.- const v2BrowserLike = {+ // Realistic v2 fixture with React-Flow-internal fields, inlined+ // here so the test is self-contained.+ const v2CrawlerLike = {graph: {nodes: [{@@ -175,13 +174,13 @@ describe('dsl-bridge round-trip stability', () => {measured: { width: 200, height: 81 },},{- id: 'Browser:BusyHatsSink',+ id: 'Crawler:BusyHatsSink',type: 'ragNode',position: { x: 385.29, y: 264.35 },data: {- label: 'Browser',- name: 'Browser_0',- form: { headless: true, max_steps: 30 },+ label: 'Crawler',+ name: 'Crawler_0',+ form: { extract_type: 'markdown', query: 'https://example.com' },},sourcePosition: 'right',targetPosition: 'left',@@ -196,7 +195,7 @@ describe('dsl-bridge round-trip stability', () => {data: {label: 'Message',name: 'Reply_0',- form: { content: ['{Browser:BusyHatsSink@content}'] },+ form: { content: ['{Crawler:BusyHatsSink@content}'] },},sourcePosition: 'right',targetPosition: 'left',@@ -207,16 +206,16 @@ describe('dsl-bridge round-trip stability', () => {],edges: [{- id: 'xy-edge__beginstart-Browser:BusyHatsSinkend',+ id: 'xy-edge__beginstart-Crawler:BusyHatsSinkend',source: 'begin',sourceHandle: 'start',- target: 'Browser:BusyHatsSink',+ target: 'Crawler:BusyHatsSink',targetHandle: 'end',data: { isHovered: false },},{- id: 'xy-edge__Browser:BusyHatsSinkstart-Message:QuietMonkeysLeadend',- source: 'Browser:BusyHatsSink',+ id: 'xy-edge__Crawler:BusyHatsSinkstart-Message:QuietMonkeysLeadend',+ source: 'Crawler:BusyHatsSink',sourceHandle: 'start',target: 'Message:QuietMonkeysLead',targetHandle: 'end',@@ -230,13 +229,13 @@ describe('dsl-bridge round-trip stability', () => {component_name: 'Begin',params: { prologue: 'Hi', mode: 'conversational' },},- downstream: ['Browser:BusyHatsSink'],+ downstream: ['Crawler:BusyHatsSink'],upstream: [],},- 'Browser:BusyHatsSink': {+ 'Crawler:BusyHatsSink': {obj: {- component_name: 'Browser',- params: { headless: true, max_steps: 30 },+ component_name: 'Crawler',+ params: { extract_type: 'markdown', query: 'https://example.com' },},downstream: ['Message:QuietMonkeysLead'],upstream: ['begin'],@@ -244,10 +243,10 @@ describe('dsl-bridge round-trip stability', () => {'Message:QuietMonkeysLead': {obj: {component_name: 'Message',- params: { content: ['{Browser:BusyHatsSink@content}'] },+ params: { content: ['{Crawler:BusyHatsSink@content}'] },},downstream: [],- upstream: ['Browser:BusyHatsSink'],+ upstream: ['Crawler:BusyHatsSink'],},},retrieval: [],@@ -325,14 +324,14 @@ describe('dsl-bridge round-trip stability', () => {});it('v2 input round-trip: graph + components survive export (modulo RF internals)', () => {- const exported = roundTrip(bridge, v2BrowserLike) as any;+ const exported = roundTrip(bridge, v2CrawlerLike) as any;// The structural parts (graph, components) must be byte-stable.// Top-level envelope fields like `retrieval`/`history` are// stripped by v2 exportDsl on purpose, so we focus on `graph`// and `components` — the two payloads that carry the canvas// state.- const diff = diffDsl(v2BrowserLike.graph, exported.graph, 'graph');+ const diff = diffDsl(v2CrawlerLike.graph, exported.graph, 'graph');if (diff.warnings.length > 0) {// oxlint-disable-next-line no-consoleconsole.warn(@@ -345,8 +344,8 @@ describe('dsl-bridge round-trip stability', () => {// Components round-trip tooexpect(exported.components).toBeDefined();expect(Object.keys(exported.components)).toHaveLength(3);- expect(exported.components['Browser:BusyHatsSink'].obj.component_name).toBe(- 'Browser',+ expect(exported.components['Crawler:BusyHatsSink'].obj.component_name).toBe(+ 'Crawler',);});diff --git a/web/src/utils/file-util.ts b/web/src/utils/file-util.tsindex 9fa8f76ee4..e2db85f276 100644--- a/web/src/utils/file-util.ts+++ b/web/src/utils/file-util.ts@@ -223,9 +223,8 @@ export const downloadJsonFile = async (// fixtures, so an exported dsl imported in v2 mode and re-// exported stays identical at the byte level.//- // JSON.stringify already leaves non-ASCII (e.g. the Chinese- // prompts we store under `Browser.prompts`) un-escaped by- // default, so no `ensure_ascii` toggle is needed.+ // JSON.stringify already leaves non-ASCII un-escaped by default,+ // so no `ensure_ascii` toggle is needed.const blob = new Blob([JSON.stringify(sortKeysDeep(data), null, 2)], {type: FileMimeType.Json,});