Skip to content

Self-improving AI Employees for everyone

fix(browser): stable session per run + instance cap

trohitgcd4b8369e745
diff --git a/.env.template b/.env.template
index a62a43f4..e31fde90 100644
--- a/.env.template
+++ b/.env.template
@@ -108,6 +108,15 @@ COMPACTION_RATIO=0.8
# Per-user overrides via the UserSettings row (Settings tab).
AGENT_RECURSION_LIMIT=200
+# Browser automation (agent-browser CLI). Each distinct browser
+# session maps to one Chrome instance. BROWSER_MAX_INSTANCES caps
+# concurrent instances — when a new session would exceed it, the
+# least-recently-used session is closed first. BROWSER_IDLE_TIMEOUT_MS
+# makes the agent-browser daemon close its browser after that many
+# milliseconds without commands (0 disables).
+BROWSER_MAX_INSTANCES=3
+BROWSER_IDLE_TIMEOUT_MS=600000
+
# Dead-letter queue for failed workflow executions. Off by default.
DLQ_ENABLED=false
diff --git a/CLAUDE.md b/CLAUDE.md
index d3ff4f2b..e07e35c5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1395,7 +1395,7 @@ See **[Email Service](./docs-internal/email_service.md)** for the full architect
### Browser Nodes (1 node)
Interactive browser automation via the [agent-browser](https://www.npmjs.com/package/agent-browser) CLI binary. Wraps a persistent headless Chromium browser with an accessibility-tree-based interaction model designed for AI agents.
-- **browser**: **Dual-purpose node** - Interactive browser automation. Works as workflow node OR AI Agent tool. Group: `['browser', 'tool']`. Session persistence across chained operations via `session` parameter (auto-derived from execution_id as `machina_{execution_id}` if not specified). Operations:
+- **browser**: **Dual-purpose node** - Interactive browser automation. Works as workflow node OR AI Agent tool. Group: `['browser', 'tool']`. Session persistence across chained operations via `session` parameter (auto-derived as `machina_{execution_id}` if not specified; execution_id is stable per workflow/agent run — threaded through MachinaWorkflow node contexts, AgentWorkflow tool payloads, the legacy tool dispatch, and delegated child agents — so every browser call in one run, including delegated sub-agents, reuses ONE browser instance while separate runs stay isolated). **Instance cap**: each distinct session = one browser instance; `BrowserService` gates new sessions against agent-browser's own registry (`session list --json`) and closes the oldest via per-session `close` when `BROWSER_MAX_INSTANCES` (default 3) would be exceeded; idle browsers self-reap via `AGENT_BROWSER_IDLE_TIMEOUT_MS` injected from `BROWSER_IDLE_TIMEOUT_MS` (default 10 min). Canonical values for both knobs live in `.env.template`. Operations:
- `navigate`: Open a URL
- `click`: Click an element (CSS selector or `@eN` ref from snapshot)
- `type`: Type text keystroke-by-keystroke
@@ -1416,13 +1416,13 @@ Interactive browser automation via the [agent-browser](https://www.npmjs.com/pac
| File | Description |
|------|-------------|
| `client/src/assets/icons/browser/` | Chrome browser icon (from @ant-design/icons-svg) |
-| `server/services/browser_service.py` | BrowserService singleton -- thin subprocess wrapper, reads first JSON line from stdout |
-| `server/services/handlers/browser.py` | Handler dispatcher mapping operation+params to agent-browser CLI args |
-| `server/skills/web_agent/browser-skill/SKILL.md` | AI agent skill documenting snapshot-act-snapshot loop |
+| `server/nodes/browser/_service.py` | BrowserService singleton -- thin subprocess wrapper, reads first JSON line from stdout; instance-cap gate via agent-browser's session registry |
+| `server/nodes/browser/browser/__init__.py` | BrowserNode plugin mapping operation+params to agent-browser CLI args; derives the per-run session |
+| `server/skills/web_agent/browser-skill/SKILL.md` | AI agent skill documenting snapshot-act-snapshot loop + session semantics |
**Installation Requirement:** `agent-browser` is MachinaOs-managed (NOT a `package.json` dep). On first browser-node invocation, [`server/nodes/browser/_install.py::agent_browser_binary_path`](../server/nodes/browser/_install.py) runs `npm install agent-browser@latest --prefix <packages_dir()>` then `<bin> install` for the Chromium runtime. Same shape as [`claude_binary_path`](../server/nodes/agent/claude_code_agent/_oauth.py) (the precedent) — both land in the single shared npm tree at [`core.paths.packages_dir()`](../server/core/paths.py) = `<DATA_DIR>/packages/` (= `~/.machina/packages/` by default), resolving to `~/.machina/packages/node_modules/.bin/agent-browser[.cmd]`. Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path` (`~/.cache/MachinaOs/`, `~/Library/Caches/MachinaOs/`, `%LOCALAPPDATA%\MachinaOs\Cache\`); it now sits under DATA_DIR with everything else MachinaOs owns.
-**Implementation Detail:** `browser_service.py` invokes the resolved binary directly via `subprocess.Popen([binary, ...args], shell=False)`. Reads only the first JSON output line from agent-browser (the daemon holds stdout open), truncates at 100KB, and kills the process tree via `psutil`. `shell=False` with list argv avoids BatBadBut (CVE-2024-1874) on Windows; `npm` itself is located via `shutil.which("npm")` which honours `PATHEXT` for the `.cmd` shim.
+**Implementation Detail:** `nodes/browser/_service.py` invokes the resolved binary directly via `subprocess.Popen([binary, ...args], shell=False)`. Reads only the first JSON output line from agent-browser (the daemon holds stdout open), truncates at 100KB, and kills the process tree via `psutil` (the Rust daemon detaches and persists between commands). `shell=False` with list argv avoids BatBadBut (CVE-2024-1874) on Windows; `npm` itself is located via `shutil.which("npm")` which honours `PATHEXT` for the `.cmd` shim. The `[Browser]` info log line carries `session=` so per-run session reuse is visible in the operator log.
---
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index e95b78a7..6ba9a57f 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -89,6 +89,10 @@ context = {
"workflow_id": "6868cbbf4a36409fbd07ca24999f8b66", # 32-hex UUID, stable across rename
"workflow_slug": "AI_Assistant_1", # Human-readable, used for Temporal child IDs
"session_id": "session-xyz",
+ "execution_id": "AI_Assistant_1-a1b2c3d4", # Stable per run (= the MachinaWorkflow Temporal id);
+ # threaded into AgentWorkflow tool payloads + delegate
+ # children so session-keyed nodes (browser) reuse one
+ # instance per run instead of minting a uuid per call
"nodes": [...], # Full list for tool/memory detection
"edges": [...], # Full list for tool/memory detection
}
diff --git a/docs-internal/node-logic-flows/web_automation/browser.md b/docs-internal/node-logic-flows/web_automation/browser.md
index 0071f826..9ddd2599 100644
--- a/docs-internal/node-logic-flows/web_automation/browser.md
+++ b/docs-internal/node-logic-flows/web_automation/browser.md
@@ -3,8 +3,8 @@
| Field | Value |
|------|-------|
| **Category** | web_automation / tool (dual-purpose) |
-| **Backend handler** | [`server/services/handlers/browser.py::handle_browser`](../../../server/services/handlers/browser.py) |
-| **Service** | [`server/services/browser_service.py::BrowserService`](../../../server/services/browser_service.py) |
+| **Backend handler** | [`server/nodes/browser/browser/__init__.py::BrowserNode`](../../../server/nodes/browser/browser/__init__.py) |
+| **Service** | [`server/nodes/browser/_service.py::BrowserService`](../../../server/nodes/browser/_service.py) |
| **Tests** | [`server/tests/nodes/test_web_automation.py`](../../../server/tests/nodes/test_web_automation.py) |
| **Skill (if any)** | [`server/skills/web_agent/browser-skill/SKILL.md`](../../../server/skills/web_agent/browser-skill/SKILL.md) |
| **Dual-purpose tool** | yes - tool name `browser` |
@@ -20,8 +20,22 @@ element refs returned by snapshot -> `snapshot` again to verify.
Session state (cookies, open tabs, auth) persists across sequential operations
that share the same `session` value. If no session is provided the handler
-derives `machina_<execution_id>` from the current execution context, so every
-workflow run gets its own isolated browser.
+derives `machina_<execution_id>` from the current execution context. The
+execution_id is stable for the whole run — threaded through MachinaWorkflow
+node contexts, AgentWorkflow tool payloads (deterministic
+`workflow.info().run_id` fallback), the legacy in-process tool dispatch, and
+delegated child agents — so every browser call in one workflow/agent run
+(including delegated sub-agents) reuses ONE browser instance, while separate
+runs stay isolated.
+
+Concurrent instances are capped: each distinct `--session` name maps to one
+browser instance, and `BrowserService` gates new sessions against
+agent-browser's own registry (`session list --json`), closing the oldest
+listed session via per-session `close` when `BROWSER_MAX_INSTANCES`
+(default 3) would be exceeded. Idle browsers self-reap via
+`AGENT_BROWSER_IDLE_TIMEOUT_MS`, injected into every spawn from
+`BROWSER_IDLE_TIMEOUT_MS` (default 600000 ms; 0 disables). Canonical values
+for both knobs live in `.env.template`.
## Inputs (handles)
@@ -129,8 +143,17 @@ flowchart TD
- **Service missing**: `get_browser_service()` returns `None` when `npx` is not on
PATH -> immediate `agent-browser not installed` error envelope.
-- **Session resolution**: empty `session` -> `machina_<execution_id>`. Only the
- stripped value is considered empty; whitespace triggers the fallback.
+- **Session resolution**: empty `session` -> `machina_<execution_id>` via the
+ typed `ctx.execution_id` accessor (handles present-but-None on the agent
+ tool-dispatch path). Only the stripped value is considered empty; whitespace
+ triggers the fallback. The resolved session is logged in the `[Browser]`
+ info line.
+- **Instance cap**: before each command, `_enforce_instance_cap` admits the
+ session (once per process, `_gated_sessions` fast-path). Unknown sessions
+ trigger one `session list --json` probe; if admitting would exceed
+ `BROWSER_MAX_INSTANCES`, the oldest listed sessions are closed first
+ (`close --session <name>`). The probe fails open — gating never blocks an
+ actual browser operation.
- **Browser upgrade**: `""` or `bundled` both normalised to `chrome`. Users who
specifically want the bundled Chromium must pick `bundled_explicit`.
- **Executable resolution**: `shutil.which()` against Linux/macOS PATH names,
@@ -170,7 +193,11 @@ flowchart TD
- **Services**: `BrowserService` singleton; `npx` on PATH; `agent-browser`
pinned in the project's `package.json` and installed under `node_modules`.
- **Python packages**: `psutil` (for process-tree kill).
-- **Environment variables**: none.
+- **Environment variables**: `BROWSER_MAX_INSTANCES` (concurrent session cap,
+ default 3), `BROWSER_IDLE_TIMEOUT_MS` (daemon idle auto-shutdown in ms,
+ default 600000, 0 disables) — canonical values in `.env.template`, mirrored
+ by `Settings` defaults. `AGENT_BROWSER_IDLE_TIMEOUT_MS` is injected into
+ every agent-browser spawn from the latter.
## Edge cases & known limits
diff --git a/server/core/config.py b/server/core/config.py
index 58755cde..ae83db95 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -241,6 +241,17 @@ class Settings(BaseSettings):
# silently allows. Override to "0.0.0.0" for container deployments.
whatsapp_bind_host: str = Field(default="localhost", env="WHATSAPP_BIND_HOST")
+ # Browser automation (agent-browser CLI). Canonical values live in
+ # .env.template (same pattern as COMPACTION_RATIO — the code default
+ # only mirrors the template for bare Settings() construction, e.g.
+ # pytest/CI without the CLI env layering). Each distinct session name
+ # maps to one Chrome instance; the cap closes the oldest session
+ # before a new one would exceed it. Idle timeout (ms) makes the
+ # agent-browser daemon shut down its browser after inactivity; 0
+ # disables.
+ browser_max_instances: int = Field(default=3, env="BROWSER_MAX_INSTANCES", ge=1, le=50)
+ browser_idle_timeout_ms: int = Field(default=600_000, env="BROWSER_IDLE_TIMEOUT_MS", ge=0)
+
# Compaction Configuration. Threshold = model context_length ×
# compaction_ratio. Per-user UserSettings row overrides at runtime.
compaction_enabled: bool = Field(default=True, env="COMPACTION_ENABLED")
diff --git a/server/nodes/browser/_service.py b/server/nodes/browser/_service.py
index 4b910d27..388b128b 100644
--- a/server/nodes/browser/_service.py
+++ b/server/nodes/browser/_service.py
@@ -22,6 +22,7 @@ Windows .CMD files natively via ``CreateProcessW``, avoiding the BatBadBut
import asyncio
import json
+import os
import subprocess
from typing import Any, Dict, List, Optional
@@ -34,6 +35,59 @@ logger = get_logger(__name__)
_MAX_OUTPUT = 100_000
+def _max_instances() -> int:
+ """Concurrent browser-session cap. Canonical value lives in
+ .env.template (BROWSER_MAX_INSTANCES); Settings read is wrapped
+ defensively because tests stub ``core.config.Settings`` (same
+ pattern as ``_default_max_iterations`` in temporal/agent_workflow.py).
+ """
+ try:
+ from core.config import Settings
+
+ value = Settings().browser_max_instances
+ # isinstance guard: tests stub Settings with MagicMock, and
+ # int(MagicMock()) silently returns 1 instead of raising.
+ if isinstance(value, int):
+ return value
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ return int(os.environ.get("BROWSER_MAX_INSTANCES") or 3)
+ except (TypeError, ValueError):
+ return 3
+
+
+def _idle_timeout_ms() -> int:
+ """agent-browser daemon idle auto-shutdown (ms); 0 disables.
+
+ Official mechanism per the agent-browser README ("Architecture"):
+ when AGENT_BROWSER_IDLE_TIMEOUT_MS is set, the daemon closes the
+ browser and exits after receiving no commands for that duration.
+ """
+ try:
+ from core.config import Settings
+
+ value = Settings().browser_idle_timeout_ms
+ if isinstance(value, int):
+ return value
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ return int(os.environ.get("BROWSER_IDLE_TIMEOUT_MS") or 600_000)
+ except (TypeError, ValueError):
+ return 600_000
+
+
+def _spawn_env() -> Optional[Dict[str, str]]:
+ """Env for agent-browser spawns. The daemon inherits this on
+ auto-start, so the idle timeout must ride every command that could
+ be the one that starts it. None -> inherit unchanged."""
+ idle = _idle_timeout_ms()
+ if idle <= 0:
+ return None
+ return {**os.environ, "AGENT_BROWSER_IDLE_TIMEOUT_MS": str(idle)}
+
+
class BrowserService:
"""Subprocess wrapper for the agent-browser CLI.
@@ -44,6 +98,11 @@ class BrowserService:
def __init__(self, argv_prefix: List[str]) -> None:
self._prefix = list(argv_prefix)
+ # Sessions already gated by this process — fast-path so the
+ # daemon's ``session list`` is queried once per new session, not
+ # on every command. The daemon registry stays the authority.
+ self._gated_sessions: set = set()
+ self._gate_lock = asyncio.Lock()
async def run(
self,
@@ -65,6 +124,8 @@ class BrowserService:
daemon process alive. We read just the first line via Popen in a
thread, then kill the process — never wait for exit.
"""
+ await self._enforce_instance_cap(session)
+
argv = [
*self._prefix,
"--session",
@@ -99,6 +160,41 @@ class BrowserService:
except json.JSONDecodeError:
return {"output": raw}
+ async def _enforce_instance_cap(self, session: str) -> None:
+ """Cap concurrent browser instances via agent-browser's own
+ primitives: ``session list --json`` (the daemon's authoritative
+ registry) and per-session ``close``. One ``--session`` name =
+ one browser instance (README "Sessions"); the CLI ships no
+ built-in cap, so admission is gated here before a NEW session
+ would exceed BROWSER_MAX_INSTANCES.
+ """
+ if session in self._gated_sessions:
+ return
+ async with self._gate_lock:
+ if session in self._gated_sessions:
+ return
+ listing = await self._session_cmd(["session", "list"])
+ names = [str(s) for s in (listing.get("data") or {}).get("sessions") or []]
+ if session not in names:
+ cap = _max_instances()
+ for stale in names[: max(0, len(names) - cap + 1)]:
+ logger.info("[Browser] instance cap %d reached; closing session %s", cap, stale)
+ await self._session_cmd(["close", "--session", stale])
+ self._gated_sessions.discard(stale)
+ self._gated_sessions.add(session)
+
+ async def _session_cmd(self, args: List[str]) -> Dict[str, Any]:
+ """Run a session-management command through the standard
+ ``_run_sync`` pipeline. Fails open ({}) — gating must never
+ block an actual browser operation.
+ """
+ try:
+ raw = await asyncio.to_thread(self._run_sync, [*self._prefix, *args, "--json"], 15, None)
+ return json.loads(raw)
+ except Exception as e: # noqa: BLE001
+ logger.debug("agent-browser session command failed: args=%s error=%s", args, e)
+ return {}
+
@staticmethod
def _run_sync(
argv: List[str],
@@ -121,6 +217,9 @@ class BrowserService:
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False,
+ # The daemon inherits this env on auto-start — carries
+ # AGENT_BROWSER_IDLE_TIMEOUT_MS (official idle auto-shutdown).
+ env=_spawn_env(),
)
try:
@@ -191,6 +290,7 @@ async def shutdown_browser_service() -> None:
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
+ svc._gated_sessions.clear()
logger.info("agent-browser daemon shut down")
except Exception as e:
logger.debug("agent-browser shutdown skipped: %s", e)
diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.py
index 291f106c..54bcd707 100644
--- a/server/nodes/browser/browser/__init__.py
+++ b/server/nodes/browser/browser/__init__.py
@@ -360,13 +360,15 @@ class BrowserNode(ActionNode):
)
op = params.operation
- session = params.session.strip() or f"machina_{ctx.raw.get('execution_id', 'default')}"
+ # Typed accessor (not ctx.raw.get) — the key can be present-but-None
+ # on the agent tool-dispatch path; `or` covers both missing and None.
+ session = params.session.strip() or f"machina_{ctx.execution_id or 'default'}"
timeout = params.timeout
browser_sel = params.browser or "chrome"
if browser_sel == "bundled":
browser_sel = "chrome"
executable_path = _resolve_browser(browser_sel, params.executable_path.strip())
- logger.info("[Browser] browser=%s executable=%s", browser_sel, executable_path)
+ logger.info("[Browser] session=%s browser=%s executable=%s", session, browser_sel, executable_path)
run_kw = dict(
headed=params.headed,
diff --git a/server/services/ai.py b/server/services/ai.py
index 87454ca6..b3c976cf 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -1803,6 +1803,9 @@ class AIService:
config["nodes"] = context.get("nodes", [])
config["edges"] = context.get("edges", [])
config["workspace_dir"] = context.get("workspace_dir", "")
+ # Stable per-run id so session-keyed tools (browser)
+ # reuse one instance across the agent loop.
+ config["execution_id"] = context.get("execution_id")
try:
result = await execute_tool(tool_name, tool_args, config)
@@ -2348,6 +2351,9 @@ class AIService:
config["nodes"] = context.get("nodes", [])
config["edges"] = context.get("edges", [])
config["workspace_dir"] = context.get("workspace_dir", "")
+ # Stable per-run id so session-keyed tools (browser)
+ # reuse one instance across the agent loop.
+ config["execution_id"] = context.get("execution_id")
try:
result = await execute_tool(tool_name, tool_args, config)
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 63b91511..a757ce88 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -151,6 +151,10 @@ async def _dispatch_tool(tool_name: str, tool_args: Dict[str, Any], config: Dict
"edges": config.get("edges", []),
"workflow_id": config.get("workflow_id"),
"parent_node_id": config.get("parent_node_id"),
+ # Stable per-run id so session-keyed tools (browser) reuse one
+ # instance across the agent loop instead of falling back to a
+ # shared default session.
+ "execution_id": config.get("execution_id"),
}
logger.info("[Tool] Executing '%s' (node_type=%s, workspace=%s)", tool_name, node_type, context["workspace_dir"])
@@ -390,8 +394,17 @@ async def _execute_delegated_agent(args: Dict[str, Any], config: Dict[str, Any])
child_params.pop("systemMessage", None)
child_params["prompt"] = task_context if task_context else task_description
- # Create execution context for child agent
- child_context = {"nodes": nodes, "edges": edges, "workflow_id": workflow_id, "outputs": {}, "parent_task_id": task_id}
+ # Create execution context for child agent. Forward the parent's
+ # execution_id so session-keyed tools (browser) used by the child
+ # share the parent run's instance.
+ child_context = {
+ "nodes": nodes,
+ "edges": edges,
+ "workflow_id": workflow_id,
+ "outputs": {},
+ "parent_task_id": task_id,
+ "execution_id": config.get("execution_id"),
+ }
broadcaster = get_status_broadcaster()
agent_label = child_params.get("label", node_type)
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 85e92dda..2cdc7720 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -752,6 +752,7 @@ class BaseNode:
nodes=context.get("nodes", []),
edges=context.get("edges", []),
session_id=context.get("session_id", "default"),
+ execution_id=context.get("execution_id"),
workflow_id=workflow_id,
outputs=context.get("inputs", {}),
extras=extras or None,
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index 82eab084..28f47b55 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -190,6 +190,13 @@ class AgentWorkflow:
start_to_close_timeout=PERSIST_TURN_TIMEOUT * 2, # 60s default
retry_policy=AGENT_ACTIVITY_RETRY,
)
+ # Stable per-run execution id, forwarded into every tool-call
+ # activity so session-keyed nodes (browser) reuse one instance
+ # across iterations instead of minting a fresh uuid per call
+ # (node_executor.py fallback). Delegation children inherit it via
+ # the ``child_context`` spread below. ``workflow.info().run_id``
+ # is deterministic — safe inside workflow code.
+ execution_id = str(context.get("execution_id") or "") or workflow.info().run_id[:8]
# ---- Build initial message list ---------------------------------
# Workflow state is JSON dicts in LangChain's canonical shape
# ({"type": "<role>", "data": {"content": "...", ...}}) so the
@@ -427,6 +434,7 @@ class AgentWorkflow:
"inputs": {},
"workflow_id": payload.get("workflow_id"),
"session_id": payload.get("session_id", "default"),
+ "execution_id": execution_id,
"nodes": child_nodes,
"edges": child_edges,
# Surface the auto-rebind toggle into the tool's ctx
diff --git a/server/services/temporal/executor.py b/server/services/temporal/executor.py
index 0b829422..8d89b068 100644
--- a/server/services/temporal/executor.py
+++ b/server/services/temporal/executor.py
@@ -93,6 +93,7 @@ class TemporalExecutor:
"session_id": session_id,
"workflow_id": workflow_id,
"workflow_slug": workflow_slug,
+ "execution_id": execution_id,
},
id=execution_id,
task_queue=self.task_queue,
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index 0753ccf5..0c6af6a4 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -197,6 +197,13 @@ class MachinaWorkflow:
# (one-off Runs without a saved DB row).
workflow_slug = workflow_data.get("workflow_slug") or workflow_id
tenant_id = workflow_data.get("tenant_id")
+ # Stable per-run execution id. The executor passes the same value
+ # it uses as this workflow's Temporal id (``<slug>-<uuid8>``), so
+ # the fallback to ``workflow.info().workflow_id`` is identical by
+ # construction. Threaded into every node activity context so
+ # session-keyed nodes (browser) share one instance per run instead
+ # of minting a fresh uuid per call (node_executor.py fallback).
+ execution_id = workflow_data.get("execution_id") or workflow.info().workflow_id
workflow.logger.info(f"Starting workflow orchestration: {len(nodes)} nodes, {len(edges)} edges")
@@ -308,6 +315,7 @@ class MachinaWorkflow:
"workflow_slug": workflow_slug,
"tenant_id": tenant_id,
"session_id": session_id,
+ "execution_id": execution_id,
"nodes": nodes, # Full list for tool/memory detection
"edges": edges, # Full list for tool/memory detection
# Include pre-executed info if applicable
diff --git a/server/skills/web_agent/browser-skill/SKILL.md b/server/skills/web_agent/browser-skill/SKILL.md
index 0cc31032..8b471223 100644
--- a/server/skills/web_agent/browser-skill/SKILL.md
+++ b/server/skills/web_agent/browser-skill/SKILL.md
@@ -163,6 +163,14 @@ Browser detection uses `shutil.which()` on Linux/macOS (PATH lookup) and the Win
The browser daemon auto-starts on first use and persists between commands (for session reuse). It is automatically shut down when MachinaOs stops -- no manual cleanup needed.
+### Sessions
+
+Each distinct session name maps to ONE browser instance. When the `session` field is left empty (the normal case), it auto-derives as `machina_<execution_id>` -- stable for the whole workflow/agent run, including delegated sub-agents -- so every browser call in a run reuses the same browser window and keeps its cookies, tabs, and login state.
+
+- **Leave `session` empty.** Do not invent a session name per call; the auto-derived session already chains your calls onto one browser.
+- Set `session` explicitly only to persist state across separate runs (e.g. `my_login_session`) or to isolate parallel flows within one run.
+- Concurrent instances are capped by `BROWSER_MAX_INSTANCES` (default 3); when a new session would exceed the cap, the oldest active session is closed first. Idle browsers auto-close after `BROWSER_IDLE_TIMEOUT_MS` (default 10 minutes) without commands.
+
## Stealth / Anti-Detection
These settings reduce bot detection. Configure them in the node's Advanced section, not as tool arguments.
diff --git a/server/tests/nodes/test_browser_service.py b/server/tests/nodes/test_browser_service.py
new file mode 100644
index 00000000..b4c42541
--- /dev/null
+++ b/server/tests/nodes/test_browser_service.py
@@ -0,0 +1,110 @@
+"""Unit tests for BrowserService instance-cap gating (nodes/browser/_service.py).
+
+The cap leans on agent-browser's own primitives -- ``session list --json``
+(the daemon's authoritative session registry) and per-session ``close`` --
+instead of mirroring daemon state in Python. These tests stub ``_run_sync``
+so no subprocess is spawned and drive the gate through ``run()``.
+"""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import patch
+
+import pytest
+
+from nodes.browser._service import BrowserService
+
+
+pytestmark = pytest.mark.unit
+
+
+def _make_fake_run_sync(active_sessions, calls, fail_session_list=False):
+ """Stub for ``BrowserService._run_sync``.
+
+ ``session list`` returns the given registry (or raises when
+ ``fail_session_list``); every other command returns a generic
+ success line. ``calls`` collects each argv list for assertions.
+ """
+
+ def fake_run_sync(argv, timeout, stdin_data):
+ calls.append(list(argv))
+ if "session" in argv and "list" in argv:
+ if fail_session_list:
+ raise RuntimeError("daemon not running")
+ return json.dumps({"success": True, "data": {"sessions": list(active_sessions)}})
+ return json.dumps({"success": True, "data": {}})
+
+ return fake_run_sync
+
+
+def _close_calls(calls):
+ return [c for c in calls if "close" in c]
+
+
+class TestInstanceCap:
+ async def test_new_session_under_cap_no_close(self, monkeypatch):
+ monkeypatch.setenv("BROWSER_MAX_INSTANCES", "3")
+ svc = BrowserService(["agent-browser"])
+ calls = []
+ fake = _make_fake_run_sync(["existing"], calls)
+
+ with patch.object(BrowserService, "_run_sync", staticmethod(fake)):
+ await svc.run(["open", "https://example.com"], "fresh_session")
+
+ assert _close_calls(calls) == []
+
+ async def test_cap_reached_closes_oldest_listed(self, monkeypatch):
+ monkeypatch.setenv("BROWSER_MAX_INSTANCES", "3")
+ svc = BrowserService(["agent-browser"])
+ calls = []
+ fake = _make_fake_run_sync(["s1", "s2", "s3"], calls)
+
+ with patch.object(BrowserService, "_run_sync", staticmethod(fake)):
+ await svc.run(["open", "https://example.com"], "s4")
+
+ closes = _close_calls(calls)
+ assert len(closes) == 1
+ assert "--session" in closes[0] and "s1" in closes[0], (
+ "the first-listed (oldest) session must be closed to make room"
+ )
+
+ async def test_existing_session_reuse_never_closes(self, monkeypatch):
+ # Session already in the daemon registry -> reuse, even at cap.
+ monkeypatch.setenv("BROWSER_MAX_INSTANCES", "3")
+ svc = BrowserService(["agent-browser"])
+ calls = []
+ fake = _make_fake_run_sync(["s1", "s2", "s3"], calls)
+
+ with patch.object(BrowserService, "_run_sync", staticmethod(fake)):
+ await svc.run(["snapshot"], "s2")
+
+ assert _close_calls(calls) == []
+
+ async def test_registry_queried_once_per_session(self, monkeypatch):
+ # Fast path: the second command on a gated session must not
+ # re-spawn a ``session list`` probe.
+ monkeypatch.setenv("BROWSER_MAX_INSTANCES", "3")
+ svc = BrowserService(["agent-browser"])
+ calls = []
+ fake = _make_fake_run_sync([], calls)
+
+ with patch.object(BrowserService, "_run_sync", staticmethod(fake)):
+ await svc.run(["open", "https://example.com"], "sess_a")
+ await svc.run(["snapshot"], "sess_a")
+
+ list_probes = [c for c in calls if "session" in c and "list" in c]
+ assert len(list_probes) == 1
+
+ async def test_session_list_failure_fails_open(self, monkeypatch):
+ # Gating must never block an actual browser operation.
+ monkeypatch.setenv("BROWSER_MAX_INSTANCES", "3")
+ svc = BrowserService(["agent-browser"])
+ calls = []
+ fake = _make_fake_run_sync([], calls, fail_session_list=True)
+
+ with patch.object(BrowserService, "_run_sync", staticmethod(fake)):
+ result = await svc.run(["open", "https://example.com"], "sess_b")
+
+ assert result.get("success") is True
+ assert _close_calls(calls) == []
diff --git a/server/tests/nodes/test_web_automation.py b/server/tests/nodes/test_web_automation.py
index f782c71b..fcfe696a 100644
--- a/server/tests/nodes/test_web_automation.py
+++ b/server/tests/nodes/test_web_automation.py
@@ -99,6 +99,27 @@ class TestBrowser:
assert args == ("snapshot", "-i")
assert session.startswith("machina_")
+ async def test_session_stable_across_calls_in_one_run(self, harness):
+ # Two browser calls sharing one execution context (one agent run)
+ # must derive the SAME session -> same browser instance. Regression:
+ # the Temporal tool path minted a fresh execution_id per call, so
+ # every call spawned a new Chrome.
+ fake = _FakeBrowserService(canned={"success": True, "data": {}})
+ ctx = harness.build_context(execution_id="run1234")
+
+ with _patch_browser_service(fake):
+ r1 = await harness.execute(
+ "browser",
+ {"operation": "navigate", "url": "https://example.com"},
+ context=ctx,
+ )
+ r2 = await harness.execute("browser", {"operation": "snapshot"}, context=ctx)
+
+ harness.assert_envelope(r1, success=True)
+ harness.assert_envelope(r2, success=True)
+ sessions = [call[1] for call in fake.calls]
+ assert sessions == ["machina_run1234", "machina_run1234"]
+
async def test_screenshot_with_jpeg_and_quality(self, harness):
fake = _FakeBrowserService(canned={"success": True, "base64": "AAAA"})
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index 9192632c..6e8e2728 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -306,6 +306,71 @@ class TestAutoRebindTools:
)
+class TestExecutionIdPropagation:
+ """A stable per-run ``execution_id`` must flow into every tool-call
+ activity. Session-keyed nodes (browser) derive their session name
+ from it — without propagation, ``NodeExecutor.execute`` mints a
+ fresh uuid per call and every browser tool call spawns a NEW Chrome
+ instance instead of reusing the run's browser.
+
+ Source-introspection invariants — a live run needs a Temporal
+ WorkflowEnvironment, too heavy for unit tests (same rationale as
+ ``TestDelegationToolDispatch``).
+ """
+
+ def test_agent_workflow_tool_payload_carries_execution_id(self):
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ src = inspect.getsource(AgentWorkflow.run)
+ assert '"execution_id"' in src, (
+ "AgentWorkflow tool_payload must include execution_id so "
+ "session-keyed tools (browser) reuse one instance per run."
+ )
+ assert "workflow.info().run_id" in src, (
+ "AgentWorkflow must fall back to the deterministic "
+ "workflow.info().run_id when the input omits execution_id."
+ )
+
+ def test_as_activity_forwards_execution_id(self):
+ import inspect
+
+ from services.plugin.base import BaseNode
+
+ src = inspect.getsource(BaseNode.as_activity)
+ assert 'execution_id=context.get("execution_id")' in src, (
+ "BaseNode.as_activity must pass execution_id through to "
+ "workflow_service.execute_node — otherwise NodeExecutor "
+ "mints a fresh uuid per tool call."
+ )
+
+ def test_machina_workflow_threads_execution_id(self):
+ import inspect
+
+ from services.temporal.workflow import MachinaWorkflow
+
+ src = inspect.getsource(MachinaWorkflow.run)
+ assert '"execution_id"' in src, (
+ "MachinaWorkflow per-node context must carry execution_id."
+ )
+ assert "workflow.info().workflow_id" in src, (
+ "MachinaWorkflow must fall back to its own workflow id "
+ "(identical to the executor-minted execution_id by construction)."
+ )
+
+ def test_temporal_executor_passes_execution_id_in_input(self):
+ import inspect
+
+ from services.temporal.executor import TemporalExecutor
+
+ src = inspect.getsource(TemporalExecutor.execute_workflow)
+ assert '"execution_id": execution_id' in src, (
+ "TemporalExecutor must thread the minted execution_id into "
+ "the MachinaWorkflow input dict, not only the workflow id."
+ )
+
+
class TestDelegationInvocationContract:
"""Regression: the delegated task must survive the child's config
resolution. Pre-fix the parent remapped ``{task, context}`` into the