Skip to content

Self-improving AI Employees for everyone

fix(cli,tests): bound uvicorn's graceful shutdown; keep test databases out of server/

trohitgc16ba55d74b7
diff --git a/CLAUDE.md b/CLAUDE.md
index 696d5baa..127d0cd5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -42,6 +42,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[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. **Two frontend hosts share one renderer**: the `isCanvasPanel` parameter panel and the new docked resizable right sidebar (`CanvasDock` + `canvasDockStore`; auto-open via `notifyPushed`, ephemeral click-to-preview from the gallery dialog, `usePanelResize` extracted from ConsolePanel). 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`. |
| **[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 Node 22 (`desktop/runtimes.json`, verified against upstream checksum manifests by `scripts/fetch-runtimes.ts`), stages the backend sibling layout from `npm pack --dry-run` (`scripts/stage.ts`, re-bundles the Node sidecar with express inlined because bun's isolated linker leaves a dangling symlink), 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 draft release + finalize) 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/node/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 `npm install agent-browser` 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`. |
| **[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 + Python 3.12 + uv; `bun install --frozen-lockfile` everywhere, publish stays `npm publish --provenance`) |
| **[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, esbuild sidecar bundle, 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)** | npm-distribution build pipeline: `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'`, esbuild Node.js sidecar bundle (drops `tsx` interpreter cost), 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`. |
diff --git a/cli/_common.py b/cli/_common.py
index d48f3371..ef7bdd5b 100644
--- a/cli/_common.py
+++ b/cli/_common.py
@@ -68,6 +68,15 @@ def free_all_ports(cfg: Config) -> list[KillResult]:
return [kill_port(port) for port in cfg.all_ports]
+# Seconds uvicorn waits for open connections / in-flight handler tasks before
+# running the lifespan shutdown. uvicorn's default is "forever": a browser
+# WebSocket that dies with a TCP reset can leave its handler task lingering,
+# and then the backend never reaches the teardown that reaps Temporal, the
+# Node sidecar and the WhatsApp bridge — the supervisor's 5 s grace expired
+# and tree-killed it instead. Same value the desktop shell passes.
+UVICORN_GRACEFUL_SHUTDOWN_SECONDS = 5
+
+
def build_backend_spec(
cfg: Config,
*,
@@ -103,6 +112,8 @@ def build_backend_spec(
str(cfg.backend_port),
"--log-level",
"warning",
+ "--timeout-graceful-shutdown",
+ str(UVICORN_GRACEFUL_SHUTDOWN_SECONDS),
],
cwd=server_dir(root),
ready_port=cfg.backend_port,
diff --git a/cli/commands/serve.py b/cli/commands/serve.py
index e890fbe6..2c7a8205 100644
--- a/cli/commands/serve.py
+++ b/cli/commands/serve.py
@@ -23,7 +23,7 @@ from pathlib import Path
import typer
-from cli._common import preflight
+from cli._common import UVICORN_GRACEFUL_SHUTDOWN_SECONDS, preflight
from cli.buildenv import validate_build
from cli.colors import console
from cli.platform_ import server_dir, server_venv_python
@@ -64,6 +64,8 @@ def serve_command(port: int | None = None) -> None:
str(bind_port),
"--log-level",
"warning",
+ "--timeout-graceful-shutdown",
+ str(UVICORN_GRACEFUL_SHUTDOWN_SECONDS),
],
cwd=server_dir(root),
env={"SERVE_STATIC_CLIENT": "1", "PORT": str(bind_port)},
diff --git a/cli/tests/test_start.py b/cli/tests/test_start.py
index 732a13c2..1427fa9d 100644
--- a/cli/tests/test_start.py
+++ b/cli/tests/test_start.py
@@ -39,6 +39,20 @@ def test_build_specs_backend_uses_venv_interpreter(tmp_path: Path):
assert server.argv[1:4] == ["-m", "uvicorn", "main:app"]
+def test_build_specs_bounds_uvicorn_graceful_shutdown(tmp_path: Path):
+ """uvicorn's default waits forever for lingering connections before the
+ lifespan teardown that reaps Temporal / node / edgymeow; a reset browser
+ WebSocket used to wedge it until the supervisor tree-killed the backend."""
+ from cli._common import UVICORN_GRACEFUL_SHUTDOWN_SECONDS
+
+ cfg = _cfg()
+ specs = start._build_specs(tmp_path, cfg)
+ server = next(s for s in specs if s.name == "server")
+ idx = server.argv.index("--timeout-graceful-shutdown")
+ assert server.argv[idx + 1] == str(UVICORN_GRACEFUL_SHUTDOWN_SECONDS)
+ assert 0 < UVICORN_GRACEFUL_SHUTDOWN_SECONDS <= 30
+
+
def test_build_specs_assigns_ready_ports(tmp_path: Path):
cfg = _cfg()
specs = start._build_specs(tmp_path, cfg)
diff --git a/server/tests/services/agent_context/test_conversation.py b/server/tests/services/agent_context/test_conversation.py
index a689f8d4..fbdc5ae5 100644
--- a/server/tests/services/agent_context/test_conversation.py
+++ b/server/tests/services/agent_context/test_conversation.py
@@ -32,7 +32,7 @@ from services.llm.protocol import Message, message_to_wire
@pytest.fixture
-async def conversation_database():
+async def conversation_database(tmp_path: Path):
# The root conftest stubs core.database for fast plugin tests, so load
# the real module privately for transaction coverage.
module_name = f"tests._conversation_database_{uuid.uuid4().hex}"
@@ -45,7 +45,7 @@ async def conversation_database():
sys.modules[module_name] = module
spec.loader.exec_module(module)
- db_path = Path.cwd() / f".conversation-{uuid.uuid4().hex}.db"
+ db_path = tmp_path / f"conversation-{uuid.uuid4().hex}.db"
settings = SimpleNamespace(
database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
database_echo=False,
diff --git a/server/tests/services/memory/test_runtime_mutations.py b/server/tests/services/memory/test_runtime_mutations.py
index bb9f02e2..df5ef096 100644
--- a/server/tests/services/memory/test_runtime_mutations.py
+++ b/server/tests/services/memory/test_runtime_mutations.py
@@ -15,7 +15,7 @@ from services.memory.runtime import append_memory_turns_atomic
@pytest.fixture
-async def runtime_database():
+async def runtime_database(tmp_path: Path):
# The suite's root conftest intentionally stubs ``core.database`` for
# fast node-contract tests. Load the real implementation under a private
# module name for these SQLite integration tests.
@@ -29,7 +29,7 @@ async def runtime_database():
sys.modules[module_name] = module
spec.loader.exec_module(module)
- db_path = Path.cwd() / f".runtime-mutations-{uuid.uuid4().hex}.db"
+ db_path = tmp_path / f"runtime-mutations-{uuid.uuid4().hex}.db"
settings = SimpleNamespace(
database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
database_echo=False,
diff --git a/server/tests/services/test_getting_started_settings.py b/server/tests/services/test_getting_started_settings.py
index 29beef1a..86486560 100644
--- a/server/tests/services/test_getting_started_settings.py
+++ b/server/tests/services/test_getting_started_settings.py
@@ -26,7 +26,7 @@ GETTING_STARTED_COLUMNS = [
@pytest.fixture
-async def settings_database():
+async def settings_database(tmp_path: Path):
module_name = "tests._real_settings_database"
spec = importlib.util.spec_from_file_location(
module_name, Path(__file__).resolve().parents[2] / "core" / "database.py"
@@ -35,7 +35,7 @@ async def settings_database():
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
- db_path = Path.cwd() / f".getting-started-{uuid.uuid4().hex}.db"
+ db_path = tmp_path / f"getting-started-{uuid.uuid4().hex}.db"
database = module.Database(SimpleNamespace(
database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
database_echo=False, database_pool_size=5, database_max_overflow=5,
diff --git a/server/tests/services/test_identity_allocation.py b/server/tests/services/test_identity_allocation.py
index be1052d0..a675d25c 100644
--- a/server/tests/services/test_identity_allocation.py
+++ b/server/tests/services/test_identity_allocation.py
@@ -43,8 +43,8 @@ def test_node_ids_are_plugin_derived_repeatable_and_idempotent():
@pytest.mark.asyncio
-async def test_allocators_are_atomic_and_execution_ids_are_workflow_scoped():
- path = Path.cwd() / f".identity-{uuid.uuid4().hex}.db"
+async def test_allocators_are_atomic_and_execution_ids_are_workflow_scoped(tmp_path: Path):
+ path = tmp_path / f"identity-{uuid.uuid4().hex}.db"
database = _load_database(path)
await database.startup()
try: