Skip to content

Self-improving AI Employees for everyone

fix: four defects found auditing client-owned business logic

trohitgb5e7ad3ec26c
diff --git a/CLAUDE.md b/CLAUDE.md
index 7079e90a..8e293d10 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -739,7 +739,9 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,
### Temporal Distributed Execution
-Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC `TEMPORAL_FRONTEND_GRPC_PORT` + Web UI `TEMPORAL_UI_PORT`, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the F4.B `agent.*` activities (unsuffixed since the V1/V2 fold; read the live set from `collect_agent_activities()` rather than a hardcoded count), heartbeat semantics, delegation input contract, the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
+Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. **Conditional edges are evaluated on this path too, as of the `machina-conditional-edges-v1` patch.** They previously were not: `MachinaWorkflow._find_ready_nodes` scheduled purely on dependency completion, so a condition set in the editor rendered an edge label and then did nothing once execution routed through Temporal — silently, with both branches running. The skip mirrors `WorkflowExecutor._evaluate_incoming_conditions` exactly rather than improving on it: **OR-any** across a node's conditional incoming edges, and **skipping is not transitive** (a skipped node counts as completed, matching `get_completed_nodes` including `SKIPPED`, so an unconditional downstream node still runs). `evaluate_condition` is imported from `services.execution.conditions` **directly, never via the package `__init__`**, which also pulls in the executor / cache / recovery sweeper / DLQ; the module itself is pure (`re` + comparisons, no IO, no clock, no randomness) so it is safe to evaluate inside a workflow. The `workflow.patched(...)` gate is mandatory — the skip changes which activities get scheduled, so an ungated change would break replay for in-flight workflows. Locked by `tests/temporal/test_conditional_edges.py`, whose patch-closed case asserts the pre-fix command sequence is still reproduced verbatim.
+
+Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC `TEMPORAL_FRONTEND_GRPC_PORT` + Web UI `TEMPORAL_UI_PORT`, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the F4.B `agent.*` activities (unsuffixed since the V1/V2 fold; read the live set from `collect_agent_activities()` rather than a hardcoded count), heartbeat semantics, delegation input contract, the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
**Months-long durability contract (July 2026).** Running and paused deployments survive backend restarts, are never auto-terminated, and keep executing for months. Load-bearing invariants: (1) `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP` stays `false` (debug-only sweep; even enabled, any control row in the shared `WORKFLOW_CONTROL_ACTIVE_STATES` — including `resetting` — vetoes it). (2) New child workflow starts carry **no** `execution_timeout`/`run_timeout` — Temporal's timeout timers keep ticking through a cooperative pause, so lifetime caps silently terminated paused runs; liveness comes from activity heartbeats (30s beat / 2min timeout), never from workflow lifetime caps. Removing/adding start options or retry policies on recorded commands requires a `workflow.patched(...)` guard (see the `*-unbounded-*` / `*-history-bounded-can-*` markers). (3) Every long-lived workflow loop must continue-as-new under history pressure (`is_continue_as_new_suggested()` + a soft cap) — Temporal hard-terminates around ~51,200 history events; `WorkflowControlWorkflow` carries triggers/queued events/seen-ids/control state across rollovers, so controller handles are addressed **by workflow id only, never run_id-pinned**. (4) `dispatch.emit` skips controllers whose `ControlEventTypes` Search Attribute doesn't match the event (absent attribute = legacy match-all). (5) The Temporal lifecycle is owned by [services/temporal/lifecycle.py](./server/services/temporal/lifecycle.py) (`main.py` only schedules it): dev-server supervision + resident watchdog (`TEMPORAL_HEALTH_MONITOR_INTERVAL_SECONDS`), worker crash-restarts that REBUILD the single-use SDK `Worker` per attempt (manager + every pool queue worker), and the boot-time `reconcile_active_controls_on_boot` pass (converges crash-stranded `starting` rows, re-arms running/paused generations from the persisted graph snapshot). (6) **Recovery policies** (env-driven, defaults in `.env.template`; full semantics in [temporal-workflow-control.md → Recovery policies](./docs-internal/temporal-workflow-control.md)): `WORKFLOW_CONTROL_CRASH_RECOVERY=pause` — after a kill/crash (dirty-bit marker cleared only by graceful teardown) boot recovers running generations as **paused** so the user consciously resumes; `WORKFLOW_CONTROL_MISSING_CONTROLLER=pause` — a killed/vanished controller converges the generation to paused and **Resume rebuilds the controller** (`WorkflowIdConflictPolicy.USE_EXISTING`, re-arm from snapshot) instead of forcing a state-archiving Reset; `WORKFLOW_CONTROL_PAUSE_ON_FAILURE=true` — repeatedly-failing trigger-spawned runs pause their deployment via the `workflow_control.pause_on_failure.v1` activity (circuit breaker; trips only after `WORKFLOW_CONTROL_PAUSE_ON_FAILURE_THRESHOLD` (default 3) failures inside a rolling `_WINDOW_SECONDS` (default 600) so one node hiccup never pauses anything; Resume resets the streak; manual canvas runs never qualify). Temporal's native Pause/Unpause (server 1.28+) is deliberately NOT used — no Python SDK surface, and it halts workflow-task dispatch so a natively-paused controller couldn't process the resume Update. (7) **Workflow-scoped event delivery**: an envelope whose `workflow_id` is set by its producer's call site reaches only that workflow's consumers (`dispatch.emit` narrows both Visibility clauses by `EventWorkflowId`); chat is the first scoped producer — the decision lives in `routers/websocket.py`, the narrowing in core dispatch, and plugin `_events.py` factories only plumb the field (see [event_framework.md](./docs-internal/event_framework.md)). (8) **Canvas editability is the server-owned `can_edit` capability** emitted by `serialize_control` (paused = editable; starting/running/transitional = locked); the FE renders it via `lib/canvasLock.ts` + Dashboard's `guardCanvasEdit` and never re-derives the rule from state strings (see [temporal-workflow-control.md → Canvas editability](./docs-internal/temporal-workflow-control.md)). Locked by `tests/temporal/test_durability_hardening.py` + `test_worker_restart.py`.
@@ -2713,6 +2715,7 @@ This function:
- Source: https://github.com/trohitg/whatsapp-rpc
- **Node Data Architecture**: `node.data` only stores `label` (display name). All parameters are stored in the database via `save_node_parameters` WebSocket handler. This prevents parameter bloat in workflow JSON exports and keeps React Flow state lightweight. `useDragAndDrop.ts` saves default parameters to DB on drop, not to `node.data`.
- **Workflow Export/Import with Parameters**: Exported workflow JSON includes a `nodeParameters` field containing all node configuration (provider, model, prompt, skillsConfig, etc.) fetched from the database at export time. On import, embedded `nodeParameters` are saved back to the database. `sanitizeNodes()` in `workflowExport.ts` still strips `node.data` to UI-only fields (`label`, `disabled`, `condition`). The `parameterSanitizer.ts` utility strips credential-bearing keys (SENSITIVE key sets + substring matching + runtime-key stripping) and is ACTIVE in the export path (`buildExportParameters` in `workflowExport.ts` calls `sanitizeParameters`). Old exports without `nodeParameters` import cleanly (backward compatible). Key files: `client/src/utils/workflowExport.ts`, `client/src/utils/parameterSanitizer.ts`, `client/src/Dashboard.tsx` (export/import handlers), `server/services/example_loader.py`.
+ - **The sanitizer is client-only, and the backend depends on it without enforcing it.** There is no server-side sanitizer and no server-side export endpoint; the raw material is freely available to any caller via `handle_get_all_node_parameters` (`routers/websocket.py`), which returns stored parameters verbatim. So *any* export path built outside the React app is unsanitized by construction. This is deliberate but load-bearing: `server/tests/test_export_sanitizer_sync.py` reads `parameterSanitizer.ts` off disk and asserts its `RUNTIME_KEYS` covers everything `clear_agent_session_state` wipes — a cross-language invariant that exists because these two lists *already drifted once*, when the sanitizer held camelCase `memoryContent` against the real `memory_content` and every export carried full conversation histories into the shipped example workflows and from there into a public repo. Two consequences worth knowing before touching either side: adding a field to `clear_agent_session_state` fails that test until `RUNTIME_KEYS` matches, and adding a server-side export path silently bypasses stripping entirely. Known accepted hole: `sanitizeParameters` recurses into objects but passes arrays through untouched (documented in its own docstring and locked by `parameterSanitizer.test.ts`), so `{tasks: [{api_key: 'sk-1'}]}` exports the key.
- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB/Master Skill customization is authoritative. Standard skills use progressive disclosure without modifying the agent system prompt: the dynamically connected `Skill` tool carries the bounded name/description catalogue, loads instructions, then separately reads/searches declared resources. Personality skills remain eager. Duplicate connected names block with `DUPLICATE_CONNECTED_SKILL_NAME`. Runtime state and sanitized `agent.skill.*` observability live in [`skill_runtime.py`](./server/services/skill_runtime.py); tool results persist in the current conversation while canvas badges clear at turn end. Icon resolution mirrors `BaseNode._metadata_dict`: per-plugin `<plugin>/icon.svg` (served as `/api/schemas/nodes/<type>/icon`) → `visuals.json` (emoji / `lobehub:<brand>`); color: per-plugin `<plugin>/meta.json` → `visuals.json`. Lives in [`skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py). Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor. **Mutation broadcasts use the CloudEvents-typed `skill_lifecycle` wire key** with stages `created` / `updated` / `deleted` / `content_saved` — see "Plugin-folder location for plugin-specific CloudEvents factories" below.
- **Example Workflows**: Auto-load example workflow seeds from `<repo>/.opencompany/workflows/` on first use (git-tracked; the only non-ignored content under `<repo>/.opencompany/`). Path resolved by `core.paths.example_workflows_dir()` — fixed, NOT under `DATA_DIR`, preserved by `company clean` via `_OPENCOMPANY_KEEP`. Uses `UserSettings.examples_loaded` flag; supports anonymous users (`user_id="default"`); embedded `nodeParameters` saved to DB on import.
- **Onboarding Service**: 5-step welcome wizard (Welcome, Concepts, API Keys, Canvas Tour, Get Started) using shadcn primitives + lucide icons. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.
diff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsx
index a58dc6d4..35ba42df 100644
--- a/client/src/components/ParameterRenderer.tsx
+++ b/client/src/components/ParameterRenderer.tsx
@@ -1000,10 +1000,18 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
// Merge database params with current form params (current takes precedence)
const resolvedParameters = { ...nodeParameters, ...allParameters };
- // Helper functions to get values from both interface types
- const getMin = () => (parameter as any).min || (parameter as any).typeOptions?.minValue || 0;
- const getMax = () => (parameter as any).max || (parameter as any).typeOptions?.maxValue || 100;
- const getStep = () => (parameter as any).step || (parameter as any).typeOptions?.numberStepSize || 1;
+ // Bounds the backend actually declared, or undefined. `??` not `||` so a
+ // declared 0 survives.
+ const getDeclaredMin = () => (parameter as any).min ?? (parameter as any).typeOptions?.minValue;
+ const getDeclaredMax = () => (parameter as any).max ?? (parameter as any).typeOptions?.maxValue;
+ const getStep = () => (parameter as any).step ?? (parameter as any).typeOptions?.numberStepSize ?? 1;
+
+ // Sliders need a finite track to render at all, so they fall back to 0..100.
+ // A plain number input must NOT: the backend only emits minValue/maxValue
+ // when a Pydantic field declares ge/le, so defaulting here silently caps
+ // every unbounded field (token limits, timeouts) at 100.
+ const getMin = () => getDeclaredMin() ?? 0;
+ const getMax = () => getDeclaredMax() ?? 100;
// Load dynamic options based on loadOptionsMethod
useEffect(() => {
@@ -1551,8 +1559,8 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({
type="number"
value={currentValue !== undefined ? currentValue : (parameter.default || 0)}
onChange={(e) => onChange(Number(e.target.value))}
- min={getMin()}
- max={getMax()}
+ min={getDeclaredMin()}
+ max={getDeclaredMax()}
step={getStep()}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
diff --git a/client/src/components/ui/TopToolbar.tsx b/client/src/components/ui/TopToolbar.tsx
index b7c7a7a9..23197cdd 100644
--- a/client/src/components/ui/TopToolbar.tsx
+++ b/client/src/components/ui/TopToolbar.tsx
@@ -317,7 +317,7 @@ const TopToolbar: React.FC<TopToolbarProps> = ({
className="text-xs"
style={{ color: meta?.color }}
>
- {meta?.label || vp.provider}
+ {vp.display_name || meta?.label || vp.provider}
</SelectLabel>
{models.map((m) => (
<SelectItem key={`${vp.provider}::${m}`} value={`${vp.provider}::${m}`}>
diff --git a/client/src/hooks/useApiKeys.ts b/client/src/hooks/useApiKeys.ts
index 7b7d8264..49814f8d 100644
--- a/client/src/hooks/useApiKeys.ts
+++ b/client/src/hooks/useApiKeys.ts
@@ -80,6 +80,10 @@ export interface APIUsageSummary {
export interface ValidatedProvider {
provider: string;
+ /** Backend-served label. Present for every provider the backend can return,
+ * including ones with no chat-model node (xai), so the UI never needs a
+ * local id -> label map that can fall behind `llm_defaults.json`. */
+ display_name: string;
models: string[];
popular_models: string[];
default_model: string | null;
diff --git a/docs-internal/ui_migration_plan.md b/docs-internal/ui_migration_plan.md
index 1d93bf40..b656d7a1 100644
--- a/docs-internal/ui_migration_plan.md
+++ b/docs-internal/ui_migration_plan.md
@@ -346,6 +346,7 @@ user-visible bugs.
| 2 — execution budget | `BaseNode.start_to_close_timeout` is now serialized as `uiHints.executionTimeoutMs`, replacing two stale client arrays (5 of 10 triggers, 16 of 21 agents) that produced a phantom 30 s `Request timeout` on 8 node types. Rides `uiHints` because `services/node_spec.py` is a hard key whitelist. Fallback is the finite 5 min `WORKFLOW_CONTROL_REQUEST_TIMEOUT`, never "no timeout" — an unsettleable promise hangs the Run spinner with no error. Fixed `cronScheduler`, which declared 10 min while sleeping up to a month. | `services/plugin/base.py`, `WebSocketContext.tsx`, `INodeProperties.ts`, `nodes/scheduler/cron_scheduler/` |
| 3 — dead modules (484 lines) | `popover.tsx`, `utils/nodeUtils.ts` (hardcoded the client-side node registry Wave 11 deleted), `DropCap.tsx` (its `::first-letter` rule exists in no theme), `styles/zIndex.ts`, `hooks/useExecution.ts` (dead frontend *execution* logic — the live path is `ExecutionService.executeNodeViaWebSocket`). Plus the `nodeOutput` drop branch with no producer, and the `googleChatModel` provider alias that `useAppStore` already migrates away. | client + 4 doc sites |
| 4 — orphan sweep (1,663 lines) | `SkillEditorModal`, `JSONTreeRenderer`, `DataPanel`, `InputNodesPanel`, `PricingConfigModal`, `usePricing`, `useAndroidOperations`, `useToolSchema`, and the two unreferenced barrels (`parameterPanel/index.ts`, `maps/index.ts`). Verified by knip program-graph closure, not regex. | client + 3 doc sites |
+| 6 — bugs the audit surfaced | Four defects found while auditing client-owned logic, none of them cleanup. (a) **Conditional edges were inert under Temporal** — no edge-condition evaluation existed anywhere in `services/temporal/`; fixed behind `machina-conditional-edges-v1`. (b) **Every unbounded numeric field was clamped to 100** — `getMax()` fell back to `100`, and the backend only emits `maxValue` when a Pydantic field declares `le`, so token limits and timeouts inherited a ceiling nothing declared; sliders keep the 0..100 track they need. (c) **`eq`/`neq` never matched numbers** — the editor stores every target as a string while `conditions.py` compared strictly, so `status_code eq 200` was permanently false; fixed server-side so the client stays a dumb editor. (d) **Providers with no client table entry rendered as raw ids** — `display_name` added to `llm_defaults.json` (the documented per-provider SSOT) and serialized, so `xai` and anything added later renders without a client-side map. | `services/temporal/workflow.py`, `services/execution/conditions.py`, `services/settings/handlers.py`, `config/llm_defaults.json`, `ParameterRenderer.tsx`, `TopToolbar.tsx`, `useApiKeys.ts`, + `tests/test_edge_conditions.py`, `tests/temporal/test_conditional_edges.py` |
| 5 — guards | pytest + `inspect.getsource`, repo idiom. No client file may carry a backend node-type literal in an array/comparison context; every registered node must serialize `executionTimeoutMs`; every `TriggerNode` must report ≥ 1 h. Includes a debt ledger that can only shrink. Adversarially verified to fail on a probe — a guard never seen failing is not a guard. | `server/tests/test_frontend_no_node_type_copies.py` |
**Wave 15 numbers:**
@@ -368,6 +369,13 @@ user-visible bugs.
- `useAndroidOperations` was a wrapper over context methods that every live Android surface already
bypassed, documenting a signature (`setupDevice`, `deviceStatus`) the file did not export.
+**Open findings, recorded not fixed:**
+- **`tool_schemas` has a live read and a dead write.** `services/ai.py` reads the table at agent-execution time to override the LLM-visible tool name / description / schema; no reachable code can write it since the editor was removed with the Android Toolkit node. See CLAUDE.md's Tool Schemas section.
+- **The export sanitizer is client-only and the backend depends on it anyway.** `test_export_sanitizer_sync.py` asserts a TypeScript file it cannot enforce. See CLAUDE.md's Workflow Export bullet.
+- **`teamMonitor` renders as a plain square.** The plugin declares `component_kind = "square"`, so `COMPONENT_BY_KIND` wins in `createNodeTypes` and the `spec.type === 'teamMonitor'` arm is unreachable — the 322-line `TeamMonitorNode` live-display component never mounts, while its parameter-panel half (`TeamMonitorPanel`) is live and tested. Fix-or-accept, deliberately left alone.
+- **Two client-owned rules with no server counterpart.** `useAppStore`'s `googleChatModel` → `geminiChatModel` rewrite is the only such migration in the system (the save path does not validate and the REST load route returns raw data), and the two `workflowOps` appliers disagree — the server writes parameters into `node.data.parameters`, which the client's next autosave strips via `sanitizeNodes`.
+- **The debt ledger cannot see reachability.** `test_the_debt_ledger_only_shrinks` matches source text, so five of its entries are unreachable `??` fallback arms behind spec reads that always resolve, and two more are dead by call graph. Treat the count as an upper bound, not a debt measure.
+
**Deliberately not deleted:** `credentials/schema/extends.ts` — unreferenced, but its docstring names
planned consumers and it mirrors `credential_registry._deep_merge`. Two divergences from that mirror
were found and are worth fixing if it is ever adopted: TS adds a `statusRows` alias the Python set
diff --git a/server/config/llm_defaults.json b/server/config/llm_defaults.json
index 9653970f..b042a2f0 100644
--- a/server/config/llm_defaults.json
+++ b/server/config/llm_defaults.json
@@ -14,6 +14,7 @@
"providers": {
"openai": {
+ "display_name": "OpenAI",
"default_model": "gpt-5.6-sol",
"popular_models": ["gpt-5.6-sol", "gpt-5.6-sol-pro", "gpt-5.6-terra", "gpt-5.6-terra-pro", "gpt-5.6-luna", "gpt-5.6-luna-pro", "gpt-5.5", "gpt-5.4", "gpt-4.1"],
"detection_patterns": ["gpt", "openai", "o1", "o3", "o4"],
@@ -52,6 +53,7 @@
"temperature_range": [0.0, 2.0]
},
"anthropic": {
+ "display_name": "Anthropic",
"default_model": "claude-opus-5",
"popular_models": ["claude-opus-5", "claude-fable-5", "claude-sonnet-5", "claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-4-6"],
"_models_note": "claude-opus-5 (released 2026-07-24) is the new Opus flagship and default: near-Fable-5 intelligence at Opus pricing ($5/$25 — half of Fable 5), 1M context, 128K max output. The claude-opus-5-fast variant (2x pricing) is deliberately not curated here; select it via the live dropdown if needed.",
@@ -101,6 +103,7 @@
"temperature_range": [0.0, 1.0]
},
"gemini": {
+ "display_name": "Gemini",
"default_model": "gemini-3.6-flash",
"popular_models": ["gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview", "gemini-3.1-flash-lite", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite"],
"detection_patterns": ["gemini", "google", "gemma"],
@@ -148,6 +151,7 @@
"incompatible_models": ["antigravity-preview-05-2026"]
},
"openrouter": {
+ "display_name": "OpenRouter",
"default_model": "anthropic/claude-sonnet-5",
"popular_models": ["anthropic/claude-sonnet-5", "openai/gpt-5.6-terra", "openai/gpt-5.6-sol", "google/gemini-3.5-flash", "moonshotai/kimi-k3", "x-ai/grok-4.20"],
"detection_patterns": ["openrouter"],
@@ -165,6 +169,7 @@
"temperature_range": [0.0, 2.0]
},
"groq": {
+ "display_name": "Groq",
"default_model": "openai/gpt-oss-120b",
"popular_models": [],
"_popular_note": "Empty per the 1M-context policy — no Groq-served model reaches 1M (all top out at 131072). Models remain reachable via live fetch_models.",
@@ -195,6 +200,7 @@
"temperature_range": [0.0, 2.0]
},
"cerebras": {
+ "display_name": "Cerebras",
"default_model": "gpt-oss-120b",
"popular_models": [],
"_popular_note": "Empty per the 1M-context policy — no Cerebras model reaches 1M (all 131072). Models remain reachable via live fetch_models.",
@@ -221,6 +227,7 @@
"temperature_range": [0.0, 1.5]
},
"xai": {
+ "display_name": "xAI",
"default_model": "grok-4.20",
"popular_models": ["grok-4.20", "grok-4.20-multi-agent", "grok-4.3"],
"_popular_note": "grok-4.5 (flagship, released 2026-07-08) and grok-3 excluded per the 1M-context policy (500K / 131072); reachable via live fetch_models. Default stays grok-4.20 (2M) so the default is selectable from the global list.",
@@ -248,6 +255,7 @@
"temperature_range": [0.0, 2.0]
},
"deepseek": {
+ "display_name": "DeepSeek",
"default_model": "deepseek-v4-flash",
"popular_models": ["deepseek-v4-flash", "deepseek-v4-pro"],
"_popular_note": "deepseek-chat / deepseek-reasoner dropped from the global list per the 1M-context policy (131072); reachable via live fetch_models.",
@@ -275,6 +283,7 @@
"temperature_range": [0.0, 2.0]
},
"kimi": {
+ "display_name": "Kimi",
"default_model": "kimi-k3",
"popular_models": ["kimi-k3"],
"_popular_note": "Only kimi-k3 meets the 1M-context policy (k2.x are 262144); k2.x remain reachable via live fetch_models.",
@@ -304,6 +313,7 @@
"temperature_range": [0.0, 1.0]
},
"mistral": {
+ "display_name": "Mistral",
"default_model": "mistral-large-latest",
"popular_models": [],
"_popular_note": "Empty per the 1M-context policy — Mistral tops out at 262144 (large/medium). Models remain reachable via live fetch_models.",
@@ -330,6 +340,7 @@
"temperature_range": [0.0, 1.5]
},
"sarvam": {
+ "display_name": "Sarvam AI",
"default_model": "sarvam-105b",
"popular_models": [],
"_popular_note": "Empty per the 1M-context policy — sarvam-105b tops out at 131072. Both models stay reachable via the per-node dropdown (fetch_models returns the curated list) and via the global selector, which falls back to the max_output_tokens keys when popular_models is empty.",
@@ -360,6 +371,7 @@
},
"ollama": {
+ "display_name": "Ollama",
"_description": "Local Ollama server (OpenAI-compatible /v1). No `default_model` because the dropdown should reflect the user's actually-pulled models — fetch_models hits the user's saved {provider}_proxy URL and returns whatever Ollama reports; when the server is offline we want an empty list (a 'start your server' cue), not a placeholder name the user almost certainly doesn't have.",
"detection_patterns": ["ollama"],
"base_url": "http://localhost:11434/v1",
@@ -372,6 +384,7 @@
},
"lmstudio": {
+ "display_name": "LM Studio",
"_description": "Local LM Studio server (pure OpenAI-compatible). Same no-default-model rule as ollama — the dropdown reflects what the user has loaded in LM Studio, not a fake placeholder.",
"detection_patterns": ["lmstudio", "lm_studio", "lm-studio"],
"base_url": "http://localhost:1234/v1",
diff --git a/server/services/execution/conditions.py b/server/services/execution/conditions.py
index 3f3b207b..9e2b4b03 100644
--- a/server/services/execution/conditions.py
+++ b/server/services/execution/conditions.py
@@ -126,10 +126,10 @@ def _evaluate_operator(operator: str, actual: Any, target: Any) -> bool:
"""
# Equality operators
if operator == "eq":
- return actual == target
+ return _loose_eq(actual, target)
elif operator == "neq":
- return actual != target
+ return not _loose_eq(actual, target)
# Comparison operators (numeric)
elif operator == "gt":
@@ -235,6 +235,33 @@ def _evaluate_operator(operator: str, actual: Any, target: Any) -> bool:
return False
+def _loose_eq(actual: Any, target: Any) -> bool:
+ """Equality that tolerates the editor storing every target as a string.
+
+ The edge-condition editor types ``eq``/``neq`` targets as ``any`` and stores
+ the raw input, so a numeric comparison arrives as ``"200"`` while the node
+ output holds ``200``. Strict ``==`` makes that permanently false, which is
+ indistinguishable from a mis-typed field name. The ordering operators
+ already coerce via :func:`_safe_compare`; this brings equality in line.
+
+ Booleans are deliberately excluded from numeric coercion -- ``float(True)``
+ is ``1.0``, so without the guard ``eq 1`` would match a ``True`` output.
+ """
+ if actual == target:
+ return True
+
+ if actual is None or target is None:
+ return False
+
+ if isinstance(actual, bool) or isinstance(target, bool):
+ return False
+
+ try:
+ return float(actual) == float(target)
+ except (ValueError, TypeError):
+ return False
+
+
def _safe_compare(actual: Any, target: Any, comparator) -> bool:
"""Safely compare two values, handling type coercion.
diff --git a/server/services/settings/handlers.py b/server/services/settings/handlers.py
index dd2f7059..7ad21f97 100644
--- a/server/services/settings/handlers.py
+++ b/server/services/settings/handlers.py
@@ -166,6 +166,12 @@ async def handle_get_validated_ai_providers(
providers.append(
{
"provider": provider,
+ # Serialized so the client never needs its own id -> label table.
+ # This list is built from PROVIDER_CONFIGS, so it can legitimately
+ # contain a provider (xai) that has no chat-model node and no
+ # credential-catalogue entry; without a name from here the UI fell
+ # back to rendering the raw id.
+ "display_name": provider_config.get("display_name") or provider,
"models": stored_models or [],
"popular_models": popular_models,
"default_model": default_model,
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index 8d5980b7..e3922ed2 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -19,6 +19,19 @@ from temporalio import workflow
from ._retry_policies import DEFAULT_ACTIVITY_RETRY, QUICK_ACTIVITY_RETRY
from services.workflow_naming import node_label_slug
+# Imported straight from the module, never the package: ``services.execution``
+# re-exports through an ``__init__`` that also pulls in the executor, cache,
+# recovery sweeper and DLQ. ``conditions`` itself is pure (``re`` + comparisons,
+# no IO, no clock, no randomness), so it is safe to evaluate inside a workflow.
+with workflow.unsafe.imports_passed_through():
+ from services.execution.conditions import evaluate_condition
+
+# Conditional edges were not evaluated on this path at all before this patch --
+# a condition set in the editor rendered a label and did nothing once execution
+# routed through Temporal. Gating the skip keeps replay deterministic for
+# histories recorded while every node was scheduled unconditionally.
+CONDITIONAL_EDGES_PATCH = "machina-conditional-edges-v1"
+
# Config handles - nodes connecting via these are config nodes (not executed)
# AI Agent handles: input-context, input-tools, input-model, input-task, input-teammates
# Zeenie handles: input-skill, input-tools
@@ -370,6 +383,8 @@ class MachinaWorkflow:
# 2. Build dependency maps
deps, node_map = self._build_dependency_maps(exec_nodes, exec_edges)
+ conditional_edges = self._build_conditional_edge_map(exec_edges, node_map)
+ use_conditional_edges = workflow.patched(CONDITIONAL_EDGES_PATCH)
# 3. Initialize state
outputs: Dict[str, Any] = {} # node_id -> result
@@ -466,6 +481,19 @@ class MachinaWorkflow:
auto_completed_this_pass += 1
continue
+ # Every dependency is done, so any incoming condition is now
+ # decidable. Mirrors WorkflowExecutor._find_ready_nodes: OR-any
+ # across the conditional edges, and a skip still counts as
+ # "completed" for dependency purposes, so skipping is NOT
+ # transitive -- an unconditional downstream node still runs.
+ if use_conditional_edges and node_id in conditional_edges:
+ if not self._conditions_met(node_id, conditional_edges[node_id], outputs):
+ workflow.logger.info(f"Skipping {node_id}: no incoming edge condition matched")
+ completed.add(node_id)
+ execution_trace.append(node_id)
+ auto_completed_this_pass += 1
+ continue
+
# Build immutable context for this node
context = {
"node_id": node_id,
@@ -880,6 +908,47 @@ class MachinaWorkflow:
return deps, node_map
+ def _build_conditional_edge_map(
+ self,
+ edges: List[Dict],
+ node_map: Dict[str, Dict],
+ ) -> Dict[str, List[Dict]]:
+ """Group incoming edges that carry a condition, keyed by target node.
+
+ Only targets that appear here are gated; a node with no conditional
+ incoming edge keeps the unconditional "all deps done" rule.
+ """
+ conditional: Dict[str, List[Dict]] = {}
+ for edge in edges:
+ target = edge.get("target")
+ if target not in node_map:
+ continue
+ if not (edge.get("data") or {}).get("condition"):
+ continue
+ conditional.setdefault(target, []).append(edge)
+ return conditional
+
+ def _conditions_met(
+ self,
+ target_node_id: str,
+ edges: List[Dict],
+ outputs: Dict[str, Any],
+ ) -> bool:
+ """Return whether any conditional incoming edge admits this node.
+
+ OR-any, matching ``WorkflowExecutor._evaluate_incoming_conditions``.
+ A source that produced no output evaluates against ``{}`` rather than
+ raising, so a skipped upstream cannot wedge the graph.
+ """
+ for edge in edges:
+ condition = (edge.get("data") or {}).get("condition")
+ if not condition:
+ continue
+ source_output = outputs.get(edge.get("source")) or {}
+ if evaluate_condition(condition, source_output):
+ return True
+ return False
+
def _find_ready_nodes(
self,
deps: Dict[str, Set[str]],
diff --git a/server/tests/temporal/test_conditional_edges.py b/server/tests/temporal/test_conditional_edges.py
new file mode 100644
index 00000000..69e62b71
--- /dev/null
+++ b/server/tests/temporal/test_conditional_edges.py
@@ -0,0 +1,200 @@
+"""MachinaWorkflow must honour conditional edges.
+
+Before this, ``server/services/temporal/`` contained no edge-condition
+evaluation at all -- every reference to "condition" in that package was
+``workflow.wait_condition`` for cooperative pause or trigger waiting. A user
+could set a condition in the editor, see it render as an edge label, and have
+it do nothing the moment execution routed through Temporal. There was no
+error and no warning; both branches simply ran.
+
+The in-process ``WorkflowExecutor`` has always evaluated them
+(``_evaluate_incoming_conditions``), so this is parity, not a new feature.
+Two semantics are deliberately mirrored rather than improved:
+
+* **OR-any** across a node's conditional incoming edges.
+* **Skipping is not transitive** -- a skipped node counts as "completed" for
+ dependency purposes (``get_completed_nodes`` includes ``SKIPPED``), so an
+ unconditional downstream node still runs.
+
+Runs the real ``MachinaWorkflow.run`` body with ``start_activity`` /
+``logger`` monkeypatched, same harness as test_machina_workflow_loop.py.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import MagicMock
+
+import pytest
+
+import nodes # noqa: F401 -- populate plugin registry
+
+
[email protected](autouse=True)
+def _patch_workflow_logger(monkeypatch):
+ from temporalio import workflow as temporal_workflow
+
+ monkeypatch.setattr(temporal_workflow, "logger", MagicMock())
+
+
+def _branching_graph():
+ """py-1 emits ``result.answer = 42``; two gated branches read it."""
+ nodes_ = [
+ {"id": "start-1", "type": "start", "data": {"label": "Start"}},
+ {"id": "py-1", "type": "pythonExecutor", "data": {"label": "Source"}},
+ {"id": "match-1", "type": "pythonExecutor", "data": {"label": "Matching"}},
+ {"id": "miss-1", "type": "pythonExecutor", "data": {"label": "Non-matching"}},
+ ]
+ edges = [
+ {"id": "e0", "source": "start-1", "target": "py-1", "targetHandle": "input-main"},
+ {
+ "id": "e1",
+ "source": "py-1",
+ "target": "match-1",
+ "targetHandle": "input-main",
+ "data": {"condition": {"field": "result.answer", "operator": "eq", "value": 42}},
+ },
+ {
+ "id": "e2",
+ "source": "py-1",
+ "target": "miss-1",
+ "targetHandle": "input-main",
+ "data": {"condition": {"field": "result.answer", "operator": "eq", "value": 99}},
+ },
+ ]
+ return nodes_, edges
+
+
+def _install_fakes(monkeypatch):
+ """Patch out activity dispatch; return the list scheduling appends to."""
+ from temporalio import workflow as temporal_workflow
+
+ from services.temporal.workflow import MachinaWorkflow
+
+ scheduled: list[str] = []
+
+ def fake_start_activity(name, **kwargs):
+ ctx = kwargs["args"][0]
+ scheduled.append(ctx["node_id"])
+ fut = asyncio.get_event_loop().create_future()
+ fut.set_result({"success": True, "node_id": ctx["node_id"], "result": {"answer": 42}})
+ return fut
+
+ async def fake_execute_activity(*args, **kwargs):
+ return None
+
+ monkeypatch.setattr(temporal_workflow, "start_activity", fake_start_activity)
+ monkeypatch.setattr(temporal_workflow, "execute_activity", fake_execute_activity)
+ # ``**_kwargs`` absorbs the routing/graph-version arguments the real
+ # resolver takes; dispatch resolution is out of scope here (test_dispatch.py
+ # owns it) and pinning the exact signature would make this test fail on
+ # every unrelated change to it.
+ monkeypatch.setattr(
+ MachinaWorkflow,
+ "_resolve_dispatch",
+ lambda self, node_type, **_kwargs: {
+ "kind": "activity",
+ "name": f"node.{node_type}.v1",
+ "queue": None,
+ },
+ )
+ return scheduled
+
+
+async def _run(graph, execution_id):
+ from services.temporal.workflow import MachinaWorkflow
+
+ nodes_, edges = graph
+ return await asyncio.wait_for(
+ MachinaWorkflow().run(
+ {
+ "nodes": nodes_,
+ "edges": edges,
+ "session_id": "test",
+ "workflow_id": "wf-cond-test",
+ "execution_id": execution_id,
+ }
+ ),
+ timeout=5.0,
+ )
+
+
+class TestConditionalEdgesGateScheduling:
+ @pytest.mark.asyncio
+ async def test_only_the_matching_branch_is_scheduled(self, monkeypatch):
+ from temporalio import workflow as temporal_workflow
+
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: True)
+ scheduled = _install_fakes(monkeypatch)
+
+ result = await _run(_branching_graph(), "wf-cond-run1")
+
+ assert "match-1" in scheduled, "the branch whose condition matched must run"
+ assert "miss-1" not in scheduled, (
+ "the branch whose condition did not match must be skipped. Pre-fix "
+ "Temporal scheduled BOTH branches because it never looked at "
+ "edge.data.condition at all."
+ )
+ assert result["success"] is True
+ # Skipped nodes still resolve, so the graph drains rather than hanging.
+ assert "miss-1" in result["execution_trace"]
+ assert "miss-1" not in result["outputs"]
+
+ @pytest.mark.asyncio
+ async def test_unpatched_history_still_schedules_both(self, monkeypatch):
+ """Determinism guard: a history recorded before the patch replays with
+ every node scheduled unconditionally, exactly as it was written."""
+ from temporalio import workflow as temporal_workflow
+
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: False)
+ scheduled = _install_fakes(monkeypatch)
+
+ await _run(_branching_graph(), "wf-cond-run2")
+
+ assert "match-1" in scheduled
+ assert "miss-1" in scheduled, (
+ "with the patch gate closed the old command sequence must be "
+ "reproduced verbatim, or in-flight workflows fail replay"
+ )
+
+
+class TestSkipIsNotTransitive:
+ @pytest.mark.asyncio
+ async def test_unconditional_downstream_of_a_skipped_node_still_runs(self, monkeypatch):
+ """Mirrors the in-process semantic, where SKIPPED counts as completed
+ in ``ExecutionContext.get_completed_nodes``."""
+ from temporalio import workflow as temporal_workflow
+
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: True)
+ scheduled = _install_fakes(monkeypatch)
+
+ nodes_, edges = _branching_graph()
+ nodes_.append({"id": "tail-1", "type": "pythonExecutor", "data": {"label": "Tail"}})
+ edges.append({"id": "e3", "source": "miss-1", "target": "tail-1", "targetHandle": "input-main"})
+
+ result = await _run((nodes_, edges), "wf-cond-run3")
+
+ assert "miss-1" not in scheduled
+ assert "tail-1" in scheduled, (
+ "a skipped node must not wedge its unconditional downstream -- it "
+ "resolves as completed so the graph drains"
+ )
+ assert result["success"] is True
+
+
+class TestUnconditionalGraphsUnaffected:
+ @pytest.mark.asyncio
+ async def test_graph_without_conditions_schedules_everything(self, monkeypatch):
+ from temporalio import workflow as temporal_workflow
+
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: True)
+ scheduled = _install_fakes(monkeypatch)
+
+ nodes_, edges = _branching_graph()
+ for edge in edges:
+ edge.pop("data", None)
+
+ await _run((nodes_, edges), "wf-cond-run4")
+
+ assert "match-1" in scheduled
+ assert "miss-1" in scheduled
diff --git a/server/tests/test_edge_conditions.py b/server/tests/test_edge_conditions.py
new file mode 100644
index 00000000..2e134d69
--- /dev/null
+++ b/server/tests/test_edge_conditions.py
@@ -0,0 +1,106 @@
+"""Edge-condition equality must tolerate the editor's string targets.
+
+The edge-condition editor (``client/src/types/EdgeCondition.ts``) types the
+``eq``/``neq`` target as ``valueType: 'any'`` and stores whatever the user
+typed, so a numeric comparison arrives as the string ``"200"`` while the node
+output holds the integer ``200``. Strict ``==`` made that permanently false,
+and a never-matching condition is indistinguishable from a mis-typed field
+name -- the branch simply never fires and nothing is logged as wrong.
+
+The ordering operators already coerced through ``_safe_compare``; these tests
+lock equality to the same behaviour, and lock the boolean carve-out that keeps
+``float(True) == 1.0`` from making ``eq 1`` match a ``True`` output.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from services.execution.conditions import evaluate_condition
+
+
+def _cond(operator: str, value, field: str = "result.status_code") -> dict:
+ return {"field": field, "operator": operator, "value": value}
+
+
+class TestStringTargetAgainstNumericOutput:
+ """The reported trap: `status_code eq 200` typed into the editor."""
+
+ def test_eq_matches_string_target_against_int_output(self):
+ output = {"result": {"status_code": 200}}
+ assert evaluate_condition(_cond("eq", "200"), output) is True
+
+ def test_eq_matches_int_target_against_string_output(self):
+ output = {"result": {"status_code": "200"}}
+ assert evaluate_condition(_cond("eq", 200), output) is True
+
+ def test_eq_matches_float_and_int_forms(self):
+ output = {"result": {"status_code": 200}}
+ assert evaluate_condition(_cond("eq", "200.0"), output) is True
+
+ def test_neq_is_the_exact_negation(self):
+ output = {"result": {"status_code": 200}}
+ assert evaluate_condition(_cond("neq", "200"), output) is False
+ assert evaluate_condition(_cond("neq", "404"), output) is True
+
+ def test_eq_still_rejects_a_genuine_mismatch(self):
+ output = {"result": {"status_code": 200}}
+ assert evaluate_condition(_cond("eq", "404"), output) is False
+
+
+class TestNonNumericEqualityUnchanged:
+ def test_plain_string_equality(self):
+ output = {"result": {"status": "success"}}
+ assert evaluate_condition(_cond("eq", "success", "result.status"), output) is True
+ assert evaluate_condition(_cond("eq", "failure", "result.status"), output) is False
+
+ def test_missing_field_does_not_match(self):
+ assert evaluate_condition(_cond("eq", "200"), {"result": {}}) is False
+
+ def test_none_target_only_matches_none(self):
+ assert evaluate_condition(_cond("eq", None), {"result": {}}) is True
+ assert evaluate_condition(_cond("eq", None), {"result": {"status_code": 200}}) is False
+
+
+class TestBooleanCarveOut:
+ """``float(True)`` is ``1.0``, so the new numeric coercion would have made
+ a truthy flag satisfy ``eq "1"``. The guard blocks that path only.
+
+ It deliberately does NOT touch ``True == 1``: that is plain Python
+ equality, it short-circuits before the guard, and it matched under the
+ old strict ``==`` too. Tightening it here would be a behaviour change
+ smuggled in under a bug fix.
+ """
+
+ @pytest.mark.parametrize("target", ["1", "true", "True"])
+ def test_true_does_not_equal_a_string(self, target):
+ output = {"result": {"ok": True}}
+ assert evaluate_condition(_cond("eq", target, "result.ok"), output) is False
+
+ @pytest.mark.parametrize("target", ["0", "false", "False"])
+ def test_false_does_not_equal_a_string(self, target):
+ output = {"result": {"ok": False}}
+ assert evaluate_condition(_cond("eq", target, "result.ok"), output) is False
+
+ @pytest.mark.parametrize("target", [1, 1.0])
+ def test_python_numeric_equality_is_preserved(self, target):
+ """Pre-existing behaviour, asserted so a future tightening is a
+ conscious decision rather than an accident."""
+ output = {"result": {"ok": True}}
+ assert evaluate_condition(_cond("eq", target, "result.ok"), output) is True
+
+ def test_boolean_still_equals_itself(self):
+ output = {"result": {"ok": True}}
+ assert evaluate_condition(_cond("eq", True, "result.ok"), output) is True
+ assert evaluate_condition(_cond("neq", False, "result.ok"), output) is True
+
+
+class TestOrderingOperatorsUnaffected:
+ """Guard against the equality change altering the comparison family."""
+
+ def test_gt_lt_still_coerce(self):
+ output = {"result": {"status_code": 200}}
+ assert evaluate_condition(_cond("gt", "199"), output) is True
+ assert evaluate_condition(_cond("lt", "201"), output) is True
+ assert evaluate_condition(_cond("gte", "200"), output) is True
+ assert evaluate_condition(_cond("lte", "200"), output) is True