Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs(browser): align runtime and workspace guides with native browser
trohitg3406e2cb8890
diff --git a/CLAUDE.md b/CLAUDE.mdindex b5c936fd..b4b5dc15 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[UI Migration Plan](./docs-internal/ARCHIVE/ui_migration_plan.md)** | *Archived.* antd → shadcn/ui migration completion log (Waves 1–10). Current state lives in [Frontend Architecture](./docs-internal/frontend_architecture.md) and [Theme System](./docs-internal/theme_system.md). || **[Temporal Cleanup & Resilience Plan (Waves 15-18)](./docs-internal/ARCHIVE/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md)** | *Archived — all four waves shipped.* 15 dead-code retirement (Redis-Streams branch in event_waiter, APScheduler cron stack, orphaned `connection_status` factory), 16 per-queue task routing (`TemporalWorkerPool`), 17 resilience hardening (cron `catchup_window`, SDK interceptors, `DEPLOYMENT_MODE`, periodic heartbeats; the one-shot LLM-step retry it records was later reverted to unlimited-with-backoff), 18 worker performance tuning. Current settings live in [Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md). || **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |-| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee card, the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; the Browser and Android tabs are placeholders), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` broadcasts. |+| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee card, the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Android remains a placeholder), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` broadcasts. || **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (toggled by Dashboard's `visibilitychange` listener; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 inline SVG glyph strings across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. || **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), 12-theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 12 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/themes/). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). || **[Schema Source of Truth RFC](./docs-internal/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |@@ -28,7 +28,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Pricing Service](./docs-internal/pricing_service.md)** | Centralized cost tracking for LLM tokens and API services (Twitter, Google Maps) with HTTPX event hooks || **[Proxy Service](./docs-internal/proxy_service.md)** | Residential proxy provider management with template-based URL formatting, health scoring, and transparent HTTP node injection || **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers |-| **[Browser Harness](./docs-internal/browser_harness.md)** | Wave 19 — `browserHarness` node integrating browser-use/browser-harness (alpha, raw CDP against the user's REAL Chrome; no Playwright). Primary op `run_python` pipes agent-authored Python to the CLI stdin against ~25 pre-imported helpers (see→act→verify loop: `capture_screenshot` → `click_at_xy` → `wait_for_load` → `js`). uv-tool install under `packages/browser-harness/`; daemon state pinned to `daemons/browser-harness/` via `BH_RUNTIME_DIR`/`BH_TMP_DIR`; Windows OK (token-auth TCP loopback IPC). Sibling of the stable `browser` node (agent-browser `@eN` refs) — NOT a replacement. Chrome must be CDP-reachable (`BU_CDP_URL` / chrome://inspect / `--remote-debugging-port`); `doctor` op diagnoses. Skill: `skills/web_agent/browser-harness-skill/`. |+| **[Browser](./docs-internal/browser.md)** | Current `browser` node: managed Chrome for Testing and pinned browser-use CLI, persistent employee/shared profiles, session leases, agent/user handoff, network policy, screenshots as workspace FileRefs, and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. |+| **[Browser Workspace](./docs-internal/browser_workspace.md)** | Home and Dev share `WorkspaceTabs` and `BrowserWorkspace`: Browser / Canvas / Android, capability-based discovery, binary JPEG frames, bounded frame credit and decoding, Take control / Hand back, visibility cleanup and payload-free opt-in diagnostics. Android remains a placeholder. || **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** — on a dual-purpose ActionNode `execute_as_tool` merges `{**node_params, **tool_args}`, so a declared field is model-settable and a prompt injection could choose the sending identity; it comes from the credential only. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. || **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. || **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). `bun add` into the shared packages tree (pinned version, via `core/js_runtime.add_package`; the CLI runs on bun). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |@@ -41,10 +42,10 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Speech Provider RFC](./docs-internal/speech_provider_rfc.md)** | Provider-abstracted speech — two nodes (`textToSpeech`, `speechToText`) with a `provider` dropdown, backed by **two registries, one per direction** (registry membership IS the capability: a synthesis-only vendor simply never appears in the transcription enum). Everything vendor-specific lives in the plugin folder [`server/nodes/speech/`](./server/nodes/speech/) — protocol, registries, dispatch, per-vendor modules; only the generic `services/provider_registry.py` and the vendor-neutral `services/media/` are shared. v1 providers: OpenAI (both directions), ElevenLabs (TTS), Deepgram + Groq (STT), Sarvam (both). Capabilities are JSON (`server/config/speech_defaults.json`) with per-model overrides, so no shared code branches on a provider name. **Audio never travels as bytes** — nodes return an `AudioRef` (a ~400 B reference) because a 12 MB base64 result blows Temporal's 2 MiB blob limit and retries 3× re-billing the provider each time. Backing routes: `GET/POST /api/workspace/{workflow_id}/…` in [`routers/workspace.py`](./server/routers/workspace.py). || **[Media Transport](./docs-internal/media_transport.md)** | How files move through the engine, and why they move as **references rather than bytes**. `services/media/` — `FileRef` (the base; `FileKind = file\|audio\|image\|video\|document`) with `AudioRef(FileRef)` as the probed-container narrowing (~400 B, `extra="forbid"` so adding a bytes field is a `ValidationError` rather than a silent regression), `write_audio` / `resolve_media` / `coerce_file_param` (the one nodes should call — accepts a `FileRef`/`AudioRef`, a bare path, or the legacy base64 envelope), `inspect_audio` (tinytag → stdlib `wave` → PCM arithmetic, **never raises**), `limits.py`, and **`preview.py` — the single owner of the inline-vs-attachment rule**, with two consumers: `routers/workspace.py` picks its `Content-Disposition` from `serves_inline`, and the gallery listing sets each row's `preview` from `preview_kind`, so the panel can never offer a preview the route refuses to serve. Containment runs through `resolve_within`, which closed a live vulnerability: a node joined a user path onto the workspace root unchecked, so `audio_file="../../credentials.db"` read the encrypted credential store and uploaded it. **The id/slug asymmetry is the trap** — workspace dirs are named by the mutable `Workflow.slug` while a ref stores the immutable `workflow_id` so refs survive rename; the lookup lives in [`services/workspace_locator.py`](./server/services/workspace_locator.py) (`resolve_workspace_root(..., allow_default=)`), and **every mutating caller must pass `allow_default=False`** or an unresolvable id silently lands the write in the shared anonymous workspace. HTTP surface in [`routers/workspace.py`](./server/routers/workspace.py): Range support comes free from Starlette's `FileResponse`; `NEVER_INLINE` is `{image/svg+xml, text/html, text/xml, application/xhtml+xml}` because `shell` / `fileDownloader` / `fileModify` can write arbitrary files into a workspace. || **[Data Node & Vision](./docs-internal/data_node.md)** | The `dataSource` agent tool (raw local data over two namespaces: workspace paths + operator-approved `mnt/<name>/...` external mounts with per-mount writable flags; typed bounded read tiers text/csv/json/pdf/html/xlsx/image-metadata/binary; write/append but **no delete**; `copy_to_workspace` imports mount files as real FileRefs), the machine-wide `data_mounts` allowlist (`services/data/mount_store.py` — refuses `DATA_DIR` overlap, drive roots, home dir), the `visionAnalyze` delegate tool (vision for every host model via openai/anthropic/gemini official SDK shapes + the `services/media/image_fit.py` visual-token budget), and the first native-image-blocks increment: `ContentBlock.source` (durable `file_ref` vs transient `bytes` — the wire codec raises on bytes), the `llm_media` tool-result opt-in, capability-gated `hydrate_image_blocks` in `run_native_llm_step`, Anthropic `tool_result` image encoding (openai/gemini encoders pending; their `vision.enabled` stays false until then). |-| **[Canvas Node](./docs-internal/canvas_node.md)** | The `canvas` node — pushed-content display board (the Claude/ChatGPT-Canvas analog) in [`server/nodes/tool/canvas/`](./server/nodes/tool/canvas/). Dual control: agents call the locked `canvas(...)` tool (paths / url / 64KB-capped markdown notes, append/replace), workflow edges auto-display upstream FileRefs via a structural scan of `connected_outputs` (`tts → canvas` is a zero-config edge; the node is the one addition to `NodeExecutor._NEEDS_CONNECTED_OUTPUTS`). Board = plugin-owned `canvas_boards`/`canvas_items` tables (mount_store mechanism, 200-item FIFO), identity-only `canvas_updated` broadcast (direct, no canary consumer), `canvas_list/remove/clear` WS handlers with the simple_memory security preamble. **Three frontend hosts share one renderer**: the `isCanvasPanel` parameter panel, the docked resizable right sidebar (`CanvasDock` + `canvasDockStore`; auto-open via `notifyPushed`, ephemeral click-to-preview from the gallery dialog, `usePanelResize` extracted from ConsolePanel), and the Canvas tab of Home's Workspace dock (`features/home/workspace/`). Renders media carousel with follow-latest image poll, markdown/code/JSON via the repo's first capped client-side text fetch (`useWorkspaceText`, 512KB), external URLs + workspace HTML in strictly sandboxed iframes (never `allow-same-origin`; `NEVER_INLINE` untouched), and inline PDF via the `INLINE_EXACT` exact-match addition to `preview.py`. Browser screenshots became displayable in the same change: both browser plugins persist shots as workspace FileRefs via the tolerant `nodes/browser/_screenshots.py`. |+| **[Canvas Node](./docs-internal/canvas_node.md)** | The `canvas` node — pushed-content display board (the Claude/ChatGPT-Canvas analog) in [`server/nodes/tool/canvas/`](./server/nodes/tool/canvas/). Dual control: agents call the locked `canvas(...)` tool (paths / url / 64KB-capped markdown notes, append/replace), workflow edges auto-display upstream FileRefs via a structural scan of `connected_outputs` (`tts → canvas` is a zero-config edge; the node is the one addition to `NodeExecutor._NEEDS_CONNECTED_OUTPUTS`). Board = plugin-owned `canvas_boards`/`canvas_items` tables (mount_store mechanism, 200-item FIFO), identity-only `canvas_updated` broadcast (direct, no canary consumer), `canvas_list/remove/clear` WS handlers with the simple_memory security preamble. **Three frontend hosts share one renderer**: the `isCanvasPanel` parameter panel, the docked resizable right sidebar (`CanvasDock` + `canvasDockStore`; auto-open via `notifyPushed`, ephemeral click-to-preview from the gallery dialog, `usePanelResize` extracted from ConsolePanel), and the Canvas tab of Home's Workspace dock (`features/home/workspace/`). Renders media carousel with follow-latest image poll, markdown/code/JSON via the repo's first capped client-side text fetch (`useWorkspaceText`, 512KB), external URLs + workspace HTML in strictly sandboxed iframes (never `allow-same-origin`; `NEVER_INLINE` untouched), and inline PDF via the `INLINE_EXACT` exact-match addition to `preview.py`. The current Browser node persists screenshots as workspace FileRefs through `nodes/browser/_screenshots.py`; live viewing uses the separate Browser workspace stream. || **[Translate / Transliterate / Detect](./docs-internal/speech_provider_rfc.md#8-what-this-pattern-should-absorb-next)** | The second application of the multi-vendor pattern, and the one that retired `nodes/sarvam/`. Three nodes (`translateText`, `transliterateText`, `detectLanguage`) in [`server/nodes/translate/`](./server/nodes/translate/), backed by **three registries — one per capability**, because the asymmetry is sharper than speech's: DeepL translates and does nothing else, while Sarvam and LLM-backed providers do all three. Membership makes an unsupported selection unrepresentable rather than a runtime failure inside a paid call. Providers: **deepl** (`Authorization: DeepL-Auth-Key`, `text` is an array, free keys ending `:fx` route to a different host, and it returns `billed_characters` so cost is the provider's own figure), **sarvam** (all three over dedicated REST), **openai** (all three via `ChatUnifier` — proves the Protocol does not care what a provider does internally; billing deliberately NOT recorded because that path bills tokens the LLM layer already costs). Capabilities in `server/config/translate_defaults.json`. || **[Desktop App](./docs-internal/desktop_app.md)** | Electron shell in [`desktop/`](./desktop/) — a standalone bun package (NOT a root workspace member; `cli/tests/test_release_pipeline_config.py` locks `workspaces`). Bundles pinned `uv`, python-build-standalone CPython 3.12 and bun 1.4.0 — the only JavaScript runtime shipped; no Node, no npm (`desktop/runtimes.json`, verified against upstream checksum manifests by `scripts/fetch-runtimes.ts`, which also fetches bun's `LICENSE.md` from the bun repo — the release zip carries none — and prunes stale runtime dirs such as a leftover `node/`), stages the backend sibling layout from `bun pm pack --dry-run` (`scripts/stage.ts`, which runs the sidecar package's own `bun run build` — `bun build --target=bun`, express inlined — and copies `dist/index.js`), sets `OPENCOMPANY_BUN_BIN` / `BUN_INSTALL=<userData>/bun` / `BUN_INSTALL_CACHE_DIR` and prepends the bundled bun dir (then uv) to PATH for the backend (`env.ts`; `OPENCOMPANY_NODE_BIN` no longer exists), provisions the venv into Electron `userData` on first launch with `uv sync --frozen --python <bundled>` (stamp = sha256 of uv.lock + pyproject + Python + uv versions; falls back to `uv python install 3.12`), pre-warms `PYTHONPYCACHEPREFIX` (with a prefix set Python ignores in-tree .pyc — 32 s vs 3 s first boot), spawns uvicorn on `127.0.0.1:5678` (persisted port; attaches to a running `company serve` instead of double-spawning), waits on `/health/ready`, loads the backend-served SPA (zero frontend changes), routes `window.open` / `_blank` to the OS browser. Quit = `POST /api/desktop/shutdown` + stdin EOF, 30 s, then tree-kill. electron-builder: NSIS x64, DMG+zip arm64/x64, AppImage+deb x64, unsigned first (`mac.identity: null`; macOS auto-update notify-only until signed — Squirrel.Mac refuses unsigned). CI: `desktop-release.yml` (tag-triggered: `prepare` drafts the GitHub Release from the annotated tag's message, three legs build and upload version-less OS-named installers such as `OpenCompany-windows-x64.exe` / `OpenCompany-macos-arm64.dmg` / `OpenCompany-linux-x86_64.AppImage` so the README can link `releases/latest/download/<file>`, each leg refuses a desktop version that differs from the tag, `finalize` undrafts) and `desktop-ci.yml` (typecheck/unit/invariants/Playwright smoke). **Gotcha: editor-hosted terminals export `ELECTRON_RUN_AS_NODE=1`, which makes Electron boot as plain Node (`electron.app` undefined) — strip it before launching; the e2e test does.** |-| **[Desktop Host Contract](./docs-internal/desktop_host_contract.md)** | The backend's side of being owned by a GUI shell. `core/approot.py` is the ONE module that locates the app tree (`OPENCOMPANY_APP_ROOT` / `OPENCOMPANY_CLIENT_DIST` / `OPENCOMPANY_ENV_FILE` / `OPENCOMPANY_ENV_TEMPLATE`); `tests/test_no_root_climb.py` forbids any other `Path(__file__).parents[N]` climb above `server/` and any `"client"/"dist"` / `.env.template` / `package.json` path join. `core/env_defaults.apply_file_defaults_to_environ()` does the CLI's `.env.template < .env < process env` layering at the top of `main.py`, and `Settings.env_file` is the absolute `(template, .env)` tuple — so a shell spawns `python -m uvicorn` from any cwd without the CLI package. Desktop mode (`OPENCOMPANY_DESKTOP=1`, `core/desktop.py`): parent-PID watchdog with create-time PID-reuse guard, stdin-EOF watchdog (polling via `PeekNamedPipe`/`select`, never a blocking read — a daemon thread parked in `ReadFile` at finalisation crashed exit with 0xC0000005), ctypes Job Object so children die with the backend (no pywin32 in the server venv), token-gated `POST /api/desktop/shutdown` (`routers/desktop.py`, public path; raises the signal uvicorn handles so the lifespan reaps Temporal/the bun sidecar/edgymeow), 45 s hard deadline. `GET /health/ready` (public) = DB up AND (Temporal disabled OR worker manager started), with `phase` written by `services/temporal/lifecycle.py` (`installing_temporal` / `starting_temporal` / `connecting` / `starting_workers` / `ready`). Plugin shutdown hooks now run under a 10 s per-hook timeout (`HOOK_TIMEOUT_SECONDS`), and the browser hook reads the module singleton instead of `get_browser_service()`, which lazily ran the `agent-browser` package install (`npm install` at the time; `bun add` via `core/js_runtime.add_package` today) AT SHUTDOWN and wedged every graceful exit (masked under the CLI by its 5 s grace + tree-kill). `server/uv.lock` is committed; `predeploy.yml` runs `uv lock --check`. |+| **[Desktop Host Contract](./docs-internal/desktop_host_contract.md)** | The backend's side of being owned by a GUI shell. `core/approot.py` is the ONE module that locates the app tree (`OPENCOMPANY_APP_ROOT` / `OPENCOMPANY_CLIENT_DIST` / `OPENCOMPANY_ENV_FILE` / `OPENCOMPANY_ENV_TEMPLATE`); `tests/test_no_root_climb.py` forbids any other `Path(__file__).parents[N]` climb above `server/` and any `"client"/"dist"` / `.env.template` / `package.json` path join. `core/env_defaults.apply_file_defaults_to_environ()` does the CLI's `.env.template < .env < process env` layering at the top of `main.py`, and `Settings.env_file` is the absolute `(template, .env)` tuple — so a shell spawns `python -m uvicorn` from any cwd without the CLI package. Desktop mode (`OPENCOMPANY_DESKTOP=1`, `core/desktop.py`): parent-PID watchdog with create-time PID-reuse guard, stdin-EOF watchdog (polling via `PeekNamedPipe`/`select`, never a blocking read — a daemon thread parked in `ReadFile` at finalisation crashed exit with 0xC0000005), ctypes Job Object so children die with the backend (no pywin32 in the server venv), token-gated `POST /api/desktop/shutdown` (`routers/desktop.py`, public path; raises the signal uvicorn handles so the lifespan reaps Temporal/the bun sidecar/edgymeow), 45 s hard deadline. `GET /health/ready` (public) = DB up AND (Temporal disabled OR worker manager started), with `phase` written by `services/temporal/lifecycle.py` (`installing_temporal` / `starting_temporal` / `connecting` / `starting_workers` / `ready`). Plugin shutdown hooks now run under a 10 s per-hook timeout (`HOOK_TIMEOUT_SECONDS`), and the current browser hook uses `peek_browser_runtime()` so shutdown never constructs or installs the runtime. Historical incident: the retired `get_browser_service()` lazily installed agent-browser at shutdown and wedged graceful exit (masked under the CLI by its 5 s grace + tree-kill). `server/uv.lock` is committed; `predeploy.yml` runs `uv lock --check`. || **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and the composite setup action (bun via SHA-pinned `oven-sh/setup-bun` reading the root `packageManager` pin + Node 22 as a CI-only convenience so bun runs vite / vitest / eslint on it via their node shebangs + Python 3.12 + uv; `bun install --frozen-lockfile` everywhere; publish is `bun publish --access public` after a `bun pm whoami` credential preflight with `~/.npmrc` written from `NPM_TOKEN` — no npm CLI, no `setup-node` in the publish jobs, and npm provenance attestation went away with npm). Also **Cutting a release**: the annotated tag is the version and its message is the release notes; `company version sync vX.Y.Z` bumps every version file for the `chore(release)` commit the tag sits on, and `desktop-release.yml` drafts the GitHub Release from the tag message and refuses a version that differs from the tag || **[Performance](./docs-internal/performance.md)** | Cold-start measurements (Application startup complete 2.90 s warm, 21.5 s cold post-`company clean` — was 71 s before the 2026-07-14 boot-delay fixes; first WS connect 8.29 s) + warm and cold per-phase timelines + optimisation history (lazy LangChain imports, lazy LLM-SDK exception refs, pre-bundled sidecar (esbuild at the time, `bun build --target=bun` today), bytecode-at-build, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`, Vite dep-cache preservation, off-loop Temporal build-id hash) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce (incl. eager SDK import at LLM provider registration, unconditional `.vite` wipe, synchronous `Worker()` on the event loop). Pairs with the build-time pipeline doc below. || **[Release Build Pipeline](./docs-internal/release_build_pipeline.md)** | Build pipeline for the registry tarball (installed with `bun add -g`; bun is the only JavaScript runtime and package manager anything shipped needs): `typescript@7` (native Go compiler, exact-pinned in **root** devDependencies — client keeps `typescript@^5.x` because typescript-eslint's peer range excludes 6/7, and one manifest cannot declare `typescript` twice) for type-check, measured 5.9× faster than tsc 5.9.3 (820 ms vs 4830 ms); `bun run --filter react-flow-client typecheck` delegates up to the root gate, Vite `manualChunks` + `target: 'es2022'`, `bun build --target=bun` sidecar bundle (self-contained `dist/index.js` with express inlined, run as `bun dist/index.js`; drops the `tsx` interpreter cost and needs no `node_modules` at runtime), bytecode pre-compile in two halves — `[tool.uv] compile-bytecode = true` (uv sync compiles `.venv/` site-packages) + `python -m compileall` for project source (plain `.pyc`, **no `-O`** — per PEP 488 the non-`-O` runtimes never load `.opt-1.pyc`; excludes `.venv/`, `tests/`). Single source of truth for the bytecode-compile path list: `cli.commands.build.COMPILEALL_SOURCE_DIRS`. Dev PM is **[email protected]** (tracked text `bun.lock`, `bunfig.toml` pins the isolated linker, ranged security pins in top-level `overrides`); `company build` step [1/6] is `bun install`. |@@ -2719,7 +2720,7 @@ This function:- Supports TTL expiration and automatic cleanup of expired entries- **Conditional Redis (historical)**: the Docker Compose topology (Redis profiles, `scripts/docker.js` wrapper) is historical — see [docs-internal/deployment_legacy.md](./docs-internal/deployment_legacy.md)- **WebSocket Reconnect via PartySocket** (`partysocket/ws` from Cloudflare): native-WS-compatible class handles jittered exponential backoff, message replay (`maxEnqueuedMessages: 200`), and intentional-close (RFC 6455 §7.4.1 code 1000) automatically. Replaces the previous flat 3 s `setTimeout(connect, 3000)` loop. Reconnect envelope (`MIN_DELAY_MS: 250`, `MAX_DELAY_MS: 8000`, `GROW_FACTOR: 1.3`) lives in `client/src/lib/connectionConfig.ts`. The +12 s WS-drop-and-reconnect cycle observed under React Strict Mode is gone — verified across two consecutive cold launches with zero `Client disconnected` events through 130+ s of activity. See `docs-internal/performance.md` for measurements.-- **Docker image runs uvicorn, not `company serve`**: `docker/entrypoint.sh` writes the three secrets into `/data/opencompany.env` once (the container env's value when set there, else a random one), then execs the desktop shell's uvicorn argv (`--timeout-graceful-shutdown 5`, port resolved through `core.env_defaults`). `company serve` would need root `node_modules` + the CLI venv, ignores `OPENCOMPANY_ENV_FILE`, and its supervisor tree-kills the backend 5 s after SIGTERM. `HOST` stays `127.0.0.1` (the backend dials itself at `ws://HOST:PORT/ws/internal`); the external bind is the `--host 0.0.0.0` argument. The image has no Node: `/usr/local/bin/node` links to bun, so the `#!/usr/bin/env node` bin scripts (agent-browser, vercel, cf) run. With the `browser` extra, Debian's `/usr/bin/chromium` launcher resets `CHROMIUM_FLAGS` from the environment and reads flags only from `/etc/chromium.d/` (hence the `no-sandbox` drop-in; Chrome refuses to run as root otherwise), and `AGENT_BROWSER_EXECUTABLE_PATH=/usr/bin/chromium` points agent-browser at it. The compose project is named `opencompany-selfhost` so it never merges with another compose project called `opencompany`. See [docker.md](./docs-internal/docker.md).+- **Docker image runs uvicorn, not `company serve`**: `docker/entrypoint.sh` writes the three secrets into `/data/opencompany.env` once (the container env's value when set there, else a random one), then execs the desktop shell's uvicorn argv (`--timeout-graceful-shutdown 5`, port resolved through `core.env_defaults`). `company serve` would need root `node_modules` + the CLI venv, ignores `OPENCOMPANY_ENV_FILE`, and its supervisor tree-kills the backend 5 s after SIGTERM. `HOST` stays `127.0.0.1` (the backend dials itself at `ws://HOST:PORT/ws/internal`); the external bind is the `--host 0.0.0.0` argument. The image has no Node: `/usr/local/bin/node` links to bun, so the `#!/usr/bin/env node` bin scripts (vercel, cf) run. Historical browser-image setup used Debian Chromium and `AGENT_BROWSER_EXECUTABLE_PATH` for agent-browser; that variable does not configure the current managed Browser runtime. Pinned Chrome for Testing/browser-use installation and deployment requirements are documented in [Browser](./docs-internal/browser.md). The compose project is named `opencompany-selfhost` so it never merges with another compose project called `opencompany`. See [docker.md](./docs-internal/docker.md).- **Configurable Authentication**: `VITE_AUTH_ENABLED` environment variable- Set to `false` to bypass login entirely (useful for local development)- Frontend creates anonymous user with owner privileges when disabled@@ -2755,7 +2756,7 @@ This function:- **`NodeUserError` (services.plugin)**: typed exception for user/LLM-correctable failures (string not found, command not found, bad cwd, missing required field, operator-only Twitter query, Python sandbox `import`, JS executor sidecar down). `BaseNode.execute()` catches it specifically: single WARN line in the operator log (no traceback) + structured `{success: False, error_type: "NodeUserError", error: ...}` envelope. Genuine bugs still flow through the generic `except Exception` branch and keep their full stacktrace via `logger.exception`. Adopted across `fileRead` / `fileModify` / `fsSearch` / `gallery` / `process_manager` / `pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`. **Plugin WS handlers that can fail user-correctably must use `@ws_response` (from `services.plugin.ws`), not `@ws_handler`** — the latter logs every exception at ERROR with a full traceback, which breaks the one-WARN-line `NodeUserError` contract. `gallery/_handlers.py` is the reference. Reach for it whenever the LLM (or user) can fix the input and retry — never for actual server bugs.- **Process manager Windows shim resolution**: `process_service.start()` resolves `argv[0]` via `shutil.which()` before `asyncio.create_subprocess_exec`. On Windows, `shutil.which` honours `PATHEXT` and returns the absolute path including the extension (e.g. a `C:\...\npm.cmd` for a generic `.cmd` shim; the shims bun writes for the plugin CLIs in the shared packages tree are `<name>.exe` launchers plus a `<name>.bunx` file, never `.cmd`); `CreateProcessW` then launches it directly. No `cmd /c` wrap — same canonical idiom used by `nodes/browser/`, `nodes/agent/claude_code_agent/_pool.py`, `nodes/agent/claude_code_agent/_oauth.py`, `nodes/email/_himalaya.py`. Without this, bare `argv[0]="npm"` raises `WinError 2` because `CreateProcessW` does NOT apply `PATHEXT` to bare names. Missing binary → early `Command not found: '<bin>'. Check spelling or ensure the binary is on PATH.` envelope (no traceback).- **Gallery — the workspace file explorer (`gallery`, `nodes/filesystem/gallery/`)**: sibling of the process-manager pattern below — the `isGalleryPanel` uiHint gives it a full-height MiddleSection panel (breadcrumbs, grid/list, image thumbnails, search, preview, upload) instead of the plain params list. It pairs the hint with `hideInputSection` but **keeps** the Output section, because unlike `processManager` it produces output worth seeing and dragging. Four rules worth knowing before touching it: (1) **The panel edits the node's own params** — navigating writes `path`, pinning writes `selection` — so what you browse is what the node emits, rather than a second copy of that state free to drift. (2) **The backend decides; the panel renders.** Each listing row arrives with a finished `ref` (a serialized `FileRef`, `null` for directories) and a `preview` verdict from `services/media/preview.py`; breadcrumbs arrive as `crumbs`; a search term is turned into a glob by `search_to_pattern` server-side. Re-deriving any of these client-side would be a second copy of a server rule — and for `preview` specifically, a second copy of a *security* decision. (3) **Drag uses its own `workspaceFile` discriminator, never the existing `nodeOutput`** — that branch calls `onChange(value)` unconditionally, so reusing it would mean dropping a file into a half-written prompt destroys the prompt. `ParameterRenderer.handleDrop` therefore branches: a `file` param takes the ref whole, everything else appends the path with smart spacing. (4) **`isFileRef` accepts every `FileKind`, not just `audio`** — the gallery emits `kind: "file"` even for a `.wav`, because `kind: "audio"` asserts `inspect_audio` probed the container and a fabricated duration would mis-bill a per-second provider downstream; narrowing the check back would render a dropped file as raw JSON. Listing rides the WebSocket (`list_workspace_files`) because the consumer already holds an authenticated socket with request correlation; `GET /api/workspace/{id}/files/{path}` stays the *content* channel (preview, download, Range). Frontend: [GalleryPanel.tsx](./client/src/components/parameterPanel/GalleryPanel.tsx) + `parameterPanel/gallery/`, [useDragWorkspaceFile.ts](./client/src/hooks/useDragWorkspaceFile.ts), [types/workspaceFiles.ts](./client/src/types/workspaceFiles.ts).-- **Canvas — the pushed-content display board (`canvas`, `nodes/tool/canvas/`)**: the third full-height-panel sibling (gallery / processManager / canvas), and the first with a SECOND host — a docked resizable right sidebar ([CanvasDock.tsx](./client/src/components/ui/CanvasDock.tsx) + [canvasDockStore.ts](./client/src/stores/canvasDockStore.ts)) that auto-opens on push and serves ephemeral click-to-preview from the gallery dialog. Both hosts render one shared component ([parameterPanel/canvas/CanvasContent.tsx](./client/src/components/parameterPanel/canvas/CanvasContent.tsx)), as does Home's Workspace dock, a third host. Rules worth knowing before touching it: (1) **The broadcast is identity-only** — `canvas_updated` carries `{workflow_id, node_id, revision}`; content flows solely through the authorized `canvas_list` handler (simple_memory security preamble: external socket + owner + graph-ownership, exactly-one-node-of-type check). (2) **The board stores references, never bytes** — `display(paths=…)` builds refs via `resolve_media` + stat (never `coerce_file_param`; don't read content to make a pointer), notes cap at 64KB with a visible marker, the board FIFO-caps at 200, and the op's Output is ids+counts only. (3) **Iframe sandboxes are test-locked security decisions**: external URLs get exactly `sandbox="allow-scripts allow-forms"` + `no-referrer`; workspace HTML renders ONLY as `srcDoc` + `sandbox="allow-scripts"` (opaque origin, no cookies — `NEVER_INLINE` respected, not worked around); PDF is a plain same-origin iframe enabled by the `INLINE_EXACT` exact-match set in `preview.py`. (4) **Never `addEventListener('canvas_updated')`** — the WebSocketContext switch case shadows the default-case fan-out. (5) The `tool` group auto-derives `isConfigNode: True`; canvas declares it `False` because `input-main` is real dataflow. (6) `hooks/useWorkspaceText.ts` is the repo's first client-side file-content fetch (streamed, cancelled at 512KB, key self-busts on `size_bytes`+`modified_at`) — attachment disposition doesn't block `fetch()`. Browser screenshots became its feedstock: both browser plugins persist shots as workspace FileRefs via the tolerant, containment-checked [nodes/browser/_screenshots.py](./server/nodes/browser/_screenshots.py). Full reference: [docs-internal/canvas_node.md](./docs-internal/canvas_node.md).+- **Canvas — the pushed-content display board (`canvas`, `nodes/tool/canvas/`)**: the third full-height-panel sibling (gallery / processManager / canvas), and the first with a SECOND host — a docked resizable right sidebar ([CanvasDock.tsx](./client/src/components/ui/CanvasDock.tsx) + [canvasDockStore.ts](./client/src/stores/canvasDockStore.ts)) that auto-opens on push and serves ephemeral click-to-preview from the gallery dialog. Both hosts render one shared component ([parameterPanel/canvas/CanvasContent.tsx](./client/src/components/parameterPanel/canvas/CanvasContent.tsx)), as does Home's Workspace dock, a third host. Rules worth knowing before touching it: (1) **The broadcast is identity-only** — `canvas_updated` carries `{workflow_id, node_id, revision}`; content flows solely through the authorized `canvas_list` handler (simple_memory security preamble: external socket + owner + graph-ownership, exactly-one-node-of-type check). (2) **The board stores references, never bytes** — `display(paths=…)` builds refs via `resolve_media` + stat (never `coerce_file_param`; don't read content to make a pointer), notes cap at 64KB with a visible marker, the board FIFO-caps at 200, and the op's Output is ids+counts only. (3) **Iframe sandboxes are test-locked security decisions**: external URLs get exactly `sandbox="allow-scripts allow-forms"` + `no-referrer`; workspace HTML renders ONLY as `srcDoc` + `sandbox="allow-scripts"` (opaque origin, no cookies — `NEVER_INLINE` respected, not worked around); PDF is a plain same-origin iframe enabled by the `INLINE_EXACT` exact-match set in `preview.py`. (4) **Never `addEventListener('canvas_updated')`** — the WebSocketContext switch case shadows the default-case fan-out. (5) The `tool` group auto-derives `isConfigNode: True`; canvas declares it `False` because `input-main` is real dataflow. (6) `hooks/useWorkspaceText.ts` is the repo's first client-side file-content fetch (streamed, cancelled at 512KB, key self-busts on `size_bytes`+`modified_at`) — attachment disposition doesn't block `fetch()`. The current Browser node persists screenshots as workspace FileRefs via the containment-checked [nodes/browser/_screenshots.py](./server/nodes/browser/_screenshots.py); the live Browser workspace has its own binary stream. Full reference: [docs-internal/canvas_node.md](./docs-internal/canvas_node.md).- **Process manager port admission + middle panel**: server commands declare listener `ports` (with compatibility inference for `--port`, `-p`, `PORT`, and `*_PORT`). `ProcessService.start()` serializes admission, checks managed reservations plus OS TCP listeners, and returns structured `PORT_IN_USE` without killing the owner or allowing framework auto-port fallback. Explicit ports/environment survive restart. The `isProcessManagerPanel` UI hint gives only `processManager` a full-height workflow-scoped process table with PID/ports/timestamps/elapsed/output and stop/restart controls. See [docs-internal/process_manager.md](./docs-internal/process_manager.md).- **Telegram message auto-split + caption spill**: the Bot API caps `sendMessage.text` at 4096 and media captions at 1024 (constants `_TG_TEXT_LIMIT` / `_TG_CAPTION_LIMIT` in `nodes/telegram/_service.py`; per https://core.telegram.org/bots/api). **Both limits are measured in UTF-16 code units, not characters** — an emoji costs 2 — so length goes through `_tg_len`, never `len()`. `_split_head` cuts one chunk at the cleanest paragraph → line → sentence → space boundary past the halfway mark, else hard-cuts; `_split_text` loops it. `send_message` chunks long text and threads each part under the previous (`reply_to_message_id` cascade), returning the first message's metadata + `parts` + `message_ids[]`. `_send_captioned_media` (used by `send_photo` / `send_document`) truncates an over-long caption at the cap and sends the remainder as a threaded reply with `disable_notification=True`, reporting `caption_truncated` + `follow_up_message_ids` — previously the whole send just failed with `BadRequest("Message caption is too long")`. **Ordering invariant: split the RAW body before `_resolve_body` runs markdown→HTML.** Splitting after conversion can separate a `<b>` from its closing tag, which Telegram rejects with "can't find end of the entity"; Telegram measures the cap against entity-parsed text, so truncating raw markdown is conservative. Locked by `tests/nodes/test_telegram_service.py`.- **Telegram inbound content types**: `_format_message` extracts detail dicts for all 11 types via the `_CONTENT_PROBES` / `_DETAIL_EXTRACTORS` tables, plus a normalized `media` block (`kind` / `file_id` / `mime_type` / `file_name` / …) that downstream nodes read instead of branching per type; MIME and filename are synthesised where Telegram omits them. **Probe order is load-bearing**: Telegram sets `message.document` on animation messages too, so `animation` and `video_note` must be probed before `document` and `video` or every GIF classifies as a document. The trigger never downloads — media travels as a `file_id`, never bytes or base64, because node results are persisted, broadcast, and replayed into the LLM conversation every turn.@@ -2776,7 +2777,7 @@ This function:- **Telegram owner detection — three layers** (f746ddf): the bot owner is captured by THREE independent paths so the realistic setup flows all converge to a working state. (1) **Explicit field**: secondary `FieldDef` in the credentials modal lets the user paste their Telegram user ID directly (recommended; works without DM'ing the bot). (2) **Pre-poll peek** in `connect()` via `_capture_owner_from_pending_updates()` — calls `bot.get_updates(timeout=0)` BEFORE `start_polling(drop_pending_updates=True)` discards the queue, scans for any historical private DM, captures + persists atomically. (3) **Atomic write-through in `_on_message_received`** — persists FIRST, sets in-memory ONLY on success. Invariant: "in-memory has owner ⇒ DB has owner" so a process restart can re-capture cleanly. Failure logged at `ERROR` with `exc_info=True` (was `WARNING` previously, masking persist failures). The lazy fallback in `telegram_send.py` (read DB → `service.set_owner`) sits on top of all three.- **Supervisor Job Object loud-failure (cli/tree.py + cli/supervisor.py)** (8a64eb9): the Windows process-tree mechanism depends entirely on a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (no fallback — `start_new_session` is POSIX-only). `pywin32>=308` is a hard supervisor dependency on Windows; the declaration in the root `pyproject.toml` (where `opencompany-cli` lives — `cli/pyproject.toml` was removed as a stale duplicate) carries an inline comment so future maintainers don't drop it. `_JobObject.__init__` splits failures into explicit `ImportError` (with reinstall command) and `Exception` (with `repr`) branches — both write to `stderr` instead of swallowing. `_JobObject.add()` verifies enrollment via `win32job.IsProcessInJob(handle, self._handle)` after assignment; on mismatch it queries `IsProcessInJob(handle, None)` so the warning explicitly names the wrapper-job hypothesis (npm / bun / conhost wrappers occasionally place us in their own non-nesting Job). `supervisor._spawn_once` checks `add_to_job` return value and emits a yellow `WARN: pid=N not enrolled in Job Object` per child if False. Without these guards, a stale pywin32 install or a wrapping Job Object silently leaks orphan Python processes on every Ctrl-C and they accumulate to the point of holding SQLite locks that block subsequent backend startup.- **Credentials envelope-shape invariant** (dc94cde): the `useCredentialPanel` query stores `{values: CredentialFormValues, hadStored: boolean}` (an envelope, NOT a flat dict). The earlier `writeValues` called `setQueryData<CredentialFormValues>` with a spread `(prev) => ({...prev, [key]: value})`, which at runtime merged the typed character at the envelope level next to `values` and `hadStored` instead of inside `.values` — the input selector `panel.values[field.key]` re-rendered with the original (server) value on every keystroke and the input felt frozen. Fix: `writeValues` now preserves the envelope shape and updates only the inner `values` dict; `hadStored` is preserved verbatim (it reflects real server state, not local edits). When introducing other queries shaped as `{data, meta}` envelopes, follow the same pattern — never spread `prev` as if it were the inner payload.-- **`core.paths` is the SSOT for on-disk locations**: only generic helpers (`data_path` / `packages_dir` / `package_dir(name)` / `daemons_dir` / `workspaces_dir` / `workspace_dir(workflow_id)` / `example_workflows_dir`). Plugin-specific subpaths are composed inline at the plugin's call site — adding a new package never requires touching `core.paths`. Reference subtree under `opencompany_root()` (= `~/.opencompany/` per default `DATA_DIR`): `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state — composed as `data_path("claude")` in `nodes/agent/claude_code_agent/_oauth.py`), `packages/` (OpenCompany-managed install root). `packages/` holds a **single shared, bun-managed packages tree** — one `package.json` + `bun.lock` + `node_modules/` covering every OpenCompany-managed npm-registry package (`@anthropic-ai/claude-code`, `edgymeow`, `agent-browser`, `cf`, `vercel`). Each plugin's `_install.py` calls `core.js_runtime.add_package(spec, trust=...)`, which runs `bun add --cwd <packages_dir> --no-progress [--trust] <spec>` and extends the shared tree idempotently (`ensure_shared_tree()` writes the minimal private manifest first); `bun_binary()` resolves bun from `OPENCOMPANY_BUN_BIN` or PATH, and `shared_tree_bin(name)` returns the shim at `node_modules/.bin/<name>` on POSIX or `<name>.exe` (plus a `<name>.bunx` file) on Windows. The shims run on the bun runtime — no Node or npm anywhere on this path (bun ignores a package's `engines.node`, and shims `node` for the lifecycle scripts it is allowed to run). bun blocks dependency lifecycle scripts unless trusted, so `trust=True` is passed only where a postinstall materialises something the plugin needs: claude-code (stages its native launcher), edgymeow (downloads the Go binary), agent-browser. Binaries that are not npm-registry packages (Stripe CLI, Temporal CLI) sit under sibling subdirs `packages/stripe/`, `packages/temporal/` via `package_dir(name)`. Also under `<DATA_DIR>/`: `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`, and the model-registry caches `local_models.json` (models registered from the user's own LLM servers) / `litellm_models.json` (LiteLLM's model table, RFC-0003 D16). Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("OpenCompany")` (`~/.cache/OpenCompany/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("opencompany-temporal")` namespace — operators reported both as "not local". The WhatsApp Go bridge (`edgymeow`) used to be a top-level pnpm dep at `<repo>/node_modules/edgymeow/`; now OpenCompany-managed via `nodes/whatsapp/_install.py` like the other CLIs. Daemon cwds used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya — system package manager). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.opencompany/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `company clean` and stay at the same path across `DATA_DIR=~/.opencompany` vs `DATA_DIR=.opencompany` configs.+- **`core.paths` is the SSOT for on-disk locations**: only generic helpers (`data_path` / `packages_dir` / `package_dir(name)` / `daemons_dir` / `workspaces_dir` / `workspace_dir(workflow_id)` / `example_workflows_dir`). Plugin-specific subpaths are composed inline at the plugin's call site — adding a new package never requires touching `core.paths`. Reference subtree under `opencompany_root()` (= `~/.opencompany/` per default `DATA_DIR`): `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state — composed as `data_path("claude")` in `nodes/agent/claude_code_agent/_oauth.py`), `packages/` (OpenCompany-managed install root). `packages/` holds a **single shared, bun-managed packages tree** — one `package.json` + `bun.lock` + `node_modules/` covering every OpenCompany-managed npm-registry package (`@anthropic-ai/claude-code`, `edgymeow`, `cf`, `vercel`). Each plugin's `_install.py` calls `core.js_runtime.add_package(spec, trust=...)`, which runs `bun add --cwd <packages_dir> --no-progress [--trust] <spec>` and extends the shared tree idempotently (`ensure_shared_tree()` writes the minimal private manifest first); `bun_binary()` resolves bun from `OPENCOMPANY_BUN_BIN` or PATH, and `shared_tree_bin(name)` returns the shim at `node_modules/.bin/<name>` on POSIX or `<name>.exe` (plus a `<name>.bunx` file) on Windows. The shims run on the bun runtime — no Node or npm anywhere on this path (bun ignores a package's `engines.node`, and shims `node` for the lifecycle scripts it is allowed to run). bun blocks dependency lifecycle scripts unless trusted, so `trust=True` is passed only where a postinstall materialises something the plugin needs: claude-code (stages its native launcher), edgymeow (downloads the Go binary). The Browser runtime does not use this npm tree: its plugin-owned installers use `packages/chrome-for-testing/` and `packages/browser-use/` (see [Browser](./docs-internal/browser.md)). Binaries that are not npm-registry packages (Stripe CLI, Temporal CLI) sit under sibling subdirs `packages/stripe/`, `packages/temporal/` via `package_dir(name)`. Also under `<DATA_DIR>/`: `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`, and the model-registry caches `local_models.json` (models registered from the user's own LLM servers) / `litellm_models.json` (LiteLLM's model table, RFC-0003 D16). Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("OpenCompany")` (`~/.cache/OpenCompany/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("opencompany-temporal")` namespace — operators reported both as "not local". The WhatsApp Go bridge (`edgymeow`) used to be a top-level pnpm dep at `<repo>/node_modules/edgymeow/`; now OpenCompany-managed via `nodes/whatsapp/_install.py` like the other CLIs. Daemon cwds used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya — system package manager). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.opencompany/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `company clean` and stay at the same path across `DATA_DIR=~/.opencompany` vs `DATA_DIR=.opencompany` configs.- **`company clean` preserves `.opencompany/{workflows,deploy,packages}/`**: `cli/commands/clean.py` iterates the canonical `<repo>/.opencompany/` and pre-rebrand `<repo>/.machina/` roots and skips anything in `_OPENCOMPANY_KEEP = frozenset({"workflows", "deploy", "packages"})`. Wipes `claude/`, `workspaces/`, `*.db` as before. `workflows/` holds the shipped seed JSONs (git-tracked); `deploy/` holds Terraform state for LIVE cloud resources (only `company deploy destroy` removes it); `packages/` holds the OpenCompany-managed binaries (Temporal CLI ~114 MB, Stripe CLI, the shared bun packages tree) — re-fetchable but expensive, so clean+build cycles stay offline-safe cache hits. Test `cli/tests/test_clean.py::test_opencompany_keep_preserves_workflows_deploy_and_packages` locks the keep-list.- **No raw `print()` outside three sanctioned helpers**: `main._startup_log` (pre-logger boot markers), `core.container._clog` (DI-bootstrap markers), and `nodes.code.python_executor.captured_print` (the sandbox builtin handed to user code). Everything else goes through `logger = get_logger(__name__)`. The supervisor prefixes every aggregated line with `[HH:MM:SS.fff]` so no inner `TimeStamper` is needed; structlog console mode is deliberately timestamp-less. Test `server/tests/test_no_raw_prints.py` AST-walks the tree and flags any unsanctioned `print(...)` call.- **`configure_logging(settings)` must run BEFORE plugin self-registration imports**: in `main.py`, `Settings()` + `configure_logging(settings)` + `init_tracing()` + `get_logger(__name__)` happen ahead of `from core.container import container` and `from routers import …`. Otherwise plugin folders that register on import call `logger.debug(...)` while structlog is still on its default processor chain (which includes `TimeStamper` + no `filter_by_level`) — symptom is double timestamps + debug records leaking despite `LOG_LEVEL=INFO`.diff --git a/README.md b/README.mdindex ca4c54d4..3908063b 100644--- a/README.md+++ b/README.md@@ -131,6 +131,7 @@ Nothing here is a black box. What an employee learns lives in its memory, its no- **Connections** to Gmail, Google Calendar, Drive, Sheets, Tasks, Contacts, Microsoft 365, any email account, WhatsApp, WhatsApp Business, Telegram, Discord, X, Stripe, GitHub, Vercel, Cloudflare, Google Cloud, your Android phone, a browser, web search, scrapers, and a knowledge base: 140+ tools in all.- **Models** from OpenAI, Anthropic, Google, xAI, DeepSeek, Kimi, Mistral, Groq, Cerebras, Sarvam, and OpenRouter, or run local models for free with Ollama, LM Studio, or any OpenAI-compatible server such as llama.cpp or vLLM.+- **A live browser workspace** in Home and Dev mode: watch an employee browse, take control to sign in or help, then hand control back. Browser profiles keep sessions between tasks. [Browser runtime](docs-internal/browser.md) | [Workspace interface](docs-internal/browser_workspace.md).- **Speech and translation**, so employees can listen, talk, and work in other languages.- **78 skills** that ship ready to use, and a place to drop your own.- **Built to keep running.** Employees survive restarts, pause and resume from Home or the canvas, and catch up on missed schedules. Your API keys are stored encrypted on your machine. Add a login for shared or cloud use; one command deploys to Google Cloud.diff --git a/docs-internal/browser.md b/docs-internal/browser.mdnew file mode 100644index 00000000..8025403f--- /dev/null+++ b/docs-internal/browser.md@@ -0,0 +1,123 @@+# Native browser runtime++The `browser` node runs a managed Chrome for Testing profile. Agents use the+browser-use CLI for ordinary browser operations; people watch and control the+same Chrome through the [Browser workspace](./browser_workspace.md). The old+agent-browser driver and separate `browserHarness` node are retired.++## Execution paths++| Path | Implementation | Lifetime |+| --- | --- | --- |+| Agent and workflow operations | `nodes/browser/browser/__init__.py` → `_scripts.py` / `_cli.py` → browser-use → Chrome CDP | A CLI subprocess per operation; Chrome and the profile's CLI daemon persist |+| WebMCP tools | `_webmcp.py` through the runtime's CDP connection | Tracked per page/frame, subject to saved node policy |+| Live picture | `_stream.py` → `Page.startScreencast` → binary `/ws/browser` frames | One capture hub per running profile, bounded queues per viewer |+| Human input | `_live_control.py` → dedicated page CDP session | One ordered command worker per hub; independent of CLI and capture resizing |+| Session and profile requests | `_handlers.py` over the application's authenticated request socket | Resolve ownership and saved node settings before opening sessions |++The native viewer is a streamed Chrome surface. Canvas URL items continue to+use sandboxed iframe previews. Neither displaying a Canvas URL nor attaching a+viewer silently starts a browser; **Start browser** explicitly opens an idle+session. Normal and Dev modes use the same viewer component.++## Installation and configuration++[`server/config/browser_runtime.json`](../server/config/browser_runtime.json)+is the version source of truth for Chrome for Testing, supported platforms,+download checksums and the browser-use CLI. The runtime ensures both tools+before launching a new Chrome process. Installation is shared and can outlive+the finite open request; the workspace polls installation status while waiting.++Chrome is installed under `<DATA_DIR>/packages/chrome-for-testing/`.+The CLI uses an isolated uv tool installation under+`<DATA_DIR>/packages/browser-use/`; it is not part of the shared Bun package+tree. `uv` must be available on PATH or through `OPENCOMPANY_UV_BIN`.++Runtime settings are declared in+[`server/core/config.py`](../server/core/config.py); stream diagnostics reads+its opt-in flag directly from the process environment:++| Setting | Default | Purpose |+| --- | --- | --- |+| `BROWSER_CHROME_PATH` | Empty | Use a supplied Chrome/Chromium executable instead of downloading the pinned browser |+| `BROWSER_MAX_INSTANCES` | `3` | Bound simultaneously running browser profiles |+| `BROWSER_IDLE_TIMEOUT_MS` | `600000` | Reap idle profiles; attached viewers and pending user work count as busy |+| `BROWSER_INSTALL_TIMEOUT_SECONDS` | `900` | Bound installer work |+| `BROWSER_SANDBOX` | `auto` | Select `auto`, `on` or `off`; auto accounts for Linux root and restricted user namespaces |+| `OPENCOMPANY_BROWSER_DIAGNOSTICS` | Unset | Set to `1` for bounded, payload-free live-stream timing summaries |++`AGENT_BROWSER_EXECUTABLE_PATH` is a legacy driver setting and is not read by+the native installer. See [Docker](./docker.md) for the current image's browser+extra and explicit system-Chromium configuration. CDP stays internal to the+runtime; deploy the authenticated application socket, not an exposed Chrome+debugging endpoint.++## Profiles, ownership and control++Profile metadata is stored in the `browser_profiles` table. Chrome state is+under `<DATA_DIR>/browser/profiles/<profile-id>/user-data/`, with generated+directory IDs rather than user-supplied names. A saved `profile_id` selects an+owner-scoped profile; leaving it empty creates/reuses the workflow's profile.+The CLI receives its own per-profile home, runtime and temporary directories.++The server derives identity from the authenticated caller and the saved+workflow. Browser discovery uses the plugin's `isBrowserPanel` hint, not a+second frontend list of browser type names. The node's profile, read-only mode,+WebMCP permissions, domain restrictions and private-network permission come+from saved operator settings, not model-supplied tool arguments.++`ProfileController` coordinates the profile lease and agent operation lock.+**Take control** waits for or interrupts an agent step before granting user+ownership. Human commands carry viewer and page generations and are checked+again immediately before CDP dispatch. **Hand back**, hiding, blur and+disconnect stop admission, discard stale queued work, settle dispatched work+and release held keys/buttons before the agent can resume. If a timed-out CDP+command has an unknown outcome, safe hand-back retires the managed Chrome; if+that fails, control remains held rather than resuming the agent prematurely.++The policy proxy in `_egress.py` enforces allowed destinations for browser+traffic. `allow_private_network` does not permit OpenCompany's protected ports+or cloud metadata endpoints. This network enforcement is separate from the+control lease and from agent read-only behavior.++## Node contract and compatibility++The tool schema exposes navigation, snapshots, element interaction, screenshots,+tabs, page reading, waits, WebMCP, user assistance and diagnostics. Workflow-only+`evaluate`, `run_python` and `close` are excluded from the model's tool schema.+See the [browser node flow](./node-logic-flows/web_automation/browser.md) for+operation and output details.++Snapshots return compact `[eN]` references; their backend node-ID mappings stay+on the server. Screenshot output is a workspace `FileRef`, never inline image+bytes or an unservable absolute host path. The screenshot helper copies the+CLI's contained temporary PNG into the workflow workspace and removes the+temporary file; persistence failure produces a notice.++[`services/workflow_migrations.py`](../server/services/workflow_migrations.py)+contains the legacy browser-node migration. `BrowserParams` also normalizes+legacy parameters from saved deployment snapshots. Use the current `browser`+node for new graphs; the [retired harness reference](./browser_harness.md)+exists to direct older links to the current implementation.++## Troubleshooting and validation++- **No Browser node listed:** save the workflow and browser node first. Normal+ mode discovers nodes from the employee summary; Dev mode observes hydrated+ node-schema hints.+- **First launch is slow:** inspect `browser_runtime_status` for installer+ progress and use `diagnose` for runtime/host details. Cold installation and+ warm live-view latency are separate measurements.+- **Frames stop or the view disconnects:** use Reconnect. Screencast attachment+ retries at 1, 2 and 4 seconds; authentication and target failures require+ explicit correction. Details and diagnostics are in+ [Browser workspace](./browser_workspace.md#live-view-latency-and-diagnostics).+- **Agent steps are slow but manual input is responsive:** each ordinary agent+ operation still starts a CLI process and can wait for page readiness. The+ stream changes do not replace that path or prove its latency improved.++Backend regression tests live in `server/tests/nodes/browser/`; viewer and+workspace tests live beside their client components. The+[local benchmark](./browser_workspace.md#reproducible-local-benchmark) exercises+real Chrome/CDP and production stream code with an isolated reference canvas.+Its recorded Chrome 153 results are not a full React or pinned-Chrome benchmark.diff --git a/docs-internal/browser_harness.md b/docs-internal/browser_harness.mdindex e08d5347..ca02699a 100644--- a/docs-internal/browser_harness.md+++ b/docs-internal/browser_harness.md@@ -1,56 +1,15 @@-# Browser Harness (browser-use/browser-harness)+# Browser Harness — historical integration-Wave 19 integration of [browser-use/browser-harness](https://github.com/browser-use/browser-harness) — a minimal (~1,000 LoC, MIT, **alpha**) Python CDP bridge that drives the user's **real Chrome** with no Playwright and no bundled Chromium. Sibling of the `browser` node (agent-browser), **not** a replacement.+The separate `browserHarness` node and its external-Chrome integration have been retired. The supported node and agent tool are both named `browser`.-## Architecture+Current documentation:-```-browserHarness node ──> BrowserHarnessService.run_code(code)- │ (subprocess: pipe Python to CLI stdin; CLI exits after exec)- ▼- browser-harness CLI ──IPC──> daemon (detached, persists)- │ │ AF_UNIX (POSIX) / token-auth TCP loopback (Windows)- │ ▼- │ one CDP WebSocket- ▼ ▼- stdout (result) user's Chrome-```+- [Native browser architecture](browser.md): managed Chrome, persistent profiles, installation, CDP, policy and runtime lifecycle.+- [Browser node flow](node-logic-flows/web_automation/browser.md): operations, operator settings, dispatch, outputs and legacy migration.+- [Browser workspace](browser_workspace.md): live viewing, frame delivery, direct input and human control.-- **Plugin**: [`server/nodes/browser/browser_harness/`](../server/nodes/browser/browser_harness/) — `_install.py` (uv tool install → `<DATA_DIR>/packages/browser-harness/{tools,bin}`, lazy on first use), `_service.py` (subprocess wrapper + `NodeUserError` mapping + daemon shutdown hook), `__init__.py` (`BrowserHarnessNode`).-- **Node ops**: `run_python` (primary — Python piped verbatim to the CLI, executed against ~25 pre-imported helpers), plus `goto` / `screenshot` / `js` / `tabs` shortcuts and `doctor` diagnostics. `task_queue=BROWSER`, `usable_as_tool=True`, `tool_name="browser_harness"`.-- **Skill**: [`server/skills/web_agent/browser-harness-skill/SKILL.md`](../server/skills/web_agent/browser-harness-skill/SKILL.md) — the see→act→verify loop (`capture_screenshot` → `click_at_xy` → `wait_for_load` → `js` fallback), helper reference, print-JSON-last convention.-- **State isolation**: `BH_RUNTIME_DIR` + `BH_TMP_DIR` are pinned to `<DATA_DIR>/daemons/browser-harness/` on every spawn — daemon pid/port/sock + screenshots + logs never land in the user-global `~/.config/browser-harness/`.-- **Windows**: verified working (2026-07-10 spike) — upstream `_ipc.py` uses AF_UNIX on POSIX and **token-authenticated TCP loopback on Windows**; daemon detaches with `CREATE_NO_WINDOW`.+The current runtime manages its own Chrome rather than requiring an already running, logged-in personal Chrome. Agent/workflow operations use generated scripts through the isolated, pinned browser-use CLI and its persistent daemon; WebMCP and live viewer capture/control have native CDP paths. The presence of browser-harness machinery inside that dependency is separate from the retired OpenCompany node.-## Chrome prerequisite+[Saved-workflow migration](../server/services/workflow_migrations.py) renames `browserHarness` to `browser` and maps `goto` to `navigate`, `js` to `evaluate`, `doctor` to `diagnose`, and `tabs` to tab listing. Existing Python code is retained with a helper-compatibility warning. `evaluate` and `run_python` are now workflow-only; duplicate Browser tool edges created by migration are removed with a warning. See the node flow for complete parameter compatibility behavior.-The harness needs a CDP-reachable Chrome, discovered in this order (upstream `daemon.py`):-1. `BU_CDP_URL` / `BU_CDP_WS` env override (dedicated automation Chrome) — passed through from the OpenCompany process env untouched.-2. `DevToolsActivePort` written by Chrome when the user enables **chrome://inspect/#remote-debugging** ("Allow remote debugging for this browser instance").-3. Port probe on 9222/9223 (e.g. `chrome --remote-debugging-port=9222`).--The node's `doctor` operation runs `browser-harness doctor` and returns the full checklist — the first thing to try when calls fail with connection guidance.--## vs the `browser` node (agent-browser)--| | `browser` (agent-browser) | `browserHarness` |-|---|---|---|-| Engine | npm-registry CLI (`agent-browser`, `bun add`ed into the shared packages tree and run on bun) + bundled Chrome-for-Testing (or system browser) | user's real Chrome over raw CDP |-| Interaction | accessibility tree, `@eN` refs | screenshots + coordinate clicks + `js()` |-| Sessions | named sessions, instance cap, idle timeout | one shared browser (daemon-held CDP socket) |-| Agent surface | 15 structured operations | freeform Python against helpers |-| Maturity | stable, Windows-tested | **alpha (v0.1.x)** |--Default to `browser`; reach for `browserHarness` when the task needs the user's logins/profile, bot-hostile or shadow-DOM-heavy sites, iframes (`iframe_target`), or raw CDP.--## Security caveats (know before enabling widely)--- Upstream is **alpha**; the HN launch thread reported an unaddressed RCE and prompt-injection exposure. The `run_python` op executes agent-authored Python **outside** the Monty sandbox (same trust level as `pythonExecutor`, but with the user's real browser attached).-- It drives the user's real, logged-in Chrome — the skill instructs agents to never touch accounts/purchases beyond the explicit task, but treat the node as `destructive + open_world` (its annotations say so).-- Node is visible in **dev mode only** (not in `enabled_nodes` — same posture as `browser`).--## Ops notes--- Install is lazy: first use runs `uv tool install --python 3.12 browser-harness` (requires `uv` on PATH — already a OpenCompany toolchain dependency).-- Daemon shutdown: FastAPI lifespan runs the `browser_harness` shutdown hook → kills the daemon via `<DATA_DIR>/daemons/browser-harness/bu.pid`.-- Upgrades: delete `<DATA_DIR>/packages/browser-harness/` and let the next use reinstall, or run the CLI's `--update`.+Do not use the old service paths, installation commands, remote-debugging setup or Python helper examples from this document's history as current setup instructions. Runtime dependency pins are maintained in [`server/config/browser_runtime.json`](../server/config/browser_runtime.json).diff --git a/docs-internal/browser_workspace.md b/docs-internal/browser_workspace.mdindex 7e0f27b6..ca684a73 100644--- a/docs-internal/browser_workspace.md+++ b/docs-internal/browser_workspace.md@@ -1,5 +1,9 @@# Browser workspace+For installation, profiles, policy and agent execution, see the+[native browser runtime](./browser.md). This document describes the shared+workspace surface and its live-stream contract.+Normal mode and Dev mode share `components/workspace/WorkspaceTabs.tsx`(Browser, Canvas, Android) and `components/browser/BrowserWorkspace.tsx`.The Dev toolbar's Workspace button opens the existing resizable dock;@@ -49,15 +53,30 @@ visibility changes or reconnecting can attempt attachment again.## Live-view latency and diagnosticsThe browser socket's receive loop handles frame ACKs without awaiting page-commands. Input commands use a bounded scheduler; pointer moves and wheel-updates coalesce, while click/key transitions retain ordering. Control release,+commands. Each profile's ordered scheduler holds at most 64 commands and+64 KiB of serialized queued messages. Only adjacent pointer moves or compatible+wheel events coalesce; wheel coordinates, button state and modifiers must match.+Click/key transitions retain ordering. Overflow reports an error and starts a+safe release instead of silently dropping a key-up or click. Control release,disconnect and page changes invalidate pending input. Input has its own CDPsession so resizing the screencast does not detach an active input command.+Release immediately blocks additional input. It then settles the dispatched+command and releases held keys/buttons before handing control back. A cancelled+takeover cannot later authorize a hidden viewer. Unknown CDP outcomes require+retiring the managed browser before agent work resumes; failure to retire keeps+control held. Pointer cancellation, window blur and hidden documents also+request release. The server is authoritative for these barriers.+Each viewer retains the newest unsent frame when its FPS limit is reached,then sends it when the limit allows. The final update must be delivered evenwhen the page stops producing frames. Viewer ACKs identify an outstandingsequence number; duplicate or unknown ACKs do not open additional credit.+Sequences remain unique across replacement hubs on a surviving viewer socket.+The client bounds decoding to two frames, acknowledges skipped frames and+updates canvas backing dimensions only when the image size changes. Frames+being decoded during disconnect, hiding or stream invalidation cannot repaint+an obsolete live view.Chrome screencast ACKs are tracked per event and per capture session, ratherthan replacing an earlier unacknowledged event with the newest one. The hubacknowledges each capture after admitting it to bounded viewer slots; it does@@ -172,5 +191,9 @@ benchmark script: 283e28a5afa86c16370e39b989b8d800462b940d1e81f6755f29bded129ahydration and viewer unmount on close.- `server/tests/nodes/browser/test_browser_stream.py`: fake-CDP startup failurerecovery and cancellation.+- `server/tests/nodes/browser/test_browser_frame_delivery.py`: trailing frames,+ independent viewer credit, duplicate ACKs, capture replacement and diagnostics.+- `server/tests/nodes/browser/test_browser_live_control.py`: bounded input queues,+ responsive receive loop, takeover/release races, held-input cleanup and teardown.- `server/tests/services/employees/test_list_employees.py`: capability-basedbrowser discovery in employee summaries.diff --git a/docs-internal/canvas_node.md b/docs-internal/canvas_node.mdindex 2cad2485..098adc54 100644--- a/docs-internal/canvas_node.md+++ b/docs-internal/canvas_node.md@@ -300,11 +300,13 @@ back; navigating onto the last item resumes following). Arrow/Home/End keyswork on the focused `role="group"` only — no document-level listeners,which would fight React Flow node nudging.-**Follow-latest** (the browser-automation live view): when the active item+**Follow-latest** (workspace image polling): when the active itemis a workspace image, a Switch enables a visibility-gated 5 s poll of theexisting `list_workspace_files` handler on the image's folder, rendering thenewest image entry in place — zero new backend. Persisted as the dock's-`followMode` pref.+`followMode` pref. This is separate from the native Chrome stream in the+[Browser workspace](./browser_workspace.md), which supports live input and+explicit takeover without polling screenshot files.Renderer dispatch is a pure function([`canvasKinds.ts`](../client/src/components/parameterPanel/canvas/canvasKinds.ts)),@@ -369,14 +371,14 @@ truncation), `browserHarness` an absolute path underThe shared helper lands the bytes in the workflow workspace via`write_media(kind="image")` so a screenshot becomes a ~400 B `FileRef`:-- `persist_screenshot_from_payload(data, ctx, fmt)` (the `browser` node's- `screenshot` op): probes the known inline-base64 keys (only `"base64"` is- evidenced in-repo; the rest are tolerated probes) then saved-file-path- keys, returns `(ref, consumed_key)` so the caller drops exactly the bulky- field from the payload.-- `persist_screenshot_file(path, ctx, contained_under)` (the harness- `screenshot` op): reads **only** files contained under the harness runtime- dir — printed process output is not a licence to read arbitrary files.+- `persist_screenshot_file(path, ctx, contained_under)` is the current native+ `browser` screenshot path. The CLI writes a temporary PNG in its profile's+ temporary directory; the node copies it into the workspace, returns it in+ `BrowserOutput.screenshot`, then removes the temporary file. Reads must stay+ within that supplied directory.+- `persist_screenshot_from_payload(data, ctx, fmt)` remains a legacy payload+ helper with tests for inline-base64 and saved-file-path shapes. It is not+ the current native node's screenshot dispatch path.**Tolerance is the contract**: an unrecognized payload shape, a missingworkspace, or a write failure logs one warning and returns `None`; the@@ -392,7 +394,7 @@ browser operation itself never breaks over persistence. Sanity bounds| `server/config/node_allowlist.json` | `"canvas"` in `enabled_nodes` | Normal-mode palette visibility (positive list) || `server/tests/test_node_spec.py` | `"isCanvasPanel"` in the uiHints `known` set | The test's own failure message instructs this || `server/services/media/preview.py` + `server/tests/routers/test_workspace.py` | `INLINE_EXACT` / `"pdf"` | The PDF surface; `NEVER_INLINE` untouched |-| `server/nodes/browser/{browser,browser_harness}/__init__.py` | screenshot post-process | Plugin-folder edits of the browser plugins |+| `server/nodes/browser/browser/__init__.py` | screenshot post-process | Current native Browser plugin; the separate harness plugin is retired || `client/src/{types/INodeProperties.ts, types/workspaceFiles.ts, components/parameterPanel/MiddleSection.tsx, contexts/WebSocketContext.tsx, Dashboard.tsx, components/ui/TopToolbar.tsx, components/ui/ConsolePanel.tsx, components/parameterPanel/gallery/FilePreviewDialog.tsx}` | hint type, `'pdf'` PreviewKind, panel dispatch, `canvas_updated` case, dock mount, toggle, `usePanelResize` extraction, click-to-preview | The standard new-panel checklist + the dock integration |Notably **not** edited: `routers/websocket.py`, `main.py`,diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.mdindex ce45f7a2..6cc831b5 100644--- a/docs-internal/cli_agent_framework.md+++ b/docs-internal/cli_agent_framework.md@@ -8,6 +8,8 @@ Multi-instance, multi-provider runtime for AI CLI agents (Claude Code, Codex, Ge| OpenAI Codex (`@openai/codex`) | shipping (no login flow yet) | User runs `codex login` manually; UI returns a graceful "not yet wired" error || Google Gemini (`@google/gemini-cli`) | v2 stub | factory raises `NotImplementedError` |+Browser automation has its own managed Chrome and browser-use runtime; it is not installed into this bun package tree. See [browser.md](./browser.md) and [browser_workspace.md](./browser_workspace.md) for its lifecycle and live control surface.+## Architecture```@@ -236,7 +238,7 @@ Steps:1. Run `claude auth status`. If it exits 0, write the marker + broadcast and return immediately (idempotent re-click).2. Otherwise schedule `_finalize_claude_login()` (in `nodes/agent/claude_code_agent/_handlers.py`), which calls `run_claude_login()` from `_oauth.py`:- - OpenCompany-managed install of `@anthropic-ai/claude-code` into the shared packages tree at `<DATA_DIR>/packages/` via `core.js_runtime.add_package("<package_name>@<package_version>", trust=True)` — `bun add --cwd <packages_dir> --no-progress --trust <spec>` (same tree as `edgymeow` / `agent-browser` / `cf` / `vercel`; skipped if already installed; `--trust` because the package's postinstall stages its native launcher, which bun otherwise blocks). The exact version is pinned in `server/config/ai_cli_providers.json` (`package_version`, the vercel / cloudflare idiom) because the stream-json contract and flag surface are verified against that version only. Binary resolves to `<DATA_DIR>/packages/node_modules/.bin/claude[.exe]` and runs on bun — no Node or npm involved (claude-code 2.1.258 verified on bun with no Node on PATH).+ - OpenCompany-managed install of `@anthropic-ai/claude-code` into the shared packages tree at `<DATA_DIR>/packages/` via `core.js_runtime.add_package("<package_name>@<package_version>", trust=True)` — `bun add --cwd <packages_dir> --no-progress --trust <spec>` (same tree as `edgymeow` / `cf` / `vercel`; skipped if already installed; `--trust` because the package's postinstall stages its native launcher, which bun otherwise blocks). The exact version is pinned in `server/config/ai_cli_providers.json` (`package_version`, the vercel / cloudflare idiom) because the stream-json contract and flag surface are verified against that version only. Binary resolves to `<DATA_DIR>/packages/node_modules/.bin/claude[.exe]` and runs on bun — no Node or npm involved (claude-code 2.1.258 verified on bun with no Node on PATH).- `claude auth login` via `run_cli_command(..., env={..., CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/}, stdin=asyncio.subprocess.PIPE)` — same way the VSCode Claude Code extension delegates to the binary. Anthropic doesn't expose `--print-url` or a programmatic OAuth helper (issue [anthropics/claude-code#7100](https://github.com/anthropics/claude-code/issues/7100), closed "not planned"), so we let the CLI open the user's browser via its own OS-level call. `stdin=PIPE` is **load-bearing** for claude-code >= 2.1.162's native binary: it reads stdin while waiting for the browser callback, and an inherited (closed) stdin EOFs it into an early exit that kills the localhost callback server before the redirect arrives — `stdin=PIPE` (never written) makes the read block so the server stays up.3. Schedule a background task that polls `claude auth status` every 2s up to 600s. On exit-0, write the synthetic `"cli-managed"` marker via `auth_service.store_oauth_tokens("claude_code", ...)` and broadcast `credential_catalogue_updated`. The catalogue's `stored` flag flips and the existing `OAuthConnect.tsx` primitive renders the modal as Connected.diff --git a/docs-internal/desktop_host_contract.md b/docs-internal/desktop_host_contract.mdindex 4d5c5026..d1de0492 100644--- a/docs-internal/desktop_host_contract.md+++ b/docs-internal/desktop_host_contract.md@@ -172,11 +172,16 @@ The backend spawns exactly one JavaScript runtime, bun, and resolves it in oneplace: `core/js_runtime.py` (`OPENCOMPANY_BUN_BIN`, else `bun` on PATH). `uv`is resolved through `OPENCOMPANY_UV_BIN` / `shutil.which`. So the bundledruntime dirs prepended to PATH (plus the two overrides) satisfy the JS-executor sidecar (`nodes/code/_runtime.py`, `[bun, dist/index.js]`), the five+executor sidecar (`nodes/code/_runtime.py`, `[bun, dist/index.js]`), theplugin installers that `bun add` into the shared `<DATA_DIR>/packages/` tree-(claude-code, edgymeow, agent-browser, cf, vercel — `core.js_runtime.add_package`),+(claude-code, edgymeow, cf, vercel — `core.js_runtime.add_package`),the codex provider (`bun x @openai/codex` when no system `codex` exists), and-`uv tool install browser-harness`. `BUN_INSTALL` / `BUN_INSTALL_CACHE_DIR`+the Browser runtime's pinned `uv tool install browser-use==<pin>` installation.+The Browser installer respects `UV_TOOL_DIR` / `UV_TOOL_BIN_DIR`; otherwise it+uses `<DATA_DIR>/packages/browser-use/{tools,bin}`. OpenCompany separately+installs and supervises Chrome for Testing, with `BROWSER_CHROME_PATH` as the+explicit executable override. See [browser.md](./browser.md) and+[browser_workspace.md](./browser_workspace.md). `BUN_INSTALL` / `BUN_INSTALL_CACHE_DIR`keep bun's own cache and global state under the app's data dir rather than adev install's `~/.bun`. There is no Node in the bundle and nothing looks forone — `tests/core_config/test_js_runtime.py::test_backend_never_spawns_node_or_npm`diff --git a/docs-internal/docker.md b/docs-internal/docker.mdindex f119b6d3..abea84a4 100644--- a/docs-internal/docker.md+++ b/docs-internal/docker.md@@ -26,10 +26,12 @@ The default image has no browser, git or uv. Add them through the `EXTRAS` build| Extra | Installs | Needed by ||---|---|---|-| `browser` | Chromium, fonts, Xvfb, uv | The browser node; the browser-harness node, which installs itself with uv |+| `browser` | Chromium, fonts, Xvfb, uv | The current Browser node needs uv to install its pinned browser-use CLI; Chromium can be selected explicitly as described below || `git` | git | The Claude Code and Codex agent nodes, which work in git worktrees |-Without its extra, the browser node fails because the Chromium the image names (`AGENT_BROWSER_EXECUTABLE_PATH`) is not there, browser-harness reports that uv is missing, and Claude Code and Codex tasks fail with `working_directory_not_git_repo`.+Without the `browser` extra, the runtime image has no uv for the Browser node's tool installer or system Chromium and its libraries. The current node normally downloads its pinned Chrome for Testing; the image's legacy browser setting does not select system Chromium. Without the `git` extra, Claude Code and Codex tasks can fail with `working_directory_not_git_repo`.++The current runtime is documented in [browser.md](./browser.md), with live viewing and control in [browser_workspace.md](./browser_workspace.md). `browserHarness` is retired; browser-use is a dependency of the single `browser` node, not a second workflow node.## Where state lives@@ -65,13 +67,17 @@ The image sets these on top of the template:| `VITE_AUTH_ENABLED` | `true` | Login required || `NODEJS_EXECUTOR_HOST` | `127.0.0.1` | The code sidecar binds IPv4 loopback, which exists even where container IPv6 is off || `NODEJS_USER_PACKAGES_DIR` | `/data/nodejs-user-packages` | Packages installed for code nodes persist |-| `AGENT_BROWSER_EXECUTABLE_PATH` | `/usr/bin/chromium` | The browser node drives the `browser` extra's Chromium |+| `AGENT_BROWSER_EXECUTABLE_PATH` | `/usr/bin/chromium` | Legacy value still present in the Dockerfile; the current Browser runtime does not read it || `PYTHONUNBUFFERED` | `1` | Log lines reach `docker compose logs` as they are written |-The image has no Node. It links `/usr/local/bin/node` to bun, so the plugin CLIs whose entry scripts start `#!/usr/bin/env node` (agent-browser, vercel, cf) run on bun, as in the official oven/bun images.+**Browser configuration mismatch:** `docker/Dockerfile` still sets `AGENT_BROWSER_EXECUTABLE_PATH`, while `nodes/browser/_install_chrome.py` reads `BROWSER_CHROME_PATH`. To use the `browser` extra's Chromium, explicitly set `BROWSER_CHROME_PATH=/usr/bin/chromium` under compose `environment:`. Otherwise the runtime downloads its pinned Chrome for Testing. This documents the current image; it does not mean the Dockerfile has been migrated or the current browser runtime has been validated in that image.++The image has no Node. It links `/usr/local/bin/node` to bun, so the plugin CLIs whose entry scripts start `#!/usr/bin/env node` (vercel, cf) run on bun, as in the official oven/bun images. Browser automation installs browser-use through uv instead.With the `browser` extra: Chrome refuses to run as root with its sandbox on, so the image adds `--no-sandbox` through a drop-in, `/etc/chromium.d/no-sandbox`. Debian's launcher reads flags only from that directory and ignores a `CHROMIUM_FLAGS` environment variable. Debian's own `dev-shm` drop-in already adds `--disable-dev-shm-usage` when Docker's `/dev/shm` is small.+Those drop-ins apply to Debian's Chromium launcher. The current runtime launches headless Chrome itself, detects sandbox/shared-memory constraints, and supplies its own launch flags; it does not use the former agent-browser/Xvfb startup path.+Leave `HOST` and `PORT` at their template values. The backend uses `HOST` to reach itself; the published bind comes from the entrypoint's `--host 0.0.0.0`. `PORT` is repeated in the Dockerfile's `EXPOSE` and the compose mapping, which do not follow a change made in `/data/opencompany.env`. Publish only the app port: the code sidecar, the WhatsApp bridge and Temporal listen on internal ports without authentication.### Serving other machines@@ -100,7 +106,7 @@ With plain `docker run`, pass `--init` and `--stop-timeout 120` to get the same- **Temporal Web UI.** The dev server binds loopback inside the container, so its UI is not reachable from outside.- **Claude Code login.** The login button in the credentials panel waits for a browser callback on the container's own localhost, so it cannot finish. Log in from an interactive shell in the container (`docker compose exec opencompany sh`) with `CLAUDE_CONFIG_DIR=/data/claude` set, or supply `ANTHROPIC_API_KEY` through `environment:`. Codex has no login button at all; run its login from the same shell.- **Owner-checked panels under login.** The image always requires a login, and the editor saves workflows through a REST route that records the placeholder owner `owner` rather than the logged-in account. The Canvas, Memory, Context and dataSource panels check that owner, so they can refuse the logged-in user for such a workflow. `company deploy` VMs, which also require a login, behave the same.-- **A second browser download.** With the `browser` extra, the browser node's first run still downloads agent-browser's own Chrome for Testing (a few hundred MB) into the volume, though agent-browser then drives the system Chromium.+- **Browser image integration.** The image still carries the legacy executable setting and Xvfb. Unless `BROWSER_CHROME_PATH` is supplied, the current node downloads and runs its pinned Chrome for Testing despite system Chromium being installed. The pinned browser-use CLI is installed separately with uv. Validate the current runtime and its required Linux libraries in the built image; adding the extra alone is not evidence of an end-to-end browser check.- **Agent nodes need the `git` extra and a git repository.** Claude Code and Codex agents work in git worktrees, and the image contains no `.git`. Run `git init` in a workflow's workspace and make a first commit before pointing an agent at it. Set a commit identity once from a shell in the container (`git config --global user.name ...` and `user.email ...`); it is stored in `/data/home` and survives upgrades.- **Bind mounts.** A bind mount works in place of the named volume, but the Temporal CLI is then downloaded on first start (a new named volume receives the copy baked into the image), and the directory must allow executables, symlinks and Unix sockets. Prefer the named volume on Windows and macOS hosts.- **Memory.** Give the container at least 1 GB. At idle the backend holds about 180 MB of process memory and the Temporal dev server about 115 MB; `docker stats` shows up to about 450 MiB because it also counts the page cache of the code they run.diff --git a/docs-internal/errors.md b/docs-internal/errors.mdindex ff7d23e1..2446b901 100644--- a/docs-internal/errors.md+++ b/docs-internal/errors.md@@ -481,11 +481,17 @@ uv then downloads its 3.12 into `~/.local/share/uv`, the venvs are usable by the## 20. Graceful backend shutdown hangs, then the supervisor tree-kills it (Temporal / node / edgymeow orphaned)+**Historical browser implementation:** the `_service.py` and agent-browser+driver named below have been retired. The current+[native browser runtime](./browser.md) owns managed Chrome, CLI daemons and+live-stream tasks. This incident remains relevant to the rule that shutdown+must never lazily install or start a runtime.+**Symptom**: `company stop`, Ctrl+C, or the desktop app's quit takes the full grace window and ends in a tree-kill. With the lifespan markers (`Lifespan shutdown: ...` in stdout) the log stops after `proxy stopped`, or never prints `Lifespan shutdown begin` at all.**Root causes** (two, found while building the desktop shell; the CLI's 5 s grace + tree-kill had masked both):-1. `nodes/browser/_service.py::shutdown_browser_service` called `get_browser_service()`, which lazily runs the `agent-browser@latest` install on first call (`npm install` at the time; `bun add` via `core/js_runtime.add_package` today) — so a process that never used the browser ran a network install *at teardown*, synchronously on the event loop, and every graceful exit wedged there.+1. `nodes/browser/_service.py::shutdown_browser_service` called `get_browser_service()`, which lazily ran the `agent-browser@latest` install on first call (`npm install` at the time; that retired driver later used `bun add`) — so a process that never used the browser ran a network install *at teardown*, synchronously on the event loop, and every graceful exit wedged there.2. uvicorn's `timeout_graceful_shutdown` defaults to `None`: it waits forever for open connections and in-flight handler tasks before sending the lifespan shutdown. A browser WebSocket that disappears with a TCP reset (the tab or window closing) can leave its handler task lingering, and the lifespan teardown — the part that reaps the child daemons — is never reached.**Fix**: the browser hook reads its module singleton and closes only a service that was actually created; every plugin shutdown hook now runs under `HOOK_TIMEOUT_SECONDS` (10 s, `services/plugin/shutdown_hooks.py`) and names the offender at WARNING; `company serve` / `company start` and the desktop shell pass `--timeout-graceful-shutdown 5` (`cli/_common.py::UVICORN_GRACEFUL_SHUTDOWN_SECONDS`). Note that the hook timeout cannot interrupt a hook that blocks the loop synchronously — keep hooks async.diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex 91325dfc..2ceba50d 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -67,7 +67,7 @@ client/src/├── features/home/ # Normal mode (see docs-internal/normal_mode.md)│ ├── HomeShell.tsx # Sidebar + header + current view + Workspace dock + Settings + orb stage│ ├── sidebar/ header/ hire/ employee/ settings/ approvals/ data/ state/ ui/-│ ├── workspace/ # The Workspace dock; its Canvas tab loads in its own chunk+│ ├── workspace/ # Home Workspace dock; shared live Browser tab, lazy Canvas tab│ ├── genui/ # Setup-screen pipeline; only its index.ts is importable (ESLint)│ └── orb/ # orb.ts (state + lifecycle), orbEngine.ts (three.js, own chunk)│@@ -498,6 +498,14 @@ See [media_transport.md](./media_transport.md).(archived; it describes the retired pre-RFC-0002 markdown memory model).- **`currentWorkflowId` lives in `useAppStore` only.** Non-React listeners (WS handlers) read it via `useAppStore.getState().currentWorkflow?.id` -- the documented Zustand escape hatch (https://github.com/pmndrs/zustand#read-state-without-subscription). The previous `currentWorkflowIdRef` mirror inside WebSocketContext was a one-render-late copy that misrouted broadcasts during workflow switches. The push to `nodeStatusStore.setCurrentWorkflowId` is driven from a single `useEffect` in `Dashboard.tsx`.+## Browser workspace live view++Home and Dev share [WorkspaceTabs](../client/src/components/workspace/WorkspaceTabs.tsx) and [BrowserWorkspace](../client/src/components/browser/BrowserWorkspace.tsx). Browser nodes are discovered through the backend `isBrowserPanel` capability; viewing attaches to a saved workflow/node without launching Chrome. The Browser tab supports server-authorized Take control / Hand back for navigation, mouse, keyboard, paste and login. Canvas retains its renderer; Android remains an explanatory placeholder.++The viewer uses a separate authenticated same-origin `/ws/browser` socket, not the general `WebSocketContext` frame stream. Binary JPEG envelopes are decoded sequentially with a two-frame local bound; consumed/skipped frames are acknowledged. Canvas dimensions change only when image dimensions change, and input coordinates use the metadata of the frame actually painted. Hidden, disposed or obsolete frames cannot restore a stale picture. Blur, pointer cancellation, hiding and unmount release user control; the server owns the release barrier and lease checks.++`?browserStreamDebug=1` enables numeric first-frame/decode/draw summaries without recording page or input payloads. The [Browser workspace contract](./browser_workspace.md) describes identity, visibility and interaction; [Browser](./browser.md) owns runtime installation, profiles, security and capture/control internals. Tests live under `components/browser/__tests__`, with Home and Dev dock integration tests beside their hosts.+## Ownership boundary: TanStack Query vs Zustand vs WebSocketContextThis is the rule that keeps the data layer schema-driven instead of imperatively glued together.diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.mdindex c008d78d..def4ed66 100644--- a/docs-internal/node-logic-flows/README.md+++ b/docs-internal/node-logic-flows/README.md@@ -30,6 +30,12 @@ match its doc here, and each doc must still describe what the code does.## Index+For the current browser architecture, see [Browser runtime](../browser.md)+and [Browser workspace](../browser_workspace.md). The registered node is+`browser`; the `browserHarness` card is retained only as historical migration+documentation. Inclusion in this generated document index does not establish+that a retired node remains registered.+<!-- AUTO-GENERATED-INDEX-START -->### ai_agents@@ -223,7 +229,7 @@ match its doc here, and each doc must still describe what the code does.- [Apify Actor (`apifyActor`)](./web_automation/apifyActor.md)- [Browser (`browser`)](./web_automation/browser.md)-- [Browser Harness (`browserHarness`)](./web_automation/browserHarness.md)+- [Browser Harness (`browserHarness`) — retired](./web_automation/browserHarness.md)- [Crawlee Scraper (`crawleeScraper`)](./web_automation/crawleeScraper.md)- [TikHub (`tikhubAction`)](./web_automation/tikhubAction.md)diff --git a/docs-internal/node-logic-flows/_TEMPLATE.md b/docs-internal/node-logic-flows/_TEMPLATE.mdindex 05bdc679..2f8dd0c7 100644--- a/docs-internal/node-logic-flows/_TEMPLATE.md+++ b/docs-internal/node-logic-flows/_TEMPLATE.md@@ -85,7 +85,7 @@ flowchart TD## External Dependencies- **Credentials**: <provider key looked up via `auth_service.get_api_key('<provider>')`>-- **Services**: <e.g. WhatsApp RPC at `localhost:${WHATSAPP_RPC_PORT}`, agent-browser CLI>+- **Services**: <e.g. WhatsApp RPC at `localhost:${WHATSAPP_RPC_PORT}`, managed Browser runtime / browser-use CLI>- **Python packages**: <e.g. `httpx`, `xdk`, `apify-client`>- **Environment variables**: <if any>diff --git a/docs-internal/node-logic-flows/ai_tools/canvas.md b/docs-internal/node-logic-flows/ai_tools/canvas.mdindex 227430e2..2dfd0734 100644--- a/docs-internal/node-logic-flows/ai_tools/canvas.md+++ b/docs-internal/node-logic-flows/ai_tools/canvas.md@@ -108,5 +108,5 @@ flowchart TD## Related- **Skills using this as a tool**: none yet (a paired skill would need a `visuals.json` alias for tool name `canvas`).-- **Other nodes that consume this output**: none — the board is a sink; browser/browserHarness screenshot ops now persist workspace `FileRef`s (`nodes/browser/_screenshots.py`) precisely so this node can display them.-- **Architecture docs**: [media_transport.md](../../media_transport.md), [plugin_system.md](../../plugin_system.md), [status_broadcaster.md](../../status_broadcaster.md).+- **Other nodes that consume this output**: none — the board is a sink; the Browser node's screenshot operation persists workspace `FileRef`s (`nodes/browser/_screenshots.py`) so this node can display them. Live browser viewing and control use the separate Browser tab, not Canvas screenshot items.+- **Architecture docs**: [browser.md](../../browser.md), [browser_workspace.md](../../browser_workspace.md), [media_transport.md](../../media_transport.md), [plugin_system.md](../../plugin_system.md), [status_broadcaster.md](../../status_broadcaster.md).diff --git a/docs-internal/node-logic-flows/web_automation/browser.md b/docs-internal/node-logic-flows/web_automation/browser.mdindex 2c379140..e822e4ad 100644--- a/docs-internal/node-logic-flows/web_automation/browser.md+++ b/docs-internal/node-logic-flows/web_automation/browser.md@@ -1,244 +1,92 @@# Browser (`browser`)-| Field | Value |-|------|-------|-| **Category** | web_automation / tool (dual-purpose) |-| **Backend handler** | [`server/nodes/browser/browser/__init__.py::BrowserNode`](../../../server/nodes/browser/browser/__init__.py) — dispatch via `BaseNode.execute()` -> `@Operation("dispatch")` |-| **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` |--## Purpose--Interactive browser automation via the `agent-browser` CLI. The binary is a-OpenCompany-managed local install resolved by-[`nodes/browser/_install.py::agent_browser_binary_path`](../../../server/nodes/browser/_install.py)-(installed on first use with `bun add --trust` into the shared-`<DATA_DIR>/packages/` tree via `core.js_runtime.add_package`, the same pattern-as Claude Code's project-local CLI — NOT a workspace `package.json` dependency-and NOT invoked through `bun x`; the shim runs on the bun runtime). Exposes 14-discrete operations (navigate,-click, type, fill, screenshot, snapshot, get_text, get_html, eval, wait, scroll,-select, console, errors) plus a `batch` meta-op. The preferred workflow for an-AI agent is `navigate` -> `snapshot` -> `click`/`fill` using the stable `@eN`-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 `opencompany_<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)--| Handle | Connection type | Required | Purpose |-|--------|-----------------|----------|---------|-| `input-main` | main | no | Upstream trigger; not consumed directly |--## Parameters--Params model is `BrowserParams` (field names are snake_case). `tool_name` /-`tool_description` are class attributes (not Params fields).--| Name | Type | Default | Required | displayOptions.show | Description |-|------|------|---------|----------|---------------------|-------------|-| `operation` | options (Literal) | `navigate` | no | - | One of `navigate`, `click`, `type`, `fill`, `screenshot`, `snapshot`, `get_text`, `get_html`, `eval`, `wait`, `scroll`, `select`, `console`, `errors`, `batch` |-| `url` | string | `""` | yes (op=navigate) | `operation=navigate` | Target URL |-| `selector` | string | `""` | yes (ops that act on an element) | `operation in [click,type,fill,get_text,get_html,wait,select]` | CSS selector or `@eN` ref from snapshot |-| `text` | string | `""` | no | `operation=type` | Text to type keystroke-by-keystroke |-| `value` | string | `""` | no | `operation in [fill, select]` | Value to fill / dropdown option value |-| `expression` | string | `""` | yes (op=eval) | `operation=eval` | JS expression to evaluate |-| `direction` | options (Literal: up/down/left/right) | `down` | no | `operation=scroll` | Scroll direction |-| `amount` | int (1-20000) | `500` | no | `operation=scroll` | Pixels to scroll |-| `commands` | string (JSON array) | `"[]"` | yes (op=batch) | `operation=batch` | JSON array of batch command dicts piped to stdin |-| `full_page` | boolean | `false` | no | `operation=screenshot` | Passes `--full` |-| `annotate` | boolean | `false` | no | `operation=screenshot` | Passes `--annotate` |-| `screenshot_format` | options (Literal: png/jpeg) | `png` | no | `operation=screenshot` | Forwarded as `--screenshot-format` when not png |-| `screenshot_quality` | int (1-100) | `85` | no | `operation=screenshot, screenshot_format=jpeg` | Forwarded as `--screenshot-quality`, only for jpeg |-| `session` | string | `""` | no | - | Session id; if empty, handler uses `opencompany_<execution_id>` |-| `browser` | options (Literal) | `chrome` | no | - | `chrome` / `edge` / `chromium` / `bundled_explicit` / `custom`. Legacy/empty `bundled` silently upgraded to `chrome` at dispatch |-| `executable_path` | string | `""` | no | `browser=custom` | Explicit browser path when `browser=custom` |-| `headed` | boolean | `true` | no | - | Show browser window (false = headless `--headed` omitted) |-| `new_window` | boolean | `true` | no | - | Appended as `--args --new-window`; only honoured when an explicit `executable_path` resolved |-| `auto_connect` | boolean | `false` | no | - | Reuse an already-running CDP browser (`--auto-connect`) |-| `chrome_profile` | string | `""` | no | - | Chrome user-profile name |-| `user_agent` | string | `""` | no | - | Custom UA string |-| `proxy` | string | `""` | no | - | Proxy URL (e.g. `http://user:pass@host:port`) |-| `action_delay` | int (0-60000) | `0` | no | - | Milliseconds to wait before the real op (a pre-command `wait` is issued first) |-| `timeout` | int (1-600) | `30` | no | - | Per-action timeout in seconds |--Operations that **require** `selector`: `click`, `type`, `fill`, `get_text`,-`get_html`, `wait`, `select`.--## Outputs (handles)--| Handle | Shape | Description |-|--------|-------|-------------|-| `output-main` | object | Standard envelope payload |-| `output-tool` | object | Same payload when wired to an AI agent's `input-tools` (`usable_as_tool=True`, tool name `browser`) |--### Output payload--```ts-{- operation: string; // echoes the requested op- data: any; // Parsed JSON from agent-browser's first stdout line- session: string; // Resolved session id-}-```--Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time: number }`.-On failure: `{ success: false, error: <string>, execution_time: number }`.--## Logic Flow--```mermaid-flowchart TD- A[BaseNode.execute -> BrowserNode.dispatch] --> B{BrowserService<br/>available?}- B -- no --> Einst[Return error:<br/>agent-browser not installed]- B -- yes --> C[Resolve session, timeout, headed, browser,<br/>executable_path, proxy, userAgent,<br/>newWindow, chromeProfile, actionDelay]- C --> C1[Upgrade legacy 'bundled' -> 'chrome'<br/>_resolve_browser looks up shutil.which or Win registry]- C1 --> D{actionDelay > 0?}- D -- yes --> D1[svc.run wait actionDelay first]- D -- no --> E{op == batch?}- D1 --> E- E -- batch --> E1[json.loads commands -> stdin]- E1 --> F[svc.run batch --json + stdin=json]- E -- other --> G[_build_args op, params]- G --> Gsw{operation switch}- Gsw -- navigate --> Gn[args: open URL<br/>URL required]- Gsw -- click / wait --> Gc[args: op SELECTOR<br/>selector required]- Gsw -- type --> Gt[args: type SELECTOR TEXT]- Gsw -- fill / select --> Gf[args: op SELECTOR VALUE]- Gsw -- screenshot --> Gs[args: screenshot + --full/--annotate/--screenshot-format/--screenshot-quality]- Gsw -- snapshot --> Gsn[args: snapshot -i]- Gsw -- get_text / get_html --> Gg[args: get text-or-html SELECTOR]- Gsw -- eval --> Gev[args: eval EXPRESSION<br/>expression required]- Gsw -- scroll --> Gsc[args: scroll DIR AMOUNT]- Gsw -- console / errors --> Gco[args: op]- Gsw -- unknown --> Gx[raise ValueError<br/>Unknown operation]- Gn & Gc & Gt & Gf & Gs & Gsn & Gg & Gev & Gsc & Gco --> H[svc.run args, session, timeout, run_kw]- F --> H- H --> H1[Popen argv via resolved agent-browser binary<br/>shell=False, reads first JSON line of stdout]- H1 --> H2{first line<br/>parseable JSON?}- H2 -- yes --> H3[data = parsed JSON]- H2 -- no --> H4[data = output: raw string]- H3 & H4 --> I{length > 100KB?}- I -- yes --> I1[truncate + append '...truncated']- I -- no --> J[finally: psutil kill process tree]- I1 --> J- J --> K[Return BaseNode success envelope<br/>operation, data, session]- Gx --> Eval[ValueError -> BaseNode generic envelope]- H --> Eother[RuntimeError / NodeUserError -> BaseNode envelope]-```--## Decision Logic--- **Service missing**: `get_browser_service()` returns `None` when the- agent-browser binary cannot be resolved (bun unavailable, or the install failed)- -> `RuntimeError("agent-browser not installed...")` -> error envelope.-- **Session resolution**: empty `session` -> `opencompany_<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,- then Windows `HKLM/HKCU\\SOFTWARE\\...\\App Paths\\<exe>` registry. If neither- resolves, `executable_path=None` and agent-browser uses its own bundled Chrome.-- **`newWindow`**: gated on `executable_path` actually resolving - if a user- requests new-window while `browser=bundled_explicit`, the flag is silently- dropped.-- **`action_delay > 0`**: issues a `wait <action_delay>` command (milliseconds)- to agent-browser BEFORE the real operation. Failures in the delay call- propagate as errors.-- **`batch`**: reads `commands` JSON string (defaults to `"[]"`) and pipes- `json.dumps(cmds).encode()` to the subprocess' stdin with flags `batch --json`.-- **Required params**: `_req(p, "url")` and `_req(p, "expression")` raise- `NodeUserError` on empty strings; `_req_sel(s)` does the same for `selector`.- `BaseNode.execute()` catches `NodeUserError` into a single-WARN error envelope.-- **Unknown operation**: `_build_args` raises `ValueError("Unknown operation: <op>")`.--## Side Effects--- **Database writes**: none.-- **Broadcasts**: none.-- **External API calls**: none (all work happens via subprocess).-- **File I/O**: agent-browser itself may write screenshots or a profile dir to- its own cache - not under this handler's control.-- **Subprocess**: spawns the resolved `agent-browser` binary directly via- `subprocess.Popen` with `shell=False`. Reads only the FIRST stdout line- (daemon holds stdout open), caps at 100 KB, then force-kills the entire- process tree via `kill_tree(proc.pid)` (`services._supervisor.util`, psutil-backed).- Always calls `proc.wait()` in a finally block.- `AGENT_BROWSER_IDLE_TIMEOUT_MS` is injected into the spawn env when the idle- timeout is > 0.-- **Long-lived daemon**: agent-browser spawns a persistent daemon between- calls. `shutdown_browser_service()` (registered in FastAPI lifespan) runs- `agent-browser close --all` to stop it.--## External Dependencies--- **Credentials**: none.-- **Services**: `BrowserService` singleton; bun (`OPENCOMPANY_BUN_BIN` or PATH)- for the first-use install and as the shim's runtime; `agent-browser`- installed into the shared `<DATA_DIR>/packages/` tree by- `nodes/browser/_install.py` (OpenCompany-managed, not a workspace dep).-- **Python packages**: `psutil` (via `kill_tree` for process-tree kill).-- **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--- **Output truncation**: responses > 100 KB are truncated with a literal- `...(truncated)` suffix appended BEFORE `json.loads`, so a truncated JSON- payload falls through the `JSONDecodeError` path and returns- `{"output": "<raw truncated string>"}` instead of structured data.-- **Empty first line**: if agent-browser writes nothing to stdout the service- reads stderr and raises `RuntimeError` with the stderr content (or the- literal fallback `agent-browser returned empty output`).-- **Silent `bundled` -> `chrome` upgrade**: a user who saved a workflow when- `bundled` was the default will now actually use system Chrome on execution.-- **`newWindow` silently disabled**: see Decision Logic.-- **Exception handling is in `BaseNode.execute()`**: `NodeUserError` (empty- required field) -> single WARN + structured envelope; `ValueError` (unknown- op) / `RuntimeError` (service missing or empty stdout) / other exceptions ->- generic envelope with traceback. The plugin's `dispatch` itself does not- catch.-- **Process tree kill race**: `psutil.NoSuchProcess` is swallowed for both the- parent and every child, so a fast-exiting daemon never leaks an exception- but may leave orphaned Chromium processes if the tree changed shape between- the `children()` call and the `kill()` call.-- **`action_delay` (ms) is a separate call**: the preliminary `wait` runs as its- own subprocess invocation with its own `timeout` budget (each invocation- resets the timer).--## Related--- **Skills using this as a tool**: [`browser-skill/SKILL.md`](../../../server/skills/web_agent/browser-skill/SKILL.md)-- **Companion nodes**: [`crawleeScraper`](./crawleeScraper.md), [`apifyActor`](./apifyActor.md)-- **Architecture docs**: [Proxy Service](../../proxy_service.md)+The Browser node drives OpenCompany-managed Chrome and exposes the same profile to the live browser workspace. It runs as a workflow step or as the agent tool named `browser`. The old `agent-browser` integration and separate `browserHarness` node have been replaced.++See [native browser architecture](../../browser.md) for runtime installation, profile storage, networking and lifecycle, and [browser workspace](../../browser_workspace.md) for the viewer and UI protocol.++## Implementation map++| Responsibility | Source |+| --- | --- |+| Node schema, dispatch and output mapping | [`BrowserNode`](../../../server/nodes/browser/browser/__init__.py) |+| Plugin registration and shutdown | [`nodes/browser/__init__.py`](../../../server/nodes/browser/__init__.py) |+| Profile runtime and managed Chrome | [`_runtime.py`](../../../server/nodes/browser/_runtime.py), [`_chrome.py`](../../../server/nodes/browser/_chrome.py) |+| Agent/workflow CLI calls and generated scripts | [`_cli.py`](../../../server/nodes/browser/_cli.py), [`_scripts.py`](../../../server/nodes/browser/_scripts.py) |+| Leases and control state | [`_session.py`](../../../server/nodes/browser/_session.py) |+| Direct live viewer capture and input | [`_stream.py`](../../../server/nodes/browser/_stream.py), [`_live_control.py`](../../../server/nodes/browser/_live_control.py) |+| Saved-workflow compatibility | [`workflow_migrations.py`](../../../server/services/workflow_migrations.py) |++The node has main input/output handles and a tool output handle. Its `ui_hints.isBrowserPanel` flag makes it discoverable as a browser panel. Activities use the `BROWSER` task queue, at most three Temporal attempts, and a 35-minute start-to-close timeout to accommodate human handoff.++## Operations++The agent schema defaults to `snapshot`; saved workflow parameters default to `navigate`.++| Operations | Important inputs and behavior |+| --- | --- |+| `navigate` | Requires `url`; validates destination policy before opening. |+| `snapshot` | Accessibility-tree text with `[eN]` references; `interactive_only` and `max_chars` limit output. Refresh after page changes. |+| `click`, `hover`, `type`, `select` | Target by `ref`, CSS `selector`, or supported coordinates. `type` uses `text`, `clear` (default true), and optional `submit`; `select` uses `values`. |+| `press` | `key` plus CDP modifier bitmask: Alt 1, Ctrl 2, Meta 4, Shift 8. |+| `scroll` | `direction` and `amount` (default 600). |+| `screenshot` | Optional `full_page`; persists an image to the workspace and returns a FileRef. |+| `tabs` | `tab_action`: `list`, `new`, `switch`, or `close`; `url`/`tab_id` as appropriate. |+| `back`, `forward`, `reload` | History/reload operations on the active tab. |+| `page_text`, `page_info` | Extract bounded page text or page information. |+| `wait` | `wait_for`: `load`, `network_idle`, `selector`, `text`, or `time`; optional `wait_value`. |+| `webmcp_list`, `webmcp_call` | Discover page-provided tools or invoke `webmcp_tool` with `webmcp_input` and optional `frame_id`. |+| `request_user` | Human handoff using `reason` and `message`. |+| `diagnose` | Runtime, host and profile diagnostics without starting Chrome. |+| `evaluate`, `run_python`, `close` | **Workflow-only**: saved `expression`, saved `code`, or stop the profile. Excluded from the agent tool schema and rejected on tool calls. |++Refs resolve against a backend-node-ID map held per target, not against model-provided executable code. The legacy selector spelling `@eN` is accepted as a ref. A missing ref raises an error asking for a fresh snapshot.++## Execution flow++1. Read operator configuration. For agent calls, reread the saved node settings so tool arguments cannot override the profile, policy, timeouts or executable code.+2. Reject workflow-only operations from agent calls and operations prohibited by `interaction`. Refuse automatic retries of operations in the node's `MUTATING` set when Temporal reports attempt greater than one; the previous action may already have occurred.+3. Resolve the owner's profile: explicit `profile_id`, otherwise the workflow's persistent default profile. Unsaved runs have a separate fallback. Register a session identified by owner, workflow and node, associated with that profile.+4. Handle `close` and `diagnose` without opening a new runtime. Other operations open or reuse the profile runtime, installing managed dependencies on first use if needed.+5. `request_user` enters the human-handoff flow. Other operations acquire the profile's agent-operation lease/lock; human control blocks agent work.+6. `webmcp_list` reads the native tracker's tool cache; `webmcp_call` invokes through the native CDP integration. Remaining operations use a generated Python script sent to the isolated browser-use CLI, whose daemon persists across calls and connects to managed Chrome.+7. Update active target, URL/title and snapshot refs from the result. Map output to the node schema and emit page/session changes. CLI daemon failure permits one retry for operations outside `MUTATING`; operations inside that set are not retried by this wrapper.++The profile is persistent across executions; it is not the old execution-ID-named CLI session. Closing it stops the shared profile runtime, so other views of that profile observe the closure.++## Policy and control++Operator settings include `profile_id`, `interaction` (`full` or `read_only`), `webmcp_mode` (`disabled`, `read_only`, `all`), `allowed_domains`, `allow_private_network`, `op_timeout_s` (default 45, range 5–300), and `request_user_timeout_s` (default 600, range 60–1800). They are server-controlled for tool calls.++The current `MUTATING` set is exactly `click`, `type`, `press`, `select`, `back`, `forward`, `reload`, `webmcp_call`, `evaluate`, and `run_python`. `read_only` rejects this set. It does not prohibit navigation, scrolling, hovering or tab operations. In particular, `webmcp_call` is rejected by `interaction=read_only` before its tool-level read-only metadata is considered; `webmcp_mode=read_only` with full interaction is the setting that admits advertised read-only WebMCP tools.++Empty `allowed_domains` allows public destinations. The managed egress proxy checks destinations and resolved addresses for browser traffic; private-network access is disabled by default. Enabling it does not allow cloud metadata or OpenCompany's own protected ports. See the canonical runtime document for policy details.++Control states are `idle`, `agent`, `awaiting_user`, and `user`. `request_user` includes instructions for login, CAPTCHA, two-factor authentication, confirmation or another manual step. Agent calls wait at most 480 seconds per handoff call; a longer configured pending request can return `still_waiting` and be awaited by another call. Workflow steps can wait for the configured deadline.++The authenticated live viewer attaches through `/ws/browser` to a saved workflow/node or a profile-login session. Watching does not grant control. Takeover, handback, visibility and disconnect are coordinated with the profile controller. Live mouse/keyboard/navigation commands use a bounded ordered queue and direct CDP, independently of the subprocess CLI path used by node operations. Frame acknowledgements and visibility messages remain responsive while commands run. Handback settles dispatched input and releases held keys/buttons before agent work resumes. See [browser workspace](../../browser_workspace.md) for frame delivery and frontend lifecycle.++## Output and failures++Outputs can include `operation`, `session_id`, profile name, `url`, `title`, `tab_id`, `snapshot`, `text`, `truncated`, screenshot FileRef, tabs, WebMCP tools/results, handoff result, `data`, and `notice`. Screenshot bytes are not embedded in node output; saving failure produces a notice. `run_python` may return the final 20,000 characters of captured script output.++Policy rejection, stale refs, missing required fields, disallowed operations and failed CLI results surface as node errors. An uncertain mutating attempt asks the caller to inspect a snapshot before trying again. Installation/runtime errors and control contention are distinct from an empty page snapshot.++## Legacy workflows++Saved-workflow normalization and the parameter model's compatibility validator cover older representations, including deployed snapshots. The retired node type `browserHarness` becomes `browser`; if this creates two same-named browser tools attached to one agent, migration keeps the original browser tool edge and drops the duplicate migrated edge with a warning.++| Legacy input | Current mapping |+| --- | --- |+| `browserHarness`: `goto`, `js`, `doctor` | `navigate`, `evaluate`, `diagnose` |+| `browserHarness`: `tabs` | `tabs` with `tab_action=list` |+| `browserHarness`: `run_python` | Code retained with a warning to check changed helper names. |+| `fill` | `type`, `clear=true`, text from legacy `value` or `text`. |+| Legacy `type` | Defaults `clear=false` when unspecified. |+| `get_text`, `get_html`, `eval` | `page_text`, `evaluate` with an HTML expression, `evaluate`. |+| `wait` with selector | `wait_for=selector`, `wait_value` from selector when mode was absent. |+| `select` with `value` | Single-item `values` when absent. |+| `console`, `errors` | `page_info`, with a warning. |+| `batch` | `run_python` containing the original commands as comments and an explicit error requiring a rewrite. |+| Numeric `timeout` | `op_timeout_s`, clamped to 5–300 when no replacement exists. |++Old agent-browser runtime settings such as `session`, `headed`, `executable_path`, `chrome_profile`, `proxy`, `user_agent`, `auto_connect` and `action_delay` are removed by migration. Nonempty profile/proxy/executable/user-agent settings produce warnings. The harness-specific branch retains other fields but they do not restore the former external-Chrome attachment behavior. Review migrated executable operations: `evaluate` and `run_python` are now workflow-only.diff --git a/docs-internal/node-logic-flows/web_automation/browserHarness.md b/docs-internal/node-logic-flows/web_automation/browserHarness.mdindex 1165ec57..25b7fd5e 100644--- a/docs-internal/node-logic-flows/web_automation/browserHarness.md+++ b/docs-internal/node-logic-flows/web_automation/browserHarness.md@@ -1,146 +1,15 @@-# Browser Harness (`browserHarness`)+# Browser Harness (`browserHarness`) — retired-| Field | Value |-|------|-------|-| **Category** | browser / tool (palette group `browser`; sibling of the stable `browser` node, not a replacement) |-| **Backend handler** | [`server/nodes/browser/browser_harness/__init__.py::BrowserHarnessNode.dispatch`](../../../server/nodes/browser/browser_harness/__init__.py) (dispatch via `BaseNode.execute()` + `@Operation("dispatch")`; plugin folder: [`_service.py`](../../../server/nodes/browser/browser_harness/_service.py) subprocess wrapper + daemon shutdown hook, [`_install.py`](../../../server/nodes/browser/browser_harness/_install.py) uv-tool installer; screenshot persistence shared with `browser` in [`nodes/browser/_screenshots.py`](../../../server/nodes/browser/_screenshots.py)) |-| **Tests** | [`server/tests/nodes/test_browser_harness.py`](../../../server/tests/nodes/test_browser_harness.py) (`TestBrowserHarnessNode`, `TestBrowserHarnessService`) |-| **Skill (if any)** | [`server/skills/web_agent/browser-harness-skill/SKILL.md`](../../../server/skills/web_agent/browser-harness-skill/SKILL.md) (`allowed-tools: browserHarness`) |-| **Dual-purpose tool** | yes - tool name `browser_harness` (`usable_as_tool = True`) |+`browserHarness` is no longer a registered node or agent tool. Use the current [Browser node flow](browser.md), [native browser architecture](../../browser.md), and [browser workspace](../../browser_workspace.md).-## Purpose+The replacement `browser` node launches OpenCompany-managed Chrome with persistent owned profiles. The live viewer and human takeover use the native CDP path. Most agent/workflow operations still use the pinned browser-use CLI and its daemon internally; this dependency does not restore the old node or its real-Chrome attachment model.-Drives the user's **real, logged-in Chrome** over raw CDP through the-`browser-harness` CLI (browser-use/browser-harness, PyPI, alpha). The-upstream driving model is "the LLM writes Python against ~25 pre-imported-helpers", so the primary operation is `run_python`: the snippet is piped-verbatim to the CLI's stdin and executed against helpers such as-`goto_url`, `click_at_xy`, `capture_screenshot`, `js`, `fill_input`,-`wait_for_load`, `list_tabs`, `page_info`. The other operations are-one-helper shortcuts generated as Python text, plus `doctor`, which runs the-CLI's own Chrome/CDP diagnosis. Reach for it when a task needs the user's-own profile/session state, canvas- or shadow-DOM-heavy or bot-hostile-sites, or raw CDP; default to the accessibility-tree `browser` node-otherwise.+[Workflow migration](../../../server/services/workflow_migrations.py) rewrites saved `browserHarness` nodes to `browser`:-## Inputs (handles)+- `goto` becomes `navigate`; `js` becomes `evaluate`; `doctor` becomes `diagnose`.+- `tabs` becomes `tabs` with `tab_action=list`.+- Numeric `timeout` becomes `op_timeout_s`, clamped to 5–300 seconds when no new value is present.+- `run_python` code remains, with a warning to check changed helper names. Both `run_python` and `evaluate` are now workflow-only, not agent tool operations.+- If the same agent already has a Browser tool, migration removes the duplicate migrated tool edge with a warning.-| Handle | Connection type | Required | Purpose |-|--------|-----------------|----------|---------|-| `input-main` | main | no | Upstream data for template substitution into `code` / `url` / `expression` |-| `output-tool` (source, synthesized) | tools | no | The class declares only `input-main` + `output-main`; because `usable_as_tool = True` and neither `hide_input_handle` nor `hide_output_handle` is declared, `BaseNode.__init_subclass__` flags both canvas handles hidden and `_metadata_dict` appends an `output-tool` handle to the NodeSpec so the node can be wired to an agent's `input-tools` |--## Parameters--Params model `BrowserHarnessParams` (`extra="ignore"`):--| Name | Type | Default | Required | displayOptions.show | Description |-|------|------|---------|----------|---------------------|-------------|-| `operation` | enum `run_python` \| `goto` \| `screenshot` \| `js` \| `tabs` \| `doctor` | `run_python` | no | - | `run_python` executes a snippet against the harness helpers; the rest are single-helper shortcuts; `doctor` diagnoses the Chrome/CDP connection |-| `code` | string (code editor, 8 rows) | `""` | no (but an empty snippet raises `NodeUserError` in `run_code`) | `operation: [run_python]` | Python for `run_python`. Helpers are pre-imported. Print a JSON object as the final line for structured output |-| `url` | string | `""` | no (required by `goto`, enforced in `_code_for`) | `operation: [goto]` | URL to open |-| `expression` | string (4 rows) | `""` | no (required by `js`, enforced in `_code_for`) | `operation: [js]` | JavaScript to evaluate in the page |-| `full_page` | boolean | `false` | no | `operation: [screenshot]` | Capture the full scrollable page |-| `timeout` | integer, `ge=5, le=600` | `60` | no | - | Script timeout in seconds (applies to every operation except `doctor`, which is fixed at 30 s) |--Generated Python per shortcut (`_code_for`; user strings are embedded with-`repr()` so quotes/backslashes cannot break out of the generated source):--| Operation | Generated snippet |-|-----------|-------------------|-| `goto` | `goto_url(<url!r>)` / `wait_for_load()` / `print(page_info())` |-| `screenshot` | `p = capture_screenshot(full=<bool>)` / `print(p)` |-| `js` | `print(js(<expression!r>))` |-| `tabs` | `print(list_tabs())` |--## Outputs (handles)--| Handle | Shape | Description |-|--------|-------|-------------|-| `output-main` | object | `BrowserHarnessOutput` (`extra="allow"`) wrapped in the standard `{success, result, execution_time}` envelope; as a tool the envelope is unwrapped to the flat object |--### Output payload (TypeScript shape)--```ts-{- operation: 'run_python' | 'goto' | 'screenshot' | 'js' | 'tabs' | 'doctor';- data: {- output: string; // full stdout (stderr when stdout was empty, e.g. doctor); capped at 100_000 chars + "...(truncated)"- result?: unknown; // present only when the LAST non-empty stdout line parses as JSON- screenshot?: FileRef; // screenshot op only: serialized workspace FileRef (kind "image") when the printed path was persisted- };-}-```--`doctor` always returns `{ output: string }` — exit code 1 is a report, not-an error.--## Logic Flow--```mermaid-flowchart TD- A[dispatch op] --> B[get_browser_harness_service]- B -- binary missing and uv install failed / uv absent --> E1[NodeUserError: uv required]- B -- ok --> C{operation}- C -- doctor --> D[svc.doctor: run CLI 'doctor', 30 s, exit code ignored]- C -- other --> F[_code_for: run_python passes code verbatim, shortcuts generate one-liners]- F -- goto without url / js without expression / unknown op --> E2[NodeUserError]- F --> G[svc.run_code: empty code -> NodeUserError]- G --> H[acquire _operation_lock - one script at a time]- H --> I[subprocess.run binary, stdin=code, env + BH_RUNTIME_DIR/BH_TMP_DIR, timeout]- I -- TimeoutExpired --> E3[NodeUserError: timed out after N s]- I -- FileNotFoundError --> E4[NodeUserError: binary vanished]- I -- exit != 0 and stderr matches Chrome hints --> E5[NodeUserError: CDP guidance + tail of stderr]- I -- exit != 0 and 'traceback'/'error' in stderr --> E6[NodeUserError: script failed]- I -- exit != 0 otherwise --> E7[RuntimeError: exited N]- I -- exit 0 --> J[_shape_output: last line JSON -> result, always output]- D --> K- J --> K{operation == screenshot and data is dict?}- K -- yes --> L[persist_screenshot_file: last stdout line must be an absolute path contained under DATA_DIR/daemons/browser-harness, .png/.jpg/.jpeg/.webp, 128 B..25 MiB]- L -- persisted --> M[data.screenshot = FileRef]- L -- any failure --> N[warning logged, raw output kept]- K -- no --> O[BrowserHarnessOutput operation + data]- M --> O- N --> O-```--## Decision Logic--- **Validation**: `get_browser_harness_service()` returns `None` when `uv` is not on PATH or `uv tool install` fails (one `NodeUserError`); `goto` without `url` and `js` without `expression` raise `NodeUserError` before any subprocess; empty `code` raises inside `run_code`; an unknown `operation` (unreachable through the Literal) raises `NodeUserError`.-- **Branches**: `doctor` bypasses `_code_for` entirely and calls the CLI with a `doctor` argv and no stdin, `check=False`; every other operation is a stdin script. The screenshot FileRef branch runs only when `data` is a dict with at least one non-empty output line — the printed path is treated as untrusted process output and must resolve under the harness runtime dir.-- **Fallbacks**: `_run_sync` returns stderr when stdout is empty (diagnostic verbs write to stderr); `_shape_output` falls back to `{output}` when the last line is not JSON.-- **Error paths**: stderr containing any of `devtoolsactiveport`, `unreachable`, `is the dedicated automation chrome running`, `chrome://inspect`, `no browser connection`, `connection refused` maps to the CDP guidance `NodeUserError`; stderr containing `traceback` or `error` maps to "script failed" (`NodeUserError`); anything else is a `RuntimeError` (full traceback in the operator log). Cancellation of the awaiting task does **not** release `_operation_lock` until the subprocess finishes (`_to_thread_until_complete`), so a cancelled script cannot overlap the next one on the single daemon/CDP socket.--## Side Effects--- **Database writes**: none from the node (no `cost=` on the operation, no usage tracking). A persisted screenshot writes a file only, no row.-- **Broadcasts**: none beyond the generic `node_status` updates `BaseNode.execute()` emits.-- **External API calls**: none directly; the CLI talks to Chrome over CDP.-- **File I/O**: first use installs into `<DATA_DIR>/packages/browser-harness/tools/` (uv tool venv) and `.../bin/browser-harness[.exe]`; every spawn creates `<DATA_DIR>/daemons/browser-harness/` and `.../tmp/` and pins `BH_RUNTIME_DIR` / `BH_TMP_DIR` there (daemon pid/port/sock, screenshots, daemon log never land in `~/.config/browser-harness`); `screenshot` copies the bytes into the run's workspace media subdir via `write_media(kind="image")` (no workspace on the run -> warning, not persisted).-- **Subprocess**: `uv tool install --python 3.12 --upgrade browser-harness` (install), then one `browser-harness` CLI process per operation; the CLI auto-starts a detached daemon that holds the single CDP WebSocket and outlives the CLI. The `browser_harness` shutdown hook (`register_shutdown_hook`) reads `<BH_RUNTIME_DIR>/bu.pid` and `kill_tree`s it on FastAPI lifespan shutdown; missing/stale pid files are ignored.--## External Dependencies--- **Credentials**: none.-- **Services**: `services.plugin.shutdown_hooks`, `services._supervisor.util.kill_tree`, `services.media.workspace.write_media` (through `_screenshots.py`), `core.paths.package_dir` / `daemons_dir`.-- **Python packages**: `uv` on PATH (install-time only); `browser-harness` (PyPI, alpha; Python 3.12 pinned by the installer).-- **Environment variables**: sets `BH_RUNTIME_DIR`, `BH_TMP_DIR` on every spawn and `UV_TOOL_DIR` / `UV_TOOL_BIN_DIR` during install; passes `BU_CDP_URL` / `BU_CDP_WS` through untouched (operator override for a dedicated automation Chrome). Chrome must be CDP-reachable: `BU_CDP_URL`/`BU_CDP_WS`, chrome://inspect remote debugging, or a Chrome started with `--remote-debugging-port` (the guidance text names port 9222 because that is the CLI's own probe default, not an OpenCompany port).-- **Task queue**: `TaskQueue.BROWSER`. Annotations: `destructive`, `open_world`.--## Edge cases & known limits--- `run_python` executes agent-authored Python **outside** any sandbox with the user's real browser attached; annotations say `destructive + open_world` for that reason.-- One script at a time per backend process (`asyncio.Lock`); parallel tool calls serialize, so a 600 s script blocks every other harness call.-- `timeout` is ignored by `doctor` (fixed 30 s).-- Output is capped at 100,000 characters; a snippet that prints large page text loses its trailing JSON line and `result` is then absent.-- The structured `result` depends purely on the LAST non-empty stdout line parsing as JSON — an extra trailing `print` from the snippet silently demotes the result to `output`.-- The stderr classification is heuristic: any non-zero exit whose stderr contains the substring `error` becomes a one-WARN-line `NodeUserError` even when the cause is a genuine harness bug.-- The daemon's own Chrome discovery, IPC (AF_UNIX on POSIX, token-auth TCP loopback on Windows) and screenshot format are upstream behaviour; `full_page` is passed as `capture_screenshot(full=...)` and nothing else about the image is controlled here.-- `screenshot` persists only when the harness printed an absolute path under `<DATA_DIR>/daemons/browser-harness`; a path anywhere else is refused (warning), so a harness build that writes elsewhere yields no `FileRef`.-- Upgrades are not automatic once the binary exists: `browser_harness_binary_path` returns the existing binary without re-running `uv tool install --upgrade`.--## Related--- **Skills using this as a tool**: [`browser-harness-skill`](../../../server/skills/web_agent/browser-harness-skill/SKILL.md) (see -> act -> verify loop, helper reference, print-JSON-last convention).-- **Other nodes that consume this output**: [`canvas`](../ai_tools/canvas.md) displays the persisted `data.screenshot` FileRef; [`browser`](./browser.md) is the stable sibling.-- **Architecture docs**: [browser_harness.md](../../browser_harness.md), [media_transport.md](../../media_transport.md), [plugin_system.md](../../plugin_system.md).+The old browser-harness service, helper examples, local-Chrome configuration and installation instructions in earlier versions of this document are historical. Follow the current node schema and runtime documentation for new workflows.diff --git a/docs-internal/performance.md b/docs-internal/performance.mdindex b4c42e8e..c1a58c8c 100644--- a/docs-internal/performance.md+++ b/docs-internal/performance.md@@ -6,6 +6,33 @@ measurements. Update this file when you ship a perf-affecting changeor take a new measurement; numbers without timestamps and a commitreference rot fast.+## Native browser live view (2026-09-26)++Commit `87322eeb` separates frame acknowledgements from ordered browser input,+retains trailing frames under FPS throttling, and returns every Chrome capture+credit after bounded queue admission. Commit `681a340f` adds the shared Normal+and Dev workspace viewer, bounded decoding and canvas backing-store reuse.++The final isolated Chrome 153 benchmark used production stream/CDP code and+a reference canvas renderer, with a 1,000 ms observation deadline:++| FPS | Baseline missed updates | Updated missed updates | Updated input-to-paint p50 / p95 |+| --- | --- | --- | --- |+| 30 | 1 / 50 | 0 / 50 | 29.6 / 41.8 ms |+| 10 | 10 / 20 | 0 / 20 | 80.8 / 129.9 ms |++All injected clicks reached the target. The evidence supports more reliable+frame delivery in this fixture, not a general speedup: baseline percentiles+exclude missed updates, runs varied during development, and the full React+renderer and pinned Chrome 154 were not measured. Agent CLI operation latency+and cold installation are separate paths. See+[Browser workspace](./browser_workspace.md#local-measurements-2026-09-26) for+complete results, source hashes, limitations and repeatable commands.++Use `OPENCOMPANY_BROWSER_DIAGNOSTICS=1` for server timing summaries and+`?browserStreamDebug=1` for numeric client decode/draw summaries. No screenshot+or input payloads are logged by these diagnostics.+## Headline numbers (current baseline)Measured on Windows, dev mode (`bun run dev` → `company dev`),diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex fdfee444..4292065f 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -519,7 +519,9 @@ Queue distribution (live count via| `triggers-event` | Push-based triggers | 100 || `triggers-poll` | Polling triggers (Gmail, etc.) | 100 || `code-exec` | Python / JS / TS sandboxes | 10 |-| `browser` | Playwright / agent-browser | 4 |+| `browser` | Managed Chrome / browser-use / CDP | 4 |++The current Browser plugin owns managed Chrome profiles, browser-use tool execution and the CDP live view. See [browser.md](./browser.md) and [browser_workspace.md](./browser_workspace.md); the retired `browserHarness` node is not a second active plugin.Env overrides: `TEMPORAL_<QUEUE>_CONCURRENCY` (e.g.`TEMPORAL_AI_HEAVY_CONCURRENCY=8`).@@ -734,7 +736,7 @@ server/│ ├── email/ # emailSend / emailRead / emailReceive│ ├── chat/ # chatSend / chatHistory│ ├── social/ # socialSend / socialReceive-│ ├── browser/ # browser (agent-browser CLI) / browser_harness (browser-use CDP)+│ ├── browser/ # browser (managed Chrome, browser-use CLI, live CDP view)│ ├── utility/ # httpRequest / webhookResponse / console / team_monitor / process_manager│ ├── text/ # textGenerator / fileHandler│ ├── location/ # gmaps_create / gmaps_locations / gmaps_nearby_placesdiff --git a/server/nodes/README.md b/server/nodes/README.mdindex c0bdbe69..cccb6f89 100644--- a/server/nodes/README.md+++ b/server/nodes/README.md@@ -145,7 +145,7 @@ tool/ — calculatorTool / currentTimeTool / writeTodos / taskManagerutility/ — console / httpRequest / webhookResponse / processManager / team_monitorworkflow/ — startskill/ — simpleMemory / masterSkill-browser/ — browser (agent-browser CLI)+browser/ — browser (managed Chrome for Testing + browser-use CLI, profiles, live view and user takeover)stripe/ — Stripe (CLI passthrough action + signed-webhook trigger)vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)github/ — GitHub (gh CLI: clone / PRs / issues / custom; palette group "vcs")@@ -163,6 +163,8 @@ translate/ — Provider-abstracted translate / transliterate / detect_language---+For Browser plugin runtime, profile and takeover contracts, see [Browser](../../docs-internal/browser.md). The shared Home/Dev interface is documented in [Browser workspace](../../docs-internal/browser_workspace.md).+## Shared helpers (one per domain)Domains with 2+ plugins share a `_base.py` (or `_<name>.py`) in the