Skip to content

Self-improving AI Employees for everyone

test(workflow_ops + auto_skill): cover protocol foundation + first consumer

trohitg94475a3d383f
diff --git a/client/src/lib/__tests__/workflowOps.test.ts b/client/src/lib/__tests__/workflowOps.test.ts
new file mode 100644
index 00000000..0524cf00
--- /dev/null
+++ b/client/src/lib/__tests__/workflowOps.test.ts
@@ -0,0 +1,435 @@
+/**
+ * Tests for the WorkflowOperation applier in lib/workflowOps.ts.
+ *
+ * Locks the protocol behaviour the backend services depend on:
+ * - operations apply in order
+ * - client_ref placeholders resolve to generated React Flow ids
+ * - PositionSpec resolution: absolute vs anchor + offset, with fallback
+ * - replace_node rewires (or drops) edges via preserve_edges
+ * - failures are collected per op, applier never throws
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import type { Node, Edge } from 'reactflow';
+import {
+ applyOperations,
+ type ApplyContext,
+ type WorkflowOperation,
+} from '../workflowOps';
+
+// ----- helpers ---------------------------------------------------------------
+
+function makeNode(id: string, type: string, x = 0, y = 0): Node {
+ return { id, type, position: { x, y }, data: { label: id } };
+}
+
+function makeEdge(id: string, source: string, target: string): Edge {
+ return { id, source, target };
+}
+
+interface HarnessState {
+ nodes: Node[];
+ edges: Edge[];
+ saveCalls: Array<{ nodeId: string; parameters: Record<string, any> }>;
+}
+
+function makeContext(initial: { nodes?: Node[]; edges?: Edge[] } = {}): {
+ ctx: ApplyContext;
+ state: HarnessState;
+} {
+ const state: HarnessState = {
+ nodes: initial.nodes ?? [],
+ edges: initial.edges ?? [],
+ saveCalls: [],
+ };
+
+ const ctx: ApplyContext = {
+ get nodes() {
+ return state.nodes;
+ },
+ get edges() {
+ return state.edges;
+ },
+ setNodes: (updater) => {
+ state.nodes = updater(state.nodes);
+ },
+ setEdges: (updater) => {
+ state.edges = updater(state.edges);
+ },
+ saveNodeParameters: vi.fn(async (nodeId: string, parameters: Record<string, any>) => {
+ state.saveCalls.push({ nodeId, parameters });
+ return true;
+ }),
+ };
+
+ return { ctx, state };
+}
+
+beforeEach(() => {
+ // Math.random feeds id generation -- pin it so test assertions on
+ // generated ids are stable. Time is mocked per-test where needed.
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+});
+
+// ----- add_node --------------------------------------------------------------
+
+describe('add_node', () => {
+ it('adds a node + persists params + records the client_ref -> id mapping', async () => {
+ const { ctx, state } = makeContext();
+ const ops: WorkflowOperation[] = [
+ {
+ type: 'add_node',
+ client_ref: 'ms',
+ node_type: 'masterSkill',
+ parameters: { skillsConfig: { 'http-request-skill': { enabled: true, instructions: '', isCustomized: false } } },
+ label: 'Master Skill',
+ position: { x: 100, y: 200 },
+ },
+ ];
+
+ const result = await applyOperations(ops, ctx);
+
+ expect(result.applied).toBe(1);
+ expect(result.errors).toEqual([]);
+ expect(state.nodes).toHaveLength(1);
+ expect(state.nodes[0].type).toBe('masterSkill');
+ expect(state.nodes[0].position).toEqual({ x: 100, y: 200 });
+ expect(state.nodes[0].data).toEqual({ label: 'Master Skill' });
+
+ expect(result.refMap.ms).toBe(state.nodes[0].id);
+
+ expect(state.saveCalls).toHaveLength(1);
+ expect(state.saveCalls[0].nodeId).toBe(state.nodes[0].id);
+ expect(state.saveCalls[0].parameters.label).toBe('Master Skill');
+ expect(state.saveCalls[0].parameters.skillsConfig).toBeDefined();
+ });
+
+ it('resolves an anchored position against existing nodes', async () => {
+ const anchor = makeNode('agent-1', 'aiAgent', 300, 400);
+ const { ctx, state } = makeContext({ nodes: [anchor] });
+
+ await applyOperations(
+ [
+ {
+ type: 'add_node',
+ client_ref: 'ms',
+ node_type: 'masterSkill',
+ parameters: {},
+ position: {
+ anchor_node_id: 'agent-1',
+ offset: { x: -60, y: 220 },
+ },
+ },
+ ],
+ ctx,
+ );
+
+ const added = state.nodes.find((n) => n.type === 'masterSkill')!;
+ expect(added.position).toEqual({ x: 240, y: 620 });
+ });
+
+ it('falls back to PositionSpec.fallback when anchor is missing', async () => {
+ const { ctx, state } = makeContext();
+ await applyOperations(
+ [
+ {
+ type: 'add_node',
+ client_ref: 'ms',
+ node_type: 'masterSkill',
+ parameters: {},
+ position: {
+ anchor_node_id: 'missing-anchor',
+ offset: { x: 10, y: 10 },
+ fallback: { x: 5, y: 7 },
+ },
+ },
+ ],
+ ctx,
+ );
+ expect(state.nodes[0].position).toEqual({ x: 5, y: 7 });
+ });
+
+ it('uses defaultPosition when anchor missing and no fallback', async () => {
+ const { ctx, state } = makeContext();
+ ctx.defaultPosition = { x: 999, y: 888 };
+ await applyOperations(
+ [
+ {
+ type: 'add_node',
+ client_ref: 'n',
+ node_type: 't',
+ parameters: {},
+ position: { anchor_node_id: 'missing' },
+ },
+ ],
+ ctx,
+ );
+ expect(state.nodes[0].position).toEqual({ x: 999, y: 888 });
+ });
+
+ it('lets a later add_edge resolve a client_ref from the same batch', async () => {
+ const target = makeNode('agent-1', 'aiAgent', 0, 0);
+ const { ctx, state } = makeContext({ nodes: [target] });
+
+ const result = await applyOperations(
+ [
+ {
+ type: 'add_node',
+ client_ref: 'ms',
+ node_type: 'masterSkill',
+ parameters: {},
+ },
+ {
+ type: 'add_edge',
+ source: { client_ref: 'ms' },
+ target: 'agent-1',
+ source_handle: 'output-tool',
+ target_handle: 'input-skill',
+ },
+ ],
+ ctx,
+ );
+
+ expect(result.applied).toBe(2);
+ expect(state.edges).toHaveLength(1);
+ expect(state.edges[0].source).toBe(result.refMap.ms);
+ expect(state.edges[0].target).toBe('agent-1');
+ expect(state.edges[0].sourceHandle).toBe('output-tool');
+ expect(state.edges[0].targetHandle).toBe('input-skill');
+ });
+});
+
+// ----- add_edge --------------------------------------------------------------
+
+describe('add_edge', () => {
+ it('creates an edge between existing node ids', async () => {
+ const { ctx, state } = makeContext({
+ nodes: [makeNode('a', 'x'), makeNode('b', 'y')],
+ });
+ await applyOperations(
+ [{ type: 'add_edge', source: 'a', target: 'b' }],
+ ctx,
+ );
+ expect(state.edges).toHaveLength(1);
+ expect(state.edges[0].source).toBe('a');
+ expect(state.edges[0].target).toBe('b');
+ });
+
+ it('records an error when a client_ref does not resolve', async () => {
+ const { ctx, state } = makeContext({ nodes: [makeNode('a', 'x')] });
+ const result = await applyOperations(
+ [{ type: 'add_edge', source: { client_ref: 'never-added' }, target: 'a' }],
+ ctx,
+ );
+ expect(state.edges).toHaveLength(0);
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0].message).toContain('unresolved client_ref');
+ });
+});
+
+// ----- set_node_parameters ---------------------------------------------------
+
+describe('set_node_parameters', () => {
+ it('forwards the params to saveNodeParameters', async () => {
+ const { ctx, state } = makeContext();
+ await applyOperations(
+ [
+ {
+ type: 'set_node_parameters',
+ node_id: 'n1',
+ parameters: { skillsConfig: {} },
+ },
+ ],
+ ctx,
+ );
+ expect(state.saveCalls).toEqual([
+ { nodeId: 'n1', parameters: { skillsConfig: {} } },
+ ]);
+ });
+
+ it('records an error when the save call returns false', async () => {
+ const { ctx } = makeContext();
+ // Override the harness mock to simulate a failed save. The mock
+ // now just returns false without pushing to saveCalls -- the assertion
+ // here is on errors, not on saveCalls.
+ (ctx.saveNodeParameters as ReturnType<typeof vi.fn>).mockResolvedValue(false);
+ const result = await applyOperations(
+ [{ type: 'set_node_parameters', node_id: 'n1', parameters: {} }],
+ ctx,
+ );
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0].message).toContain('saveNodeParameters returned false');
+ });
+});
+
+// ----- delete_node / delete_edge --------------------------------------------
+
+describe('delete_node', () => {
+ it('removes the node and cascades incident edges', async () => {
+ const { ctx, state } = makeContext({
+ nodes: [makeNode('a', 'x'), makeNode('b', 'y'), makeNode('c', 'z')],
+ edges: [makeEdge('e1', 'a', 'b'), makeEdge('e2', 'b', 'c'), makeEdge('e3', 'a', 'c')],
+ });
+ await applyOperations([{ type: 'delete_node', node_id: 'b' }], ctx);
+ expect(state.nodes.map((n) => n.id)).toEqual(['a', 'c']);
+ // Both edges touching `b` are gone; `a -> c` survives.
+ expect(state.edges.map((e) => e.id)).toEqual(['e3']);
+ });
+});
+
+describe('delete_edge', () => {
+ it('removes only the named edge', async () => {
+ const { ctx, state } = makeContext({
+ edges: [makeEdge('e1', 'a', 'b'), makeEdge('e2', 'a', 'c')],
+ });
+ await applyOperations([{ type: 'delete_edge', edge_id: 'e1' }], ctx);
+ expect(state.edges.map((e) => e.id)).toEqual(['e2']);
+ });
+});
+
+// ----- move_node -------------------------------------------------------------
+
+describe('move_node', () => {
+ it('updates the node position absolutely', async () => {
+ const { ctx, state } = makeContext({ nodes: [makeNode('a', 'x', 1, 2)] });
+ await applyOperations(
+ [{ type: 'move_node', node_id: 'a', position: { x: 99, y: 100 } }],
+ ctx,
+ );
+ expect(state.nodes[0].position).toEqual({ x: 99, y: 100 });
+ });
+
+ it('resolves an anchored position relative to another node', async () => {
+ const { ctx, state } = makeContext({
+ nodes: [makeNode('a', 'x', 0, 0), makeNode('anchor', 'y', 10, 20)],
+ });
+ await applyOperations(
+ [
+ {
+ type: 'move_node',
+ node_id: 'a',
+ position: { anchor_node_id: 'anchor', offset: { x: 5, y: 5 } },
+ },
+ ],
+ ctx,
+ );
+ expect(state.nodes.find((n) => n.id === 'a')!.position).toEqual({ x: 15, y: 25 });
+ });
+});
+
+// ----- replace_node ----------------------------------------------------------
+
+describe('replace_node', () => {
+ it('replaces in place + rewires edges by default (preserve_edges=true)', async () => {
+ const { ctx, state } = makeContext({
+ nodes: [makeNode('old', 'oldType', 50, 60), makeNode('peer', 'p')],
+ edges: [makeEdge('e1', 'peer', 'old'), makeEdge('e2', 'old', 'peer')],
+ });
+
+ const result = await applyOperations(
+ [
+ {
+ type: 'replace_node',
+ node_id: 'old',
+ node_type: 'newType',
+ parameters: { foo: 1 },
+ label: 'New',
+ },
+ ],
+ ctx,
+ );
+
+ expect(result.applied).toBe(1);
+ expect(state.nodes.find((n) => n.id === 'old')).toBeUndefined();
+ const replacement = state.nodes.find((n) => n.type === 'newType');
+ expect(replacement).toBeDefined();
+ expect(replacement!.position).toEqual({ x: 50, y: 60 });
+ expect(replacement!.data).toEqual({ label: 'New' });
+
+ // Edges point at the replacement now, not at the old id.
+ for (const edge of state.edges) {
+ expect(edge.source).not.toBe('old');
+ expect(edge.target).not.toBe('old');
+ }
+ expect(state.edges.map((e) => e.id).sort()).toEqual(['e1', 'e2']);
+ });
+
+ it('drops incident edges when preserve_edges=false', async () => {
+ const { ctx, state } = makeContext({
+ nodes: [makeNode('old', 'oldType')],
+ edges: [makeEdge('e1', 'peer', 'old'), makeEdge('e2', 'old', 'peer')],
+ });
+ await applyOperations(
+ [
+ {
+ type: 'replace_node',
+ node_id: 'old',
+ node_type: 'newType',
+ parameters: {},
+ preserve_edges: false,
+ },
+ ],
+ ctx,
+ );
+ expect(state.edges).toEqual([]);
+ });
+
+ it('records an error if the target node is missing', async () => {
+ const { ctx } = makeContext();
+ const result = await applyOperations(
+ [{ type: 'replace_node', node_id: 'missing', node_type: 't', parameters: {} }],
+ ctx,
+ );
+ expect(result.applied).toBe(0);
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0].message).toContain('not found');
+ });
+});
+
+// ----- best-effort + ordering ------------------------------------------------
+
+describe('applier semantics', () => {
+ it('continues applying ops after one fails (best-effort, no rollback)', async () => {
+ const { ctx, state } = makeContext({ nodes: [makeNode('a', 'x')] });
+ const result = await applyOperations(
+ [
+ // op 0: succeeds
+ { type: 'set_node_parameters', node_id: 'a', parameters: { foo: 1 } },
+ // op 1: fails (unresolved client_ref)
+ { type: 'add_edge', source: { client_ref: 'ghost' }, target: 'a' },
+ // op 2: succeeds despite earlier failure
+ { type: 'delete_node', node_id: 'a' },
+ ],
+ ctx,
+ );
+ expect(result.applied).toBe(2);
+ expect(result.errors).toHaveLength(1);
+ expect(state.nodes).toEqual([]);
+ expect(state.saveCalls).toHaveLength(1);
+ });
+
+ it('add_node + add_edge work in the same batch (cumulative state visible to ops 2..N)', async () => {
+ const target = makeNode('agent', 'aiAgent', 0, 0);
+ const { ctx, state } = makeContext({ nodes: [target] });
+
+ await applyOperations(
+ [
+ { type: 'add_node', client_ref: 'ms', node_type: 'masterSkill', parameters: {} },
+ {
+ type: 'add_edge',
+ source: { client_ref: 'ms' },
+ target: 'agent',
+ target_handle: 'input-skill',
+ },
+ // a follow-up op should see the just-added edge in the live state
+ { type: 'delete_edge', edge_id: state.edges[0]?.id ?? 'NONE' },
+ ],
+ ctx,
+ );
+
+ // After all three ops: MS is added, edge was added then deleted.
+ expect(state.nodes.find((n) => n.type === 'masterSkill')).toBeDefined();
+ // The third op fired with edge id NONE -- silently no-ops, doesn't crash.
+ expect(state.edges).toHaveLength(1);
+ });
+});
diff --git a/server/tests/test_auto_skill.py b/server/tests/test_auto_skill.py
new file mode 100644
index 00000000..dc2a5770
--- /dev/null
+++ b/server/tests/test_auto_skill.py
@@ -0,0 +1,306 @@
+"""Test the auto-add-skill policy in services/auto_skill.evaluate.
+
+The policy decides what (if anything) happens when a tool node is
+connected to (or disconnected from) an AI agent's input-tools handle.
+Output is always a workflow_ops batch (`{operations: [...]}`); the
+three meaningful outcomes are:
+
+ - empty batch (event is irrelevant)
+ - one set_node_parameters op (Master Skill exists; toggle the skill)
+ - add_node + add_edge (no Master Skill; spawn one wired to the agent)
+
+These tests stub the two external lookups -- get_skill (visuals.json
+reverse map) and get_node_class (plugin registry agent check) -- so
+they exercise the policy logic without touching real plugin imports.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from services import auto_skill
+
+
+# --- helpers -----------------------------------------------------------------
+
+
+def _agent_class():
+ """Stand-in for a registered AI agent plugin class."""
+ return SimpleNamespace(component_kind="agent")
+
+
+def _non_agent_class():
+ return SimpleNamespace(component_kind="tool")
+
+
+def _patch_lookups(*, skill: str = "http-request-skill", is_agent: bool = True):
+ """Patch the two external lookups auto_skill.evaluate consults."""
+ return [
+ patch("services.auto_skill.get_skill", return_value=skill),
+ patch(
+ "services.auto_skill.get_node_class",
+ return_value=_agent_class() if is_agent else _non_agent_class(),
+ ),
+ ]
+
+
+def _enter(patches):
+ return [p.__enter__() for p in patches]
+
+
+def _exit(patches):
+ for p in reversed(patches):
+ p.__exit__(None, None, None)
+
+
+def _evaluate(**overrides):
+ """Default-args wrapper so each test only states what it cares about."""
+ kwargs = {
+ "action": "connect",
+ "source_type": "httpRequest",
+ "target_type": "aiAgent",
+ "target_handle": "input-tools",
+ "target_node_id": "agent-1",
+ "master_skill_id": None,
+ "master_skill_config": None,
+ }
+ kwargs.update(overrides)
+ return auto_skill.evaluate(**kwargs)
+
+
+# --- empty / no-op outcomes --------------------------------------------------
+
+
+def test_wrong_target_handle_is_noop():
+ """Connecting to input-skill (or anything other than input-tools) is irrelevant."""
+ patches = _patch_lookups()
+ _enter(patches)
+ try:
+ result = _evaluate(target_handle="input-skill")
+ assert result == {"operations": []}
+ finally:
+ _exit(patches)
+
+
+def test_non_agent_target_is_noop():
+ patches = _patch_lookups(is_agent=False)
+ _enter(patches)
+ try:
+ result = _evaluate()
+ assert result == {"operations": []}
+ finally:
+ _exit(patches)
+
+
+def test_unknown_target_node_class_is_noop():
+ """get_node_class returns None when the type isn't registered -- treat as non-agent."""
+ with patch("services.auto_skill.get_skill", return_value="http-request-skill"), \
+ patch("services.auto_skill.get_node_class", return_value=None):
+ result = _evaluate()
+ assert result == {"operations": []}
+
+
+def test_source_with_no_skill_mapping_is_noop():
+ """A tool node that has no `skill` field in visuals.json is silently skipped."""
+ patches = _patch_lookups(skill="")
+ _enter(patches)
+ try:
+ result = _evaluate()
+ assert result == {"operations": []}
+ finally:
+ _exit(patches)
+
+
+def test_disconnect_with_no_master_skill_is_noop():
+ """Removing a tool when no Master Skill is wired -- nothing to remove from."""
+ patches = _patch_lookups()
+ _enter(patches)
+ try:
+ result = _evaluate(action="disconnect", master_skill_id=None)
+ assert result == {"operations": []}
+ finally:
+ _exit(patches)
+
+
+def test_connect_without_target_node_id_is_noop():
+ """If the frontend can't tell us the agent id, we can't anchor a new MS."""
+ patches = _patch_lookups()
+ _enter(patches)
+ try:
+ result = _evaluate(target_node_id=None, master_skill_id=None)
+ assert result == {"operations": []}
+ finally:
+ _exit(patches)
+
+
+# --- update existing Master Skill --------------------------------------------
+
+
+def test_connect_with_existing_master_skill_returns_set_params():
+ """An MS already wired -> a single set_node_parameters op enabling the skill."""
+ patches = _patch_lookups(skill="http-request-skill")
+ _enter(patches)
+ try:
+ result = _evaluate(master_skill_id="ms-1", master_skill_config={})
+ assert len(result["operations"]) == 1
+ op = result["operations"][0]
+ assert op["type"] == "set_node_parameters"
+ assert op["node_id"] == "ms-1"
+ skills_config = op["parameters"]["skillsConfig"]
+ assert "http-request-skill" in skills_config
+ assert skills_config["http-request-skill"]["enabled"] is True
+ finally:
+ _exit(patches)
+
+
+def test_disconnect_with_existing_master_skill_disables_skill():
+ patches = _patch_lookups(skill="http-request-skill")
+ _enter(patches)
+ try:
+ result = _evaluate(
+ action="disconnect",
+ master_skill_id="ms-1",
+ master_skill_config={
+ "http-request-skill": {
+ "enabled": True,
+ "instructions": "",
+ "isCustomized": False,
+ }
+ },
+ )
+ skills_config = result["operations"][0]["parameters"]["skillsConfig"]
+ assert skills_config["http-request-skill"]["enabled"] is False
+ finally:
+ _exit(patches)
+
+
+def test_existing_skill_customisation_is_preserved_on_toggle():
+ """User-customised instructions must survive an enable/disable toggle."""
+ patches = _patch_lookups(skill="http-request-skill")
+ _enter(patches)
+ try:
+ result = _evaluate(
+ action="disconnect",
+ master_skill_id="ms-1",
+ master_skill_config={
+ "http-request-skill": {
+ "enabled": True,
+ "instructions": "Custom user instructions",
+ "isCustomized": True,
+ }
+ },
+ )
+ entry = result["operations"][0]["parameters"]["skillsConfig"]["http-request-skill"]
+ assert entry["instructions"] == "Custom user instructions"
+ assert entry["isCustomized"] is True
+ assert entry["enabled"] is False # only the enabled flag flipped
+ finally:
+ _exit(patches)
+
+
+def test_other_skills_in_config_are_preserved():
+ """Toggling one skill must not erase entries for other skills."""
+ patches = _patch_lookups(skill="http-request-skill")
+ _enter(patches)
+ try:
+ result = _evaluate(
+ master_skill_id="ms-1",
+ master_skill_config={
+ "calculator-skill": {
+ "enabled": True,
+ "instructions": "",
+ "isCustomized": False,
+ }
+ },
+ )
+ skills_config = result["operations"][0]["parameters"]["skillsConfig"]
+ assert "calculator-skill" in skills_config
+ assert skills_config["calculator-skill"]["enabled"] is True
+ assert skills_config["http-request-skill"]["enabled"] is True
+ finally:
+ _exit(patches)
+
+
+# --- spawn new Master Skill --------------------------------------------------
+
+
+def test_connect_with_no_master_skill_spawns_one():
+ """No MS exists -> add_node + add_edge wiring it to the agent."""
+ patches = _patch_lookups(skill="http-request-skill")
+ _enter(patches)
+ try:
+ result = _evaluate(master_skill_id=None)
+ ops = result["operations"]
+ assert len(ops) == 2
+
+ add_node, add_edge = ops
+ assert add_node["type"] == "add_node"
+ assert add_node["node_type"] == "masterSkill"
+ assert add_node["label"] == "Master Skill"
+ assert "http-request-skill" in add_node["parameters"]["skillsConfig"]
+ assert add_node["parameters"]["skillsConfig"]["http-request-skill"]["enabled"] is True
+
+ # Position is anchored to the agent so the frontend places it nearby.
+ assert add_node["position"]["anchor_node_id"] == "agent-1"
+ assert add_node["position"]["offset"]["y"] == 220
+
+ # Edge wires the new MS into the agent's input-skill handle.
+ assert add_edge["type"] == "add_edge"
+ assert add_edge["source"] == {"client_ref": add_node["client_ref"]}
+ assert add_edge["target"] == "agent-1"
+ assert add_edge["target_handle"] == "input-skill"
+ assert add_edge["source_handle"] == "output-tool"
+ finally:
+ _exit(patches)
+
+
+def test_spawned_master_skill_uses_consistent_client_ref():
+ """The add_edge must reference the same client_ref as the add_node."""
+ patches = _patch_lookups()
+ _enter(patches)
+ try:
+ result = _evaluate(master_skill_id=None)
+ add_node, add_edge = result["operations"]
+ assert add_edge["source"]["client_ref"] == add_node["client_ref"]
+ finally:
+ _exit(patches)
+
+
+# --- internal helper ---------------------------------------------------------
+
+
+def test_toggle_skill_creates_entry_with_defaults():
+ """_toggle_skill on empty config creates a default SkillConfig entry."""
+ result = auto_skill._toggle_skill(None, "calculator-skill", True)
+ assert result == {
+ "calculator-skill": {
+ "enabled": True,
+ "instructions": "",
+ "isCustomized": False,
+ }
+ }
+
+
+def test_toggle_skill_preserves_instructions_on_disable():
+ config = {
+ "x-skill": {"enabled": True, "instructions": "custom", "isCustomized": True},
+ }
+ result = auto_skill._toggle_skill(config, "x-skill", False)
+ assert result["x-skill"]["enabled"] is False
+ assert result["x-skill"]["instructions"] == "custom"
+ assert result["x-skill"]["isCustomized"] is True
+
+
[email protected]("action", ["connect", "disconnect"])
+def test_irrelevant_event_returns_empty_for_either_action(action):
+ """Whatever the action, a non-input-tools handle is always a no-op."""
+ patches = _patch_lookups()
+ _enter(patches)
+ try:
+ result = _evaluate(action=action, target_handle="input-main")
+ assert result == {"operations": []}
+ finally:
+ _exit(patches)
diff --git a/server/tests/test_workflow_ops.py b/server/tests/test_workflow_ops.py
new file mode 100644
index 00000000..6eb9eef4
--- /dev/null
+++ b/server/tests/test_workflow_ops.py
@@ -0,0 +1,230 @@
+"""Test workflow_ops builder helpers.
+
+Locks the wire format that the frontend applier (lib/workflowOps.ts)
+consumes -- if any of these change, the matching applyOperations
+branch in TS must change too.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from services import workflow_ops
+
+
+# --- empty -------------------------------------------------------------------
+
+
+def test_empty_returns_no_operations():
+ assert workflow_ops.empty() == {"operations": []}
+
+
+# --- add_node ----------------------------------------------------------------
+
+
+def test_add_node_minimal_omits_optional_fields():
+ op = workflow_ops.add_node("ref1", "httpRequest")
+ assert op == {
+ "type": "add_node",
+ "client_ref": "ref1",
+ "node_type": "httpRequest",
+ "parameters": {},
+ }
+ # No label/position keys when omitted -- frontend applier defaults them.
+ assert "label" not in op
+ assert "position" not in op
+
+
+def test_add_node_with_label_and_parameters():
+ op = workflow_ops.add_node(
+ "ref1",
+ "masterSkill",
+ {"skillsConfig": {"http-request-skill": {"enabled": True}}},
+ label="Master Skill",
+ )
+ assert op["label"] == "Master Skill"
+ assert op["parameters"] == {
+ "skillsConfig": {"http-request-skill": {"enabled": True}}
+ }
+
+
+def test_add_node_with_anchored_position():
+ pos = workflow_ops.anchored("agent-1", offset_x=-60, offset_y=220)
+ op = workflow_ops.add_node("ms", "masterSkill", position=pos)
+ assert op["position"] == {
+ "anchor_node_id": "agent-1",
+ "offset": {"x": -60, "y": 220},
+ }
+
+
+def test_add_node_with_absolute_position():
+ op = workflow_ops.add_node(
+ "n1",
+ "httpRequest",
+ position={"x": 100, "y": 200},
+ )
+ assert op["position"] == {"x": 100, "y": 200}
+
+
+# --- add_edge ----------------------------------------------------------------
+
+
+def test_add_edge_minimal():
+ op = workflow_ops.add_edge("source-1", "target-1")
+ assert op == {
+ "type": "add_edge",
+ "source": "source-1",
+ "target": "target-1",
+ }
+ assert "source_handle" not in op
+ assert "target_handle" not in op
+
+
+def test_add_edge_with_handles():
+ op = workflow_ops.add_edge(
+ "src",
+ "tgt",
+ source_handle="output-tool",
+ target_handle="input-skill",
+ )
+ assert op["source_handle"] == "output-tool"
+ assert op["target_handle"] == "input-skill"
+
+
+def test_add_edge_with_client_refs():
+ op = workflow_ops.add_edge({"client_ref": "ms"}, "agent-1")
+ assert op["source"] == {"client_ref": "ms"}
+ assert op["target"] == "agent-1"
+
+
+# --- set_node_parameters -----------------------------------------------------
+
+
+def test_set_node_parameters():
+ op = workflow_ops.set_node_parameters("node-1", {"skillsConfig": {}})
+ assert op == {
+ "type": "set_node_parameters",
+ "node_id": "node-1",
+ "parameters": {"skillsConfig": {}},
+ }
+
+
+# --- delete_node / delete_edge -----------------------------------------------
+
+
+def test_delete_node():
+ assert workflow_ops.delete_node("n1") == {"type": "delete_node", "node_id": "n1"}
+
+
+def test_delete_edge():
+ assert workflow_ops.delete_edge("e1") == {"type": "delete_edge", "edge_id": "e1"}
+
+
+# --- move_node ---------------------------------------------------------------
+
+
+def test_move_node_with_absolute_position():
+ op = workflow_ops.move_node("n1", {"x": 50, "y": 100})
+ assert op == {
+ "type": "move_node",
+ "node_id": "n1",
+ "position": {"x": 50, "y": 100},
+ }
+
+
+def test_move_node_with_anchored_position():
+ op = workflow_ops.move_node(
+ "n1",
+ workflow_ops.anchored("anchor-1", offset_x=10, offset_y=20),
+ )
+ assert op["position"]["anchor_node_id"] == "anchor-1"
+
+
+# --- replace_node ------------------------------------------------------------
+
+
+def test_replace_node_defaults_preserve_edges_true():
+ op = workflow_ops.replace_node("old-id", "newType", {"foo": "bar"})
+ assert op == {
+ "type": "replace_node",
+ "node_id": "old-id",
+ "node_type": "newType",
+ "parameters": {"foo": "bar"},
+ "preserve_edges": True,
+ }
+
+
+def test_replace_node_can_drop_edges():
+ op = workflow_ops.replace_node("old-id", "newType", preserve_edges=False)
+ assert op["preserve_edges"] is False
+
+
+def test_replace_node_with_label():
+ op = workflow_ops.replace_node("old-id", "newType", label="New Label")
+ assert op["label"] == "New Label"
+
+
+# --- anchored helper ---------------------------------------------------------
+
+
+def test_anchored_default_zero_offset():
+ pos = workflow_ops.anchored("anchor-1")
+ assert pos == {
+ "anchor_node_id": "anchor-1",
+ "offset": {"x": 0, "y": 0},
+ }
+
+
+def test_anchored_with_fallback():
+ pos = workflow_ops.anchored("anchor-1", fallback={"x": 0, "y": 0})
+ assert pos["fallback"] == {"x": 0, "y": 0}
+
+
+# --- batch shape -------------------------------------------------------------
+
+
+def test_full_batch_round_trip():
+ """A typical auto-skill batch: spawn MS + wire it to an agent."""
+ batch = {
+ "operations": [
+ workflow_ops.add_node(
+ "ms",
+ "masterSkill",
+ {"skillsConfig": {"http-request-skill": {"enabled": True}}},
+ label="Master Skill",
+ position=workflow_ops.anchored("agent-1", offset_x=-60, offset_y=220),
+ ),
+ workflow_ops.add_edge(
+ {"client_ref": "ms"},
+ "agent-1",
+ source_handle="output-tool",
+ target_handle="input-skill",
+ ),
+ ],
+ }
+
+ assert len(batch["operations"]) == 2
+ add_node_op, add_edge_op = batch["operations"]
+
+ assert add_node_op["type"] == "add_node"
+ assert add_node_op["client_ref"] == "ms"
+ assert add_edge_op["source"] == {"client_ref": "ms"}
+ assert add_edge_op["target"] == "agent-1"
+
+
+ "factory,kwargs,expected_type",
+ [
+ (workflow_ops.add_node, {"client_ref": "r", "node_type": "t"}, "add_node"),
+ (workflow_ops.add_edge, {"source": "s", "target": "t"}, "add_edge"),
+ (workflow_ops.set_node_parameters, {"node_id": "n", "parameters": {}}, "set_node_parameters"),
+ (workflow_ops.delete_node, {"node_id": "n"}, "delete_node"),
+ (workflow_ops.delete_edge, {"edge_id": "e"}, "delete_edge"),
+ (workflow_ops.move_node, {"node_id": "n", "position": {"x": 0, "y": 0}}, "move_node"),
+ (workflow_ops.replace_node, {"node_id": "n", "node_type": "t"}, "replace_node"),
+ ],
+)
+def test_every_builder_sets_type_field(factory, kwargs, expected_type):
+ """Each builder must stamp the discriminant `type` field correctly."""
+ op = factory(**kwargs)
+ assert op["type"] == expected_type