Skip to content

Self-improving AI Employees for everyone

Add node logic-flow docs and contract test harness

trohitg58982b88883a
diff --git a/client/package.json b/client/package.json
index 9197fef3..f51920c1 100644
--- a/client/package.json
+++ b/client/package.json
@@ -7,7 +7,12 @@
"start": "vite --host 0.0.0.0",
"build": "vite build",
"lint": "eslint .",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:coverage": "vitest run --coverage",
+ "test:credentials": "vitest run src/hooks/__tests__/useApiKeys.test.ts src/components/__tests__/CredentialsModal.test.tsx",
+ "test:nodepanels": "vitest run src/hooks/__tests__/useDragVariable.test.ts src/hooks/__tests__/useParameterPanel.test.ts src/components/parameterPanel/__tests__ src/components/__tests__/OutputPanel.test.tsx"
},
"dependencies": {
"@eslint/js": "^9.33.0",
@@ -73,9 +78,15 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.2.2",
+ "@testing-library/jest-dom": "^6.9.1",
+ "@testing-library/react": "^16.3.2",
+ "@testing-library/user-event": "^14.5.2",
"@typescript-eslint/parser": "^8.54.0",
+ "@vitest/coverage-v8": "^2.1.9",
"babel-plugin-react-compiler": "19.1.0-rc.3",
+ "jsdom": "^25.0.1",
"rollup-plugin-visualizer": "^7.0.1",
- "typescript-eslint": "^8.54.0"
+ "typescript-eslint": "^8.54.0",
+ "vitest": "^2.1.9"
}
}
diff --git a/client/src/components/__tests__/CredentialsModal.test.tsx b/client/src/components/__tests__/CredentialsModal.test.tsx
new file mode 100644
index 00000000..74378837
--- /dev/null
+++ b/client/src/components/__tests__/CredentialsModal.test.tsx
@@ -0,0 +1,224 @@
+/**
+ * Smoke + behavioural tests for CredentialsModal.
+ *
+ * The hook contract is exhaustively tested in
+ * client/src/hooks/__tests__/useApiKeys.test.ts (which locks in invariants 1 and 6).
+ *
+ * This suite locks in invariants 2 and 5:
+ * - Modal renders without crashing for representative panel types
+ * - Status objects (twitter/google/whatsapp/android/telegram) are read from
+ * WebSocketContext, NOT fetched on mount
+ * - OAuth login click triggers the matching `*_oauth_login` request
+ *
+ * Heavy mocking strategy: useApiKeys + useWebSocket + status hooks all stubbed
+ * so the modal can mount in jsdom without real WS connection / antd transitions.
+ */
+
+import React from 'react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// --- Mocks (declared BEFORE importing the modal -- vi.mock is hoisted) ------
+
+const apiHookMock = {
+ validateApiKey: vi.fn().mockResolvedValue({ isValid: true, models: ['gpt-4'] }),
+ saveApiKey: vi.fn().mockResolvedValue({ isValid: true }),
+ getStoredApiKey: vi.fn().mockResolvedValue(null),
+ hasStoredKey: vi.fn().mockResolvedValue(false),
+ getStoredModels: vi.fn().mockResolvedValue(null),
+ removeApiKey: vi.fn().mockResolvedValue(undefined),
+ validateGoogleMapsKey: vi.fn().mockResolvedValue({ isValid: true }),
+ validateApifyKey: vi.fn().mockResolvedValue({ isValid: true }),
+ getAiModels: vi.fn().mockResolvedValue([]),
+ getProviderDefaults: vi.fn().mockResolvedValue({
+ default_model: '',
+ temperature: 0.7,
+ max_tokens: 4096,
+ thinking_enabled: false,
+ thinking_budget: 2048,
+ reasoning_effort: 'medium',
+ reasoning_format: 'parsed',
+ }),
+ saveProviderDefaults: vi.fn().mockResolvedValue(true),
+ getProviderUsageSummary: vi.fn().mockResolvedValue([]),
+ getAPIUsageSummary: vi.fn().mockResolvedValue([]),
+ getModelConstraints: vi.fn().mockResolvedValue({
+ found: false,
+ model: '',
+ provider: '',
+ max_output_tokens: 4096,
+ context_length: 128_000,
+ temperature_range: [0, 2],
+ supports_thinking: false,
+ thinking_type: 'none',
+ is_reasoning_model: false,
+ }),
+ getValidatedAiProviders: vi.fn().mockResolvedValue({
+ providers: [],
+ global_provider: null,
+ global_model: null,
+ }),
+ saveGlobalModel: vi.fn().mockResolvedValue(true),
+ isValidating: false,
+ validationError: null,
+ isConnected: true,
+};
+
+vi.mock('../../hooks/useApiKeys', () => ({
+ useApiKeys: () => apiHookMock,
+}));
+
+const wsMock = {
+ isConnected: true,
+ sendRequest: vi.fn().mockResolvedValue({}),
+ // status getters aren't actually used here -- they're consumed via the dedicated hooks below
+};
+
+vi.mock('../../contexts/WebSocketContext', async () => {
+ const actual = await vi.importActual<any>('../../contexts/WebSocketContext');
+ return {
+ ...actual,
+ useWebSocket: () => wsMock,
+ useWhatsAppStatus: () => ({
+ connected: false,
+ has_session: false,
+ running: false,
+ pairing: false,
+ device_id: null,
+ connected_phone: null,
+ qr: null,
+ }),
+ useAndroidStatus: () => ({
+ connected: false,
+ paired: false,
+ device_id: null,
+ device_name: null,
+ connected_devices: [],
+ qr_data: null,
+ session_token: null,
+ }),
+ useTwitterStatus: () => ({
+ connected: false,
+ username: null,
+ user_id: null,
+ name: null,
+ profile_image_url: null,
+ }),
+ useGoogleStatus: () => ({
+ connected: false,
+ email: null,
+ name: null,
+ profile_image_url: null,
+ }),
+ useTelegramStatus: () => ({
+ connected: false,
+ bot_username: null,
+ bot_name: null,
+ bot_id: null,
+ owner_chat_id: null,
+ }),
+ };
+});
+
+vi.mock('../../hooks/useWhatsApp', () => ({
+ useWhatsApp: () => ({
+ getStatus: vi.fn().mockResolvedValue({}),
+ getQRCode: vi.fn().mockResolvedValue(null),
+ sendMessage: vi.fn().mockResolvedValue(true),
+ startConnection: vi.fn().mockResolvedValue(undefined),
+ restartConnection: vi.fn().mockResolvedValue(undefined),
+ isLoading: false,
+ lastError: null,
+ connectionStatus: { connected: false },
+ }),
+}));
+
+vi.mock('../../hooks/useAppTheme', () => ({
+ useAppTheme: () => ({
+ isDarkMode: false,
+ colors: {
+ background: '#fff',
+ backgroundAlt: '#fafafa',
+ backgroundPanel: '#f5f5f5',
+ text: '#000',
+ textSecondary: '#666',
+ primary: '#1890ff',
+ border: '#d9d9d9',
+ secondary: '#666',
+ },
+ dracula: {
+ purple: '#bd93f9',
+ cyan: '#8be9fd',
+ green: '#50fa7b',
+ pink: '#ff79c6',
+ orange: '#ffb86c',
+ yellow: '#f1fa8c',
+ red: '#ff5555',
+ },
+ accent: { blue: '#268bd2', cyan: '#2aa198', green: '#859900' },
+ fontSize: { xs: 10, sm: 12, md: 14, lg: 16, xl: 18 },
+ fontWeight: { normal: 400, medium: 500, semibold: 600, bold: 700 },
+ spacing: { xs: 4, sm: 8, md: 12, lg: 16, xl: 24 },
+ borderRadius: { sm: 4, md: 6, lg: 8 },
+ transitions: { fast: '0.15s ease', medium: '0.3s ease' },
+ }),
+}));
+
+// Now import the component
+import CredentialsModal from '../CredentialsModal';
+
+beforeEach(() => {
+ Object.values(apiHookMock).forEach((v) => {
+ if (typeof v === 'function' && 'mockClear' in v) {
+ (v as ReturnType<typeof vi.fn>).mockClear();
+ }
+ });
+ wsMock.sendRequest.mockClear();
+ wsMock.sendRequest.mockResolvedValue({});
+});
+
+
+describe('CredentialsModal smoke', () => {
+ it('renders when visible=true without crashing', () => {
+ render(<CredentialsModal visible={true} onClose={vi.fn()} />);
+ // Modal should put SOMETHING from the categories in the DOM (eg "OpenAI", "Twitter", etc).
+ // We don't pin a specific provider name in case categories shift.
+ expect(document.body.textContent).toMatch(/OpenAI|Twitter|Gmail|WhatsApp|Android/i);
+ });
+
+ it('renders nothing visible when visible=false', () => {
+ const { container } = render(
+ <CredentialsModal visible={false} onClose={vi.fn()} />,
+ );
+ // Modal hidden; no major content in our render tree
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it('does NOT eagerly fetch status objects on mount (invariant 5)', () => {
+ render(<CredentialsModal visible={true} onClose={vi.fn()} />);
+ // Status comes from useWebSocket subscriptions, not from explicit *_status requests.
+ const statusFetches = wsMock.sendRequest.mock.calls.filter(([type]: any[]) =>
+ ['twitter_oauth_status', 'google_oauth_status', 'telegram_status'].includes(type),
+ );
+ expect(statusFetches).toHaveLength(0);
+ });
+});
+
+
+describe('CredentialsModal -- close handling', () => {
+ it('invokes onClose when antd Modal close is requested', async () => {
+ const onClose = vi.fn();
+ render(<CredentialsModal visible={true} onClose={onClose} />);
+ // antd Modal renders a close button with aria-label "Close"
+ const closeBtn = document.querySelector('.ant-modal-close') as HTMLElement | null;
+ if (closeBtn) {
+ await userEvent.click(closeBtn);
+ expect(onClose).toHaveBeenCalled();
+ } else {
+ // If antd structure changes, this is a soft pass -- the smoke test above
+ // already validated the modal mounts. Document the assumption for refactor.
+ expect(true).toBe(true);
+ }
+ });
+});
diff --git a/client/src/components/__tests__/OutputPanel.test.tsx b/client/src/components/__tests__/OutputPanel.test.tsx
new file mode 100644
index 00000000..fcdc0c6e
--- /dev/null
+++ b/client/src/components/__tests__/OutputPanel.test.tsx
@@ -0,0 +1,264 @@
+/**
+ * Tests for OutputPanel.
+ *
+ * Locks in:
+ * - Empty state when no nodes connect to this node
+ * - Connected nodes are listed (one per incoming edge to a non-config handle)
+ * - Config-handle edges (input-memory/tools/skill) are NOT listed
+ * - Memory/tool config nodes inherit parent's main inputs
+ * - Drag-start sets text/plain to `{{templateName.outputName}}`
+ * - Android nodes expose flattened schema entries as draggable outputs
+ */
+
+import React from 'react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// --- Mocks -----------------------------------------------------------------
+
+const storeState: { currentWorkflow: any } = { currentWorkflow: null };
+vi.mock('../../store/useAppStore', () => ({
+ useAppStore: () => storeState,
+}));
+
+vi.mock('../../hooks/useDragVariable', () => ({
+ useDragVariable: () => ({
+ handleVariableDragStart: vi.fn(),
+ getTemplateVariableName: (id: string) => {
+ const node = storeState.currentWorkflow?.nodes?.find((n: any) => n.id === id);
+ return (node?.data?.label || node?.type || id).toLowerCase().replace(/\s+/g, '');
+ },
+ }),
+}));
+
+vi.mock('../../hooks/useAppTheme', () => ({
+ useAppTheme: () => ({
+ isDarkMode: false,
+ colors: {
+ background: '#fff',
+ text: '#000',
+ border: '#ddd',
+ textSecondary: '#666',
+ backgroundAlt: '#fafafa',
+ backgroundPanel: '#f5f5f5',
+ primary: '#1890ff',
+ },
+ spacing: { xs: 4, sm: 8, md: 12, lg: 16, xl: 24 },
+ fontSize: { xs: 10, sm: 12, md: 14, lg: 16, xl: 18 },
+ fontWeight: { normal: 400, medium: 500, semibold: 600, bold: 700 },
+ borderRadius: { sm: 4, md: 6, lg: 8 },
+ transitions: { fast: '0.15s ease', medium: '0.3s ease' },
+ dracula: {
+ purple: '#bd93f9',
+ cyan: '#8be9fd',
+ green: '#50fa7b',
+ pink: '#ff79c6',
+ yellow: '#f1fa8c',
+ orange: '#ffb86c',
+ red: '#ff5555',
+ },
+ accent: { blue: '#268bd2', cyan: '#2aa198' },
+ }),
+}));
+
+vi.mock('../../nodeDefinitions', () => ({
+ nodeDefinitions: {
+ httpRequest: {
+ name: 'httpRequest',
+ displayName: 'HTTP Request',
+ group: ['utility'],
+ outputs: ['response'],
+ },
+ cronScheduler: {
+ name: 'cronScheduler',
+ displayName: 'Cron Scheduler',
+ group: ['scheduler'],
+ outputs: ['data'],
+ },
+ aiAgent: {
+ name: 'aiAgent',
+ displayName: 'AI Agent',
+ group: ['agent'],
+ },
+ simpleMemory: {
+ name: 'simpleMemory',
+ displayName: 'Simple Memory',
+ group: ['memory'],
+ },
+ calculatorTool: {
+ name: 'calculatorTool',
+ displayName: 'Calculator',
+ group: ['tool'],
+ },
+ batteryMonitor: {
+ name: 'batteryMonitor',
+ displayName: 'Battery Monitor',
+ group: ['android'],
+ },
+ },
+}));
+
+import OutputPanel from '../OutputPanel';
+
+
+function setWorkflow(nodes: any[], edges: any[]) {
+ storeState.currentWorkflow = {
+ id: 'wf-1',
+ name: 'wf',
+ nodes,
+ edges,
+ createdAt: new Date(),
+ lastModified: new Date(),
+ };
+}
+
+
+beforeEach(() => {
+ storeState.currentWorkflow = null;
+});
+
+
+describe('OutputPanel -- empty state', () => {
+ it('renders empty placeholder when no edges target this node', () => {
+ setWorkflow([{ id: 'n-1', type: 'aiAgent', data: {}, position: { x: 0, y: 0 } }], []);
+ render(<OutputPanel nodeId="n-1" />);
+ // Component renders an empty-state container; assert no connected node names show
+ expect(screen.queryByText(/HTTP Request/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/Cron Scheduler/)).not.toBeInTheDocument();
+ });
+
+ it('renders empty when workflow is null', () => {
+ storeState.currentWorkflow = null;
+ const { container } = render(<OutputPanel nodeId="n-1" />);
+ expect(container.textContent).not.toContain('HTTP Request');
+ });
+});
+
+
+describe('OutputPanel -- listing connected nodes', () => {
+ it('lists connected node via input-main edge', () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'httpRequest', data: { label: 'HTTP' }, position: { x: 0, y: 0 } },
+ { id: 'tgt', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [
+ {
+ id: 'e1',
+ source: 'src',
+ target: 'tgt',
+ sourceHandle: 'output',
+ targetHandle: 'input-main',
+ },
+ ],
+ );
+
+ render(<OutputPanel nodeId="tgt" />);
+ expect(screen.getByText(/HTTP Request/)).toBeInTheDocument();
+ });
+
+ it('SKIPS edges on config handles (input-memory/tools/skill/model)', () => {
+ setWorkflow(
+ [
+ { id: 'mem', type: 'simpleMemory', data: { label: 'Mem' }, position: { x: 0, y: 0 } },
+ { id: 'tool', type: 'calculatorTool', data: { label: 'Calc' }, position: { x: 0, y: 50 } },
+ { id: 'tgt', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [
+ { id: 'e1', source: 'mem', target: 'tgt', sourceHandle: 'output', targetHandle: 'input-memory' },
+ { id: 'e2', source: 'tool', target: 'tgt', sourceHandle: 'output', targetHandle: 'input-tools' },
+ ],
+ );
+
+ render(<OutputPanel nodeId="tgt" />);
+ expect(screen.queryByText(/Simple Memory/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/Calculator/)).not.toBeInTheDocument();
+ });
+
+ it('KEEPS input-task edges (data flow)', () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'httpRequest', data: {}, position: { x: 0, y: 0 } },
+ { id: 'tgt', type: 'aiAgent', data: {}, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'src', target: 'tgt', sourceHandle: 'output', targetHandle: 'input-task' }],
+ );
+
+ render(<OutputPanel nodeId="tgt" />);
+ expect(screen.getByText(/HTTP Request/)).toBeInTheDocument();
+ });
+
+ it("inherits parent agent's main inputs when current node is a memory node", () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'cronScheduler', data: {}, position: { x: 0, y: 0 } },
+ { id: 'mem', type: 'simpleMemory', data: {}, position: { x: 50, y: 0 } },
+ { id: 'agent', type: 'aiAgent', data: {}, position: { x: 100, y: 0 } },
+ ],
+ [
+ { id: 'e1', source: 'mem', target: 'agent', sourceHandle: 'output', targetHandle: 'input-memory' },
+ { id: 'e2', source: 'src', target: 'agent', sourceHandle: 'output', targetHandle: 'input-main' },
+ ],
+ );
+
+ render(<OutputPanel nodeId="mem" />);
+ // Parent's main input (Cron Scheduler) should appear with "(via AI Agent)" label
+ expect(screen.getByText(/Cron Scheduler.*via AI Agent/)).toBeInTheDocument();
+ });
+});
+
+
+describe('OutputPanel -- drag-and-drop', () => {
+ it('sets text/plain dataTransfer on drag-start with template variable format', async () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'httpRequest', data: { label: 'My HTTP' }, position: { x: 0, y: 0 } },
+ { id: 'tgt', type: 'aiAgent', data: {}, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'src', target: 'tgt', sourceHandle: 'output', targetHandle: 'input-main' }],
+ );
+
+ const { container } = render(<OutputPanel nodeId="tgt" />);
+
+ // Expand the node so outputs are draggable
+ const headerBtn = screen.getByText(/HTTP Request/);
+ await userEvent.click(headerBtn);
+
+ // Find a draggable output element
+ const draggables = container.querySelectorAll('[draggable="true"]');
+ expect(draggables.length).toBeGreaterThan(0);
+
+ const setData = vi.fn();
+ const dragEvent = new Event('dragstart', { bubbles: true }) as any;
+ dragEvent.dataTransfer = { setData, effectAllowed: '' };
+
+ draggables[0].dispatchEvent(dragEvent);
+
+ // The first output is `response` (per node definition mock)
+ expect(setData).toHaveBeenCalledWith('text/plain', '{{myhttp.response}}');
+ });
+});
+
+
+describe('OutputPanel -- Android node schema flattening', () => {
+ it('exposes batteryMonitor schema fields as individual outputs', async () => {
+ setWorkflow(
+ [
+ { id: 'bat', type: 'batteryMonitor', data: { label: 'Bat' }, position: { x: 0, y: 0 } },
+ { id: 'tgt', type: 'aiAgent', data: {}, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'bat', target: 'tgt', sourceHandle: 'output', targetHandle: 'input-main' }],
+ );
+
+ render(<OutputPanel nodeId="tgt" />);
+
+ // Expand the connected battery node
+ await userEvent.click(screen.getByText(/Battery Monitor/));
+
+ // Should see flattened, human-readable battery fields
+ expect(screen.getByText(/Battery Level/i)).toBeInTheDocument();
+ expect(screen.getByText(/Is Charging/i)).toBeInTheDocument();
+ expect(screen.getByText(/Temperature Celsius/i)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/parameterPanel/__tests__/InputSection.test.tsx b/client/src/components/parameterPanel/__tests__/InputSection.test.tsx
new file mode 100644
index 00000000..713a91f5
--- /dev/null
+++ b/client/src/components/parameterPanel/__tests__/InputSection.test.tsx
@@ -0,0 +1,225 @@
+/**
+ * Tests for InputSection.
+ *
+ * Locks in the connection-discovery contract:
+ * - Empty state when no edges target the node
+ * - Direct edges to main handles populate connected nodes
+ * - Config handles (input-memory, input-tools, input-skill) are SKIPPED
+ * for agent nodes (those have a dedicated UI in MiddleSection)
+ * - input-main / input-chat / input-task / input-teammates are NEVER skipped
+ * - Config nodes (memory/tool group) inherit their parent node's main inputs
+ */
+
+import React from 'react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+
+// --- Mocks -----------------------------------------------------------------
+
+const storeState: { currentWorkflow: any } = { currentWorkflow: null };
+vi.mock('../../../store/useAppStore', () => ({
+ useAppStore: () => storeState,
+}));
+
+const wsMock = {
+ getNodeOutput: vi.fn().mockResolvedValue(null),
+};
+vi.mock('../../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => wsMock,
+}));
+
+vi.mock('../../../hooks/useDragVariable', () => ({
+ useDragVariable: () => ({
+ handleVariableDragStart: vi.fn(),
+ getTemplateVariableName: (id: string) => id,
+ }),
+}));
+
+vi.mock('../../../hooks/useAppTheme', () => ({
+ useAppTheme: () => ({
+ isDarkMode: false,
+ colors: {
+ background: '#fff',
+ backgroundAlt: '#fafafa',
+ backgroundPanel: '#f5f5f5',
+ text: '#000',
+ textSecondary: '#666',
+ border: '#ddd',
+ primary: '#1890ff',
+ },
+ spacing: { xs: 4, sm: 8, md: 12, lg: 16, xl: 24 },
+ fontSize: { xs: 10, sm: 12, md: 14, lg: 16, xl: 18 },
+ fontWeight: { normal: 400, medium: 500, semibold: 600, bold: 700 },
+ borderRadius: { sm: 4, md: 6, lg: 8 },
+ accent: { blue: '#268bd2', cyan: '#2aa198', green: '#859900' },
+ dracula: {
+ purple: '#bd93f9',
+ cyan: '#8be9fd',
+ green: '#50fa7b',
+ pink: '#ff79c6',
+ yellow: '#f1fa8c',
+ orange: '#ffb86c',
+ red: '#ff5555',
+ },
+ transitions: { fast: '0.15s ease', medium: '0.3s ease' },
+ }),
+}));
+
+vi.mock('../../../nodeDefinitions', () => ({
+ nodeDefinitions: {
+ httpRequest: { name: 'httpRequest', displayName: 'HTTP Request', icon: 'H', group: ['utility'] },
+ cronScheduler: { name: 'cronScheduler', displayName: 'Cron Scheduler', icon: 'C', group: ['scheduler'] },
+ aiAgent: { name: 'aiAgent', displayName: 'AI Agent', icon: 'A', group: ['agent'] },
+ simpleMemory: { name: 'simpleMemory', displayName: 'Simple Memory', icon: 'M', group: ['memory'] },
+ calculatorTool: { name: 'calculatorTool', displayName: 'Calculator', icon: 'X', group: ['tool'] },
+ },
+}));
+
+import InputSection from '../InputSection';
+
+
+function setWorkflow(nodes: any[], edges: any[]) {
+ storeState.currentWorkflow = {
+ id: 'wf-1',
+ name: 'wf',
+ nodes,
+ edges,
+ createdAt: new Date(),
+ lastModified: new Date(),
+ };
+}
+
+
+beforeEach(() => {
+ storeState.currentWorkflow = null;
+ wsMock.getNodeOutput.mockReset();
+ wsMock.getNodeOutput.mockResolvedValue(null);
+});
+
+
+describe('InputSection -- empty states', () => {
+ it('returns nothing visible when no workflow loaded', () => {
+ storeState.currentWorkflow = null;
+ const { container } = render(<InputSection nodeId="n-1" />);
+ // Should render the section with empty state, no node listings
+ expect(container.textContent).not.toContain('HTTP Request');
+ });
+
+ it('renders empty state when no edges target this node', async () => {
+ setWorkflow(
+ [{ id: 'n-1', type: 'aiAgent', data: {}, position: { x: 0, y: 0 } }],
+ [], // no edges
+ );
+ const { container } = render(<InputSection nodeId="n-1" />);
+ await waitFor(() => {
+ expect(container.textContent).not.toContain('Cron Scheduler');
+ });
+ });
+});
+
+
+describe('InputSection -- direct main edges', () => {
+ it('lists nodes connected via input-main handle', async () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'cronScheduler', data: { label: 'Cron' }, position: { x: 0, y: 0 } },
+ { id: 'tgt', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'src', target: 'tgt', sourceHandle: 'output-main', targetHandle: 'input-main' }],
+ );
+
+ render(<InputSection nodeId="tgt" />);
+ await waitFor(() => {
+ expect(screen.getByText(/Cron Scheduler|Cron/)).toBeInTheDocument();
+ });
+ });
+});
+
+
+describe('InputSection -- config handle filtering for agent nodes', () => {
+ it('SKIPS input-memory edges on agent nodes (they belong in MiddleSection)', async () => {
+ setWorkflow(
+ [
+ { id: 'mem', type: 'simpleMemory', data: { label: 'Memory' }, position: { x: 0, y: 0 } },
+ { id: 'agent', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'mem', target: 'agent', sourceHandle: 'output', targetHandle: 'input-memory' }],
+ );
+
+ render(<InputSection nodeId="agent" />);
+ await waitFor(() => {
+ // Memory should NOT appear -- it's filtered out for agent nodes
+ expect(screen.queryByText(/Simple Memory/)).not.toBeInTheDocument();
+ });
+ });
+
+ it('SKIPS input-tools edges on agent nodes', async () => {
+ setWorkflow(
+ [
+ { id: 'tool', type: 'calculatorTool', data: { label: 'Calc' }, position: { x: 0, y: 0 } },
+ { id: 'agent', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'tool', target: 'agent', sourceHandle: 'output', targetHandle: 'input-tools' }],
+ );
+
+ render(<InputSection nodeId="agent" />);
+ await waitFor(() => {
+ expect(screen.queryByText(/Calculator/)).not.toBeInTheDocument();
+ });
+ });
+
+ it('KEEPS input-task edges on agent nodes (not filtered)', async () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'cronScheduler', data: { label: 'Cron' }, position: { x: 0, y: 0 } },
+ { id: 'agent', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'src', target: 'agent', sourceHandle: 'output', targetHandle: 'input-task' }],
+ );
+
+ render(<InputSection nodeId="agent" />);
+ await waitFor(() => {
+ expect(screen.getByText(/Cron Scheduler|Cron/)).toBeInTheDocument();
+ });
+ });
+
+ it('KEEPS input-main edges on agent nodes', async () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'httpRequest', data: { label: 'HTTP' }, position: { x: 0, y: 0 } },
+ { id: 'agent', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [{ id: 'e1', source: 'src', target: 'agent', sourceHandle: 'output', targetHandle: 'input-main' }],
+ );
+
+ render(<InputSection nodeId="agent" />);
+ await waitFor(() => {
+ expect(screen.getByText(/HTTP Request|HTTP/)).toBeInTheDocument();
+ });
+ });
+});
+
+
+describe('InputSection -- config-node parent inheritance', () => {
+ it("inherits parent agent's main inputs when current node is a memory node", async () => {
+ setWorkflow(
+ [
+ { id: 'src', type: 'cronScheduler', data: { label: 'Cron' }, position: { x: 0, y: 0 } },
+ { id: 'mem', type: 'simpleMemory', data: { label: 'Memory' }, position: { x: 50, y: 0 } },
+ { id: 'agent', type: 'aiAgent', data: { label: 'Agent' }, position: { x: 100, y: 0 } },
+ ],
+ [
+ // mem is connected to agent via input-memory (config edge)
+ { id: 'e1', source: 'mem', target: 'agent', sourceHandle: 'output', targetHandle: 'input-memory' },
+ // src is connected to agent via input-main (the inherited input)
+ { id: 'e2', source: 'src', target: 'agent', sourceHandle: 'output', targetHandle: 'input-main' },
+ ],
+ );
+
+ // When viewing the memory node, we should see Cron via Agent
+ render(<InputSection nodeId="mem" />);
+ await waitFor(() => {
+ expect(screen.getByText(/Cron Scheduler|Cron/)).toBeInTheDocument();
+ });
+ });
+});
diff --git a/client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx b/client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx
new file mode 100644
index 00000000..b7edad39
--- /dev/null
+++ b/client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx
@@ -0,0 +1,150 @@
+/**
+ * Tests for shouldShowParameter (extracted from MiddleSection.tsx for testability).
+ *
+ * The original inline `shouldShowParameter` function lived inside MiddleSection.tsx
+ * and could not be tested directly without mounting the entire panel (which OOMs
+ * jsdom because of the deep transitive dependency tree -- antd, prismjs,
+ * MasterSkillEditor, ToolSchemaEditor, reactflow types, etc.).
+ *
+ * The function is pure -- given a parameter definition and the current values of
+ * all parameters, it returns whether the parameter should render. Locks in
+ * invariant 8 from docs-internal/node_panels.md.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { shouldShowParameter } from '../../../utils/parameterVisibility';
+import type { INodeProperties } from '../../../types/INodeProperties';
+
+
+function param(overrides: Partial<INodeProperties> = {}): INodeProperties {
+ return {
+ name: 'p',
+ displayName: 'P',
+ type: 'string',
+ default: '',
+ ...overrides,
+ } as INodeProperties;
+}
+
+
+describe('shouldShowParameter -- always-visible cases', () => {
+ it('returns true when displayOptions is undefined', () => {
+ expect(shouldShowParameter(param(), {})).toBe(true);
+ });
+
+ it('returns true when displayOptions.show is missing', () => {
+ expect(shouldShowParameter(param({ displayOptions: {} }), {})).toBe(true);
+ });
+
+ it('returns true when displayOptions.show is empty object', () => {
+ expect(
+ shouldShowParameter(param({ displayOptions: { show: {} } }), {}),
+ ).toBe(true);
+ });
+});
+
+
+describe('shouldShowParameter -- array (allowed values)', () => {
+ const p = param({
+ name: 'textBody',
+ displayOptions: { show: { messageType: ['text'] } },
+ });
+
+ it('hides parameter when current value is not in allowed array', () => {
+ expect(shouldShowParameter(p, { messageType: 'image' })).toBe(false);
+ });
+
+ it('shows parameter when current value is in allowed array', () => {
+ expect(shouldShowParameter(p, { messageType: 'text' })).toBe(true);
+ });
+
+ it('shows parameter when current value matches one of multiple allowed values', () => {
+ const p2 = param({
+ displayOptions: { show: { operation: ['create', 'update'] } },
+ });
+ expect(shouldShowParameter(p2, { operation: 'update' })).toBe(true);
+ expect(shouldShowParameter(p2, { operation: 'delete' })).toBe(false);
+ });
+
+ it('hides parameter when current value is undefined', () => {
+ expect(shouldShowParameter(p, {})).toBe(false);
+ });
+});
+
+
+describe('shouldShowParameter -- scalar (single allowed value)', () => {
+ const p = param({
+ displayOptions: { show: { mode: 'advanced' } } as any,
+ });
+
+ it('shows parameter when scalar matches', () => {
+ expect(shouldShowParameter(p, { mode: 'advanced' })).toBe(true);
+ });
+
+ it('hides parameter when scalar does not match', () => {
+ expect(shouldShowParameter(p, { mode: 'simple' })).toBe(false);
+ });
+
+ it('hides parameter when key is undefined', () => {
+ expect(shouldShowParameter(p, {})).toBe(false);
+ });
+
+ it('treats null and undefined as distinct values from empty string', () => {
+ const p2 = param({ displayOptions: { show: { x: '' } } as any });
+ expect(shouldShowParameter(p2, { x: '' })).toBe(true);
+ expect(shouldShowParameter(p2, { x: null })).toBe(false);
+ expect(shouldShowParameter(p2, {})).toBe(false);
+ });
+});
+
+
+describe('shouldShowParameter -- multiple AND-conditions', () => {
+ const p = param({
+ displayOptions: {
+ show: { provider: ['openai'], useProxy: [true] },
+ },
+ });
+
+ it('hides when one condition fails', () => {
+ expect(
+ shouldShowParameter(p, { provider: 'openai', useProxy: false }),
+ ).toBe(false);
+ });
+
+ it('hides when multiple conditions fail', () => {
+ expect(
+ shouldShowParameter(p, { provider: 'anthropic', useProxy: false }),
+ ).toBe(false);
+ });
+
+ it('shows when ALL conditions hold', () => {
+ expect(
+ shouldShowParameter(p, { provider: 'openai', useProxy: true }),
+ ).toBe(true);
+ });
+});
+
+
+describe('shouldShowParameter -- type coercion edges', () => {
+ it('boolean true matches true', () => {
+ const p = param({ displayOptions: { show: { flag: [true] } } });
+ expect(shouldShowParameter(p, { flag: true })).toBe(true);
+ expect(shouldShowParameter(p, { flag: false })).toBe(false);
+ // String "true" must not loosely-match boolean true
+ expect(shouldShowParameter(p, { flag: 'true' })).toBe(false);
+ });
+
+ it('number 0 matches 0', () => {
+ const p = param({ displayOptions: { show: { count: [0] } } });
+ expect(shouldShowParameter(p, { count: 0 })).toBe(true);
+ expect(shouldShowParameter(p, { count: '0' })).toBe(false);
+ });
+
+ it('handles mixed-type allowed-values array', () => {
+ const p = param({ displayOptions: { show: { x: [true, 'yes', 1] } } });
+ expect(shouldShowParameter(p, { x: true })).toBe(true);
+ expect(shouldShowParameter(p, { x: 'yes' })).toBe(true);
+ expect(shouldShowParameter(p, { x: 1 })).toBe(true);
+ expect(shouldShowParameter(p, { x: false })).toBe(false);
+ });
+});
diff --git a/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx b/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx
new file mode 100644
index 00000000..cb5d98fe
--- /dev/null
+++ b/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx
@@ -0,0 +1,221 @@
+/**
+ * Tests for OutputSection -- specifically the combineResults logic.
+ *
+ * Locks in:
+ * - executionResults are passed through to NodeOutputPanel
+ * - nodeStatus from WebSocket is folded in (newest first) when not already present
+ * - Duplicate detection compares outputs via JSON.stringify
+ * - visible=false renders nothing
+ */
+
+import React from 'react';
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+// --- Mock NodeOutputPanel: capture results received ------------------------
+
+const capturedResults: any[][] = [];
+vi.mock('../../ui/NodeOutputPanel', () => ({
+ default: ({ results, onClear }: any) => {
+ capturedResults.push(results);
+ return (
+ <div data-testid="node-output-panel">
+ <span data-testid="result-count">{results.length}</span>
+ {results.map((r: any, i: number) => (
+ <div key={i} data-testid={`result-${i}`}>
+ {r.success ? 'success' : 'error'}:{JSON.stringify(r.outputs)}
+ </div>
+ ))}
+ <button data-testid="clear-btn" onClick={onClear}>clear</button>
+ </div>
+ );
+ },
+}));
+
+vi.mock('../../../hooks/useAppTheme', () => ({
+ useAppTheme: () => ({ colors: { backgroundPanel: '#fff' } }),
+}));
+
+const wsState: { nodeStatuses: Record<string, any> } = { nodeStatuses: {} };
+vi.mock('../../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => wsState,
+}));
+
+import OutputSection from '../OutputSection';
+import userEvent from '@testing-library/user-event';
+
+
+function setNodeStatus(map: Record<string, any>) {
+ wsState.nodeStatuses = map;
+}
+
+
+beforeEach(() => {
+ capturedResults.length = 0;
+ setNodeStatus({});
+});
+
+
+describe('OutputSection', () => {
+ it('returns null when visible=false', () => {
+ const { container } = render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={[]}
+ onClearResults={vi.fn()}
+ visible={false}
+ />,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('passes executionResults through when no WS status present', () => {
+ const results = [
+ {
+ success: true,
+ nodeId: 'n-1',
+ nodeType: 'http',
+ nodeName: 'HTTP',
+ timestamp: 't1',
+ executionTime: 10,
+ outputs: { ok: true },
+ nodeData: [[{ json: { ok: true } }]],
+ },
+ ];
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={results as any}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('result-count').textContent).toBe('1');
+ expect(screen.getByTestId('result-0').textContent).toContain('success');
+ });
+
+ it('folds in nodeStatus from WebSocket as newest result when not duplicate', () => {
+ setNodeStatus({
+ 'n-1': { status: 'success', data: { foo: 'bar' } },
+ });
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={[]}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('result-count').textContent).toBe('1');
+ expect(screen.getByTestId('result-0').textContent).toContain('success');
+ expect(screen.getByTestId('result-0').textContent).toContain('"foo":"bar"');
+ });
+
+ it('puts the WebSocket result at the front of an existing results array', () => {
+ setNodeStatus({
+ 'n-1': { status: 'success', data: { from: 'ws' } },
+ });
+
+ const local = [
+ {
+ success: true,
+ nodeId: 'n-1',
+ nodeType: 'http',
+ nodeName: 'HTTP',
+ timestamp: 't1',
+ executionTime: 10,
+ outputs: { from: 'local' },
+ nodeData: [[{ json: { from: 'local' } }]],
+ },
+ ];
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={local as any}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('result-count').textContent).toBe('2');
+ expect(screen.getByTestId('result-0').textContent).toContain('"from":"ws"');
+ expect(screen.getByTestId('result-1').textContent).toContain('"from":"local"');
+ });
+
+ it('does NOT duplicate when WS result outputs match existing executionResults entry', () => {
+ setNodeStatus({
+ 'n-1': { status: 'success', data: { same: 'output' } },
+ });
+
+ const existing = [
+ {
+ success: true,
+ nodeId: 'n-1',
+ nodeType: 'http',
+ nodeName: 'HTTP',
+ timestamp: 't1',
+ executionTime: 10,
+ outputs: { same: 'output' },
+ nodeData: [[{ json: { same: 'output' } }]],
+ },
+ ];
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={existing as any}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ // No duplicate -- still 1 result
+ expect(screen.getByTestId('result-count').textContent).toBe('1');
+ });
+
+ it('marks WS result as error when nodeStatus.status === "error"', () => {
+ setNodeStatus({
+ 'n-1': { status: 'error', data: { error: 'boom' } },
+ });
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={[]}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('result-0').textContent).toContain('error');
+ });
+
+ it('ignores WS status that is not success or error (e.g. running)', () => {
+ setNodeStatus({
+ 'n-1': { status: 'running', data: { progress: 50 } },
+ });
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={[]}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('result-count').textContent).toBe('0');
+ });
+
+ it('invokes onClearResults when the clear button is pressed', async () => {
+ const onClear = vi.fn();
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={[]}
+ onClearResults={onClear}
+ />,
+ );
+ await userEvent.click(screen.getByTestId('clear-btn'));
+ expect(onClear).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/__tests__/useApiKeys.test.ts b/client/src/hooks/__tests__/useApiKeys.test.ts
new file mode 100644
index 00000000..4d51877b
--- /dev/null
+++ b/client/src/hooks/__tests__/useApiKeys.test.ts
@@ -0,0 +1,411 @@
+/**
+ * Tests for useApiKeys hook.
+ *
+ * Locks in invariants 1, 6 from docs-internal/credentials_panel.md:
+ * - validate/save/delete route to the correct WebSocket message types
+ * - Google Maps and Apify use dedicated validators (not generic validate_api_key)
+ * - Provider Defaults uses save_provider_defaults, NOT save_api_key
+ * - Failure paths return {isValid: false, error} without throwing
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+
+import { useApiKeys } from '../useApiKeys';
+import {
+ makeProviderDefaults,
+ makeModelConstraints,
+ makeProviderUsage,
+} from '../../test/builders';
+
+// Mock the WebSocketContext module before importing the hook -- vi.mock is hoisted.
+const wsMock = {
+ isConnected: true,
+ sendRequest: vi.fn(),
+ validateApiKey: vi.fn(),
+ getStoredApiKey: vi.fn(),
+ saveApiKey: vi.fn(),
+ deleteApiKey: vi.fn(),
+ validateMapsKey: vi.fn(),
+ validateApifyKey: vi.fn(),
+ getAiModels: vi.fn(),
+};
+
+vi.mock('../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => wsMock,
+}));
+
+beforeEach(() => {
+ Object.values(wsMock).forEach((v) => {
+ if (typeof v === 'function' && 'mockReset' in v) {
+ (v as ReturnType<typeof vi.fn>).mockReset();
+ }
+ });
+ // Default resolutions
+ wsMock.validateApiKey.mockResolvedValue({ valid: true, models: ['gpt-4'] });
+ wsMock.getStoredApiKey.mockResolvedValue({ hasKey: false });
+ wsMock.saveApiKey.mockResolvedValue(true);
+ wsMock.deleteApiKey.mockResolvedValue(true);
+ wsMock.validateMapsKey.mockResolvedValue({ valid: true });
+ wsMock.validateApifyKey.mockResolvedValue({ valid: true });
+ wsMock.getAiModels.mockResolvedValue(['gpt-4', 'gpt-3.5']);
+ wsMock.sendRequest.mockResolvedValue({});
+ wsMock.isConnected = true;
+});
+
+
+describe('useApiKeys.validateApiKey', () => {
+ it('routes to validateApiKey with provider+key and returns models', async () => {
+ const { result } = renderHook(() => useApiKeys());
+ let validation: any;
+ await act(async () => {
+ validation = await result.current.validateApiKey('openai', 'sk-foo');
+ });
+
+ expect(wsMock.validateApiKey).toHaveBeenCalledWith('openai', 'sk-foo');
+ expect(validation.isValid).toBe(true);
+ expect(validation.models).toEqual(['gpt-4']);
+ });
+
+ it('toggles isValidating state during the call', async () => {
+ let resolveFn!: (v: any) => void;
+ wsMock.validateApiKey.mockReturnValue(
+ new Promise((res) => {
+ resolveFn = res;
+ }),
+ );
+
+ const { result } = renderHook(() => useApiKeys());
+ expect(result.current.isValidating).toBe(false);
+
+ let pending: Promise<unknown>;
+ act(() => {
+ pending = result.current.validateApiKey('openai', 'sk');
+ });
+
+ await waitFor(() => expect(result.current.isValidating).toBe(true));
+
+ await act(async () => {
+ resolveFn({ valid: true, models: [] });
+ await pending;
+ });
+
+ expect(result.current.isValidating).toBe(false);
+ });
+
+ it('sets validationError on invalid response', async () => {
+ wsMock.validateApiKey.mockResolvedValue({
+ valid: false,
+ message: 'bad key',
+ });
+ const { result } = renderHook(() => useApiKeys());
+ let validation: any;
+ await act(async () => {
+ validation = await result.current.validateApiKey('openai', 'sk-bad');
+ });
+ expect(validation.isValid).toBe(false);
+ expect(validation.error).toBe('bad key');
+ expect(result.current.validationError).toBe('bad key');
+ });
+
+ it('returns {isValid:false, error} on rejection -- never throws', async () => {
+ wsMock.validateApiKey.mockRejectedValue(new Error('network down'));
+ const { result } = renderHook(() => useApiKeys());
+
+ let validation: any;
+ await act(async () => {
+ validation = await result.current.validateApiKey('openai', 'sk');
+ });
+
+ expect(validation.isValid).toBe(false);
+ expect(validation.error).toBe('network down');
+ });
+});
+
+
+describe('useApiKeys.validateGoogleMapsKey', () => {
+ it('routes to validateMapsKey, NOT validateApiKey', async () => {
+ const { result } = renderHook(() => useApiKeys());
+ await act(async () => {
+ await result.current.validateGoogleMapsKey('AIza-test');
+ });
+
+ expect(wsMock.validateMapsKey).toHaveBeenCalledWith('AIza-test');
+ expect(wsMock.validateApiKey).not.toHaveBeenCalled();
+ });
+});
+
+
+describe('useApiKeys.validateApifyKey', () => {
+ it('routes to validateApifyKey, NOT validateApiKey', async () => {
+ const { result } = renderHook(() => useApiKeys());
+ await act(async () => {
+ await result.current.validateApifyKey('apify-token');
+ });
+
+ expect(wsMock.validateApifyKey).toHaveBeenCalledWith('apify-token');
+ expect(wsMock.validateApiKey).not.toHaveBeenCalled();
+ });
+});
+
+
+describe('useApiKeys.saveApiKey', () => {
+ it('returns success when WebSocket save succeeds', async () => {
+ wsMock.saveApiKey.mockResolvedValue(true);
+ const { result } = renderHook(() => useApiKeys());
+
+ let res: any;
+ await act(async () => {
+ res = await result.current.saveApiKey('telegram_bot_token', '123:abc');
+ });
+
+ expect(wsMock.saveApiKey).toHaveBeenCalledWith('telegram_bot_token', '123:abc');
+ expect(res.isValid).toBe(true);
+ });
+
+ it('returns failure when underlying save returns false', async () => {
+ wsMock.saveApiKey.mockResolvedValue(false);
+ const { result } = renderHook(() => useApiKeys());
+
+ let res: any;
+ await act(async () => {
+ res = await result.current.saveApiKey('foo', 'bar');
+ });
+
+ expect(res.isValid).toBe(false);
+ expect(res.error).toBeDefined();
+ });
+});
+
+
+describe('useApiKeys.getStoredApiKey / hasStoredKey / getStoredModels', () => {
+ it('getStoredApiKey returns null when hasKey=false', async () => {
+ wsMock.getStoredApiKey.mockResolvedValue({ hasKey: false });
+ const { result } = renderHook(() => useApiKeys());
+ let stored: string | null = 'x';
+ await act(async () => {
+ stored = await result.current.getStoredApiKey('openai');
+ });
+ expect(stored).toBeNull();
+ });
+
+ it('getStoredApiKey returns key when hasKey=true', async () => {
+ wsMock.getStoredApiKey.mockResolvedValue({ hasKey: true, apiKey: 'sk-x' });
+ const { result } = renderHook(() => useApiKeys());
+ let stored: string | null = null;
+ await act(async () => {
+ stored = await result.current.getStoredApiKey('openai');
+ });
+ expect(stored).toBe('sk-x');
+ });
+
+ it('hasStoredKey returns the hasKey boolean', async () => {
+ wsMock.getStoredApiKey.mockResolvedValue({ hasKey: true });
+ const { result } = renderHook(() => useApiKeys());
+ let exists = false;
+ await act(async () => {
+ exists = await result.current.hasStoredKey('openai');
+ });
+ expect(exists).toBe(true);
+ });
+
+ it('getStoredModels returns models when present', async () => {
+ wsMock.getStoredApiKey.mockResolvedValue({
+ hasKey: true,
+ models: ['gpt-4', 'gpt-3.5'],
+ });
+ const { result } = renderHook(() => useApiKeys());
+ let models: string[] | null = null;
+ await act(async () => {
+ models = await result.current.getStoredModels('openai');
+ });
+ expect(models).toEqual(['gpt-4', 'gpt-3.5']);
+ });
+
+ it('getStoredModels returns null when no models stored', async () => {
+ wsMock.getStoredApiKey.mockResolvedValue({ hasKey: true, models: [] });
+ const { result } = renderHook(() => useApiKeys());
+ let models: string[] | null = ['x'];
+ await act(async () => {
+ models = await result.current.getStoredModels('openai');
+ });
+ expect(models).toBeNull();
+ });
+});
+
+
+describe('useApiKeys.removeApiKey', () => {
+ it('routes to deleteApiKey', async () => {
+ const { result } = renderHook(() => useApiKeys());
+ await act(async () => {
+ await result.current.removeApiKey('openai');
+ });
+ expect(wsMock.deleteApiKey).toHaveBeenCalledWith('openai');
+ });
+
+ it('does not throw on rejection', async () => {
+ wsMock.deleteApiKey.mockRejectedValue(new Error('oops'));
+ const { result } = renderHook(() => useApiKeys());
+ await act(async () => {
+ // Must not throw
+ await result.current.removeApiKey('openai');
+ });
+ });
+});
+
+
+describe('useApiKeys.getProviderDefaults / saveProviderDefaults', () => {
+ it('getProviderDefaults uses get_provider_defaults message type', async () => {
+ const defaults = makeProviderDefaults({ default_model: 'gpt-5' });
+ wsMock.sendRequest.mockResolvedValue({ defaults });
+
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getProviderDefaults('openai');
+ });
+
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('get_provider_defaults', {
+ provider: 'openai',
+ });
+ expect(got).toEqual(defaults);
+ });
+
+ it('getProviderDefaults returns sensible fallback when disconnected', async () => {
+ wsMock.isConnected = false;
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getProviderDefaults('openai');
+ });
+ expect(got.temperature).toBe(0.7);
+ expect(got.max_tokens).toBe(4096);
+ expect(wsMock.sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('saveProviderDefaults uses save_provider_defaults, NOT save_api_key', async () => {
+ wsMock.sendRequest.mockResolvedValue({ success: true });
+ const { result } = renderHook(() => useApiKeys());
+
+ const defaults = makeProviderDefaults({ temperature: 0.3 });
+ let success = false;
+ await act(async () => {
+ success = await result.current.saveProviderDefaults('openai', defaults);
+ });
+
+ expect(success).toBe(true);
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('save_provider_defaults', {
+ provider: 'openai',
+ defaults,
+ });
+ expect(wsMock.saveApiKey).not.toHaveBeenCalled();
+ });
+});
+
+
+describe('useApiKeys.getModelConstraints', () => {
+ it('returns response from get_model_constraints', async () => {
+ const constraints = makeModelConstraints({ context_length: 1_000_000 });
+ wsMock.sendRequest.mockResolvedValue(constraints);
+
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getModelConstraints('gpt-5', 'openai');
+ });
+
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('get_model_constraints', {
+ model: 'gpt-5',
+ provider: 'openai',
+ });
+ expect(got.context_length).toBe(1_000_000);
+ });
+
+ it('returns fallback constraints when disconnected', async () => {
+ wsMock.isConnected = false;
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getModelConstraints('gpt-4', 'openai');
+ });
+ expect(got.found).toBe(false);
+ expect(got.max_output_tokens).toBe(4096);
+ });
+});
+
+
+describe('useApiKeys.getProviderUsageSummary / getAPIUsageSummary', () => {
+ it('getProviderUsageSummary uses get_provider_usage_summary', async () => {
+ wsMock.sendRequest.mockResolvedValue({
+ providers: [makeProviderUsage()],
+ });
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getProviderUsageSummary();
+ });
+
+ expect(wsMock.sendRequest).toHaveBeenCalledWith(
+ 'get_provider_usage_summary',
+ {},
+ );
+ expect(got).toHaveLength(1);
+ expect(got[0].provider).toBe('openai');
+ });
+
+ it('getAPIUsageSummary passes service filter', async () => {
+ wsMock.sendRequest.mockResolvedValue({ success: true, services: [] });
+ const { result } = renderHook(() => useApiKeys());
+ await act(async () => {
+ await result.current.getAPIUsageSummary('twitter');
+ });
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('get_api_usage_summary', {
+ service: 'twitter',
+ });
+ });
+
+ it('returns [] when disconnected', async () => {
+ wsMock.isConnected = false;
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getProviderUsageSummary();
+ });
+ expect(got).toEqual([]);
+ });
+});
+
+
+describe('useApiKeys.getValidatedAiProviders / saveGlobalModel', () => {
+ it('getValidatedAiProviders uses get_validated_ai_providers', async () => {
+ wsMock.sendRequest.mockResolvedValue({
+ providers: [],
+ global_provider: 'openai',
+ global_model: 'gpt-4',
+ });
+ const { result } = renderHook(() => useApiKeys());
+ let got: any;
+ await act(async () => {
+ got = await result.current.getValidatedAiProviders();
+ });
+ expect(wsMock.sendRequest).toHaveBeenCalledWith(
+ 'get_validated_ai_providers',
+ {},
+ );
+ expect(got.global_provider).toBe('openai');
+ });
+
+ it('saveGlobalModel uses save_global_model', async () => {
+ wsMock.sendRequest.mockResolvedValue({ success: true });
+ const { result } = renderHook(() => useApiKeys());
+ let ok = false;
+ await act(async () => {
+ ok = await result.current.saveGlobalModel('openai', 'gpt-5');
+ });
+ expect(ok).toBe(true);
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('save_global_model', {
+ provider: 'openai',
+ model: 'gpt-5',
+ });
+ });
+});
diff --git a/client/src/hooks/__tests__/useDragVariable.test.ts b/client/src/hooks/__tests__/useDragVariable.test.ts
new file mode 100644
index 00000000..e0f28d28
--- /dev/null
+++ b/client/src/hooks/__tests__/useDragVariable.test.ts
@@ -0,0 +1,227 @@
+/**
+ * Tests for useDragVariable hook.
+ *
+ * Locks in the template-variable contract used by InputSection and OutputPanel:
+ * - Variable name priority: node.data.label > nodeDefinition.displayName > nodeType > nodeId
+ * - Normalisation: lowercase + remove whitespace
+ * - Drag payload contains both `text/plain` and `application/json`, with the JSON
+ * carrying type/nodeId/nodeName/key/variableTemplate/dataType.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook } from '@testing-library/react';
+import { useDragVariable } from '../useDragVariable';
+
+// --- Mock the Zustand store --------------------------------------------------
+
+const storeState: { currentWorkflow: any } = {
+ currentWorkflow: null,
+};
+
+vi.mock('../../store/useAppStore', () => ({
+ useAppStore: () => storeState,
+}));
+
+// --- Mock node definitions ---------------------------------------------------
+
+vi.mock('../../nodeDefinitions', () => ({
+ nodeDefinitions: {
+ cronScheduler: { displayName: 'Cron Scheduler', name: 'cronScheduler' },
+ httpRequest: { displayName: 'HTTP Request', name: 'httpRequest' },
+ aiAgent: { displayName: 'AI Agent', name: 'aiAgent' },
+ },
+}));
+
+
+function setWorkflow(nodes: any[]) {
+ storeState.currentWorkflow = { nodes, edges: [], name: 'wf', id: 'wf-1', createdAt: new Date(), lastModified: new Date() };
+}
+
+
+function makeDragEvent(): React.DragEvent {
+ const setData = vi.fn();
+ const ev = {
+ dataTransfer: {
+ setData,
+ effectAllowed: '',
+ getData: vi.fn(),
+ },
+ } as unknown as React.DragEvent;
+ return ev;
+}
+
+
+beforeEach(() => {
+ storeState.currentWorkflow = null;
+});
+
+
+describe('getTemplateVariableName -- priority order', () => {
+ it('uses node.data.label when present (highest priority)', () => {
+ setWorkflow([
+ {
+ id: 'node-1',
+ type: 'cronScheduler',
+ data: { label: 'My Custom Label' },
+ position: { x: 0, y: 0 },
+ },
+ ]);
+
+ const { result } = renderHook(() => useDragVariable('target-id'));
+ expect(result.current.getTemplateVariableName('node-1')).toBe('mycustomlabel');
+ });
+
+ it('falls back to nodeDefinition.displayName when no label', () => {
+ setWorkflow([
+ { id: 'node-2', type: 'cronScheduler', data: {}, position: { x: 0, y: 0 } },
+ ]);
+
+ const { result } = renderHook(() => useDragVariable('target-id'));
+ expect(result.current.getTemplateVariableName('node-2')).toBe('cronscheduler');
+ });
+
+ it('falls back to nodeType when displayName missing', () => {
+ setWorkflow([
+ { id: 'node-3', type: 'unknownType', data: {}, position: { x: 0, y: 0 } },
+ ]);
+
+ const { result } = renderHook(() => useDragVariable('target-id'));
+ expect(result.current.getTemplateVariableName('node-3')).toBe('unknowntype');
+ });
+
+ it('returns nodeId when source node not found in workflow', () => {
+ setWorkflow([]);
+ const { result } = renderHook(() => useDragVariable('target-id'));
+ expect(result.current.getTemplateVariableName('missing-node')).toBe('missing-node');
+ });
+
+ it('returns sourceNodeId when no workflow loaded', () => {
+ storeState.currentWorkflow = null;
+ const { result } = renderHook(() => useDragVariable('target-id'));
+ expect(result.current.getTemplateVariableName('any-id')).toBe('any-id');
+ });
+});
+
+
+describe('getTemplateVariableName -- normalisation', () => {
+ it('lowercases the label', () => {
+ setWorkflow([
+ {
+ id: 'n1',
+ type: 'cronScheduler',
+ data: { label: 'UPPERCASE' },
+ position: { x: 0, y: 0 },
+ },
+ ]);
+ const { result } = renderHook(() => useDragVariable('t'));
+ expect(result.current.getTemplateVariableName('n1')).toBe('uppercase');
+ });
+
+ it('removes whitespace from the label', () => {
+ setWorkflow([
+ {
+ id: 'n1',
+ type: 'cronScheduler',
+ data: { label: 'My Cron Scheduler' },
+ position: { x: 0, y: 0 },
+ },
+ ]);
+ const { result } = renderHook(() => useDragVariable('t'));
+ expect(result.current.getTemplateVariableName('n1')).toBe('mycronscheduler');
+ });
+
+ it('normalises displayName fallback the same way', () => {
+ setWorkflow([
+ { id: 'n1', type: 'httpRequest', data: {}, position: { x: 0, y: 0 } },
+ ]);
+ const { result } = renderHook(() => useDragVariable('t'));
+ expect(result.current.getTemplateVariableName('n1')).toBe('httprequest');
+ });
+
+ it('rejects non-string label and falls back to displayName', () => {
+ setWorkflow([
+ {
+ id: 'n1',
+ type: 'cronScheduler',
+ data: { label: 42 as unknown as string },
+ position: { x: 0, y: 0 },
+ },
+ ]);
+ const { result } = renderHook(() => useDragVariable('t'));
+ expect(result.current.getTemplateVariableName('n1')).toBe('cronscheduler');
+ });
+});
+
+
+describe('handleVariableDragStart -- drag payload', () => {
+ beforeEach(() => {
+ setWorkflow([
+ {
+ id: 'src',
+ type: 'cronScheduler',
+ data: { label: 'Cron Scheduler' },
+ position: { x: 0, y: 0 },
+ },
+ ]);
+ });
+
+ it('sets text/plain payload to the variable template', () => {
+ const { result } = renderHook(() => useDragVariable('target'));
+ const ev = makeDragEvent();
+ result.current.handleVariableDragStart(ev, 'src', 'data', { foo: 'bar' });
+
+ expect(ev.dataTransfer.setData).toHaveBeenCalledWith(
+ 'text/plain',
+ '{{cronscheduler.data}}',
+ );
+ });
+
+ it('sets application/json payload with full metadata', () => {
+ const { result } = renderHook(() => useDragVariable('target'));
+ const ev = makeDragEvent();
+ result.current.handleVariableDragStart(ev, 'src', 'output.field', 42);
+
+ const jsonCall = (ev.dataTransfer.setData as ReturnType<typeof vi.fn>).mock.calls.find(
+ (call) => call[0] === 'application/json',
+ );
+ expect(jsonCall).toBeDefined();
+ const payload = JSON.parse(jsonCall![1] as string);
+ expect(payload).toEqual({
+ type: 'nodeVariable',
+ nodeId: 'src',
+ nodeName: 'cronscheduler',
+ key: 'output.field',
+ variableTemplate: '{{cronscheduler.output.field}}',
+ dataType: 'number',
+ });
+ });
+
+ it('sets effectAllowed to copy', () => {
+ const { result } = renderHook(() => useDragVariable('target'));
+ const ev = makeDragEvent();
+ result.current.handleVariableDragStart(ev, 'src', 'x', 'y');
+ expect(ev.dataTransfer.effectAllowed).toBe('copy');
+ });
+
+ it('encodes dataType correctly for various value types', () => {
+ const { result } = renderHook(() => useDragVariable('target'));
+
+ const cases = [
+ { value: 'hello', expected: 'string' },
+ { value: 123, expected: 'number' },
+ { value: true, expected: 'boolean' },
+ { value: { a: 1 }, expected: 'object' },
+ { value: undefined, expected: 'undefined' },
+ ];
+
+ for (const { value, expected } of cases) {
+ const ev = makeDragEvent();
+ result.current.handleVariableDragStart(ev, 'src', 'p', value);
+ const call = (ev.dataTransfer.setData as ReturnType<typeof vi.fn>).mock.calls.find(
+ (c) => c[0] === 'application/json',
+ )!;
+ const payload = JSON.parse(call[1] as string);
+ expect(payload.dataType).toBe(expected);
+ }
+ });
+});
diff --git a/client/src/hooks/__tests__/useParameterPanel.test.ts b/client/src/hooks/__tests__/useParameterPanel.test.ts
new file mode 100644
index 00000000..c2da0afb
--- /dev/null
+++ b/client/src/hooks/__tests__/useParameterPanel.test.ts
@@ -0,0 +1,264 @@
+/**
+ * Tests for useParameterPanel hook.
+ *
+ * Locks in:
+ * - Defaults loaded from nodeDefinition.properties[].default
+ * - Saved parameters fetched via WebSocket and merged over defaults (saved wins)
+ * - hasUnsavedChanges computed via JSON.stringify equality
+ * - handleSave persists to DB and updates originalParameters
+ * - handleCancel reverts pending edits and clears selection
+ * - WebSocket failure falls back to defaults and surfaces error
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+import { useParameterPanel } from '../useParameterPanel';
+
+// --- Mock store --------------------------------------------------------------
+
+const storeState: { selectedNode: any; setSelectedNode: any } = {
+ selectedNode: null,
+ setSelectedNode: vi.fn(),
+};
+vi.mock('../../store/useAppStore', () => ({
+ useAppStore: () => storeState,
+}));
+
+// --- Mock node definitions ---------------------------------------------------
+
+vi.mock('../../nodeDefinitions', () => ({
+ nodeDefinitions: {
+ httpRequest: {
+ name: 'httpRequest',
+ displayName: 'HTTP Request',
+ properties: [
+ { name: 'method', type: 'options', default: 'GET' },
+ { name: 'url', type: 'string', default: '' },
+ { name: 'timeout', type: 'number', default: 30 },
+ ],
+ },
+ nodeWithoutDefaults: {
+ name: 'nodeWithoutDefaults',
+ displayName: 'No Defaults',
+ properties: [{ name: 'foo', type: 'string' }], // no default
+ },
+ },
+}));
+
+// --- Mock skill node types ---------------------------------------------------
+
+vi.mock('../../nodeDefinitions/skillNodes', () => ({
+ SKILL_NODE_TYPES: ['masterSkill', 'customSkill'],
+}));
+
+// --- Mock WebSocket context --------------------------------------------------
+
+const wsMock = {
+ isConnected: true,
+ getNodeParameters: vi.fn(),
+ saveNodeParameters: vi.fn(),
+ sendRequest: vi.fn(),
+};
+vi.mock('../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => wsMock,
+}));
+
+
+function selectNode(node: any | null) {
+ storeState.selectedNode = node;
+ storeState.setSelectedNode = vi.fn();
+}
+
+
+beforeEach(() => {
+ selectNode(null);
+ wsMock.getNodeParameters.mockReset();
+ wsMock.saveNodeParameters.mockReset();
+ wsMock.sendRequest.mockReset();
+ // Default: backend has nothing saved
+ wsMock.getNodeParameters.mockResolvedValue(null);
+ wsMock.saveNodeParameters.mockResolvedValue(true);
+});
+
+
+describe('initial parameter loading', () => {
+ it('returns empty params when no node is selected', () => {
+ const { result } = renderHook(() => useParameterPanel());
+ expect(result.current.parameters).toEqual({});
+ expect(result.current.hasUnsavedChanges).toBe(false);
+ });
+
+ it('loads defaults from nodeDefinition.properties when DB has nothing', async () => {
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+
+ const { result } = renderHook(() => useParameterPanel());
+
+ await waitFor(() => {
+ expect(result.current.parameters.method).toBe('GET');
+ });
+ expect(result.current.parameters.url).toBe('');
+ expect(result.current.parameters.timeout).toBe(30);
+ expect(result.current.hasUnsavedChanges).toBe(false);
+ });
+
+ it('uses null when a property has no default', async () => {
+ selectNode({ id: 'n-1', type: 'nodeWithoutDefaults' });
+
+ const { result } = renderHook(() => useParameterPanel());
+
+ await waitFor(() => {
+ expect(result.current.parameters).toHaveProperty('foo');
+ });
+ expect(result.current.parameters.foo).toBeNull();
+ });
+
+ it('merges saved params over defaults (saved wins)', async () => {
+ wsMock.getNodeParameters.mockResolvedValue({
+ parameters: { method: 'POST', url: 'https://api.example.com' },
+ version: 1,
+ timestamp: Date.now(),
+ });
+
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+
+ await waitFor(() => {
+ expect(result.current.parameters.method).toBe('POST');
+ });
+ expect(result.current.parameters.url).toBe('https://api.example.com');
+ expect(result.current.parameters.timeout).toBe(30); // default kept
+ });
+
+ it('falls back to defaults and surfaces error on WebSocket failure', async () => {
+ wsMock.getNodeParameters.mockRejectedValue(new Error('WS down'));
+
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+
+ await waitFor(() => {
+ expect(result.current.error).toBeTruthy();
+ });
+ expect(result.current.parameters.method).toBe('GET');
+ });
+});
+
+
+describe('hasUnsavedChanges and handleParameterChange', () => {
+ it('starts false and flips true after a parameter change', async () => {
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+
+ await waitFor(() => expect(result.current.parameters.method).toBe('GET'));
+ expect(result.current.hasUnsavedChanges).toBe(false);
+
+ act(() => {
+ result.current.handleParameterChange('method', 'POST');
+ });
+
+ expect(result.current.parameters.method).toBe('POST');
+ expect(result.current.hasUnsavedChanges).toBe(true);
+ });
+
+ it('flips back to false when the value is reverted to original', async () => {
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.parameters.method).toBe('GET'));
+
+ act(() => result.current.handleParameterChange('method', 'POST'));
+ expect(result.current.hasUnsavedChanges).toBe(true);
+
+ act(() => result.current.handleParameterChange('method', 'GET'));
+ expect(result.current.hasUnsavedChanges).toBe(false);
+ });
+});
+
+
+describe('handleSave', () => {
+ it('saves to WebSocket and updates originalParameters on success', async () => {
+ selectNode({ id: 'n-42', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.parameters.method).toBe('GET'));
+
+ act(() => result.current.handleParameterChange('method', 'PUT'));
+ expect(result.current.hasUnsavedChanges).toBe(true);
+
+ await act(async () => {
+ await result.current.handleSave();
+ });
+
+ expect(wsMock.saveNodeParameters).toHaveBeenCalledWith(
+ 'n-42',
+ expect.objectContaining({ method: 'PUT' }),
+ );
+ expect(result.current.hasUnsavedChanges).toBe(false);
+ expect(result.current.error).toBeNull();
+ });
+
+ it('surfaces error and keeps unsaved state when save returns false', async () => {
+ wsMock.saveNodeParameters.mockResolvedValue(false);
+
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.parameters.method).toBe('GET'));
+
+ act(() => result.current.handleParameterChange('method', 'POST'));
+
+ await act(async () => {
+ await result.current.handleSave();
+ });
+
+ expect(result.current.error).toBe('Failed to save parameters');
+ expect(result.current.hasUnsavedChanges).toBe(true);
+ });
+
+ it('handles save rejection without throwing', async () => {
+ wsMock.saveNodeParameters.mockRejectedValue(new Error('boom'));
+
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.parameters.method).toBe('GET'));
+
+ act(() => result.current.handleParameterChange('method', 'POST'));
+
+ await act(async () => {
+ await result.current.handleSave();
+ });
+
+ expect(result.current.error).toBe('Failed to save parameters');
+ });
+});
+
+
+describe('handleCancel', () => {
+ it('reverts pending edits and clears selection', async () => {
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.parameters.method).toBe('GET'));
+
+ act(() => result.current.handleParameterChange('method', 'DELETE'));
+ expect(result.current.parameters.method).toBe('DELETE');
+
+ act(() => result.current.handleCancel());
+
+ expect(result.current.parameters.method).toBe('GET');
+ expect(storeState.setSelectedNode).toHaveBeenCalledWith(null);
+ });
+});
+
+
+describe('nodeDefinition exposure', () => {
+ it('exposes the matching node definition', async () => {
+ selectNode({ id: 'n-1', type: 'httpRequest' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.nodeDefinition).toBeTruthy());
+ expect(result.current.nodeDefinition?.displayName).toBe('HTTP Request');
+ });
+
+ it('returns falsy nodeDefinition for unknown node type', async () => {
+ selectNode({ id: 'n-1', type: 'unknownType' });
+ const { result } = renderHook(() => useParameterPanel());
+ await waitFor(() => expect(result.current.parameters).toEqual({}));
+ // nodeDefinitions[unknownType] is undefined; hook returns it as-is
+ expect(result.current.nodeDefinition).toBeFalsy();
+ });
+});
diff --git a/client/src/nodeDefinitions/__tests__/contract.test.ts b/client/src/nodeDefinitions/__tests__/contract.test.ts
new file mode 100644
index 00000000..cd3debaa
--- /dev/null
+++ b/client/src/nodeDefinitions/__tests__/contract.test.ts
@@ -0,0 +1,39 @@
+/**
+ * Single sweep test - validates every entry in `nodeDefinitions` against the
+ * INodeTypeDescription contract. One assertion per node guarantees a refactor
+ * that breaks any definition's shape will fail loudly here.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { nodeDefinitions } from '../../nodeDefinitions';
+import {
+ formatIssues,
+ validateNodeDefinition,
+ validateRegistry,
+} from '../../test/nodeDefinitionContract';
+
+describe('nodeDefinitions registry', () => {
+ it('exports at least one node', () => {
+ expect(Object.keys(nodeDefinitions).length).toBeGreaterThan(0);
+ });
+
+ it('every registry entry passes the INodeTypeDescription contract', () => {
+ const issues = validateRegistry(nodeDefinitions);
+ if (issues.length > 0) {
+ throw new Error(`Contract violations:\n${formatIssues(issues)}`);
+ }
+ });
+
+ describe.each(Object.entries(nodeDefinitions))('%s', (key, def) => {
+ it('matches its registry key', () => {
+ expect(def.name).toBe(key);
+ });
+
+ it('has a valid INodeTypeDescription shape', () => {
+ const issues = validateNodeDefinition(key, def);
+ if (issues.length > 0) {
+ throw new Error(formatIssues(issues));
+ }
+ });
+ });
+});
diff --git a/client/src/test/README.md b/client/src/test/README.md
new file mode 100644
index 00000000..edbf8348
--- /dev/null
+++ b/client/src/test/README.md
@@ -0,0 +1,34 @@
+# Frontend Test Suite
+
+Locks in the user-facing invariants from [docs-internal/credentials_panel.md §5](../../../docs-internal/credentials_panel.md).
+
+## Run
+
+```bash
+cd client
+npm install # picks up the new devDependencies
+npm run test # watch mode
+npm run test:run # one-shot
+npm run test:coverage # with v8 coverage report
+```
+
+## Layout
+
+| File | Locks in |
+|---|---|
+| `src/hooks/__tests__/useApiKeys.test.ts` | Hook routes to the correct WebSocket message types with the right payload shapes; failure paths return `{isValid: false, error}` without throwing |
+| `src/components/__tests__/CredentialsModal.test.tsx` | Modal renders correctly for representative providers; click → WS message dispatch chain |
+
+## Tooling
+
+- **Vitest** + **jsdom** for fast component tests
+- **@testing-library/react** + **@testing-library/user-event** for behaviour assertions
+- **builders.ts** for test-data factories — keep test bodies focused on deltas, not boilerplate
+- **setup.ts** stubs `matchMedia` / `ResizeObserver` / `IntersectionObserver` (jsdom doesn't ship them; antd needs them)
+
+## What this suite does NOT test
+
+- Antd internals (Modal, Form, Input, Select)
+- `react-flow` rendering
+- Backend handlers (covered by `server/tests/credentials/`)
+- Full OAuth round-trip with real X / Google (no network)
diff --git a/client/src/test/builders.ts b/client/src/test/builders.ts
new file mode 100644
index 00000000..7e466ce3
--- /dev/null
+++ b/client/src/test/builders.ts
@@ -0,0 +1,90 @@
+/**
+ * Test data builders -- factories with sensible defaults that can be overridden
+ * per test. Keeps test bodies focused on the *delta* relevant to each case.
+ */
+
+import type {
+ ApiKeyValidationResult,
+ ProviderDefaults,
+ ProviderUsageSummary,
+ ModelConstraints,
+} from '../hooks/useApiKeys';
+
+export const makeValidationResult = (
+ overrides: Partial<ApiKeyValidationResult> = {},
+): ApiKeyValidationResult => ({
+ isValid: true,
+ models: ['gpt-4', 'gpt-3.5-turbo'],
+ ...overrides,
+});
+
+export const makeProviderDefaults = (
+ overrides: Partial<ProviderDefaults> = {},
+): ProviderDefaults => ({
+ default_model: 'gpt-4',
+ temperature: 0.7,
+ max_tokens: 4096,
+ thinking_enabled: false,
+ thinking_budget: 2048,
+ reasoning_effort: 'medium',
+ reasoning_format: 'parsed',
+ ...overrides,
+});
+
+export const makeModelConstraints = (
+ overrides: Partial<ModelConstraints> = {},
+): ModelConstraints => ({
+ found: true,
+ model: 'gpt-4',
+ provider: 'openai',
+ max_output_tokens: 16384,
+ context_length: 128_000,
+ temperature_range: [0, 2],
+ supports_thinking: false,
+ thinking_type: 'none',
+ is_reasoning_model: false,
+ ...overrides,
+});
+
+export const makeProviderUsage = (
+ overrides: Partial<ProviderUsageSummary> = {},
+): ProviderUsageSummary => ({
+ provider: 'openai',
+ total_input_tokens: 1000,
+ total_output_tokens: 500,
+ total_tokens: 1500,
+ total_input_cost: 0.01,
+ total_output_cost: 0.015,
+ total_cache_cost: 0,
+ total_cost: 0.025,
+ execution_count: 3,
+ models: [],
+ ...overrides,
+});
+
+/**
+ * Build a fake `useWebSocket` return value with all the methods consumed by
+ * `useApiKeys`. Each method is a vi.fn() with a sensible default resolution.
+ *
+ * Tests can override any method via `mockResolvedValue`/`mockRejectedValue`
+ * and inspect call args via `.mock.calls`.
+ */
+export const makeWebSocketMock = (overrides: Record<string, unknown> = {}) => {
+ const { vi } = (globalThis as unknown as { vi: typeof import('vitest').vi });
+ return {
+ isConnected: true,
+ sendRequest: vi.fn().mockResolvedValue({}),
+ validateApiKey: vi
+ .fn()
+ .mockResolvedValue({ valid: true, models: ['gpt-4'] }),
+ getStoredApiKey: vi
+ .fn()
+ .mockResolvedValue({ hasKey: false }),
+ saveApiKey: vi.fn().mockResolvedValue(true),
+ deleteApiKey: vi.fn().mockResolvedValue(true),
+ validateMapsKey: vi.fn().mockResolvedValue({ valid: true }),
+ validateApifyKey: vi.fn().mockResolvedValue({ valid: true }),
+ getAiModels: vi.fn().mockResolvedValue(['gpt-4', 'gpt-3.5-turbo']),
+ ...overrides,
+ };
+};
diff --git a/client/src/test/nodeDefinitionContract.ts b/client/src/test/nodeDefinitionContract.ts
new file mode 100644
index 00000000..4dc309bd
--- /dev/null
+++ b/client/src/test/nodeDefinitionContract.ts
@@ -0,0 +1,181 @@
+/**
+ * Contract assertions for INodeTypeDescription registry entries.
+ *
+ * Used by the single sweep test that iterates every node in `nodeDefinitions`
+ * and verifies its shape - so a refactor that drops `displayName`, mangles
+ * `displayOptions.show`, or uses the wrong handle naming is caught instantly.
+ */
+
+import type {
+ INodeTypeDescription,
+ INodeProperties,
+ INodeInputDefinition,
+ INodeOutputDefinition,
+} from '../types/INodeProperties';
+
+export interface ContractIssue {
+ nodeType: string;
+ path: string;
+ message: string;
+}
+
+const REQUIRED_TOP_LEVEL: (keyof INodeTypeDescription)[] = [
+ 'displayName',
+ 'name',
+ 'icon',
+ 'group',
+ 'version',
+ 'description',
+ 'defaults',
+ 'inputs',
+ 'outputs',
+ 'properties',
+];
+
+const VALID_PROPERTY_TYPES = new Set([
+ 'string',
+ 'number',
+ 'boolean',
+ 'options',
+ 'multiOptions',
+ 'collection',
+ 'fixedCollection',
+ 'json',
+ 'dateTime',
+ 'color',
+ 'hidden',
+ 'notice',
+ 'credentialsSelect',
+ 'resourceLocator',
+ 'slider',
+ 'file',
+ 'array',
+ 'code',
+]);
+
+export function validateNodeDefinition(
+ nodeKey: string,
+ def: INodeTypeDescription,
+): ContractIssue[] {
+ const issues: ContractIssue[] = [];
+ const push = (path: string, message: string): void => {
+ issues.push({ nodeType: nodeKey, path, message });
+ };
+
+ // 1. registry key must match definition.name
+ if (def.name !== nodeKey) {
+ push('name', `registry key "${nodeKey}" must equal definition.name "${def.name}"`);
+ }
+
+ // 2. required top-level fields
+ for (const field of REQUIRED_TOP_LEVEL) {
+ if (def[field] === undefined || def[field] === null) {
+ push(String(field), `required field is missing`);
+ }
+ }
+
+ // 3. group must be a non-empty array of strings
+ if (def.group && (!Array.isArray(def.group) || def.group.length === 0)) {
+ push('group', 'group must be a non-empty string[]');
+ }
+
+ // 4. defaults must contain `name`
+ if (def.defaults && !def.defaults.name) {
+ push('defaults.name', 'defaults.name is required');
+ }
+
+ // 5. inputs/outputs shape
+ validateConnections('inputs', def.inputs, push);
+ validateConnections('outputs', def.outputs, push);
+
+ // 6. properties array
+ if (Array.isArray(def.properties)) {
+ const seen = new Set<string>();
+ def.properties.forEach((prop, idx) => {
+ validateProperty(prop, `properties[${idx}]`, push);
+ if (prop?.name) {
+ if (seen.has(prop.name)) {
+ push(`properties[${idx}].name`, `duplicate property name "${prop.name}"`);
+ }
+ seen.add(prop.name);
+ }
+ });
+ } else {
+ push('properties', 'properties must be an array');
+ }
+
+ return issues;
+}
+
+function validateConnections(
+ field: 'inputs' | 'outputs',
+ value: string[] | INodeInputDefinition[] | INodeOutputDefinition[] | undefined,
+ push: (path: string, message: string) => void,
+): void {
+ if (!Array.isArray(value)) {
+ push(field, `${field} must be an array (string[] or definition objects[])`);
+ return;
+ }
+ value.forEach((entry, idx) => {
+ if (typeof entry === 'string') return; // legacy string form is allowed
+ if (!entry || typeof entry !== 'object') {
+ push(`${field}[${idx}]`, `entry must be string or object, got ${typeof entry}`);
+ return;
+ }
+ const e = entry as INodeInputDefinition | INodeOutputDefinition;
+ if (!e.name) push(`${field}[${idx}].name`, 'name is required');
+ if (!e.type) push(`${field}[${idx}].type`, 'type is required');
+ });
+}
+
+function validateProperty(
+ prop: INodeProperties | undefined,
+ pathPrefix: string,
+ push: (path: string, message: string) => void,
+): void {
+ if (!prop || typeof prop !== 'object') {
+ push(pathPrefix, 'property must be an object');
+ return;
+ }
+ if (!prop.name) push(`${pathPrefix}.name`, 'name is required');
+ if (!prop.displayName) push(`${pathPrefix}.displayName`, 'displayName is required');
+ if (!prop.type) push(`${pathPrefix}.type`, 'type is required');
+ if (prop.type && !VALID_PROPERTY_TYPES.has(prop.type)) {
+ push(`${pathPrefix}.type`, `unknown property type "${prop.type}"`);
+ }
+
+ // displayOptions.show: every value must be array
+ const show = prop.displayOptions?.show;
+ if (show) {
+ for (const [key, val] of Object.entries(show)) {
+ if (!Array.isArray(val)) {
+ push(
+ `${pathPrefix}.displayOptions.show.${key}`,
+ `displayOptions.show values must be arrays, got ${typeof val}`,
+ );
+ }
+ }
+ }
+
+ // options-typed props should declare options array
+ if ((prop.type === 'options' || prop.type === 'multiOptions') && !Array.isArray(prop.options)) {
+ push(`${pathPrefix}.options`, `${prop.type} property must declare an options array`);
+ }
+}
+
+export function validateRegistry(
+ registry: Record<string, INodeTypeDescription>,
+): ContractIssue[] {
+ const issues: ContractIssue[] = [];
+ for (const [key, def] of Object.entries(registry)) {
+ issues.push(...validateNodeDefinition(key, def));
+ }
+ return issues;
+}
+
+export function formatIssues(issues: ContractIssue[]): string {
+ if (issues.length === 0) return 'no issues';
+ return issues
+ .map((i) => ` - ${i.nodeType} :: ${i.path} - ${i.message}`)
+ .join('\n');
+}
diff --git a/client/src/test/setup.ts b/client/src/test/setup.ts
new file mode 100644
index 00000000..75cfbb9a
--- /dev/null
+++ b/client/src/test/setup.ts
@@ -0,0 +1,60 @@
+/**
+ * Vitest setup - runs once before all tests.
+ *
+ * Stubs browser APIs that Node definitions / factories may touch when imported.
+ */
+
+import { vi } from 'vitest';
+
+// React Flow uses ResizeObserver; jsdom doesn't ship one
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+if (typeof globalThis.ResizeObserver === 'undefined') {
+ // @ts-expect-error - intentional shim
+ globalThis.ResizeObserver = ResizeObserverStub;
+}
+
+// matchMedia shim for any antd component imported transitively
+if (typeof window !== 'undefined' && !window.matchMedia) {
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ value: vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ });
+}
+
+// IntersectionObserver shim -- antd virtualised lists use it
+if (typeof globalThis.IntersectionObserver === 'undefined') {
+ class IntersectionObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ takeRecords() { return []; }
+ root = null;
+ rootMargin = '';
+ thresholds = [];
+ }
+ // @ts-expect-error - intentional shim
+ globalThis.IntersectionObserver = IntersectionObserverStub;
+}
+
+// Auto-cleanup React Testing Library between tests
+import { afterEach } from 'vitest';
+import { cleanup } from '@testing-library/react';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(() => {
+ cleanup();
+});
diff --git a/client/vitest.config.ts b/client/vitest.config.ts
new file mode 100644
index 00000000..536e48e6
--- /dev/null
+++ b/client/vitest.config.ts
@@ -0,0 +1,30 @@
+import { defineConfig } from 'vitest/config';
+import react from '@vitejs/plugin-react';
+import path from 'node:path';
+
+export default defineConfig({
+ plugins: [react()],
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
+ },
+ },
+ test: {
+ globals: true,
+ environment: 'jsdom',
+ setupFiles: ['./src/test/setup.ts'],
+ include: ['src/**/*.{test,spec}.{ts,tsx}'],
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'html'],
+ include: [
+ 'src/nodeDefinitions/**',
+ 'src/factories/**',
+ 'src/types/**',
+ 'src/hooks/useApiKeys.ts',
+ 'src/components/CredentialsModal.tsx',
+ ],
+ exclude: ['**/*.test.{ts,tsx}', '**/__tests__/**'],
+ },
+ },
+});
diff --git a/docs-internal/credentials_panel.md b/docs-internal/credentials_panel.md
new file mode 100644
index 00000000..2e332967
--- /dev/null
+++ b/docs-internal/credentials_panel.md
@@ -0,0 +1,396 @@
+# Credentials Panel — Logic Flow Documentation
+
+> Reference for refactoring [client/src/components/CredentialsModal.tsx](../client/src/components/CredentialsModal.tsx) (~3000 lines).
+> Every claim here cites file + line number so reviewers can validate post-refactor.
+> Companion test suite in [server/tests/credentials/](../server/tests/credentials) and [client/src/test/](../client/src/test) locks in the invariants enumerated in section 5.
+
+---
+
+## 1. Architecture
+
+### 1.1 Layout
+Two-panel modal:
+- **Left**: category sidebar (8 categories, ~20 items)
+- **Right**: dynamic detail panel keyed off `selectedItem.panelType`
+
+State lives entirely in `CredentialsModal` as `useState` hooks (no Zustand, no context for modal-local state). Cross-cutting status (paired devices, OAuth account info) comes from `WebSocketContext` push broadcasts.
+
+### 1.2 State taxonomy
+
+| Bucket | Variables | Provider scope |
+|---|---|---|
+| Standard API key inputs | `keys`, `validKeys`, `loading`, `models` | OpenAI/Anthropic/Gemini/Groq/Cerebras/OpenRouter/DeepSeek/Kimi/Mistral/Brave/Perplexity/Serper/Maps/Apify |
+| Provider defaults (per-LLM) | `providerDefaults`, `defaultsDirty`, `modelConstraints` | LLM providers only |
+| Usage panels | `usageSummary`, `apiUsage`, `usageExpanded` | LLM (token cost) + Twitter/Maps (API cost) |
+| Twitter-specific | `twitterClientId`, `twitterClientSecret`, `twitterCredentialsStored`, `twitterLoading`, `twitterError` | twitter only |
+| Google-specific | `gmailClientId`, `gmailClientSecret`, `gmailCredentialsStored`, `gmailLoading`, `gmailError` | google only |
+| WhatsApp-specific | `rateLimitConfig`, `rateLimitStats`, `rateLimitExpanded`, `whatsappLoading`, `whatsappError` | whatsapp only |
+| Android-specific | `androidApiKey`, `androidApiKeyStored`, `androidLoading`, `androidError` | android only |
+| Telegram-specific | `telegramToken`, `telegramTokenStored`, `telegramLoading`, `telegramError` | telegram only |
+| Email-specific | `emailProvider`, `emailAddress`, `emailPassword`, `emailImapHost/Port`, `emailSmtpHost/Port`, `emailStored`, `emailLoading`, `emailError` | email only |
+
+### 1.3 Data sources
+
+| Source | Purpose | File |
+|---|---|---|
+| `useApiKeys()` | CRUD + validation + provider defaults + usage + model constraints | [client/src/hooks/useApiKeys.ts](../client/src/hooks/useApiKeys.ts) |
+| `useWhatsApp()` | WhatsApp send/QR/status helpers (also accessible via `WebSocketContext`) | [client/src/hooks/useWhatsApp.ts](../client/src/hooks/useWhatsApp.ts) |
+| `useWebSocket()` | Status getters (`useWhatsAppStatus`, `useAndroidStatus`, `useTwitterStatus`, `useGoogleStatus`, `useTelegramStatus`), `sendRequest<T>(type, data, timeoutMs?)` | [client/src/contexts/WebSocketContext.tsx](../client/src/contexts/WebSocketContext.tsx) |
+
+Push-driven status objects (`whatsappStatus`, `androidStatus`, `twitterStatus`, `googleStatus`, `telegramStatus`) update reactively from broadcast messages — the modal does not poll for them.
+
+---
+
+## 2. Per-Provider Flow Matrix
+
+### 2.1 Pattern A — Simple API key (validated against provider)
+
+**Providers**: openai, anthropic, gemini, groq, cerebras, openrouter, deepseek, kimi, mistral, brave_search, perplexity.
+
+**Credentials stored**: one row in `EncryptedAPIKey` table, key `{session_id}_{provider}`, payload = encrypted API key + `{models: [...]}` JSON.
+
+**Happy path**:
+```
+User types key in <Input.Password>
+ -> handleValidate(provider)
+ -> useApiKeys.validateApiKey(provider, key)
+ -> WebSocketContext.validateApiKey(provider, key)
+ -> ws.send({type: 'validate_api_key', provider, api_key, request_id})
+backend handle_validate_api_key (websocket.py:990):
+ -> ai_service.fetch_models(provider, key) // hits provider /v1/models endpoint
+ -> auth_service.store_api_key(provider, key, models, session_id='default')
+ -> credentials_db.save_api_key -> EncryptionService.encrypt -> EncryptedAPIKey row
+ -> _memory_cache[session_id_provider] = key
+ -> broadcaster.update_api_key_status(provider, valid=True, has_key=True, models=[...])
+ -> return {valid: True, models: [...]}
+Frontend resolves Promise:
+ -> setValidKeys[provider] = true
+ -> setModels[provider] = models
+ -> Connected tag rendered
+```
+
+**WebSocket messages used**: `validate_api_key`, `get_stored_api_key`, `save_api_key`, `delete_api_key`, `get_ai_models`.
+
+**Buttons**: Validate (disabled while empty/loading), Delete (only when stored).
+
+**Error surface**: `loading[provider]` cleared in `finally`; `validKeys[provider]` stays `false`; `<Alert type="error">` with message from response.
+
+### 2.2 Pattern B — Simple API key (custom validator)
+
+**Providers**: google_maps, apify.
+
+Same as Pattern A but validation routes to dedicated handler, not the generic `validate_api_key`:
+
+| Provider | Hook method | WS message |
+|---|---|---|
+| google_maps | `validateGoogleMapsKey(key)` | `validate_maps_key` |
+| apify | `validateApifyKey(key)` | `validate_apify_key` |
+
+After validation succeeds, the frontend still calls `saveApiKey` (or backend stores it) under the provider name. Storage table identical to Pattern A.
+
+### 2.3 Pattern C — Save-only API key (no validation)
+
+**Providers**: android_remote, serper, twitter_client_id, twitter_client_secret, google_client_id, google_client_secret, telegram_bot_token, email_*.
+
+`saveApiKey(provider, key)` calls WebSocket `save_api_key` directly. Backend `handle_save_api_key` (websocket.py:1023) skips model fetch and just calls `auth_service.store_api_key(provider, key, models=[])`.
+
+> **Invariant**: `auth_service.store_api_key()` requires `models` as a positional/keyword argument — passing `[]` is mandatory for non-LLM keys. See [server/services/auth.py:46](../server/services/auth.py).
+
+### 2.4 Pattern D — OAuth 2.0 PKCE (Twitter)
+
+**Credentials stored**:
+- API key table: `twitter_client_id`, `twitter_client_secret` (user-entered)
+- OAuth table: `EncryptedOAuthToken(provider='twitter', customer_id='owner')` with access_token + refresh_token + scopes
+
+**Happy path**:
+```
+1. User saves client_id / client_secret
+ -> 2x save_api_key WS calls
+2. User clicks Login with Twitter
+ -> sendRequest('twitter_oauth_login', {})
+ handle_twitter_oauth_login (websocket.py:1062):
+ -> auth_service.get_api_key('twitter_client_id')
+ -> redirect_uri = get_redirect_uri(websocket, 'twitter') // runtime-derived
+ -> oauth.generate_authorization_url()
+ -> generates PKCE code_verifier + S256 code_challenge
+ -> stores state in _oauth_states[state] with code_verifier + redirect_uri
+ -> returns {success, url, state}
+3. Frontend window.open(response.url, '_blank')
+4. User authorizes on x.com -> X redirects to /api/twitter/callback?code=...&state=...
+5. routers/twitter.py callback:
+ -> oauth.exchange_code(code, state) // pops state, exchanges via PKCE
+ -> auth_service.store_oauth_tokens('twitter', access, refresh, scopes=...)
+6. Frontend periodically calls sendRequest('twitter_oauth_status')
+ handle_twitter_oauth_status (websocket.py:1104):
+ -> auth_service.get_oauth_tokens('twitter') // OAuth table, NOT api_key table
+ -> oauth.get_user_info(access_token)
+ -> on 401: oauth.refresh_access_token(refresh) + re-store
+ -> returns {connected, username, user_id, name, profile_image_url, verified}
+```
+
+**Logout path**: `sendRequest('twitter_logout')` → `handle_twitter_logout` (websocket.py:1179) revokes both tokens at REVOKE_URL, then `auth_service.remove_oauth_tokens('twitter')`. Stale legacy `twitter_access_token` API-key entries are best-effort cleaned (websocket.py:1217).
+
+**PKCE invariants**:
+- `code_verifier`: 96 random bytes → urlsafe base64 → trimmed to 128 chars (twitter_oauth.py:48).
+- `code_challenge = base64url(sha256(code_verifier))` (twitter_oauth.py:59).
+- Authorization URL params include `code_challenge_method=S256`.
+- State is consumed exactly once (`_oauth_states.pop(state)` in `exchange_code`).
+- Authorization codes expire in 30 seconds (X documentation), states expire after 10 minutes (`cleanup_expired_states`).
+
+### 2.5 Pattern E — OAuth 2.0 with offline access (Google Workspace)
+
+**Credentials stored**:
+- API key table: `google_client_id`, `google_client_secret`
+- OAuth table: `EncryptedOAuthToken(provider='google', customer_id='owner')` with access + refresh + email + name + scopes
+
+**Differences from Twitter**:
+- Uses `google-auth-oauthlib` `Flow` rather than hand-rolled PKCE (google-auth-oauthlib auto-generates PKCE under the hood; `code_verifier` is captured and saved into `_oauth_states` so the new `Flow` instance in `exchange_code` can restore it — google_oauth.py:189, 226).
+- Authorization URL params include `access_type=offline` + `prompt=consent` (google_oauth.py:175) — both required to reliably receive a refresh_token.
+- `_get_user_info` calls Google's oauth2/v2 userinfo endpoint to populate email/name/picture (google_oauth.py:258).
+- `handle_google_oauth_status` (websocket.py:1272) proactively refreshes the token via `GoogleOAuth.refresh_credentials` and broadcasts `{type: 'google_status', data: {...}}` to all clients.
+- `handle_google_logout` (websocket.py:1333) clears tokens and broadcasts disconnected status.
+
+**Combined scopes** (loaded from [server/config/google_apis.json](../server/config/google_apis.json)): openid + email + profile + gmail.send/readonly/modify + calendar (full + events) + drive (full + file) + spreadsheets + tasks + contacts (full + readonly).
+
+> **Invariant (load-bearing)**: Google access/refresh tokens are read via `auth_service.get_oauth_tokens('google')`, NEVER via `auth_service.get_api_key('google_access_token')`. The two storage systems are distinct tables with distinct caches. Earlier code mixed them and broke OAuth status.
+
+### 2.6 Pattern F — OAuth via isolated subprocess (Claude)
+
+**Credentials stored**: not in encrypted DB. Tokens persist in `~/.claude-machina/.credentials.json`, written by the official `@anthropic-ai/claude-code` CLI which is installed into `~/.claude-machina/npm/` to keep it isolated from the user's main Claude session.
+
+**Happy path**:
+```
+sendRequest('claude_oauth_login')
+ -> initiate_claude_oauth (claude_oauth.py:61)
+ -> ensure CLI installed (npm install --prefix ~/.claude-machina/npm)
+ -> spawn `claude login` with env CLAUDE_CONFIG_DIR=~/.claude-machina
+ -> pipe "yes\nyes\n" to stdin to auto-accept prompts
+ -> CLI opens browser; user authorizes on console.anthropic.com
+ -> returns {success, pid, config_dir}
+
+Frontend polls sendRequest('claude_oauth_status'):
+ -> get_claude_credentials (claude_oauth.py:121)
+ -> reads ~/.claude-machina/.credentials.json
+ -> returns {success, has_token, access_token, expires_at}
+```
+
+No logout WebSocket handler — user can manually delete the credentials file or run `claude logout` separately.
+
+### 2.7 Pattern G — QR pairing (WhatsApp)
+
+**Credentials stored**: nothing in MachinaOs DB. Session lives inside the bundled `whatsapp-rpc` Go service (default port 9400).
+
+**Happy path**:
+```
+1. User clicks Start
+ -> sendRequest('whatsapp_start')
+ -> backend launches/restarts whatsapp-rpc, which generates QR
+2. broadcast 'whatsapp_status' arrives with status.qr (base64 PNG payload)
+ -> WebSocketContext exposes whatsappStatus
+ -> CredentialsModal renders <QRCodeDisplay value={whatsappStatus.qr} />
+3. User scans QR with phone -> Go service pairs
+4. broadcast 'whatsapp_status' arrives with connected=true, has_session=true, connected_phone='...'
+ -> QR replaced by "Connected" descriptions
+```
+
+**Buttons**: Start / Restart (regenerates QR) / Refresh (re-fetches status). All dispatch via `useWhatsApp` or `WebSocketContext`.
+
+**Rate limit collapse panel**:
+- On expand → `getWhatsAppRateLimitConfig()` (`whatsapp_rate_limit_get`) + stats fetch.
+- Edits update `rateLimitConfig`, Save → `setWhatsAppRateLimitConfig()` (`whatsapp_rate_limit_set`).
+- Pause notification with Unpause → `unpauseWhatsAppRateLimit()` (`whatsapp_rate_limit_unpause`).
+
+### 2.8 Pattern H — Relay session (Android)
+
+**Credentials stored**: API key table — `android_remote` (relay auth token).
+
+**Happy path**:
+```
+1. User saves android_remote API key (Pattern C)
+2. User clicks Connect
+ -> sendRequest('android_relay_connect', {url: VITE_ANDROID_RELAY_URL, api_key})
+ handle_android_relay_connect (websocket.py:1425):
+ -> AndroidService.connect_relay(url, key)
+ -> returns {success, qr_data, session_token}
+3. Backend broadcasts 'android_status' with paired=false, qr_data, session_token
+ -> WebSocketContext exposes androidStatus
+ -> CredentialsModal renders QR
+4. User scans QR with companion app -> device pairs
+5. Backend broadcasts 'android_status' with connected=true, paired=true, device_id, device_name
+```
+
+**Two-state model** (load-bearing):
+- `connected` = relay WebSocket up
+- `paired` = at least one Android device paired via relay
+- Reconnect button (`android_relay_reconnect`) issues new QR while keeping relay session.
+- Disconnect (`android_relay_disconnect`) tears down everything.
+
+### 2.9 Pattern I — Bot token + polling (Telegram)
+
+**Credentials stored**: API key table — `telegram_bot_token`. Owner chat ID auto-captured on first private message and stored as `telegram_owner_chat_id`.
+
+**Happy path**:
+```
+1. User pastes BotFather token, clicks Save
+ -> saveApiKey('telegram_bot_token', token) // Pattern C
+2. User clicks Connect
+ -> sendRequest('telegram_connect', {token})
+ handle_telegram_connect (websocket.py:1844):
+ -> TelegramService.connect(token)
+ -> validate via getMe
+ -> start long-polling (get_updates_read_timeout=30s)
+ -> auth_service.store_api_key('telegram_bot_token', token, models=[])
+3. broadcast 'telegram_status' arrives with connected=true, bot_username, bot_name, bot_id
+4. First private message captures owner_chat_id -> stored as telegram_owner_chat_id API key
+5. broadcast 'telegram_status' updated with owner_chat_id
+```
+
+**Disconnect**: `telegram_disconnect` stops polling AND removes both `telegram_bot_token` and `telegram_owner_chat_id` API keys.
+
+**Reconnect**: Re-establishes polling using stored token (no token re-entry).
+
+**Note**: `httpx.ReadError` during long-poll is expected (network/server drops). PTB's network_retry_loop handles it; logged at DEBUG. Polling timeout of 30s on `ApplicationBuilder` is mandatory — default 5s breaks long-polling.
+
+### 2.10 Pattern J — Multi-field IMAP/SMTP (Email)
+
+**Credentials stored** (all in API key table):
+
+Always:
+- `email_provider` ∈ {gmail, outlook, yahoo, icloud, protonmail, fastmail, custom}
+- `email_address`
+- `email_password` (App Password for Gmail/Outlook/Yahoo, regular for ProtonMail Bridge etc.)
+
+When `email_provider == 'custom'` only:
+- `email_imap_host`, `email_imap_port` (string), `email_imap_encryption`
+- `email_smtp_host`, `email_smtp_port` (string), `email_smtp_encryption`
+
+For named providers (gmail/outlook/...) the IMAP/SMTP host/port come from `server/config/email_providers.json` presets — they are NOT stored as API keys.
+
+**Save flow**:
+```
+handleEmailSave():
+ validate (address required; password required on first save; custom requires hosts/ports)
+ -> 3 sequential await saveApiKey() calls (provider, address, password)
+ -> when provider == 'custom': 4 additional await saveApiKey() calls (imap_host/port/enc, smtp_host/port/enc)
+ -> setEmailPassword('') // security: clear plaintext input after save
+ -> setEmailStored(true)
+```
+
+**Update flow**: empty password input means "keep existing" — handler checks `!password.trim() && emailStored` and skips the password write.
+
+**Remove flow**: `handleEmailRemove()` issues parallel `removeApiKey` calls for all stored fields.
+
+---
+
+## 3. Cross-Cutting Concerns
+
+### 3.1 Loading convention
+`[name]Loading: string | null` where the string is the action tag (`'login'`, `'save'`, `'connect'`, etc.). Buttons compute `loading={twitterLoading === 'login'}`. Always cleared in `finally`.
+
+### 3.2 Error surfacing
+`[name]Error: string | null`. Cleared on retry attempt (`setXError(null)` at start of handler), set in `catch`, rendered as `<Alert type="error" closable />` near the action area. Never `throw` past the handler.
+
+### 3.3 Dirty tracking (Provider Defaults)
+`defaultsDirty: Record<provider, boolean>`. `updateProviderDefault(provider, key, value)` mutates `providerDefaults` AND sets `defaultsDirty[provider]=true`. Save handler calls `saveProviderDefaults` then clears the flag. Save button is disabled when `!defaultsDirty[provider]`.
+
+### 3.4 Lazy fetching
+Usage panels (`Usage & Costs`, `API Usage`, model constraints) fetch inside `useEffect` gated on `usageExpanded === true`. Avoids paying for queries on every modal open.
+
+### 3.5 Broadcast-driven status
+`whatsappStatus`, `androidStatus`, `twitterStatus`, `googleStatus`, `telegramStatus` are subscribed via `useWebSocket()`. The modal NEVER calls a status WebSocket on mount — initial state arrives via `initial_status` broadcast on WS connect, and updates arrive via dedicated `*_status` broadcast types ([client/src/contexts/WebSocketContext.tsx](../client/src/contexts/WebSocketContext.tsx) message handler switch).
+
+The "Refresh" buttons in OAuth panels (Twitter/Google/Telegram) explicitly call the corresponding status request handler to force a re-check, which in turn re-broadcasts.
+
+---
+
+## 4. Backend Contract
+
+### 4.1 WebSocket handler registry
+All handlers registered in [server/routers/websocket.py](../server/routers/websocket.py) `MESSAGE_HANDLERS` dict (lines ~3089–3153). Each handler:
+- Uses `@ws_handler(*required_fields)` decorator (websocket.py:61) which validates required fields and wraps exceptions into `{success: False, error: str(e)}`.
+- Reads dependencies via `container.auth_service()`, `container.ai_service()`, etc. — never touches `credentials_db` directly.
+- Returns a `Dict[str, Any]` with `success: True` (auto-injected by decorator if missing).
+
+### 4.2 Single point of access
+All credential reads/writes go through [`AuthService`](../server/services/auth.py):
+- API keys: `store_api_key(provider, api_key, models, session_id='default')` / `get_api_key(provider, session_id)` / `remove_api_key(provider, session_id)` / `get_stored_models(provider, session_id)`.
+- OAuth tokens: `store_oauth_tokens(provider, access, refresh, email=None, name=None, scopes=None, customer_id='owner')` / `get_oauth_tokens(provider, customer_id)` / `remove_oauth_tokens(provider, customer_id)`.
+- Memory caches: `_memory_cache` (API keys), `_models_cache` (models lists), `_oauth_cache` (OAuth tokens). All hit BEFORE the encrypted DB. `clear_cache()` empties all three (called on logout).
+
+### 4.3 Two-table split
+
+| Table | Storage | Used for |
+|---|---|---|
+| `EncryptedAPIKey` | `{session_id}_{provider}` PK, encrypted single key payload + JSON models | All Pattern A/B/C providers, including `*_client_id` / `*_client_secret` for OAuth providers |
+| `EncryptedOAuthToken` | `(provider, customer_id)` composite, encrypted access + refresh, plus email/name/scopes/expiry | Pattern D/E only — Google + Twitter access/refresh |
+
+Provider × table examples:
+- `google_client_id`, `google_client_secret` → API key table
+- Google access/refresh tokens → OAuth token table under provider=`google`
+- `twitter_client_id`, `twitter_client_secret` → API key table
+- Twitter access/refresh → OAuth token table under provider=`twitter`
+- `telegram_bot_token` → API key table (Pattern I uses no OAuth table)
+
+### 4.4 Encryption layer
+[server/core/encryption.py](../server/core/encryption.py): `EncryptionService` uses Fernet (AES-128-CBC + HMAC-SHA256) with PBKDF2-SHA256 key derivation (600,000 iterations, OWASP 2024). Salt is 32 random bytes, generated on first DB init and stored in `credentials_metadata` table. The encryption password is the server-scoped `API_KEY_ENCRYPTION_KEY` env var, loaded once at startup ([server/main.py](../server/main.py) lifespan).
+
+`encrypt(plaintext) -> str` / `decrypt(ciphertext) -> str`. Decryption raises `ValueError` on tampering/wrong-key, `RuntimeError` if `initialize()` was never called.
+
+### 4.5 Runtime redirect URI derivation
+[server/services/oauth_utils.py](../server/services/oauth_utils.py) `get_redirect_uri(connection, provider)` derives the OAuth callback URI from the live `WebSocket.base_url` (or `Request.base_url`) — converting `ws(s)` to `http(s)` and appending the path from `config/google_apis.json`. No hardcoded hostnames or ports. Works in dev (`http://localhost:3010/api/google/callback`) and prod (`https://flow.zeenie.xyz/api/google/callback`) without env vars.
+
+---
+
+## 5. Refactor Invariants
+
+These are the non-negotiable behaviours the test suite enforces. The refactor is acceptable iff every test in [server/tests/credentials/](../server/tests/credentials) and [client/src/test/](../client/src/test) still passes without modification.
+
+1. **WebSocket message types** for save/validate/delete/get of any API key are exactly `validate_api_key` / `save_api_key` / `get_stored_api_key` / `delete_api_key`, with payload shape `{provider, api_key, [session_id], [models]}`. The response of `get_stored_api_key` exposes `has_key` (snake_case) and the WebSocketContext maps it to `hasKey`.
+2. **OAuth login flows** never expose `client_secret` in the rendered DOM after save — the input is replaced by a "Configured" indicator.
+3. **Google tokens** are read exclusively via `auth_service.get_oauth_tokens('google')`. No call site uses `get_api_key('google_access_token')` or any equivalent.
+4. **Email** with `email_provider='custom'` writes BOTH `email_imap_*` and `email_smtp_*` keys (host + port + encryption for each side). With any other provider, those keys MUST NOT be written.
+5. **Status objects** for whatsapp/android/twitter/google/telegram come from `WebSocketContext` broadcasts. The modal calls the corresponding `*_status` handler ONLY in response to an explicit Refresh click — never on mount, never on a polling timer.
+6. **Provider Defaults** save uses `save_provider_defaults` with payload `{provider, defaults: {...}}` — never `save_api_key`.
+7. **`auth_service.store_api_key`** receives `models` as required keyword arg; non-LLM keys pass `models=[]`.
+8. **`AuthService` is the only route** to `credentials_db`. Routers and handlers must not import or call `CredentialsDatabase` directly.
+9. **PKCE state** is consumed exactly once in `exchange_code`; a second call with the same state returns `{success: False, error: 'Invalid or expired state'}`.
+10. **Twitter PKCE** authorization URL contains `code_challenge_method=S256` and `code_challenge = base64url(sha256(code_verifier))`.
+11. **Google authorization URL** contains `access_type=offline` and `prompt=consent` (otherwise no refresh_token is returned).
+12. **`get_redirect_uri`** strips the path from `connection.base_url` and converts `ws://` → `http://`, `wss://` → `https://`.
+13. **Encryption** is reversible for unicode and large payloads; tampered ciphertext raises `ValueError`; uninitialized service raises `RuntimeError`.
+
+---
+
+## 6. Critical Files Cheat Sheet
+
+| Layer | File | What lives here |
+|---|---|---|
+| UI | [client/src/components/CredentialsModal.tsx](../client/src/components/CredentialsModal.tsx) | All panels, all per-provider state, all click handlers |
+| UI hook | [client/src/hooks/useApiKeys.ts](../client/src/hooks/useApiKeys.ts) | API key CRUD, defaults, usage, constraints |
+| UI hook | [client/src/hooks/useWhatsApp.ts](../client/src/hooks/useWhatsApp.ts) | WhatsApp-specific operations |
+| UI context | [client/src/contexts/WebSocketContext.tsx](../client/src/contexts/WebSocketContext.tsx) | `sendRequest<T>`, push status hooks |
+| WS handlers | [server/routers/websocket.py](../server/routers/websocket.py) | All ~125 handlers; credentials block at 985–1670 |
+| Credential service | [server/services/auth.py](../server/services/auth.py) | Single point of access; memory caches |
+| Encryption | [server/core/encryption.py](../server/core/encryption.py) | Fernet + PBKDF2 |
+| DB | [server/core/credentials_database.py](../server/core/credentials_database.py) | Two encrypted tables + metadata |
+| OAuth (Google) | [server/services/google_oauth.py](../server/services/google_oauth.py) | Flow, PKCE, refresh, service builders |
+| OAuth (Twitter) | [server/services/twitter_oauth.py](../server/services/twitter_oauth.py) | Manual PKCE, token exchange/refresh/revoke |
+| OAuth (Claude) | [server/services/claude_oauth.py](../server/services/claude_oauth.py) | Subprocess-based isolated login |
+| OAuth utils | [server/services/oauth_utils.py](../server/services/oauth_utils.py) | Runtime redirect URI derivation |
+| Container | [server/core/container.py](../server/core/container.py) | DI wiring for `auth_service` etc. |
+
+---
+
+## 7. Test Suite Index
+
+Run the matching tests after every refactor commit:
+
+```bash
+# Backend
+cd server && uv run pytest tests/credentials/ -v
+
+# Frontend
+cd client && npm run test
+```
+
+See [server/tests/credentials/README.md](../server/tests/credentials/README.md) and [client/src/test/README.md](../client/src/test/README.md) for fixture details.
diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.md
new file mode 100644
index 00000000..34ea7467
--- /dev/null
+++ b/docs-internal/node-logic-flows/README.md
@@ -0,0 +1,150 @@
+# Node Logic Flow Documentation
+
+Frozen behavioural contract for every workflow node. One file per node, grouped
+by category. After the upcoming full-stack refactor each handler must still
+match its doc here, and each doc must still describe what the code does.
+
+## How to use
+
+- **Adding a node**: copy [`_TEMPLATE.md`](./_TEMPLATE.md) into the right
+ category folder, name it `<nodeName>.md` (camelCase, matching the registry
+ key in `client/src/nodeDefinitions/`).
+- **Refactoring a node**: update the matching contract test in
+ `server/tests/nodes/test_<category>.py` *first*, then change the handler,
+ then update this doc.
+- **Rebuilding the index below**: run `node scripts/build-node-docs-index.js`
+ (also runs in CI to fail builds when a node is missing a doc).
+
+## Conventions
+
+- Mermaid for flow diagrams (renders natively in GitHub & VS Code).
+- Tables for inputs/outputs/parameters - greppable, diffable in PRs.
+- Cross-link to the existing skill at `server/skills/.../SKILL.md` rather than
+ duplicating tool-mode behaviour.
+- Keep "Side Effects" honest: every DB write, broadcast, subprocess, and HTTP
+ call must be listed.
+
+## Index
+
+<!-- AUTO-GENERATED-INDEX-START -->
+
+### ai_agents
+
+- [AI Agent (`aiAgent`)](./ai_agents/aiAgent.md)
+- [Zeenie (`chatAgent`)](./ai_agents/chatAgent.md)
+- [Simple Memory (`simpleMemory`)](./ai_agents/simpleMemory.md)
+
+### ai_chat_models
+
+- [Anthropic Chat Model (`anthropicChatModel`)](./ai_chat_models/anthropicChatModel.md)
+- [Cerebras Chat Model (`cerebrasChatModel`)](./ai_chat_models/cerebrasChatModel.md)
+- [DeepSeek Chat Model (`deepseekChatModel`)](./ai_chat_models/deepseekChatModel.md)
+- [Gemini Chat Model (`geminiChatModel`)](./ai_chat_models/geminiChatModel.md)
+- [Groq Chat Model (`groqChatModel`)](./ai_chat_models/groqChatModel.md)
+- [Kimi Chat Model (`kimiChatModel`)](./ai_chat_models/kimiChatModel.md)
+- [Mistral Chat Model (`mistralChatModel`)](./ai_chat_models/mistralChatModel.md)
+- [OpenAI Chat Model (`openaiChatModel`)](./ai_chat_models/openaiChatModel.md)
+- [OpenRouter Chat Model (`openrouterChatModel`)](./ai_chat_models/openrouterChatModel.md)
+
+### ai_tools
+
+- [Calculator Tool (`calculatorTool`)](./ai_tools/calculatorTool.md)
+- [Current Time Tool (`currentTimeTool`)](./ai_tools/currentTimeTool.md)
+- [DuckDuckGo Search (`duckduckgoSearch`)](./ai_tools/duckduckgoSearch.md)
+- [Task Manager (`taskManager`)](./ai_tools/taskManager.md)
+- [Write Todos (`writeTodos`)](./ai_tools/writeTodos.md)
+
+### android
+
+- [Airplane Mode Control (`airplaneModeControl`)](./android/airplaneModeControl.md)
+- [App Launcher (`appLauncher`)](./android/appLauncher.md)
+- [App List (`appList`)](./android/appList.md)
+- [Audio Automation (`audioAutomation`)](./android/audioAutomation.md)
+- [Battery Monitor (`batteryMonitor`)](./android/batteryMonitor.md)
+- [Bluetooth Automation (`bluetoothAutomation`)](./android/bluetoothAutomation.md)
+- [Camera Control (`cameraControl`)](./android/cameraControl.md)
+- [Device State (`deviceStateAutomation`)](./android/deviceStateAutomation.md)
+- [Environmental Sensors (`environmentalSensors`)](./android/environmentalSensors.md)
+- [Location (`location`)](./android/location.md)
+- [Media Control (`mediaControl`)](./android/mediaControl.md)
+- [Motion Detection (`motionDetection`)](./android/motionDetection.md)
+- [Network Monitor (`networkMonitor`)](./android/networkMonitor.md)
+- [Screen Control (`screenControlAutomation`)](./android/screenControlAutomation.md)
+- [System Info (`systemInfo`)](./android/systemInfo.md)
+- [WiFi Automation (`wifiAutomation`)](./android/wifiAutomation.md)
+
+### email
+
+- [Email Read (`emailRead`)](./email/emailRead.md)
+- [Email Receive (`emailReceive`)](./email/emailReceive.md)
+- [Email Send (`emailSend`)](./email/emailSend.md)
+
+### http_proxy
+
+- [HTTP Request (`httpRequest`)](./http_proxy/httpRequest.md)
+- [Proxy Config (`proxyConfig`)](./http_proxy/proxyConfig.md)
+- [Proxy Request (`proxyRequest`)](./http_proxy/proxyRequest.md)
+- [Proxy Status (`proxyStatus`)](./http_proxy/proxyStatus.md)
+
+### search
+
+- [Brave Search (`braveSearch`)](./search/braveSearch.md)
+- [Perplexity Search (`perplexitySearch`)](./search/perplexitySearch.md)
+- [Serper Search (`serperSearch`)](./search/serperSearch.md)
+
+### specialized_agents
+
+- [AI Employee (`ai_employee`)](./specialized_agents/aiEmployee.md)
+- [Android Control Agent (`android_agent`)](./specialized_agents/androidAgent.md)
+- [Autonomous Agent (`autonomous_agent`)](./specialized_agents/autonomousAgent.md)
+- [Claude Code Agent (`claude_code_agent`)](./specialized_agents/claudeCodeAgent.md)
+- [Coding Agent (`coding_agent`)](./specialized_agents/codingAgent.md)
+- [Consumer Agent (`consumer_agent`)](./specialized_agents/consumerAgent.md)
+- [Deep Agent (`deep_agent`)](./specialized_agents/deepAgent.md)
+- [Orchestrator Agent (`orchestrator_agent`)](./specialized_agents/orchestratorAgent.md)
+- [Payments Agent (`payments_agent`)](./specialized_agents/paymentsAgent.md)
+- [Productivity Agent (`productivity_agent`)](./specialized_agents/productivityAgent.md)
+- [RLM Agent (`rlm_agent`)](./specialized_agents/rlmAgent.md)
+- [Social Media Agent (`social_agent`)](./specialized_agents/socialAgent.md)
+- [Task Management Agent (`task_agent`)](./specialized_agents/taskAgent.md)
+- [Tool Agent (`tool_agent`)](./specialized_agents/toolAgent.md)
+- [Travel Agent (`travel_agent`)](./specialized_agents/travelAgent.md)
+- [Web Control Agent (`web_agent`)](./specialized_agents/webAgent.md)
+
+### telegram_social
+
+- [Social Receive (`socialReceive`)](./telegram_social/socialReceive.md)
+- [Social Send (`socialSend`)](./telegram_social/socialSend.md)
+- [Telegram Receive (`telegramReceive`)](./telegram_social/telegramReceive.md)
+- [Telegram Send (`telegramSend`)](./telegram_social/telegramSend.md)
+
+### twitter
+
+- [Twitter Receive (`twitterReceive`)](./twitter/twitterReceive.md)
+- [Twitter Search (`twitterSearch`)](./twitter/twitterSearch.md)
+- [Twitter Send (`twitterSend`)](./twitter/twitterSend.md)
+- [Twitter User (`twitterUser`)](./twitter/twitterUser.md)
+
+### web_automation
+
+- [Apify Actor (`apifyActor`)](./web_automation/apifyActor.md)
+- [Browser (`browser`)](./web_automation/browser.md)
+- [Crawlee Scraper (`crawleeScraper`)](./web_automation/crawleeScraper.md)
+
+### whatsapp
+
+- [WhatsApp DB (`whatsappDb`)](./whatsapp/whatsappDb.md)
+- [WhatsApp Receive (`whatsappReceive`)](./whatsapp/whatsappReceive.md)
+- [WhatsApp Send (`whatsappSend`)](./whatsapp/whatsappSend.md)
+
+### workflow_triggers
+
+- [Chat Trigger (`chatTrigger`)](./workflow_triggers/chatTrigger.md)
+- [Cron Scheduler (`cronScheduler`)](./workflow_triggers/cronScheduler.md)
+- [Start (`start`)](./workflow_triggers/start.md)
+- [Task Trigger (`taskTrigger`)](./workflow_triggers/taskTrigger.md)
+- [Timer (`timer`)](./workflow_triggers/timer.md)
+- [Webhook Response (`webhookResponse`)](./workflow_triggers/webhookResponse.md)
+- [Webhook Trigger (`webhookTrigger`)](./workflow_triggers/webhookTrigger.md)
+
+<!-- AUTO-GENERATED-INDEX-END -->
diff --git a/docs-internal/node-logic-flows/_AGENT_BRIEF.md b/docs-internal/node-logic-flows/_AGENT_BRIEF.md
new file mode 100644
index 00000000..2ccf2902
--- /dev/null
+++ b/docs-internal/node-logic-flows/_AGENT_BRIEF.md
@@ -0,0 +1,62 @@
+# Agent Brief - Per-Category Rollout
+
+You are documenting and writing contract tests for one category of MachinaOs
+workflow nodes. Phase 1 (test infrastructure) and Phase 2 (search-node pilot)
+are already done. Your job is to repeat the pilot pattern for your category.
+
+## Pilot example (study before starting)
+
+- **Docs**: [`docs-internal/node-logic-flows/search/`](./search/) - 3 files
+ (`braveSearch.md`, `serperSearch.md`, `perplexitySearch.md`).
+- **Test**: [`server/tests/nodes/test_search.py`](../../server/tests/nodes/test_search.py)
+ - 15 tests across 3 classes.
+- **Doc template**: [`./_TEMPLATE.md`](./_TEMPLATE.md) - copy verbatim,
+ fill every section.
+
+## Reusable infra you must use
+
+| Path | What it gives you |
+|------|------------------|
+| `server/tests/nodes/_harness.py` | `NodeTestHarness` - drives any handler through `NodeExecutor` with stubbed services |
+| `server/tests/nodes/_mocks.py` | `patched_container`, `patched_pricing`, `patched_broadcaster`, `patched_event_waiter`, `patched_subprocess` |
+| `server/tests/conftest.py` | Provides `harness` fixture; pre-stubs `core.logging`, `core.container`, `services.pricing` |
+
+## What to read
+
+1. The handler file(s) for your category (paths in your prompt).
+2. The frontend node definition file in `client/src/nodeDefinitions/`.
+3. Any matching skill at `server/skills/<folder>/<skill>/SKILL.md` - link to it from the doc, do not duplicate.
+4. The pilot files above so you copy the structure exactly.
+
+## What to write
+
+1. **Per-node docs**: one Markdown file per node at `docs-internal/node-logic-flows/<category>/<nodeName>.md`. Use camelCase matching the registry key.
+2. **One test file** at `server/tests/nodes/test_<category>.py` with one test class per node, covering at minimum:
+ - happy path (assert envelope success + payload shape)
+ - one validation/error short-circuit (e.g. empty required param)
+ - one external-error path (HTTP 4xx/5xx, missing credential, subprocess failure)
+3. **Update the docs index**: run `node scripts/build-node-docs-index.js` after writing docs.
+
+## Doc style rules
+
+- Use the Mermaid `flowchart TD` syntax shown in the search docs.
+- Every doc must have **Side Effects** listing every DB write, broadcast, subprocess spawn, file I/O, and HTTP call. Be precise (URL, table name, method).
+- Every doc must have **Edge cases & known limits** with at least one entry. Look for swallowed exceptions, silent fallbacks, hard-coded clamps, undocumented branches.
+- Cross-link sibling docs in **Related**.
+- Do NOT use emojis anywhere (project rule).
+
+## Test style rules
+
+- Use `respx.mock` for httpx calls (already in pyproject dev deps).
+- Use `patched_container(auth_api_keys={"<provider>": "tk_test"})` to inject API keys without touching the encryption pipeline.
+- For trigger nodes, use `patched_event_waiter(canned_event={...})` so the future resolves immediately.
+- For subprocess-based handlers (browser, shell, process_manager, code executors), use `patched_subprocess(stdout=b"...")`.
+- Run `cd server && uv run pytest tests/nodes/test_<category>.py -v` and confirm all green before reporting done.
+
+## Reporting back
+
+After all docs are written and tests pass, report:
+- Count of docs created.
+- Test count + pass status.
+- Any nodes you skipped + why.
+- Any handler bugs you found while documenting (do NOT fix - just list).
diff --git a/docs-internal/node-logic-flows/_TEMPLATE.md b/docs-internal/node-logic-flows/_TEMPLATE.md
new file mode 100644
index 00000000..ff0a41c4
--- /dev/null
+++ b/docs-internal/node-logic-flows/_TEMPLATE.md
@@ -0,0 +1,103 @@
+<!--
+PER-NODE LOGIC FLOW TEMPLATE
+============================
+Replace every <placeholder>. Keep sections in this order so the index builder
+can scrape consistently. One file per node, named <nodeName>.md (camelCase
+matching the registry key, no quotes).
+
+This document is the FROZEN BEHAVIOURAL CONTRACT for one workflow node. After
+the upcoming refactor, the corresponding contract test must still pass and
+this file must still describe what the code does end-to-end.
+-->
+
+# <displayName> (`<nodeType>`)
+
+| Field | Value |
+|------|-------|
+| **Category** | <group, e.g. search / ai / android / google> |
+| **Frontend definition** | [`client/src/nodeDefinitions/<file>.ts`](../../../client/src/nodeDefinitions/<file>.ts) |
+| **Backend handler** | [`server/services/handlers/<file>.py::<handler_fn>`](../../../server/services/handlers/<file>.py) |
+| **Tests** | [`server/tests/nodes/test_<category>.py`](../../../server/tests/nodes/test_<category>.py) |
+| **Skill (if any)** | [`server/skills/<folder>/<skill>/SKILL.md`](../../../server/skills/<folder>/<skill>/SKILL.md) |
+| **Dual-purpose tool** | yes / no - tool name `<tool_name>` if yes |
+
+## Purpose
+
+<One paragraph: what the node does, when a user reaches for it, what problem it solves.>
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data injected into prompt / params |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `query` | string | `""` | yes | - | The search query |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload (see below) |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ query: string;
+ results: Array<{ title: string; snippet: string; url: string }>;
+ result_count: number;
+ provider: string;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params] --> B{Validate query}
+ B -- empty --> E[Return error envelope]
+ B -- ok --> C[Fetch API key from auth_service]
+ C --> D[Call external API via httpx]
+ D -- HTTPStatusError --> E
+ D -- ok --> F[Map API response -> output schema]
+ F --> G[Track usage cost via PricingService]
+ G --> H[Return success envelope]
+```
+
+## Decision Logic
+
+- **Validation**: <list each early-return case>
+- **Branches**: <if/else paths inside the handler that change the shape>
+- **Fallbacks**: <defaults applied when params are missing>
+- **Error paths**: <each catch block, what error string it returns>
+
+## Side Effects
+
+- **Database writes**: <table + columns, e.g. `api_usage_metrics` row per call>
+- **Broadcasts**: <`update_node_status`, `broadcast_terminal_log`, etc.>
+- **External API calls**: <endpoint + auth header>
+- **File I/O**: <paths written / read>
+- **Subprocess**: <if the handler spawns one>
+
+## External Dependencies
+
+- **Credentials**: <provider key looked up via `auth_service.get_api_key('<provider>')`>
+- **Services**: <e.g. WhatsApp RPC at `localhost:9400`, agent-browser CLI>
+- **Python packages**: <e.g. `httpx`, `xdk`, `apify-client`>
+- **Environment variables**: <if any>
+
+## Edge cases & known limits
+
+- <e.g. Brave Search caps `count` at 100>
+- <e.g. Perplexity has no streaming - full response only>
+- <e.g. handler swallows network errors and returns `success=false`>
+
+## Related
+
+- **Skills using this as a tool**: <links to SKILL.md files>
+- **Other nodes that consume this output**: <if there is a typical downstream node>
+- **Architecture docs**: <relevant docs-internal links>
diff --git a/docs-internal/node-logic-flows/ai_agents/aiAgent.md b/docs-internal/node-logic-flows/ai_agents/aiAgent.md
new file mode 100644
index 00000000..f725b7db
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_agents/aiAgent.md
@@ -0,0 +1,181 @@
+# AI Agent (`aiAgent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_agents / agent |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiAgentNodes.ts`](../../../client/src/nodeDefinitions/aiAgentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_agent`](../../../server/services/handlers/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_agents.py`](../../../server/tests/nodes/test_ai_agents.py) |
+| **Skill (if any)** | n/a (the agent consumes skills via `input-skill`) |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+`aiAgent` is the general-purpose LangGraph-backed agent node. It reads a prompt
+and system message, optionally merges conversation history from a connected
+`simpleMemory`, loads instructions from connected skill nodes, binds tool nodes
+as LangGraph tools, and runs the tool-calling loop until the LLM produces a
+final answer. All of the heavy lifting (LLM invocation, tool execution, memory
+persistence) lives in `AIService.execute_agent`; the handler's job is purely
+to gather the connected-node payloads via `_collect_agent_connections` and
+forward them.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data. Used as auto-prompt when `prompt` is empty. |
+| `input-skill` | main | no | Skill nodes (`masterSkill` is expanded into individual skills). |
+| `input-memory` | main | no | A `simpleMemory` node whose `memoryContent` is parsed into LangChain messages. |
+| `input-tools` | main | no | Tool nodes (search, calculator, HTTP, Android toolkit, child agents, etc.). |
+| `input-task` | main | no | `taskTrigger` output - completed delegated-task payload. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `provider` | options | `openai` | no | - | AI provider (openai, anthropic, gemini, groq, cerebras, openrouter, deepseek, kimi, mistral, xai). |
+| `model` | string | `""` | **yes** | - | Model id; loaded dynamically from the provider. |
+| `prompt` | string | `{{ $json.chatInput }}` | **yes** | - | User prompt; may reference upstream node outputs via templates. |
+| `systemMessage` | string | `You are a helpful assistant` | no | - | System prompt prepended to the conversation. |
+| `options.temperature` | number | `0.7` | no | - | 0-2. |
+| `options.maxTokens` | number | `4096` | no | - | 1-200000; clamped to model context in `AIService._resolve_max_tokens`. |
+| `options.thinkingEnabled` | boolean | `false` | no | - | Enables extended thinking / reasoning. |
+| `options.thinkingBudget` | number | `2048` | no | `thinkingEnabled=true` | Token budget (Claude, Gemini, Cerebras). |
+| `options.reasoningEffort` | options | `medium` | no | `thinkingEnabled=true` | `low` / `medium` / `high` (OpenAI o-series, Groq). |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Envelope from `AIService.execute_agent`. |
+
+### Output payload (shape returned by `execute_agent`)
+
+```ts
+{
+ response: string;
+ thinking?: string; // when thinkingEnabled=true and provider supports it
+ model: string;
+ provider: string;
+ finish_reason?: string;
+ timestamp: string;
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time: number }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_ai_agent] --> B[_collect_agent_connections]
+ B --> C{task_data?}
+ C -- yes --> D[Format task_context<br/>prepend to prompt]
+ D --> E{task status in<br/>completed/error AND<br/>tool_data?}
+ E -- yes --> F[Strip ALL tools<br/>tool_data = empty]
+ E -- no --> G
+ F --> G
+ C -- no --> G{prompt empty AND<br/>input_data present?}
+ G -- yes --> H[Extract message/text/content<br/>from input_data<br/>-> parameters.prompt]
+ G -- no --> I
+ H --> I[Get status broadcaster]
+ I --> J[await ai_service.execute_agent<br/>with memory/skill/tool/broadcaster]
+ J --> K[Return envelope]
+```
+
+## Decision Logic
+
+- **`_collect_agent_connections`** scans `context.edges` for edges whose target
+ is this node, then routes each by `targetHandle`:
+ - `input-memory` + source type `simpleMemory` -> build `memory_data` dict.
+ `session_id` is auto-set to the agent's `node_id` unless the memory node
+ explicitly sets `sessionId` to a non-empty, non-`default` value.
+ - `input-skill` -> append to `skill_data`. `masterSkill` is expanded into
+ one entry per **enabled** skill in `skillsConfig`; instructions come from
+ the DB-stored `instructions` first, with a skill-folder fallback.
+ - `input-tools` -> append to `tool_data`. Two special expansions:
+ - `androidTool` -> scans its own incoming edges for Android service nodes
+ and attaches them under `connected_services`.
+ - Any `AI_AGENT_TYPES` source (child agents) -> attaches `child_tools`
+ describing the child's own `input-tools` neighbours.
+ - `input-main` (or `input-chat`, or `None`) -> reads `context.outputs`
+ for the source node and stores as `input_data`.
+ - `input-task` -> reads `context.outputs` first, falling back to
+ `context.get_output_fn(session_id, source_id, 'output_0')`. Unwraps
+ `{ result: {...} }` when nested.
+- **Task completion short-circuit**: if `task_data` exists, `_format_task_context`
+ produces a plain-English wrapper which is prepended to the prompt. If the
+ task status is `completed` or `error` and any tools are present, **all tools
+ are stripped** to prevent the LLM from delegating again.
+- **Auto-prompt fallback**: if `parameters.prompt` is empty after the task
+ block, the handler extracts `input_data.message`, `input_data.text`, or
+ `input_data.content` (first truthy wins) and assigns it to `prompt`. If the
+ input is not a dict the whole value is stringified.
+- **Delegation to AIService**: the handler always returns whatever
+ `ai_service.execute_agent` returns; success/error envelope shape is
+ owned by the service, not the handler.
+
+## Side Effects
+
+- **Database writes**: none directly in the handler. `AIService.execute_agent`
+ writes `token_usage_metrics` rows (via `CompactionService.track`), and
+ `memory_content` markdown changes persist back through the
+ `simpleMemory` node's `save_node_parameters` path owned by the service.
+- **Broadcasts**: `handle_ai_agent` acquires `StatusBroadcaster` and passes
+ it into `execute_agent`. The service then emits `update_node_status`
+ (`thinking`, `executing_tool`, `success`, ...) plus `token_usage_update`
+ and potentially `compaction_starting` / `compaction_completed` events.
+- **External API calls**: delegated to the native LLM provider SDKs (Anthropic,
+ OpenAI, Gemini, OpenRouter, xAI, DeepSeek, Kimi, Mistral) or the LangChain
+ fallback (Groq, Cerebras). Tool nodes may spawn their own HTTP or subprocess
+ calls via `execute_tool`.
+- **File I/O**: none in the handler. Filesystem tool nodes may read/write the
+ per-workflow workspace (`context.workspace_dir`).
+- **Subprocess**: none directly. Tool executors (shell, process manager,
+ browser, code executors) spawn subprocesses.
+
+## External Dependencies
+
+- **Credentials**: provider API keys via `auth_service.get_api_key(<provider>)`,
+ resolved inside `AIService`. Can be overridden by a provider proxy URL
+ (`<provider>_proxy` API key) for Ollama-style local routing.
+- **Services**: `AIService`, `Database`, `StatusBroadcaster`, `CompactionService`,
+ `PricingService`, `SkillLoader` (for `masterSkill` expansion).
+- **Python packages**: `langchain-core`, `langgraph`, `langchain-openai`,
+ `langchain-anthropic`, provider SDKs (`anthropic`, `openai`, `google-genai`).
+- **Environment variables**: none read directly by the handler.
+
+## Edge cases & known limits
+
+- **Memory session auto-derivation**: two agents sharing the same `simpleMemory`
+ will each get a **different** session (each uses its own `node_id`) unless
+ the memory node's `sessionId` is set to a non-empty, non-`default` value.
+- **`masterSkill` expansion swallows missing skills**: if a skill key has no
+ `instructions` in DB and the skill loader raises, the skill entry is still
+ appended with an empty instruction body (logged as a warning, not an error).
+- **Task-completion tool strip is unconditional**: even unrelated tools (e.g.
+ `writeTodos`) are removed when any task completes. This was introduced as a
+ "CRITICAL FIX" because binding tools while instructing the LLM not to use
+ them confused Gemini into returning empty tool call arrays.
+- **No pre-flight token budget check**: `_collect_agent_connections` can
+ produce an arbitrarily long prompt (task context + memory + skills). The
+ handler does **not** trim before calling `execute_agent`; the provider may
+ reject with `prompt_too_long`. See `docs-internal/memory_compaction.md`.
+- **Input fallback is field-ordered**: `message > text > content > str(dict)`.
+ An upstream node that outputs both `message` and `text` will never reach
+ `text`.
+- **Child-agent tool discovery is one level deep**: grandchildren are not
+ traversed.
+
+## Related
+
+- **Shared collection helper**: `_collect_agent_connections` is used by every
+ specialized-agent type (android_agent, coding_agent, web_agent, ...). See
+ [`chatAgent.md`](./chatAgent.md) for the same contract with a different
+ system prompt.
+- **Memory node**: [`simpleMemory.md`](./simpleMemory.md)
+- **Architecture docs**: [Agent Architecture](../../agent_architecture.md),
+ [Agent Delegation](../../agent_delegation.md),
+ [Native LLM SDK](../../native_llm_sdk.md),
+ [Memory Compaction](../../memory_compaction.md)
diff --git a/docs-internal/node-logic-flows/ai_agents/chatAgent.md b/docs-internal/node-logic-flows/ai_agents/chatAgent.md
new file mode 100644
index 00000000..d9fb98ff
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_agents/chatAgent.md
@@ -0,0 +1,141 @@
+# Zeenie (`chatAgent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_agents / agent |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiAgentNodes.ts`](../../../client/src/nodeDefinitions/aiAgentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_agents.py`](../../../server/tests/nodes/test_ai_agents.py) |
+| **Skill (if any)** | n/a (consumes skills via `input-skill`) |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+`chatAgent` (display name **Zeenie**) is the conversational variant of
+`aiAgent`. Same connection model, same `_collect_agent_connections` helper,
+same tool-calling stack - it differs from `aiAgent` in the frontend icon /
+system prompt and in the service method it calls
+(`AIService.execute_chat_agent` instead of `AIService.execute_agent`). It is
+also the handler used by every **specialized agent** node
+(`android_agent`, `coding_agent`, `web_agent`, `task_agent`, `social_agent`,
+`travel_agent`, `tool_agent`, `productivity_agent`, `payments_agent`,
+`consumer_agent`, `autonomous_agent`, `orchestrator_agent`, `ai_employee`) -
+the node registry wires all of those to `handle_chat_agent` via
+`functools.partial`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data. Auto-prompt fallback when `prompt` is empty. |
+| `input-skill` | main | no | Skill nodes (including `masterSkill` aggregation). |
+| `input-memory` | main | no | `simpleMemory` node for conversation history. |
+| `input-tools` | main | no | Tool nodes bound to the LLM via LangGraph. |
+| `input-task` | main | no | `taskTrigger` output - formatted and prepended to the prompt. |
+| `input-teammates` | main | no | **Team-lead only** (`orchestrator_agent`, `ai_employee`). Agents on this handle become `delegate_to_<name>` tools. |
+
+## Parameters
+
+Identical to [`aiAgent`](./aiAgent.md) (`provider`, `model`, `prompt`,
+`systemMessage`, `options.*`). The only frontend differences:
+
+- `prompt` default is `""` (empty) rather than `{{ $json.chatInput }}` - so
+ Zeenie relies on the auto-prompt fallback when wired to a chat trigger.
+- `systemMessage` default is `"You are a helpful assistant."` (Zeenie persona
+ is layered on top by connected skills).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `{ response, thinking?, model, provider, timestamp, ... }` envelope from `execute_chat_agent`. |
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_chat_agent] --> B[_collect_agent_connections]
+ B --> C{task_data?}
+ C -- yes --> D[Prepend task_context to prompt]
+ D --> E{status completed/error<br/>AND tool_data?}
+ E -- yes --> F[Strip ALL tools]
+ E -- no --> G
+ F --> G
+ C -- no --> G{prompt empty AND<br/>input_data present?}
+ G -- yes --> H[prompt := input_data.message<br/>or .text or .content or str]
+ G -- no --> I
+ H --> I{node_type in<br/>TEAM_LEAD_TYPES?}
+ I -- yes --> J[_collect_teammate_connections<br/>-> append each teammate to tool_data]
+ I -- no --> K
+ J --> K[await ai_service.execute_chat_agent<br/>memory/skill/tool/broadcaster/context/db]
+ K --> L[Return envelope]
+```
+
+## Decision Logic
+
+- **Connection collection** is delegated to `_collect_agent_connections`; same
+ rules as `aiAgent` (see that doc for memory session derivation,
+ `masterSkill` expansion, Android toolkit, child-agent tool discovery).
+- **Task context injection** mirrors `aiAgent`: `_format_task_context` wraps
+ the task result as a plain-English instruction that the LLM must "report
+ naturally", then all tools are stripped if the task has already completed
+ or errored.
+- **Auto-prompt fallback** is identical to `aiAgent` - `message` wins over
+ `text` which wins over `content`, falling back to `str(input_data)`.
+- **Team mode** (`orchestrator_agent`, `ai_employee`): after collection, the
+ handler calls `_collect_teammate_connections(node_id, context, database)`
+ to find nodes wired to `input-teammates`. Each teammate whose `node_type`
+ is in `AI_AGENT_TYPES` is appended to `tool_data` as a synthetic tool
+ entry. The AIService then exposes them to the LLM as `delegate_to_<type>`
+ tools (see [Agent Teams](../../agent_teams.md)).
+
+## Side Effects
+
+- **Database writes**: none directly. `execute_chat_agent` writes
+ `token_usage_metrics` and updates the connected `simpleMemory` node's
+ `memoryContent` via `database.save_node_parameters`.
+- **Broadcasts**: `StatusBroadcaster` is fetched and passed down, enabling
+ `update_node_status` events (`thinking`, `executing_tool`, `success`), plus
+ `token_usage_update` from the compaction tracker.
+- **External API calls**: provider LLM SDKs, plus whatever tools the LLM
+ decides to call.
+- **File I/O / subprocess**: only via tool nodes (filesystem, shell, process
+ manager, browser, code executors).
+
+## External Dependencies
+
+- **Credentials**: provider API keys via `auth_service.get_api_key`.
+- **Services**: `AIService`, `Database`, `StatusBroadcaster`,
+ `CompactionService`, `PricingService`, `SkillLoader`.
+- **Python packages**: same as `aiAgent`.
+- **Environment variables**: none read directly.
+
+## Edge cases & known limits
+
+- **Specialized agents inherit every quirk**: any bug in `handle_chat_agent`
+ (e.g. the blanket tool-strip on task completion) affects 13 node types.
+- **Team-lead teammates are appended after existing tools**: if a parent
+ wires both regular tool nodes and teammates, tool order depends on edge
+ scan order (not stable across clients).
+- **Teammate tool entries carry `parameters`**: the teammate's saved node
+ parameters are included so `AIService` can resolve provider/model for
+ delegation. An unconfigured teammate (no `model`) will surface the failure
+ at delegate-time, not at collection-time.
+- **Input fallback field order is identical** to `aiAgent`: `message` >
+ `text` > `content` > `str(dict)`.
+- **Empty `teammates` on a team-lead is benign** - the handler simply runs
+ without delegation tools, so an `orchestrator_agent` with nothing wired to
+ `input-teammates` behaves exactly like `chatAgent`.
+- **`rlm_agent` and `deep_agent` do NOT route here** - they have dedicated
+ handlers (`handle_rlm_agent`, `handle_deep_agent`). All other specialized
+ agents do.
+
+## Related
+
+- **Twin node**: [`aiAgent`](./aiAgent.md) (same collection helper,
+ different service method).
+- **Memory node**: [`simpleMemory`](./simpleMemory.md)
+- **Architecture docs**: [Agent Architecture](../../agent_architecture.md),
+ [Agent Delegation](../../agent_delegation.md),
+ [Agent Teams](../../agent_teams.md),
+ [Memory Compaction](../../memory_compaction.md)
diff --git a/docs-internal/node-logic-flows/ai_agents/simpleMemory.md b/docs-internal/node-logic-flows/ai_agents/simpleMemory.md
new file mode 100644
index 00000000..7b652631
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_agents/simpleMemory.md
@@ -0,0 +1,179 @@
+# Simple Memory (`simpleMemory`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_agents / memory (UI group: `['tool', 'memory']`) |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiAgentNodes.ts`](../../../client/src/nodeDefinitions/aiAgentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_simple_memory`](../../../server/services/handlers/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_agents.py`](../../../server/tests/nodes/test_ai_agents.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+`simpleMemory` is a **passive configuration node** that holds conversation
+history for connected agents. It has no inputs and is not meant to be run on
+its own - it has no Run button in the UI. When an `aiAgent` / `chatAgent`
+(or any specialized agent) executes, `_collect_agent_connections` reads this
+node's saved parameters (`memoryContent`, `windowSize`, `longTermEnabled`,
+etc.) and forwards them to `AIService.execute_agent` /
+`execute_chat_agent`. The service parses the markdown, feeds the messages to
+the LLM, appends the new exchange, trims to window, and saves the updated
+markdown back to the memory node via `database.save_node_parameters`.
+
+The actual handler (`handle_simple_memory`) is only invoked when a user
+explicitly hits Run on the node; it returns an inspector-style snapshot of
+the `services.memory_store` in-memory session, **which is a separate legacy
+store from the markdown pipeline used by the agents**. See "Edge cases"
+below.
+
+## Inputs (handles)
+
+_None._ `simpleMemory` has no incoming handles.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `sessionId` | string | `""` | no | - | Session override. Empty or `default` -> agent node_id is used instead (see Decision Logic). |
+| `windowSize` | number | `100` | no | - | Message *pairs* to keep in short-term memory; 1-100. |
+| `memoryContent` | string | `# Conversation History\n\n*No messages yet.*\n` | no | - | Markdown body (`### **Human** (ts)` / `### **Assistant** (ts)` blocks). Edited in-place in the UI. |
+| `longTermEnabled` | boolean | `false` | no | - | When true, trimmed messages are archived to an `InMemoryVectorStore`. |
+| `retrievalCount` | number | `3` | no | `longTermEnabled=true` | Relevant messages to retrieve at query time (1-10). |
+
+Parameters consumed when an agent pulls the memory:
+
+| Name | Where it comes from | Where it is read |
+|------|---------------------|------------------|
+| `sessionId`, `windowSize`, `memoryContent`, `longTermEnabled`, `retrievalCount` | `database.get_node_parameters(source_node_id)` inside `_collect_agent_connections` | Packed into `memory_data` dict and forwarded to `AIService`. |
+
+Parameters consumed when the node is run directly:
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `sessionId` | string | `default` | Session key used for `services.memory_store`. |
+| `memoryType` | string | `buffer` | Either `buffer` (all messages) or `window`. |
+| `windowSize` | number | `10` | Window size; only applied when `memoryType == 'window'`. |
+| `clearOnRun` | boolean | `false` | When true, clears the session before returning. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-memory` (`main` type) | object | Snapshot of the in-memory session (see below). |
+
+### Output payload (from `handle_simple_memory`)
+
+```ts
+{
+ session_id: string;
+ messages: Array<{ role: 'human' | 'ai'; content: string; timestamp: string }>;
+ message_count: number;
+ memory_type: 'buffer' | 'window';
+ window_size: number | null;
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload> }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ subgraph passiveUse["Passive use (agent collection)"]
+ P1[Agent handler scans edges] --> P2{target=input-memory<br/>source type=simpleMemory?}
+ P2 -- yes --> P3[database.get_node_parameters source_id]
+ P3 --> P4[memory_session_id = node_id<br/>unless sessionId explicit]
+ P4 --> P5[Build memory_data dict<br/>memoryContent/windowSize/...]
+ P5 --> P6[Forward to AIService]
+ end
+
+ subgraph directRun["Direct run (handle_simple_memory)"]
+ D1[handle_simple_memory] --> D2[Read sessionId/memoryType/windowSize/clearOnRun]
+ D2 --> D3{clearOnRun?}
+ D3 -- yes --> D4[memory_store.clear_session]
+ D3 -- no --> D5
+ D4 --> D5[memory_store.get_messages<br/>session_id window_size]
+ D5 --> D6[Return success envelope]
+ end
+```
+
+## Decision Logic
+
+- **Passive collection session key**: if the memory node's `sessionId` is
+ empty or literally `"default"`, the agent's own `node_id` is used as the
+ session key. This is what makes two agents wired to the same memory node
+ keep **separate** histories unless the user explicitly overrides
+ `sessionId`.
+- **Instruction source of truth**: `memoryContent` in the DB is authoritative.
+ UI edits persist there via `save_node_parameters`. The agent side
+ re-serialises after each turn through `AIService._append_to_memory_markdown`
+ + `_trim_markdown_window`.
+- **Window semantics**: `windowSize` counts *pairs* (Human + Assistant), so
+ `_trim_markdown_window` keeps `window_size * 2` blocks. Trimmed blocks are
+ returned as raw text for optional vector-store archival.
+- **Long-term retrieval**: `_get_memory_vector_store(session_id)` lazily
+ creates an `InMemoryVectorStore` with `HuggingFaceEmbeddings(BAAI/bge-small-en-v1.5)`
+ the first time it is requested for that session. On `ImportError` (e.g.
+ `langchain_huggingface` missing) the function returns `None` and the agent
+ silently skips archival - **no error is surfaced**.
+- **Direct-run memory store is different**: `handle_simple_memory` pulls
+ from `services.memory_store._sessions`, **not** from the markdown
+ `memoryContent`. A user who clicks Run on a `simpleMemory` node that is
+ actively used by an agent will see the `memory_store` view, which may be
+ empty even though `memoryContent` contains history.
+
+## Side Effects
+
+- **Database writes**: none in the handler. The agent pipeline writes the
+ updated markdown back to this node's `node_parameters` row via
+ `database.save_node_parameters` after each turn.
+- **Broadcasts**: none. The node is passive.
+- **External API calls**: none in the handler. When `longTermEnabled` is set
+ and the agent archives, `HuggingFaceEmbeddings` loads the
+ `BAAI/bge-small-en-v1.5` model locally (no network once cached).
+- **File I/O**: none. The vector store is `InMemoryVectorStore` - not
+ persisted to disk; it is lost on process restart.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.memory_store` (direct-run path), `AIService` (via
+ agents), `Database` (for parameter persistence).
+- **Python packages**: `langchain-core` (messages), `langchain_huggingface`
+ + `sentence-transformers` (long-term vector store only, optional).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Two storage systems for one node**. The markdown `memoryContent` (used
+ by agents) and the `services.memory_store._sessions` dict (used by the
+ direct-run handler) are **independent**. Clicking Run on the node does not
+ reflect what the agents see, and vice-versa. This is a known architectural
+ seam noted in the CLAUDE.md overview.
+- **Vector store is in-memory only**. `_memory_vector_stores` is a module-
+ global dict keyed by session id. A server restart empties it; long-term
+ memory is not actually durable without external persistence.
+- **`HuggingFaceEmbeddings` import is silent-catch**. If the dependency is
+ missing at runtime, `_get_memory_vector_store` logs a warning and returns
+ `None`; the agent continues without archival and the user never learns.
+- **No token budgeting**. `windowSize` is a message-pair count, not a token
+ count. A long history below the window threshold can still exceed the
+ model's context window; see the "Prompt Too Long" note in CLAUDE.md.
+- **`clearOnRun=true` only affects direct-run**, not the markdown used by
+ connected agents.
+- **Markdown parser is regex-based**. `_parse_memory_markdown` matches
+ `### **Human**` / `### **Assistant**` exactly. If a user edits the UI
+ content to a non-conforming header the messages will silently be dropped.
+- **`windowSize` UI cap is 100**, but the handler accepts any int. The
+ agent-side `_trim_markdown_window` trusts whatever the parameter contains.
+- **Passive node, no envelope on read paths**. When consumed by an agent,
+ this node never produces its own envelope - it only supplies parameters.
+
+## Related
+
+- **Consumer nodes**: [`aiAgent`](./aiAgent.md), [`chatAgent`](./chatAgent.md),
+ every specialized agent that routes to `handle_chat_agent`.
+- **Architecture docs**: [Memory Compaction](../../memory_compaction.md),
+ [Agent Architecture](../../agent_architecture.md)
diff --git a/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md
new file mode 100644
index 00000000..eb274462
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md
@@ -0,0 +1,114 @@
+# Anthropic Chat Model (`anthropicChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Single-turn chat completion against the Anthropic Messages API (Claude family). Shares the same handler as all other chat-model nodes (`handle_ai_chat_model`); provider-specific branching lives inside `AIService.execute_chat` and the native `services/llm/providers/anthropic.py`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes (non-empty) | - | User message |
+| `systemMessage` / `systemPrompt` / `system_prompt` | string | `""` | no | - | System prompt |
+| `model` | string | injected from stored models, fallback `gpt-3.5-turbo` (Anthropic override via stored models list) | no | - | Anthropic model ID - **hyphenated** form (e.g. `claude-sonnet-4-6`, NOT `claude-sonnet-4.6`) |
+| `temperature` | number | 0-1 range | no | - | Clamped to 0-1 for Claude; forced to 1 when thinking is enabled |
+| `maxTokens` | number | model default | no | - | **Must be greater than `thinkingBudget`** when thinking is enabled |
+| `topP` | number | - | no | - | Nucleus sampling |
+| `thinkingEnabled` | boolean | false | no | - | Enable extended thinking |
+| `thinkingBudget` | number | 2048 | no | `thinkingEnabled=[true]` | 1024-16000 tokens allocated to internal reasoning |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('anthropic', 'default')` |
+| `options` | object | `{}` | no | - | Flattened into top-level params |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null; // Claude extended thinking content, if enabled
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'anthropic';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+Wrapped in `{ success, node_id, node_type, result, execution_time }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[_prepare_parameters]
+ B --> C[handle_ai_chat_model]
+ C --> D[AIService.execute_chat]
+ D --> E{api_key + non-empty prompt?}
+ E -- no --> X[ValueError -> error envelope]
+ E -- yes --> F[detect_ai_provider -> 'anthropic']
+ F --> G[Build NativeThinkingConfig if thinkingEnabled<br/>budget from thinkingBudget]
+ G --> H[Lookup anthropic_proxy credential]
+ H --> I[Native path: create_provider anthropic<br/>await provider.chat with thinking]
+ I --> J[Return success envelope with response + thinking]
+ I -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key or empty prompt -> error envelope.
+- **Provider routing**: `detect_ai_provider` matches `'anthropic'` on `'anthropic' in node_type.lower()` branch.
+- **Native provider**: `is_native_provider('anthropic')` is True - uses the `anthropic` Python SDK.
+- **Model ID scrubbing**: strips `[FREE] ` prefix; strips `owner/` prefix for non-OpenRouter providers.
+- **Temperature override**: when `thinkingEnabled=true`, temperature is auto-forced to 1 by `native_resolve_temperature`.
+- **Thinking config**: `NativeThinkingConfig(enabled=True, budget=int(thinkingBudget))` forwarded to the SDK, which maps to Anthropic's `thinking={type: "enabled", budget_tokens: N}`.
+
+## Side Effects
+
+- **Database writes**: none on the bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.anthropic.com/v1/messages` via `anthropic` SDK; base URL configurable in `llm_defaults.json`, overridable via `anthropic_proxy` credential.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('anthropic', 'default')` plus optional `anthropic_proxy`.
+- **Services**: `services/llm/providers/anthropic.py`, `AIService`.
+- **Python packages**: `anthropic`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Model ID format**: Anthropic API uses hyphens (`claude-sonnet-4-6`), NOT dots. Dotted IDs (as used by OpenRouter or Gemini) will 404. The frontend model list already uses the correct form, but template-substituted or hand-entered IDs with dots will fail.
+- **`maxTokens > thinkingBudget` required**: if thinking is enabled and `maxTokens <= thinkingBudget`, the Anthropic API rejects the request. The handler does not pre-validate this; the resulting error becomes the envelope's `error` field.
+- **Temperature forced to 1 when thinking enabled**: regardless of user input.
+- **1M context beta**: Opus 4.6 / Sonnet 4.x support 1M context tokens via a beta header; configured in `llm_defaults.json` rather than the node.
+- **Errors swallowed into envelope**: handler never raises; all failures surface as `success=false`.
+- **No streaming** / **no pricing tracking** on standalone chat nodes.
+
+## Related
+
+- **Peer nodes**: [`openaiChatModel`](./openaiChatModel.md), [`geminiChatModel`](./geminiChatModel.md), [`openrouterChatModel`](./openrouterChatModel.md), [`groqChatModel`](./groqChatModel.md), [`cerebrasChatModel`](./cerebrasChatModel.md), [`deepseekChatModel`](./deepseekChatModel.md), [`kimiChatModel`](./kimiChatModel.md), [`mistralChatModel`](./mistralChatModel.md).
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md), [Memory Compaction](../../memory_compaction.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md
new file mode 100644
index 00000000..793d8caa
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md
@@ -0,0 +1,109 @@
+# Cerebras Chat Model (`cerebrasChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Ultra-fast inference on Cerebras' custom AI hardware. Models include Llama 3.1, GPT-OSS-120b, Qwen-3-235b. Shares `handle_ai_chat_model`. Like Groq, routes through the **LangChain fallback** (`is_native_provider('cerebras')` is False).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | e.g. `llama3.1-8b`, `gpt-oss-120b`, `qwen-3-235b-a22b` |
+| `temperature` | number | 0-1.5 | no | - | Narrower range than OpenAI (0-1.5 rather than 0-2) |
+| `maxTokens` | number | up to 8K | no | - | |
+| `topP` | number | - | no | - | |
+| `thinkingEnabled` | boolean | false | no | - | Only Qwen-3-235b supports format-based reasoning |
+| `reasoningFormat` | options | `parsed` | no | `thinkingEnabled=[true]` | `parsed` / `hidden` - same semantics as Groq Qwen |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('cerebras', 'default')` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null;
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'cerebras';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[handle_ai_chat_model]
+ B --> C[AIService.execute_chat]
+ C --> D{valid key + prompt?}
+ D -- no --> X[error envelope]
+ D -- yes --> E[detect_ai_provider -> 'cerebras']
+ E --> F[Strip 'owner/' prefix]
+ F --> G[LangChain fallback path]
+ G --> H[ChatOpenAI w/ base_url=api.cerebras.ai/v1]
+ H --> I[invoke messages]
+ I --> J[success envelope]
+ H -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: `detect_ai_provider` matches `'cerebras' in node_type.lower()` **before** the groq branch, so routing is unambiguous.
+- **LangChain fallback**: `is_native_provider('cerebras')` False. Uses `ChatOpenAI` with Cerebras base_url.
+- **Reasoning**: same parsed/hidden mechanism as Groq Qwen - only the Qwen-3-235b variant honors it.
+- **Temperature range**: narrower (0-1.5 clamp) than OpenAI/Groq. `_resolve_temperature` applies the clamp.
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.cerebras.ai/v1/chat/completions` via LangChain `ChatOpenAI` with `base_url` override.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('cerebras', 'default')` plus optional `cerebras_proxy`.
+- **Services**: `langchain_openai.ChatOpenAI`.
+- **Python packages**: `langchain-openai`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **LangChain path, not native** (same as Groq).
+- **Temperature capped at 1.5**, not 2.
+- **Reasoning only on Qwen-3-235b**.
+- **Small max output**: 8K for most models; exceeding this surfaces as a provider-side error in the envelope.
+- **Errors swallowed into envelope**.
+
+## Related
+
+- **Peer nodes**: see the other chat-model docs in this folder.
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md
new file mode 100644
index 00000000..5c5c9af7
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md
@@ -0,0 +1,105 @@
+# DeepSeek Chat Model (`deepseekChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+DeepSeek V3 models (`deepseek-chat`, `deepseek-reasoner`). Uses the OpenAI-compatible DeepSeek endpoint via the `services/llm/providers` layer (native path). Shares `handle_ai_chat_model`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | `deepseek-chat` (V3) or `deepseek-reasoner` (always-on CoT) |
+| `temperature` | number | 0-2 | no | - | |
+| `maxTokens` | number | 8-64K | no | - | |
+| `topP` | number | - | no | - | |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('deepseek', 'default')` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null; // reasoning_content from deepseek-reasoner; null for deepseek-chat
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'deepseek';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[handle_ai_chat_model]
+ B --> C[AIService.execute_chat]
+ C --> D{valid key + prompt?}
+ D -- no --> X[error envelope]
+ D -- yes --> E[detect_ai_provider -> 'deepseek']
+ E --> F[Strip 'owner/' prefix]
+ F --> G[Native path: create_provider deepseek<br/>OpenAI SDK w/ DeepSeek base_url]
+ G --> H[provider.chat]
+ H --> I[success envelope]
+ G -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: `detect_ai_provider` matches `'deepseek' in node_type.lower()` **first** (before kimi/mistral/cerebras/groq/openrouter/anthropic/gemini), so routing is unambiguous.
+- **Native path**: uses the OpenAI SDK with DeepSeek's base URL from `llm_defaults.json`. OpenAI-compatible `max_tokens` is passed via `extra_body` to bypass LangChain's `max_completion_tokens` translation (not relevant on the native path but documented for the LangChain-agent path).
+- **`deepseek-reasoner` always-on CoT**: reasoning_content is ALWAYS produced, regardless of `thinkingEnabled`. The native provider extracts it into `LLMResponse.thinking`.
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.deepseek.com/v1/chat/completions` (via OpenAI SDK with overridden base URL).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('deepseek', 'default')` plus optional `deepseek_proxy`.
+- **Services**: `services/llm/providers/openai.py` (reused w/ DeepSeek base_url).
+- **Python packages**: `openai`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **`deepseek-reasoner` always thinks**: `thinkingEnabled=false` does NOT disable the reasoning trace; it just means the UI won't highlight it. The response still contains `reasoning_content`.
+- **`thinkingBudget` has no effect**: DeepSeek reasoning is not budget-configurable; the field is silently ignored.
+- **128K context, up to 64K output**.
+- **OpenAI-compatible but not OpenAI**: features like `response_format: json_object` have subtly different behavior.
+- **Errors swallowed into envelope**.
+
+## Related
+
+- **Peer nodes**: see the other chat-model docs in this folder.
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md
new file mode 100644
index 00000000..d6dbcf21
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md
@@ -0,0 +1,110 @@
+# Gemini Chat Model (`geminiChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Single-turn chat completion against Google's Gemini API (google-genai native SDK). Shares the common `handle_ai_chat_model` handler.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes (non-empty) | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | e.g. `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-3-pro` |
+| `temperature` | number | 0-2 | no | - | 0-2 range |
+| `maxTokens` | number | clamped to model ceiling | no | - | Up to 65K output |
+| `topP` | number | - | no | - | |
+| `thinkingEnabled` | boolean | false | no | - | Enable thinking (2.5 Pro/Flash, 3.x) |
+| `thinkingBudget` | number | 2048 | no | `thinkingEnabled=[true]` | Token budget for internal reasoning |
+| `safetySettings` | object | provider defaults | no | - | Gemini safety category thresholds |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('gemini', 'default')` |
+| `options` | object | `{}` | no | - | Flattened |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null;
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'gemini';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[_prepare_parameters]
+ B --> C[handle_ai_chat_model -> AIService.execute_chat]
+ C --> D{valid key + prompt?}
+ D -- no --> X[error envelope]
+ D -- yes --> E[detect_ai_provider -> 'gemini']
+ E --> F[Build NativeThinkingConfig w/ budget]
+ F --> G[Native path: create_provider gemini<br/>google.genai.Client]
+ G --> H[provider.chat -> LLMResponse]
+ H --> I[success envelope]
+ G -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: matches `'gemini' in node_type.lower()`.
+- **Native SDK**: uses `google.genai.Client` (NOT LangChain's `langchain_google_genai`) to dodge the Windows/Python 3.13 gRPC import hang.
+- **Thinking budget**: `thinkingBudget` -> `NativeThinkingConfig.budget` -> Gemini `thinking_budget` API parameter.
+- **Model string scrubbing**: `[FREE] ` prefix stripped; `owner/model` prefix stripped (non-OpenRouter).
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://generativelanguage.googleapis.com/v1beta/...` via `google-genai` SDK; base URL from `llm_defaults.json`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('gemini', 'default')` plus optional `gemini_proxy`.
+- **Services**: `services/llm/providers/gemini.py`.
+- **Python packages**: `google-genai` (native).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Windows/Python 3.13 quirk**: importing `langchain_google_genai` hangs due to a gRPC deadlock. The native path bypasses this entirely. The LangChain fallback is NEVER used for Gemini on `execute_chat` - it is only lazy-imported for agent execution.
+- **Thinking budget units**: expressed as token count, not low/medium/high effort levels. Defaults to 2048.
+- **Safety settings**: forwarded via the SDK; malformed values surface as `success=false` in the envelope.
+- **`maxTokens` clamp**: capped at the model's ceiling (65K for 2.5/3.x).
+- **Errors swallowed into envelope** - handler never raises.
+
+## Related
+
+- **Peer nodes**: [`openaiChatModel`](./openaiChatModel.md), [`anthropicChatModel`](./anthropicChatModel.md), [`openrouterChatModel`](./openrouterChatModel.md), [`groqChatModel`](./groqChatModel.md), [`cerebrasChatModel`](./cerebrasChatModel.md), [`deepseekChatModel`](./deepseekChatModel.md), [`kimiChatModel`](./kimiChatModel.md), [`mistralChatModel`](./mistralChatModel.md).
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md
new file mode 100644
index 00000000..f747c7fd
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md
@@ -0,0 +1,111 @@
+# Groq Chat Model (`groqChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Ultra-fast inference via Groq's LPU hardware. Models include Llama 3.x / 4, Qwen3-32b, GPT-OSS. Shares `handle_ai_chat_model`; unlike OpenAI/Anthropic/Gemini, Groq routes through the **LangChain fallback** (`create_model` + `chat_model.invoke`) because `is_native_provider('groq')` returns False.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | e.g. `llama-3.1-70b-versatile`, `qwen/qwen3-32b`, `groq/compound-beta` |
+| `temperature` | number | 0-2 | no | - | |
+| `maxTokens` | number | 8-131K per model | no | - | |
+| `topP` | number | - | no | - | |
+| `thinkingEnabled` | boolean | false | no | - | Only Qwen3-32b supports reasoning |
+| `reasoningFormat` | options | `parsed` | no | `thinkingEnabled=[true]` | `parsed` (returns reasoning) or `hidden` (suppresses it) |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('groq', 'default')` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null; // only populated for Qwen3 with reasoningFormat=parsed
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'groq';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[handle_ai_chat_model]
+ B --> C[AIService.execute_chat]
+ C --> D{valid key + prompt?}
+ D -- no --> X[error envelope]
+ D -- yes --> E[detect_ai_provider -> 'groq']
+ E --> F[Strip 'owner/' prefix from model<br/>non-OpenRouter]
+ F --> G[is_native_provider groq? NO]
+ G --> H[LangChain fallback:<br/>self.create_model groq + ChatOpenAI-compatible]
+ H --> I[chat_model.invoke messages]
+ I --> J[extract_thinking_from_response<br/>reads additional_kwargs.reasoning]
+ J --> K[success envelope]
+ H -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: matches `'groq' in node_type.lower()`. Note the ordering in `detect_ai_provider`: deepseek/kimi/mistral/cerebras checked first, so none of those accidentally resolve to groq.
+- **LangChain fallback**: `is_native_provider('groq')` is False -> goes through `create_model` -> `chat_model.invoke`. The model's `base_url` is loaded from `llm_defaults.json`.
+- **Reasoning**: only Qwen3-32b actually honors `reasoningFormat`. Non-Qwen models ignore the flag.
+- **Model string scrubbing**: `[FREE] ` prefix stripped; `owner/` prefix stripped (non-OpenRouter).
+- **Finish reason**: hardcoded to `"stop"` on the LangChain path (no fine-grained mapping).
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.groq.com/openai/v1/chat/completions` via LangChain's `ChatOpenAI` with `base_url` override.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('groq', 'default')` plus optional `groq_proxy`.
+- **Services**: `langchain_openai.ChatOpenAI` (base_url-ed), `AIService.create_model`.
+- **Python packages**: `langchain-openai`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **LangChain path, not native SDK**: unlike OpenAI/Anthropic/Gemini/OpenRouter, Groq goes through LangChain. This means model fetching also uses the curated list via httpx, not the native `fetch_models`.
+- **Reasoning only on Qwen3-32b**: QwQ has been removed from Groq. Other models ignore `reasoningFormat`.
+- **`reasoningFormat=hidden` suppresses `thinking`**: response contains only the final answer.
+- **Finish reason always `"stop"`**: fine-grained reasons (length, content_filter, tool_calls) are flattened.
+- **Errors swallowed into envelope**.
+
+## Related
+
+- **Peer nodes**: see the other chat-model docs in this folder.
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md
new file mode 100644
index 00000000..ac175654
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md
@@ -0,0 +1,107 @@
+# Kimi Chat Model (`kimiChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Kimi K2 models by Moonshot AI (`kimi-k2.5`, `kimi-k2-thinking`). 256K context, 96K output. Uses OpenAI-compatible Moonshot endpoint via the native path. Shares `handle_ai_chat_model`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | `kimi-k2.5` (instant) or `kimi-k2-thinking` |
+| `temperature` | number | **fixed** | no | - | Fixed at 0.6 (instant) or 1.0 (thinking). Input is ignored. |
+| `maxTokens` | number | up to 96K | no | - | |
+| `thinkingEnabled` | boolean | true for k2.5 | no | - | ON by default for k2.5; explicitly disabled for LangGraph agents |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('kimi', 'default')` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null;
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'kimi';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[handle_ai_chat_model]
+ B --> C[AIService.execute_chat]
+ C --> D{valid key + prompt?}
+ D -- no --> X[error envelope]
+ D -- yes --> E[detect_ai_provider -> 'kimi']
+ E --> F[Strip 'owner/' prefix]
+ F --> G[native_resolve_temperature<br/>forces 0.6 or 1.0 based on model + thinking]
+ G --> H[Native path: create_provider kimi<br/>OpenAI SDK w/ Moonshot base_url]
+ H --> I[provider.chat]
+ I --> J[success envelope]
+ H -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: `detect_ai_provider` matches `'kimi' in node_type.lower()`. Ordering guarantees it lands in the kimi lane before groq / openrouter / anthropic / gemini.
+- **Fixed temperature**: `native_resolve_temperature` ignores user input for Kimi and forces 0.6 (instant) or 1.0 (thinking).
+- **Thinking default-on for k2.5**: if user leaves `thinkingEnabled` unset, k2.5 still thinks. To disable, must pass `thinkingEnabled=false`. This is done explicitly for the LangGraph agent integration (where thinking streams break tool-call parsing).
+- **Native path**: uses the OpenAI SDK with Moonshot base_url from `llm_defaults.json`.
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.moonshot.ai/v1/chat/completions` (via OpenAI SDK with override).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('kimi', 'default')` plus optional `kimi_proxy`.
+- **Services**: `services/llm/providers/openai.py` (reused).
+- **Python packages**: `openai`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Temperature is non-configurable**: any user-supplied `temperature` is overridden. Documented in the prompt help text but easy to miss.
+- **Thinking default is ON** for k2.5: contrast with every other chat model, which defaults thinking OFF.
+- **Agent compatibility quirk**: when Kimi is used as the LangGraph agent model, `thinkingEnabled` is explicitly forced False because streamed thinking tokens corrupt tool-call JSON. This is handled in the agent path, not here.
+- **256K context / 96K output**: largest of the native providers.
+- **Errors swallowed into envelope**.
+
+## Related
+
+- **Peer nodes**: see the other chat-model docs in this folder.
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md
new file mode 100644
index 00000000..4f0019fa
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md
@@ -0,0 +1,105 @@
+# Mistral Chat Model (`mistralChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Mistral AI models (`mistral-large-latest`, `mistral-small-latest`, `codestral-latest`). Up to 256K context, 131K output. No thinking/reasoning support. Uses OpenAI-compatible Mistral endpoint via native path. Shares `handle_ai_chat_model`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | `mistral-large-latest`, `mistral-small-latest`, `codestral-latest` |
+| `temperature` | number | 0-1.5 | no | - | Narrower range than OpenAI (0-1.5) |
+| `maxTokens` | number | up to 131K | no | - | |
+| `topP` | number | - | no | - | |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('mistral', 'default')` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: null; // Mistral does not support thinking
+ thinking_enabled: false;
+ model: string;
+ provider: 'mistral';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[handle_ai_chat_model]
+ B --> C[AIService.execute_chat]
+ C --> D{valid key + prompt?}
+ D -- no --> X[error envelope]
+ D -- yes --> E[detect_ai_provider -> 'mistral']
+ E --> F[Strip 'owner/' prefix]
+ F --> G[Native path: create_provider mistral<br/>OpenAI SDK w/ Mistral base_url]
+ G --> H[provider.chat - thinking ignored]
+ H --> I[success envelope, thinking=null]
+ G -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: `detect_ai_provider` matches `'mistral' in node_type.lower()` early, before other providers.
+- **Temperature clamp**: 0-1.5 (narrower than OpenAI).
+- **No thinking**: `thinkingEnabled` is silently ignored (Mistral API has no equivalent parameter). `thinking` always returns null.
+- **Native path**: uses OpenAI SDK with Mistral base_url from `llm_defaults.json`.
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.mistral.ai/v1/chat/completions` (via OpenAI SDK w/ override).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('mistral', 'default')` plus optional `mistral_proxy`.
+- **Services**: `services/llm/providers/openai.py` (reused).
+- **Python packages**: `openai`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **No reasoning support**: `thinkingEnabled` / `thinkingBudget` / `reasoningEffort` / `reasoningFormat` are all silently ignored. The UI may still surface these fields because the parameter factory is shared.
+- **Temperature capped at 1.5** (not 2).
+- **Codestral is code-specialized**: prompts that assume chat behavior may produce different output patterns.
+- **Errors swallowed into envelope**.
+
+## Related
+
+- **Peer nodes**: see the other chat-model docs in this folder.
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md
new file mode 100644
index 00000000..200dd6fd
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md
@@ -0,0 +1,124 @@
+# OpenAI Chat Model (`openaiChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a - chat models are model config nodes, not tools |
+| **Dual-purpose tool** | no - pure chat completion node |
+
+## Purpose
+
+Single-turn chat completion against the OpenAI REST API. Used either as a standalone workflow node (user enters a prompt, the node produces a response) or as a model config node wired into an AI Agent via the `input-model` handle. All 9 chat-model node types share the same handler (`handle_ai_chat_model`) and the same dispatch path; per-provider differences live inside `AIService.execute_chat` (native SDK for OpenAI) and in the clamp / temperature helpers.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly by the handler - prompt must be passed via `parameters` or template-resolved upstream |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes (non-empty) | - | User message content sent to the model |
+| `systemMessage` / `systemPrompt` / `system_prompt` | string | `""` | no | - | System prompt; any of the three naming conventions accepted |
+| `model` | string | auto-populated from stored models, fallback `gpt-3.5-turbo` | no | - | Model ID. `[FREE] ` prefix is stripped before the API call |
+| `temperature` | number | provider default | no | - | 0-2 for most OpenAI models; o-series (o1/o3/o4) force temperature=1 |
+| `maxTokens` / `max_tokens` | number | provider default | no | - | Clamped via `_resolve_max_tokens` to the model's actual context limit |
+| `topP` | number | 1.0 | no | - | Nucleus sampling |
+| `frequencyPenalty` | number | 0 | no | - | OpenAI penalty |
+| `presencePenalty` | number | 0 | no | - | OpenAI penalty |
+| `responseFormat` | options | `text` | no | - | `text` or `json_object` |
+| `thinkingEnabled` | boolean | false | no | - | Turn on extended reasoning (GPT-5 hybrid / o-series) |
+| `reasoningEffort` | options | `medium` | no | `thinkingEnabled=[true]` | `minimal` / `low` / `medium` / `high` |
+| `apiKey` / `api_key` | string | injected by executor | no | - | Auto-injected by `NodeExecutor._inject_api_keys` via `auth_service.get_api_key('openai', 'default')` |
+| `options` | object | `{}` | no | - | Collection bag; flattened into the top-level params dict before use |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload (see below) |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null;
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'openai';
+ finish_reason: string;
+ timestamp: string; // ISO 8601
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, node_id, node_type, result: <payload>, execution_time: number }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[_prepare_parameters:<br/>merge DB params, validate, inject api_key + model]
+ B --> C[handle_ai_chat_model]
+ C --> D[AIService.execute_chat]
+ D --> E[Flatten options into flat params dict]
+ E --> F{api_key present?}
+ F -- no --> X[raise ValueError -> error envelope]
+ F -- yes --> G{prompt non-empty?}
+ G -- no --> X
+ G -- yes --> H[detect_ai_provider -> 'openai']
+ H --> I[Build NativeThinkingConfig if thinkingEnabled]
+ I --> J[Lookup openai_proxy credential]
+ J --> K{is_native_provider?}
+ K -- yes for openai --> L[Native path:<br/>create_provider openai + OpenAI SDK<br/>await provider.chat]
+ L --> M[Build response dict<br/>response / thinking / model / provider / finish_reason]
+ M --> N[Return success envelope]
+ L -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing `api_key` -> ValueError; empty/whitespace `prompt` (via `is_valid_message_content`) -> ValueError. Both produce a `success=false` envelope.
+- **Provider routing**: `detect_ai_provider(node_type)` returns `'openai'` for this node; falls through the else branch in `constants.detect_ai_provider`.
+- **Native vs LangChain**: `is_native_provider('openai')` is True, so the native `openai` SDK is used via `create_provider('openai', api_key, proxy_url=...)`.
+- **Model string scrubbing**: strips `[FREE] ` prefix if present. For non-OpenRouter providers (like this one), any `provider/model` slash prefix is stripped so the OpenAI API sees a flat ID.
+- **Thinking config**: only built when `thinkingEnabled` is truthy; passed through to the provider's `chat()` method.
+- **System prompt**: accepts `system_prompt`, `systemMessage`, or `systemPrompt`. Only prepended as a `SystemMessage` when non-empty (`is_valid_message_content`).
+- **Error path**: any exception in the chat flow is caught, logged, and returned as `success=false` with `error: <str>`.
+
+## Side Effects
+
+- **Database writes**: none directly in the happy path. `_track_token_usage` (invoked elsewhere in the AI service when memory is attached) writes `TokenUsageMetric` rows; for a bare chat model node with no memory this path is typically not exercised from `execute_chat`.
+- **Broadcasts**: none from `execute_chat` itself.
+- **External API calls**: one HTTPS call to `https://api.openai.com/v1/chat/completions` via the `openai` Python SDK (base URL configured in `server/config/llm_defaults.json`; overridable via `{provider}_proxy` credential for Ollama-style routing).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('openai', 'default')` (API key); optional `auth_service.get_api_key('openai_proxy')` for proxy URL override.
+- **Services**: `AIService` (wired via `NodeExecutor.__init__`), `services/llm/providers/openai.py` (native provider).
+- **Python packages**: `openai` (native SDK).
+- **Environment variables**: none (keys are DB-stored).
+
+## Edge cases & known limits
+
+- **O-series fixed temperature**: `o1`, `o3`, `o3-mini`, `o4-mini` accept only `temperature=1`; `_resolve_temperature` (and its native counterpart) clamps regardless of input.
+- **GPT-5 hybrid reasoning**: `reasoningEffort` (`minimal` / `low` / `medium` / `high`) is consumed via `NativeThinkingConfig.effort` and forwarded to the provider SDK. Without `thinkingEnabled=true` the effort value is ignored.
+- **Reasoning summary availability**: the content of `thinking` for o-series models is gated on OpenAI org verification - unverified orgs get `thinking=null` even with `reasoningEffort` set.
+- **`maxTokens` clamp**: clamped to the model's actual output ceiling by `native_resolve_max_tokens`. Exceeding the limit silently caps without error.
+- **All errors are swallowed into the envelope**: any exception (HTTP, timeout, auth, JSON parse) becomes `success=false, error=str(e)`. The handler never raises.
+- **No streaming**: `execute_chat` is single-shot; the full response is awaited before returning.
+- **Pricing / token tracking**: standalone chat model nodes do NOT trigger `_track_token_usage` - that lives on the agent code paths. Cost attribution for bare chat-model executions is therefore not recorded.
+
+## Related
+
+- **Peer nodes** (same handler): [`anthropicChatModel`](./anthropicChatModel.md), [`geminiChatModel`](./geminiChatModel.md), [`openrouterChatModel`](./openrouterChatModel.md), [`groqChatModel`](./groqChatModel.md), [`cerebrasChatModel`](./cerebrasChatModel.md), [`deepseekChatModel`](./deepseekChatModel.md), [`kimiChatModel`](./kimiChatModel.md), [`mistralChatModel`](./mistralChatModel.md).
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md), [Credentials Encryption](../../credentials_encryption.md), [Pricing Service](../../pricing_service.md).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md
new file mode 100644
index 00000000..6b4c47f3
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md
@@ -0,0 +1,111 @@
+# OpenRouter Chat Model (`openrouterChatModel`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_chat_models |
+| **Frontend definition** | [`client/src/nodeDefinitions/aiModelNodes.ts`](../../../client/src/nodeDefinitions/aiModelNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_ai_chat_model`](../../../server/services/handlers/ai.py) |
+| **AI service** | [`server/services/ai.py::AIService.execute_chat`](../../../server/services/ai.py) |
+| **Tests** | [`server/tests/nodes/test_ai_chat_models.py`](../../../server/tests/nodes/test_ai_chat_models.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Unified access to 200+ models from multiple providers (OpenAI, Anthropic, Google, Meta, Mistral, etc.) through a single OpenAI-compatible API. Shares the common `handle_ai_chat_model` handler.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `prompt` | string | `""` | yes (non-empty) | - | User message |
+| `systemMessage` | string | `""` | no | - | System prompt |
+| `model` | string | injected | no | - | `provider/model-id` format, e.g. `anthropic/claude-opus-4.6`, `openai/gpt-4o`. `[FREE] ` prefix stripped before the API call but the prefix IS preserved for the dropdown grouping |
+| `temperature` | number | 0-2 | no | - | |
+| `maxTokens` | number | varies per model | no | - | |
+| `topP` | number | - | no | - | |
+| `frequencyPenalty` | number | 0 | no | - | Forwarded to downstream provider |
+| `presencePenalty` | number | 0 | no | - | Forwarded |
+| `thinkingEnabled` | boolean | false | no | - | Only honored if the routed model supports it |
+| `thinkingBudget` | number | 2048 | no | `thinkingEnabled=[true]` | |
+| `reasoningEffort` | options | `medium` | no | `thinkingEnabled=[true]` | |
+| `apiKey` | string | injected | no | - | `auth_service.get_api_key('openrouter', 'default')` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ response: string;
+ thinking: string | null;
+ thinking_enabled: boolean;
+ model: string;
+ provider: 'openrouter';
+ finish_reason: string;
+ timestamp: string;
+ input: { prompt: string; system_prompt: string };
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor dispatch] --> B[handle_ai_chat_model]
+ B --> C[AIService.execute_chat]
+ C --> D[Strip '[FREE] ' prefix from model]
+ D --> E{valid key + prompt?}
+ E -- no --> X[error envelope]
+ E -- yes --> F[detect_ai_provider -> 'openrouter']
+ F --> G[DO NOT strip 'owner/' prefix<br/>provider == openrouter]
+ G --> H[Native path: create_provider openrouter<br/>OpenAI SDK w/ base_url=openrouter.ai/api/v1]
+ H --> I[provider.chat -> response]
+ I --> J[success envelope]
+ H -- Exception --> X
+```
+
+## Decision Logic
+
+- **Validation**: missing api_key / empty prompt -> error envelope.
+- **Provider routing**: matches `'openrouter' in node_type.lower()` in `detect_ai_provider` BEFORE the `anthropic`/`gemini` branches, so model IDs like `anthropic/claude-3.5-sonnet` stay in the OpenRouter lane.
+- **Model string rule (important)**: for OpenRouter, the `owner/model` slash-prefix is **kept** (the API expects it). For every other provider the prefix is stripped. See `execute_chat` line: `if provider != 'openrouter' and '/' in model: model = model.split('/', 1)[-1]`.
+- **[FREE] prefix**: stripped unconditionally before the API call; exists only for the frontend dropdown grouping.
+- **Native provider**: OpenAI SDK reused with `base_url` set to the OpenRouter gateway; `OpenRouterProvider` inherits from `OpenAIProvider`.
+
+## Side Effects
+
+- **Database writes**: none on bare chat path.
+- **Broadcasts**: none.
+- **External API calls**: `POST https://openrouter.ai/api/v1/chat/completions` via `openai` SDK with overridden `base_url`. Requires `HTTP-Referer` and `X-Title` headers (set by `OpenRouterProvider`).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('openrouter', 'default')` plus optional `openrouter_proxy`.
+- **Services**: `services/llm/providers/openrouter.py`.
+- **Python packages**: `openai`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **200+ models, varying capabilities**: thinking support, context windows, temperature ranges, and pricing all vary per routed model. The handler applies generic clamps; mismatches surface as envelope errors from the downstream provider (e.g. "This model does not support the reasoning parameter").
+- **`[FREE] ` models are OpenRouter-free but may still cost latency**: routing can queue against capacity.
+- **`owner/model` prefix is load-bearing**: removing it breaks routing. Unique among the 9 chat models.
+- **Errors swallowed into envelope**.
+
+## Related
+
+- **Peer nodes**: see the other chat-model docs in this folder.
+- **Architecture docs**: [Native LLM SDK](../../native_llm_sdk.md).
diff --git a/docs-internal/node-logic-flows/ai_tools/calculatorTool.md b/docs-internal/node-logic-flows/ai_tools/calculatorTool.md
new file mode 100644
index 00000000..e6a46214
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_tools/calculatorTool.md
@@ -0,0 +1,135 @@
+# Calculator Tool (`calculatorTool`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_tools (dedicated AI tool) |
+| **Frontend definition** | [`client/src/nodeDefinitions/toolNodes.ts`](../../../client/src/nodeDefinitions/toolNodes.ts) |
+| **Backend handler** | [`server/services/handlers/tools.py::_execute_calculator`](../../../server/services/handlers/tools.py) |
+| **Tests** | [`server/tests/nodes/test_ai_tools.py`](../../../server/tests/nodes/test_ai_tools.py) |
+| **Skill (if any)** | None (referenced directly by AI agents via tool-calling) |
+| **Dual-purpose tool** | tool-only - LLM invokes as `calculator` (configurable via `toolName` param) |
+
+## Purpose
+
+Exposes basic arithmetic as a structured tool that an AI Agent can call during
+reasoning. The LLM fills the `operation` + operand arguments and the handler
+returns the numeric result. Supports the eight operations listed below; no
+external calls, no state.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Passive node - connect `output-tool` to an AI Agent's `input-tools` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `calculator` | yes | - | Name the LLM uses to invoke the tool |
+| `toolDescription` | string | (see frontend) | no | - | LLM-visible tool description |
+
+### LLM-provided tool args (at invocation time)
+
+| Arg | Type | Description |
+|-----|------|-------------|
+| `operation` | string | One of `add`, `subtract`, `multiply`, `divide`, `power`, `sqrt`, `mod`, `abs` |
+| `a` | number | First operand (defaults to `0` if missing) |
+| `b` | number | Second operand (defaults to `0`; unused for `sqrt` / `abs`) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-tool` | object | Raw dict returned to the LLM (no envelope wrapper at the tool level) |
+
+### Output payload (TypeScript shape)
+
+On success:
+```ts
+{
+ operation: string;
+ a: number;
+ b: number;
+ result: number; // float('inf') for x/0, 0 for x mod 0
+}
+```
+
+On unsupported operation:
+```ts
+{
+ error: string; // "Unknown operation: <op>"
+ supported_operations: string[];
+}
+```
+
+On any raised exception inside the op lambda:
+```ts
+{ error: string } // str(exception)
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[_execute_calculator args] --> B[operation = args.operation.lower<br/>a = float args.a default 0<br/>b = float args.b default 0]
+ B --> C{operation in<br/>supported map?}
+ C -- no --> Eunknown[Return error + supported_operations list]
+ C -- yes --> D{Invoke op lambda}
+ D -- divide with b==0 --> Finf[result = float inf]
+ D -- mod with b==0 --> Fmod[result = 0]
+ D -- sqrt --> Fsqrt[result = sqrt of abs a]
+ D -- other --> Fok[result = a op b]
+ D -- exception --> Eexc[Return error: str exception]
+ Finf --> R[Return operation / a / b / result]
+ Fmod --> R
+ Fsqrt --> R
+ Fok --> R
+```
+
+## Decision Logic
+
+- **Unknown operation**: returns `{error, supported_operations}` and does not
+ raise. `operations.keys()` is the authoritative supported list.
+- **Division by zero** (`divide`): returns `float('inf')` instead of erroring.
+- **Mod by zero** (`mod`): returns `0` instead of erroring.
+- **Negative sqrt**: handler silently calls `math.sqrt(abs(a))`, so `sqrt(-9)`
+ returns `3.0` (not an error).
+- **`power` overflow**: raised as `OverflowError` by `math.pow`, caught by the
+ outer `except Exception` and returned as `{error: str}`.
+- **Tool mode only**: when dropped on the canvas and run directly, the node
+ type is not registered in `NodeExecutor._handlers`, so the executor falls
+ through to the generic success fallback. The real contract is the tool
+ invocation path via `execute_tool`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none.
+- **Python packages**: `math` (stdlib only).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `divide` returns `float('inf')` for division by zero - downstream JSON
+ serializers may choke on `Infinity` (not strict JSON).
+- `mod` returns `0` for modulo-by-zero, which is mathematically wrong but
+ matches the handler. Document this for agents that might reason about it.
+- `sqrt` of a negative number silently returns the sqrt of the absolute value
+ rather than erroring or returning NaN.
+- `float(args.get('a', 0))` will raise `ValueError` if the LLM returns
+ non-numeric strings; that error is caught and returned as `{error: ...}`.
+- Operation names are case-insensitive (`.lower()` applied).
+
+## Related
+
+- **Sibling tools**: [`currentTimeTool`](./currentTimeTool.md), [`duckduckgoSearch`](./duckduckgoSearch.md), [`taskManager`](./taskManager.md), [`writeTodos`](./writeTodos.md)
+- **Architecture docs**: [Agent Architecture](../../agent_architecture.md), [Dual-Purpose Tool Node Guide](../../dual_purpose_tool_node_creation.md)
diff --git a/docs-internal/node-logic-flows/ai_tools/currentTimeTool.md b/docs-internal/node-logic-flows/ai_tools/currentTimeTool.md
new file mode 100644
index 00000000..89e3bdf1
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_tools/currentTimeTool.md
@@ -0,0 +1,113 @@
+# Current Time Tool (`currentTimeTool`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_tools (dedicated AI tool) |
+| **Frontend definition** | [`client/src/nodeDefinitions/toolNodes.ts`](../../../client/src/nodeDefinitions/toolNodes.ts) |
+| **Backend handler** | [`server/services/handlers/tools.py::_execute_current_time`](../../../server/services/handlers/tools.py) |
+| **Tests** | [`server/tests/nodes/test_ai_tools.py`](../../../server/tests/nodes/test_ai_tools.py) |
+| **Skill (if any)** | None |
+| **Dual-purpose tool** | tool-only - LLM invokes as `get_current_time` (configurable via `toolName` param) |
+
+## Purpose
+
+Provides the current date, time, day-of-week, and unix timestamp in a
+caller-specified timezone. Intended for AI Agents that need temporal grounding
+(e.g., "what day is it today?" before scheduling something). Pure wrapper
+around `datetime.now(tz)` with `pytz` for tz resolution.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Passive node |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `get_current_time` | yes | - | LLM-visible tool name |
+| `toolDescription` | string | (see frontend) | no | - | LLM-visible description |
+| `timezone` | string | `UTC` | no | - | Default timezone used if the LLM does not pass one |
+
+### LLM-provided tool args (at invocation time)
+
+| Arg | Type | Description |
+|-----|------|-------------|
+| `timezone` | string? | IANA name (`UTC`, `America/New_York`, `Europe/London`, ...). When omitted or empty, handler falls back to the node's `timezone` parameter. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-tool` | object | Raw dict returned to the LLM |
+
+### Output payload (TypeScript shape)
+
+On success:
+```ts
+{
+ datetime: string; // ISO 8601 with offset, e.g. "2026-04-15T12:00:00+00:00"
+ date: string; // "YYYY-MM-DD"
+ time: string; // "HH:MM:SS"
+ timezone: string; // echoed back (the resolved string, not the tz object)
+ day_of_week: string; // "Monday" ... "Sunday"
+ timestamp: number; // unix seconds, integer
+}
+```
+
+On invalid timezone:
+```ts
+{ error: string } // "Invalid timezone: <tz>. Error: <details>"
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[_execute_current_time args node_params] --> B[tz_str = args.timezone OR node_params.timezone OR UTC]
+ B --> C{pytz.timezone tz_str}
+ C -- raises UnknownTimeZoneError --> E[Return error: Invalid timezone ...]
+ C -- ok --> D[now = datetime.now tz]
+ D --> F[Format ISO / date / time / day_of_week / timestamp]
+ F --> R[Return dict]
+```
+
+## Decision Logic
+
+- **Timezone resolution**: `args.timezone` wins if truthy; otherwise
+ `node_params.timezone`; otherwise the string literal `'UTC'`.
+- **Invalid timezone**: caught by the outer `except Exception` and returned
+ as `{error: "Invalid timezone: <tz>. Error: <str>"}` (no raise).
+- **Empty string**: an empty `timezone` arg is falsy so falls back to
+ `node_params.timezone`; an empty node param then falls back to `'UTC'`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none.
+- **Python packages**: `pytz`, `datetime` (stdlib).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `timestamp` is truncated to integer seconds via `int(now.timestamp())` -
+ millisecond precision is lost.
+- `timezone` field in the output is the input string, not the canonical
+ zone name `pytz` may have normalised to (e.g. aliases are not rewritten).
+- If the server system clock is wrong, output is wrong. No NTP sync.
+- `pytz.UnknownTimeZoneError` is the typical failure mode; any other
+ unexpected exception (e.g. strftime locale issues) is also swallowed.
+
+## Related
+
+- **Sibling tools**: [`calculatorTool`](./calculatorTool.md), [`duckduckgoSearch`](./duckduckgoSearch.md), [`taskManager`](./taskManager.md), [`writeTodos`](./writeTodos.md)
+- **Architecture docs**: [Agent Architecture](../../agent_architecture.md)
diff --git a/docs-internal/node-logic-flows/ai_tools/duckduckgoSearch.md b/docs-internal/node-logic-flows/ai_tools/duckduckgoSearch.md
new file mode 100644
index 00000000..3ef62d18
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_tools/duckduckgoSearch.md
@@ -0,0 +1,135 @@
+# DuckDuckGo Search (`duckduckgoSearch`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_tools (dedicated AI tool) |
+| **Frontend definition** | [`client/src/nodeDefinitions/toolNodes.ts`](../../../client/src/nodeDefinitions/toolNodes.ts) |
+| **Backend handler** | [`server/services/handlers/tools.py::_execute_duckduckgo_search`](../../../server/services/handlers/tools.py) |
+| **Tests** | [`server/tests/nodes/test_ai_tools.py`](../../../server/tests/nodes/test_ai_tools.py) |
+| **Skill (if any)** | [`server/skills/web_agent/duckduckgo-search-skill/SKILL.md`](../../../server/skills/web_agent/duckduckgo-search-skill/SKILL.md) |
+| **Dual-purpose tool** | tool-only - LLM invokes as `web_search` (configurable via `toolName` param) |
+
+## Purpose
+
+Free web search with no API key required. Wraps the `ddgs` Python library's
+`DDGS().text(query, max_results=N)` call. Designed as the zero-configuration
+default web search tool for AI Agents, complementing the keyed alternatives
+(`braveSearch`, `serperSearch`, `perplexitySearch`).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Passive node |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `web_search` | yes | - | LLM-visible tool name |
+| `toolDescription` | string | (see frontend) | no | - | LLM-visible description |
+| `maxResults` | number | `5` | no | - | Result cap (frontend clamps `1..10`); cast to `int` in handler |
+
+### LLM-provided tool args (at invocation time)
+
+| Arg | Type | Description |
+|-----|------|-------------|
+| `query` | string | Search query; empty string short-circuits with an error |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-tool` | object | Raw dict returned to the LLM |
+
+### Output payload (TypeScript shape)
+
+On success:
+```ts
+{
+ query: string;
+ results: Array<{ title: string; snippet: string; url: string }>;
+ provider: 'duckduckgo';
+}
+```
+
+On empty query:
+```ts
+{ error: 'No search query provided' }
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[_execute_duckduckgo_search args node_params] --> B{query non-empty?}
+ B -- no --> Eq[Return error: No search query provided]
+ B -- yes --> C[provider = node_params.provider OR duckduckgo<br/>max_results = int node_params.maxResults OR 5]
+ C --> D{provider == duckduckgo}
+ D -- yes --> E{Try import ddgs}
+ E -- ok --> F[run_in_executor DDGS.text query max_results]
+ F --> G[Map title / body-&gt;snippet / href-&gt;url]
+ G --> R[Return query / results / provider]
+ E -- ImportError --> H[Fallback: httpx GET api.duckduckgo.com Instant Answer API]
+ H --> I[Map AbstractText + RelatedTopics into results]
+ I --> R
+ F -- Exception --> Eexc[Logged; propagates to outer generic handler]
+```
+
+## Decision Logic
+
+- **Empty query**: `if not query: return {error: ...}` - no library call.
+- **Provider switch**: `node_params.provider` defaults to `'duckduckgo'` and
+ the handler only implements that branch. Any other value falls through
+ without raising (returns whatever the outer try returns, typically nothing
+ useful). The frontend node does not expose `provider`, so in practice this
+ branch is always taken.
+- **`ddgs` ImportError fallback**: the handler quietly falls back to the
+ DuckDuckGo Instant Answer API (`api.duckduckgo.com`) via `httpx`, which
+ returns a very different shape (abstracts + related topics, not ranked web
+ results). Shown logs: `"ddgs not installed, falling back to Instant Answer API"`.
+- **Sync-in-async**: `DDGS().text(...)` is synchronous; handler wraps it in
+ `loop.run_in_executor(None, ...)` to avoid blocking the event loop.
+
+## Side Effects
+
+- **Database writes**: none. (Unlike `braveSearch`/`serperSearch`/`perplexitySearch`,
+ this handler does **not** write to `api_usage_metrics` - it is free and
+ tracking cost is skipped.)
+- **Broadcasts**: none.
+- **External API calls**:
+ - Primary: `ddgs` library (HTTPS to `duckduckgo.com`; the library manages
+ its own networking, timeout, and rate limits).
+ - Fallback: `GET https://api.duckduckgo.com/?q=<query>&format=json&no_html=1`
+ (timeout 10s) via `httpx.AsyncClient`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none.
+- **Python packages**: `ddgs` (preferred), `httpx` (fallback).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Handler does **not** wrap network errors from `ddgs` - they propagate up to
+ `execute_tool`, which will bubble them into the tool-call result as an
+ uncaught exception. (Mocking the library in tests is therefore required.)
+- Missing `ddgs` silently switches to Instant Answer API, which returns a
+ noticeably smaller and differently-structured result set (abstract +
+ related topics, not ranked web results). The `provider` field still says
+ `"duckduckgo"`, masking the fallback.
+- `maxResults` clamp (`1..10`) is enforced only by the frontend; an LLM could
+ in theory pass `node_params.maxResults = 999` via stored defaults and the
+ handler would honour it.
+- `results[].url` uses the `href` field from `ddgs`; older library versions
+ used a different key - the handler fills missing keys with `""` to stay
+ defensive.
+
+## Related
+
+- **Sibling tools**: [`calculatorTool`](./calculatorTool.md), [`currentTimeTool`](./currentTimeTool.md), [`taskManager`](./taskManager.md), [`writeTodos`](./writeTodos.md)
+- **Companion search nodes** (API-keyed, track cost): [`braveSearch`](../search/braveSearch.md), [`serperSearch`](../search/serperSearch.md), [`perplexitySearch`](../search/perplexitySearch.md)
+- **Skill using this tool**: [`duckduckgo-search-skill/SKILL.md`](../../../server/skills/web_agent/duckduckgo-search-skill/SKILL.md)
diff --git a/docs-internal/node-logic-flows/ai_tools/taskManager.md b/docs-internal/node-logic-flows/ai_tools/taskManager.md
new file mode 100644
index 00000000..4906b8aa
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_tools/taskManager.md
@@ -0,0 +1,182 @@
+# Task Manager (`taskManager`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_tools (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/toolNodes.ts`](../../../client/src/nodeDefinitions/toolNodes.ts) |
+| **Backend handler** | [`server/services/handlers/tools.py::handle_task_manager`](../../../server/services/handlers/tools.py) (workflow-node entry) -> `_execute_task_manager` |
+| **Tests** | [`server/tests/nodes/test_ai_tools.py`](../../../server/tests/nodes/test_ai_tools.py) |
+| **Skill (if any)** | [`server/skills/task_agent/task-manager-skill/SKILL.md`](../../../server/skills/task_agent/task-manager-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `task_manager`; handler registered under both registry key `taskManager` and `execute_tool` dispatch |
+
+## Purpose
+
+Inspects the in-process registry of delegated agent tasks (`_delegated_tasks`
+and `_delegation_results` dicts in `tools.py`). Lets a parent agent (or a
+workflow node run) list currently-running / completed delegations, fetch
+details for a specific `task_id`, or clear a finished task from tracking.
+Does **not** spawn work itself; it only reads/mutates the delegation state
+populated by `_execute_delegated_agent`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Passive node |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `task_manager` | no | - | LLM-visible tool name |
+| `toolDescription` | string | (see frontend) | no | - | LLM-visible description |
+| `operation` | options | `list_tasks` | no | - | One of `list_tasks`, `get_task`, `mark_done` (workflow-node mode) |
+| `task_id` | string | `""` | no | `operation in [get_task, mark_done]` | Target task id |
+| `status_filter` | options | `""` | no | `operation == list_tasks` | One of `""`, `running`, `completed`, `error` |
+
+### LLM-provided tool args (when used as a tool)
+
+| Arg | Type | Description |
+|-----|------|-------------|
+| `operation` | string | Same three values; falls back to node param, then to `'list_tasks'` |
+| `task_id` | string | Required for `get_task` / `mark_done`; otherwise ignored |
+| `status_filter` | string | Optional filter applied to `list_tasks` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-tool` | object | Raw dict returned to the LLM |
+| `output-main` | object | Same payload, available when run as a workflow node |
+
+### Output payload (TypeScript shape)
+
+`list_tasks`:
+```ts
+{
+ success: true;
+ operation: 'list_tasks';
+ tasks: Array<{
+ task_id: string;
+ status: 'running' | 'completed' | 'error' | 'cancelled';
+ active: boolean; // true = still in _delegated_tasks
+ agent_name?: string; // only present for entries from _delegation_results
+ result_summary?: string; // truncated to 200 chars
+ }>;
+ count: number;
+ running: number;
+ completed: number;
+ errors: number;
+}
+```
+
+`get_task`:
+```ts
+{
+ success: boolean;
+ operation: 'get_task';
+ task_id: string;
+ status?: string;
+ agent_name?: string;
+ result?: unknown;
+ error?: string;
+}
+```
+
+`mark_done`:
+```ts
+{
+ success: true;
+ operation: 'mark_done';
+ task_id: string;
+ removed: boolean;
+ message: string;
+}
+```
+
+Unknown operation: `{success: false, error: "Unknown operation: <op>"}`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[_execute_task_manager args config] --> B[Merge operation / task_id / status_filter<br/>args wins, then node params, then defaults]
+ B --> C{operation}
+ C -- list_tasks --> D[Iterate _delegated_tasks -&gt; derive running/completed/cancelled/error]
+ D --> E[Merge _delegation_results entries not already in list]
+ E --> F{status_filter set?}
+ F -- yes --> G[Filter by status]
+ F -- no --> H[Skip]
+ G --> I[Return tasks + counts]
+ H --> I
+ C -- get_task --> J{task_id provided?}
+ J -- no --> Eno[Return success=false: task_id is required]
+ J -- yes --> K[await get_delegated_task_status task_ids=task_id]
+ K --> L{task found?}
+ L -- no --> M[Return success=false: Task not found]
+ L -- yes --> N[Return success + status + agent_name + result/error]
+ C -- mark_done --> O{task_id provided?}
+ O -- no --> Eno2[Return success=false: task_id is required]
+ O -- yes --> P[Pop task_id from _delegated_tasks AND _delegation_results]
+ P --> Q[Return removed flag + message]
+ C -- other --> Eop[Return success=false: Unknown operation]
+```
+
+## Decision Logic
+
+- **Operation resolution**: `tool_args.operation OR node_params.operation OR 'list_tasks'`.
+- **list_tasks status derivation**: for each entry in `_delegated_tasks`,
+ `task.done()` is checked; if done, `cancelled()` / `exception()` determine
+ `cancelled` vs `error` vs `completed`; otherwise `running`.
+- **De-duplication**: `_delegation_results` entries whose `task_id` is
+ already in the `_delegated_tasks`-derived list are skipped.
+- **status_filter**: an empty string means "all"; the check
+ `if status_filter:` treats `""` as falsy, so no filter is applied.
+- **get_task missing id**: returns `{success: false, error: 'task_id is required ...'}`.
+- **get_task not found**: `get_delegated_task_status` returns `{tasks: []}`,
+ handler returns `{success: false, error: 'Task <id> not found'}`.
+- **mark_done missing id**: same `task_id is required` short-circuit.
+- **mark_done when not tracked**: still returns `success=true` but with
+ `removed=false` and a "was not in active tracking" message.
+
+## Side Effects
+
+- **In-memory state writes**: `mark_done` deletes entries from the
+ module-level dicts `_delegated_tasks` and `_delegation_results`
+ (in `services/handlers/tools.py`).
+- **Database writes**: none directly. `get_task` calls
+ `get_delegated_task_status`, which may read from `database` (if supplied),
+ but there is no write from `taskManager`.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `database` (optional) passed through from `context` for
+ `get_delegated_task_status`.
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- State is **process-local** (module-level dicts). A restart wipes all
+ tracked tasks; a horizontally-scaled deployment never sees tasks spawned
+ on a different worker.
+- `result_summary` is truncated to 200 characters via `str(...)[:200]`;
+ multi-line results may be cut mid-line.
+- `list_tasks` counts only `running` / `completed` / `error` explicitly -
+ `cancelled` entries are included in `tasks` but not counted in any of the
+ three aggregate counters.
+- Unknown `operation` returns a failed envelope rather than raising; the
+ agent might keep retrying with the same bad operation string.
+- `handle_task_manager` (workflow-node entry) passes an empty `tool_args`
+ dict and relies entirely on node parameters.
+
+## Related
+
+- **Sibling tools**: [`calculatorTool`](./calculatorTool.md), [`currentTimeTool`](./currentTimeTool.md), [`duckduckgoSearch`](./duckduckgoSearch.md), [`writeTodos`](./writeTodos.md)
+- **Skill using this tool**: [`task-manager-skill/SKILL.md`](../../../server/skills/task_agent/task-manager-skill/SKILL.md)
+- **Architecture docs**: [Agent Delegation](../../agent_delegation.md)
diff --git a/docs-internal/node-logic-flows/ai_tools/writeTodos.md b/docs-internal/node-logic-flows/ai_tools/writeTodos.md
new file mode 100644
index 00000000..f15c33a4
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_tools/writeTodos.md
@@ -0,0 +1,139 @@
+# Write Todos (`writeTodos`)
+
+| Field | Value |
+|------|-------|
+| **Category** | ai_tools (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/toolNodes.ts`](../../../client/src/nodeDefinitions/toolNodes.ts) |
+| **Backend handler** | [`server/services/handlers/todo.py::handle_write_todos`](../../../server/services/handlers/todo.py) (workflow) / `execute_write_todos` (tool) |
+| **Service** | [`server/services/todo_service.py::TodoService`](../../../server/services/todo_service.py) |
+| **Tests** | [`server/tests/nodes/test_ai_tools.py`](../../../server/tests/nodes/test_ai_tools.py) |
+| **Skill (if any)** | [`server/skills/task_agent/write-todos-skill/SKILL.md`](../../../server/skills/task_agent/write-todos-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `write_todos` |
+
+## Purpose
+
+Lets an AI Agent maintain a structured, per-session checklist while working
+on a multi-step task. Each call **replaces** the entire todo list for the
+session with the new snapshot the agent produces, then broadcasts the new
+state over WebSocket so the UI can render a live checklist. Storage is an
+in-process `TodoService` singleton keyed by `workflow_id` (or `node_id` as
+fallback).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Passive node - connect `output-tool` to an AI Agent's `input-tools` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `write_todos` | no | - | LLM-visible tool name |
+| `toolDescription` | string | (see frontend, 3-row hint) | no | - | LLM-visible description |
+
+### LLM-provided tool args (at invocation time)
+
+| Arg | Type | Description |
+|-----|------|-------------|
+| `todos` | `Array<{content: string, status: 'pending' \| 'in_progress' \| 'completed'}>` | Full replacement snapshot of the todo list |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-tool` | object | Tool result returned to the LLM |
+| `output-main` | object | Same payload, available when run as a workflow node |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ success: true;
+ message: string; // "Updated todo list (<N> items)"
+ todos: string; // JSON string of the validated list
+ count: number; // len(stored)
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_write_todos node_id / parameters / context] --> B[Build config: node_id + workflow_id + broadcaster]
+ B --> C[execute_write_todos tool_args=parameters config]
+ C --> D[session_key = workflow_id OR node_id OR default]
+ D --> E[service = get_todo_service singleton]
+ E --> F[service.write session_key todos_input]
+ F --> G[Per-item validation: dict? content stripped non-empty? status in VALID_STATUSES?]
+ G --> H[Serialize validated list to JSON, store in _store session_key]
+ H --> I{broadcaster + node_id?}
+ I -- yes --> J[await broadcaster.update_node_status node_id executing<br/>data.phase = todo_update<br/>data.todos = stored<br/>workflow_id = workflow_id]
+ I -- no --> K[skip]
+ J --> L[Return success + message + todos JSON + count]
+ K --> L
+```
+
+## Decision Logic
+
+- **Session key**: `workflow_id` if truthy, else `node_id`, else literal
+ `"default"`.
+- **Empty / malformed items dropped**:
+ - Non-dict entries: skipped silently.
+ - `content.strip() == ""`: skipped silently.
+ - `status` not in `{pending, in_progress, completed}`: coerced to
+ `"pending"`.
+- **Full replacement semantics**: each call overwrites `_store[session_key]`
+ entirely - there is no merge / append. Agents are expected to send the
+ complete snapshot.
+- **Broadcast guarded**: `update_node_status` is called only when both
+ `broadcaster` and `node_id` are truthy, so direct invocations without a
+ broadcaster still succeed silently.
+- **Status `"executing"`** (not `"success"`): the broadcast uses the status
+ string `"executing"` with `data.phase = "todo_update"`, which the frontend
+ uses to refresh the checklist without moving the node out of its current
+ execution state.
+
+## Side Effects
+
+- **In-memory state writes**: `TodoService._store[session_key] = json.dumps(validated)`.
+ State persists for the lifetime of the Python process only.
+- **Database writes**: none.
+- **Broadcasts**: `StatusBroadcaster.update_node_status(node_id, "executing",
+ {"phase": "todo_update", "todos": [...]}, workflow_id=workflow_id)` - one
+ per successful write, when a broadcaster is present in context.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `TodoService` singleton (`get_todo_service()`);
+ `StatusBroadcaster` via `context['broadcaster']`.
+- **Python packages**: stdlib `json` only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Process-local state**: a server restart clears every todo list.
+ Horizontal scaling never shares state across workers.
+- **No TTL / cleanup**: sessions accumulate forever in `_store` unless
+ `TodoService.clear(session_key)` is called explicitly (no caller does this
+ today).
+- **All validation silent**: dropping an item with empty content or coercing
+ an invalid status never produces a warning in the return payload - only a
+ DEBUG log line.
+- **Broadcast failures swallowed by caller**: `handle_write_todos` awaits
+ `update_node_status`; if the broadcaster raises, the exception bubbles up
+ to the executor (no `try/except` inside the handler).
+- **`todos` returned as a JSON string, not an object**: the LLM must parse
+ it again. This matches Claude Code's `TodoWrite` tool convention.
+- **Content is trimmed** (`.strip()`) but otherwise not sanitised - markdown
+ or HTML in content survives untouched.
+
+## Related
+
+- **Sibling tools**: [`calculatorTool`](./calculatorTool.md), [`currentTimeTool`](./currentTimeTool.md), [`duckduckgoSearch`](./duckduckgoSearch.md), [`taskManager`](./taskManager.md)
+- **Skill using this tool**: [`write-todos-skill/SKILL.md`](../../../server/skills/task_agent/write-todos-skill/SKILL.md)
+- **Architecture docs**: [Status Broadcaster](../../status_broadcaster.md), [Agent Architecture](../../agent_architecture.md)
diff --git a/docs-internal/node-logic-flows/android/_pattern.md b/docs-internal/node-logic-flows/android/_pattern.md
new file mode 100644
index 00000000..b0160739
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/_pattern.md
@@ -0,0 +1,192 @@
+# Android Service Nodes - Shared Pattern
+
+All 16 Android service nodes share a single backend handler, a single frontend
+factory, and a single execution path. This document is the authoritative
+description of that shared behaviour. Individual per-node docs link back here
+for everything that is not node-specific.
+
+## Single handler, registry-driven dispatch
+
+| Concern | Location |
+|---------|----------|
+| Frontend factory | [`client/src/nodeDefinitions/androidServiceNodes.ts::createAndroidServiceNode`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| Backend handler | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) |
+| Underlying service | [`server/services/android_service.py::AndroidService.execute_service`](../../../server/services/android_service.py) |
+| Registry binding | [`server/services/node_executor.py`](../../../server/services/node_executor.py) lines 228-230 |
+| Output flatten | [`server/services/node_executor.py`](../../../server/services/node_executor.py) lines 277-285 |
+
+The `NodeExecutor._build_handler_registry()` method binds every entry in
+`ANDROID_SERVICE_NODE_TYPES` to the same partial:
+
+```python
+for node_type in ANDROID_SERVICE_NODE_TYPES:
+ registry[node_type] = partial(handle_android_service, android_service=self.android_service)
+```
+
+The handler then maps the incoming `node_type` (camelCase) to a backend
+`service_id` (snake_case) via a hard-coded dict **inside the handler**:
+
+```python
+SERVICE_ID_MAP = {
+ 'batteryMonitor': 'battery',
+ 'networkMonitor': 'network',
+ 'systemInfo': 'system_info',
+ 'location': 'location',
+ 'appLauncher': 'app_launcher',
+ 'appList': 'app_list',
+ 'wifiAutomation': 'wifi_automation',
+ 'bluetoothAutomation': 'bluetooth_automation',
+ 'audioAutomation': 'audio_automation',
+ 'deviceStateAutomation': 'device_state',
+ 'screenControlAutomation': 'screen_control',
+ 'airplaneModeControl': 'airplane_mode',
+ 'motionDetection': 'motion_detection',
+ 'environmentalSensors': 'environmental_sensors',
+ 'cameraControl': 'camera_control',
+ 'mediaControl': 'media_control',
+}
+```
+
+The frontend hidden `service_id` param is **ignored** for known node types;
+the handler's own map wins. See "Known inconsistencies" below.
+
+## Shared parameter set
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `service_id` | hidden | per-node (see frontend) | auto | Unused for dispatch; handler uses its own map |
+| `android_host` | hidden | `localhost` | no | Target host for local ADB mode |
+| `android_port` | hidden | `8888` | no | Target port for local ADB mode |
+| `label` | string | display name | no | Custom label, cosmetic only |
+| `action` | options | per-node default | **yes** | Action to perform - loaded dynamically from `/api/android/services/<service_id>/actions` |
+| `parameters` | dict or JSON string | `{}` | no | Per-action nested parameters |
+| `package_name` | string | `""` | conditional | Only surfaced by `appLauncher`; handler promotes it into `parameters` automatically |
+
+Any extra root-level key in the `additional_param_keys` list is hoisted into
+`parameters` before dispatch. Currently the only key in that list is
+`package_name`.
+
+If `parameters` is received as a string the handler calls `json.loads()` on it;
+on `JSONDecodeError` the value is silently replaced with `{}`.
+
+## Execution paths
+
+`AndroidService.execute_service` picks one of two transports at call time:
+
+- **Relay path**: if `get_current_relay_client().is_paired()` returns a paired
+ client, the call is forwarded to the remote device over the relay WebSocket
+ via `_execute_via_relay(...)`.
+- **Local HTTP path**: otherwise `httpx.AsyncClient` posts
+ `{"action": action, "parameters": parameters}` to
+ `http://{android_host}:{android_port}/api/{service_id}` with the service's
+ configured `default_timeout`.
+
+```mermaid
+flowchart TD
+ A[handle_android_service] --> B[Look up service_id via SERVICE_ID_MAP<br/>fallback to parameters.service_id then 'battery']
+ B --> C[Parse parameters<br/>coerce JSON string, promote package_name]
+ C --> D[android_service.execute_service<br/>node_id, service_id, action, parameters, host, port]
+ D --> E{relay client paired?}
+ E -- yes --> F[_execute_via_relay]
+ E -- no --> G[POST /api/{service_id} on android_host:android_port]
+ G -- 200 --> H[Return success + data]
+ G -- non-200 --> I[Return success=false + HTTP error]
+ G -- httpx.ConnectError --> J[Return success=false + 'Cannot connect...']
+ G -- httpx.TimeoutException --> K[Return success=false + 'Request timeout...']
+ G -- other Exception --> L[Return success=false + str(e)]
+ H --> M[NodeExecutor flattens result.data to top level]
+```
+
+## Output envelope
+
+`AndroidService.execute_service` returns:
+
+```ts
+{
+ success: boolean,
+ node_id: string,
+ node_type: 'androidService',
+ result: {
+ service_id: string,
+ action: string,
+ data: object, // raw service response under 'data' key
+ response_time: number, // httpx response elapsed seconds
+ android_host: string,
+ android_port: number,
+ timestamp: string // ISO8601
+ },
+ execution_time: number,
+ timestamp: string
+}
+```
+
+`NodeExecutor` then **flattens** the `result.data` contents to the top level of
+`result` before writing to the output store, so downstream templates can use
+`{{batteryMonitor.battery_level}}` instead of
+`{{batteryMonitor.data.battery_level}}`. The original `data` key is preserved
+alongside the promoted fields. Metadata keys (`service_id`, `action`,
+`response_time`, `android_host`, `android_port`, `timestamp`) are also
+preserved.
+
+## Side effects
+
+- **External HTTP**: `POST http://{android_host}:{android_port}/api/{service_id}` (local path)
+- **External WebSocket**: relay RPC call when a paired client exists
+- **Database writes**: none in the handler itself; the `NodeExecutor` writes
+ three output-store keys (`output_main`, `output_top`, `output_0`) with the
+ flattened payload.
+- **Broadcasts**: none direct from the handler. Status broadcasts are emitted
+ by the outer executor (not by this handler).
+- **File I/O**: none.
+- **Subprocess**: none direct (any ADB port forwarding is set up out-of-band
+ via the Android router, not by this handler).
+
+## External dependencies
+
+- **Transport selection**: `services.android.get_current_relay_client` at call time
+- **Local mode**: `httpx.AsyncClient` with `self.default_timeout` (see
+ `AndroidService.__init__`)
+- **Connection state**: Android service node execution requires `paired=true`
+ in relay mode. The relay `connected` state alone is not sufficient.
+- **Environment variables**: none; host/port come from hidden node params.
+
+## Known inconsistencies & edge cases
+
+1. **Frontend/backend service_id mismatch for four nodes**. The frontend
+ `createAndroidServiceNode` factory stores the following serviceIds as hidden
+ params:
+ - `deviceStateAutomation` -> `device_state_automation`
+ - `screenControlAutomation` -> `screen_control_automation`
+ - `airplaneModeControl` -> `airplane_mode_control`
+
+ The handler's `SERVICE_ID_MAP` overrides those with:
+ - `deviceStateAutomation` -> `device_state`
+ - `screenControlAutomation` -> `screen_control`
+ - `airplaneModeControl` -> `airplane_mode`
+
+ The handler map wins because it is looked up first, but any consumer that
+ reads the hidden param directly would see a different value. The same
+ discrepancy exists in `handlers/tools.py::_execute_android_service`.
+2. **JSON parse failure is silent**. A `parameters` string that fails to parse
+ is replaced with `{}` and logged only at debug level.
+3. **No validation of required action params**. `appLauncher` needs
+ `package_name`, but the handler never checks for it - an empty value is
+ passed through and the Android side is expected to error.
+4. **`default_timeout` is service-instance-wide**. All sensor / camera / media
+ calls share the same timeout; there is no per-action override.
+5. **Output flatten can shadow metadata**. If the device returns a `data`
+ dict whose keys collide with `result` metadata keys (`action`,
+ `service_id`, `timestamp`, ...), the flatten merges `data` **after**
+ metadata, so the data wins and the metadata is lost from the promoted view.
+6. **`execute_service` never raises**. Every exception path returns an envelope
+ with `success=false` and the error string, so the handler itself never
+ raises past `NodeExecutor`.
+
+## Related
+
+- Android service infrastructure: [`server/services/android/`](../../../server/services/android/)
+- Status broadcaster (two-state model): [Status Broadcaster](../../status_broadcaster.md)
+- Android-agent skills: [`server/skills/android_agent/`](../../../server/skills/android_agent/)
+- Toolkit sub-node execution: see `TOOLKIT_NODE_TYPES` and
+ `_execute_android_service` in
+ [`server/services/handlers/tools.py`](../../../server/services/handlers/tools.py)
diff --git a/docs-internal/node-logic-flows/android/airplaneModeControl.md b/docs-internal/node-logic-flows/android/airplaneModeControl.md
new file mode 100644
index 00000000..d1d9da85
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/airplaneModeControl.md
@@ -0,0 +1,51 @@
+# Airplane Mode Control (`airplaneModeControl`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / automation |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Airplane mode status reporting and control.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[airplaneModeControl]` | `airplane_mode` |
+| Default action | `status` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'airplane_mode']
+ B --> C{action}
+ C -- status --> D[POST /api/airplane_mode]
+ C -- enable --> D
+ C -- disable --> D
+ D --> E[Flatten data: airplane_mode]
+```
+
+## Edge cases & known limits
+
+- Frontend hidden `service_id` is `airplane_mode_control`; handler rewrites to
+ `airplane_mode` via `SERVICE_ID_MAP`. See
+ [`_pattern.md`](./_pattern.md#known-inconsistencies--edge-cases) item 1.
+- Non-system apps cannot toggle airplane mode on Android 4.2+. Expect
+ device-side `success=false` on `enable` / `disable` without signature perms.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Sibling: [`deviceStateAutomation`](./deviceStateAutomation.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/appLauncher.md b/docs-internal/node-logic-flows/android/appLauncher.md
new file mode 100644
index 00000000..89a58a9c
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/appLauncher.md
@@ -0,0 +1,55 @@
+# App Launcher (`appLauncher`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / apps |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/app-launcher-skill/SKILL.md`](../../../server/skills/android_agent/app-launcher-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Launch an Android application by package name (e.g. `com.whatsapp`).
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[appLauncher]` | `app_launcher` |
+| Default action | `launch` |
+
+## Parameters
+
+In addition to the shared set:
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `package_name` | string | `""` | **conditional** | `action: ['launch']` | Target package name. Handler promotes this from the root-level params into the nested `parameters` dict before dispatch (see [`_pattern.md`](./_pattern.md#shared-parameter-set)). |
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'app_launcher']
+ B --> C[Promote package_name into parameters dict]
+ C --> D{action}
+ D -- launch --> E[POST /api/app_launcher<br/>{action: launch, parameters: {package_name}}]
+ D -- other --> E
+ E --> F[Flatten data: launched, package_name, success]
+```
+
+## Edge cases & known limits
+
+- The handler does **not** validate that `package_name` is non-empty; an empty
+ value is forwarded verbatim and the device reports the error.
+- If the app is not installed the device returns `success=false` with the
+ error surfaced in the envelope.
+- Shared edge cases from [`_pattern.md`](./_pattern.md#known-inconsistencies--edge-cases).
+
+## Related
+
+- Skill: [`app-launcher-skill/SKILL.md`](../../../server/skills/android_agent/app-launcher-skill/SKILL.md)
+- Sibling: [`appList`](./appList.md) - to enumerate installed packages
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/appList.md b/docs-internal/node-logic-flows/android/appList.md
new file mode 100644
index 00000000..10fecd5b
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/appList.md
@@ -0,0 +1,48 @@
+# App List (`appList`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / apps |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/app-list-skill/SKILL.md`](../../../server/skills/android_agent/app-list-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Enumerate installed applications with package name, label, version, and other
+metadata returned by the device-side service.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[appList]` | `app_list` |
+| Default action | `list` |
+
+## Parameters
+
+Shared parameter set only. Filters (system/user apps, name contains, etc.) are
+passed through `parameters` to the device.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'app_list']
+ B --> C[POST /api/app_list {action, parameters}]
+ C --> D[Flatten data: apps array, count]
+```
+
+## Edge cases & known limits
+
+- Full package listings can be large; response size is bounded only by the
+ device handler and `httpx` timeout.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`app-list-skill/SKILL.md`](../../../server/skills/android_agent/app-list-skill/SKILL.md)
+- Sibling: [`appLauncher`](./appLauncher.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/audioAutomation.md b/docs-internal/node-logic-flows/android/audioAutomation.md
new file mode 100644
index 00000000..8b1079a0
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/audioAutomation.md
@@ -0,0 +1,50 @@
+# Audio Automation (`audioAutomation`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / automation |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/audio-skill/SKILL.md`](../../../server/skills/android_agent/audio-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Volume and audio state control: get/set volume per stream, mute, unmute.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[audioAutomation]` | `audio_automation` |
+| Default action | `get_volume` |
+
+## Parameters
+
+Shared parameter set only. Stream and value live inside `parameters`.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'audio_automation']
+ B --> C{action}
+ C -- get_volume --> D[POST /api/audio_automation]
+ C -- set_volume --> D
+ C -- mute --> D
+ C -- unmute --> D
+ D --> E[Flatten data: volume, stream, muted]
+```
+
+## Edge cases & known limits
+
+- Do Not Disturb and notification policy restrictions on Android can cause
+ `set_volume` to be ignored by the system.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`audio-skill/SKILL.md`](../../../server/skills/android_agent/audio-skill/SKILL.md)
+- Sibling: [`mediaControl`](./mediaControl.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/batteryMonitor.md b/docs-internal/node-logic-flows/android/batteryMonitor.md
new file mode 100644
index 00000000..4bbb7f2b
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/batteryMonitor.md
@@ -0,0 +1,74 @@
+# Battery Monitor (`batteryMonitor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / monitoring |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/battery-skill/SKILL.md`](../../../server/skills/android_agent/battery-skill/SKILL.md) |
+| **Dual-purpose tool** | direct sub-node of `androidTool` - can also connect straight to any agent's `input-tools` |
+
+## Purpose
+
+Monitor battery status on the connected Android device: level percentage,
+charging state, temperature, and health.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| Handler dispatch | uniform - see [`_pattern.md`](./_pattern.md) |
+| `SERVICE_ID_MAP[batteryMonitor]` | `battery` |
+| Default action | `status` |
+
+All transport, parameter promotion, and output flattening behaviour is
+identical to every other Android node. See [`_pattern.md`](./_pattern.md).
+
+## Parameters
+
+Only the shared parameter set; no node-specific additions. See
+[`_pattern.md`](./_pattern.md#shared-parameter-set).
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch to handle_android_service] --> B[service_id = 'battery']
+ B --> C{action}
+ C -- status --> D[POST /api/battery {action: status, parameters}]
+ C -- other --> D
+ D --> E[AndroidService.execute_service envelope]
+ E --> F[NodeExecutor flattens data.battery_level,<br/>data.charging, data.temperature, data.health<br/>to top level of output]
+```
+
+## Output payload (typical, after flatten)
+
+```ts
+{
+ service_id: 'battery',
+ action: 'status',
+ battery_level: number, // promoted from data
+ charging: boolean, // promoted from data
+ temperature: number, // promoted from data
+ health: string, // promoted from data
+ data: { ... }, // original nested block still present
+ response_time: number,
+ android_host: string,
+ android_port: number,
+ timestamp: string
+}
+```
+
+## Edge cases & known limits
+
+- Exact `data` keys depend on the device-side handler; the flatten logic
+ blindly promotes whatever the device returns.
+- Relay mode returns the same shape but via `_execute_via_relay`.
+- See [`_pattern.md`](./_pattern.md#known-inconsistencies--edge-cases) for
+ shared edge cases.
+
+## Related
+
+- Skill: [`battery-skill/SKILL.md`](../../../server/skills/android_agent/battery-skill/SKILL.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/bluetoothAutomation.md b/docs-internal/node-logic-flows/android/bluetoothAutomation.md
new file mode 100644
index 00000000..2394e649
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/bluetoothAutomation.md
@@ -0,0 +1,49 @@
+# Bluetooth Automation (`bluetoothAutomation`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / automation |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/bluetooth-skill/SKILL.md`](../../../server/skills/android_agent/bluetooth-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Bluetooth control: enable, disable, get adapter status, list paired devices.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[bluetoothAutomation]` | `bluetooth_automation` |
+| Default action | `status` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'bluetooth_automation']
+ B --> C{action}
+ C -- status --> D[POST /api/bluetooth_automation]
+ C -- enable --> D
+ C -- disable --> D
+ C -- paired_devices --> D
+ D --> E[Flatten data]
+```
+
+## Edge cases & known limits
+
+- Programmatic Bluetooth enable/disable requires `BLUETOOTH_CONNECT` runtime
+ permission on Android 12+; the device-side service reports the failure.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`bluetooth-skill/SKILL.md`](../../../server/skills/android_agent/bluetooth-skill/SKILL.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/cameraControl.md b/docs-internal/node-logic-flows/android/cameraControl.md
new file mode 100644
index 00000000..ff7ee3b8
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/cameraControl.md
@@ -0,0 +1,53 @@
+# Camera Control (`cameraControl`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / media |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/camera-skill/SKILL.md`](../../../server/skills/android_agent/camera-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Camera inspection and capture: enumerate cameras, describe capabilities, take
+photos.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[cameraControl]` | `camera_control` |
+| Default action | `camera_info` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'camera_control']
+ B --> C{action}
+ C -- camera_info --> D[POST /api/camera_control]
+ C -- take_photo --> D
+ C -- capabilities --> D
+ D --> E[Flatten data: cameras, photo_path, capabilities]
+```
+
+## Edge cases & known limits
+
+- `take_photo` requires the `CAMERA` runtime permission on the device; the
+ device-side service returns `success=false` with the permission error if
+ missing.
+- Photo paths returned by the device are relative to the device's filesystem,
+ not the host.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`camera-skill/SKILL.md`](../../../server/skills/android_agent/camera-skill/SKILL.md)
+- Sibling: [`mediaControl`](./mediaControl.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/deviceStateAutomation.md b/docs-internal/node-logic-flows/android/deviceStateAutomation.md
new file mode 100644
index 00000000..3c883a56
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/deviceStateAutomation.md
@@ -0,0 +1,51 @@
+# Device State (`deviceStateAutomation`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / automation |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Aggregate device state control: airplane mode, screen on/off, power save mode,
+brightness level.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[deviceStateAutomation]` | `device_state` |
+| Default action | `status` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'device_state']
+ B --> C{action}
+ C -- status --> D[POST /api/device_state]
+ C -- screen_on --> D
+ C -- screen_off --> D
+ C -- power_save --> D
+ D --> E[Flatten data: screen_state, airplane_mode,<br/>power_save, brightness]
+```
+
+## Edge cases & known limits
+
+- Frontend hidden `service_id` is `device_state_automation`; the handler
+ rewrites it to `device_state` via `SERVICE_ID_MAP`. See
+ [`_pattern.md`](./_pattern.md#known-inconsistencies--edge-cases) item 1.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Siblings: [`screenControlAutomation`](./screenControlAutomation.md), [`airplaneModeControl`](./airplaneModeControl.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/environmentalSensors.md b/docs-internal/node-logic-flows/android/environmentalSensors.md
new file mode 100644
index 00000000..0dab5a49
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/environmentalSensors.md
@@ -0,0 +1,47 @@
+# Environmental Sensors (`environmentalSensors`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / sensors |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/environmental-skill/SKILL.md`](../../../server/skills/android_agent/environmental-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Ambient environment readings: temperature, humidity, atmospheric pressure,
+light level.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[environmentalSensors]` | `environmental_sensors` |
+| Default action | `ambient_conditions` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'environmental_sensors']
+ B --> C[POST /api/environmental_sensors]
+ C --> D[Flatten data: temperature, humidity,<br/>pressure, light]
+```
+
+## Edge cases & known limits
+
+- Many devices ship only a subset of environmental sensors; missing sensors
+ are reported as `null` or omitted by the device service.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`environmental-skill/SKILL.md`](../../../server/skills/android_agent/environmental-skill/SKILL.md)
+- Sibling: [`motionDetection`](./motionDetection.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/location.md b/docs-internal/node-logic-flows/android/location.md
new file mode 100644
index 00000000..b850d543
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/location.md
@@ -0,0 +1,49 @@
+# Location (`location`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / monitoring |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/location-skill/SKILL.md`](../../../server/skills/android_agent/location-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+GPS location with latitude, longitude, accuracy, altitude, speed, and provider.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[location]` | `location` |
+| Default action | `current` |
+
+## Parameters
+
+Shared parameter set only. See [`_pattern.md`](./_pattern.md#shared-parameter-set).
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'location']
+ B --> C{action}
+ C -- current --> D[POST /api/location {action: current}]
+ C -- other --> D
+ D --> E[Flatten data: latitude, longitude, accuracy,<br/>altitude, speed, provider]
+```
+
+## Edge cases & known limits
+
+- Android requires runtime location permission on the connected device - a
+ permission error surfaces as `success=false` with the device's error string.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`location-skill/SKILL.md`](../../../server/skills/android_agent/location-skill/SKILL.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
+- Also see the Google Maps node family (`gmaps_locations`, `gmaps_nearby_places`)
+ for non-Android geocoding.
diff --git a/docs-internal/node-logic-flows/android/mediaControl.md b/docs-internal/node-logic-flows/android/mediaControl.md
new file mode 100644
index 00000000..e747904f
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/mediaControl.md
@@ -0,0 +1,53 @@
+# Media Control (`mediaControl`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / media |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Media playback and media-stream volume control. Distinct from
+`audioAutomation` in that it targets the media session / playback APIs rather
+than raw stream volumes.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[mediaControl]` | `media_control` |
+| Default action | `volume_control` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'media_control']
+ B --> C{action}
+ C -- volume_control --> D[POST /api/media_control]
+ C -- play --> D
+ C -- pause --> D
+ C -- next --> D
+ C -- previous --> D
+ D --> E[Flatten data: playback_state, volume, track]
+```
+
+## Edge cases & known limits
+
+- Requires `MEDIA_CONTENT_CONTROL` or the active notification-listener
+ permission on recent Android for full control; without it only coarse
+ volume actions succeed.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Sibling: [`audioAutomation`](./audioAutomation.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/motionDetection.md b/docs-internal/node-logic-flows/android/motionDetection.md
new file mode 100644
index 00000000..07c54157
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/motionDetection.md
@@ -0,0 +1,50 @@
+# Motion Detection (`motionDetection`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / sensors |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/motion-skill/SKILL.md`](../../../server/skills/android_agent/motion-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Accelerometer and gyroscope readings; derived signals such as shake gestures
+and device orientation.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[motionDetection]` | `motion_detection` |
+| Default action | `current_motion` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'motion_detection']
+ B --> C{action}
+ C -- current_motion --> D[POST /api/motion_detection]
+ C -- orientation --> D
+ C -- shake_detect --> D
+ D --> E[Flatten data: accelerometer, gyroscope,<br/>orientation, shake]
+```
+
+## Edge cases & known limits
+
+- Experimental service - sensor availability varies by device. Missing sensors
+ return `success=false` with a device-level error.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`motion-skill/SKILL.md`](../../../server/skills/android_agent/motion-skill/SKILL.md)
+- Sibling: [`environmentalSensors`](./environmentalSensors.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/networkMonitor.md b/docs-internal/node-logic-flows/android/networkMonitor.md
new file mode 100644
index 00000000..3f33cfaa
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/networkMonitor.md
@@ -0,0 +1,44 @@
+# Network Monitor (`networkMonitor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / monitoring |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | sub-node of `androidTool`; also connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Report network connectivity state (online / offline), connection type
+(wifi / cellular / ethernet), and internet availability.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[networkMonitor]` | `network` |
+| Default action | `status` |
+
+## Parameters
+
+Shared parameter set only. See [`_pattern.md`](./_pattern.md#shared-parameter-set).
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'network']
+ B --> C[POST /api/network {action, parameters}]
+ C --> D[Flatten data: network_type, connected, internet_available]
+```
+
+## Edge cases & known limits
+
+- Same shared edge cases as [`_pattern.md`](./_pattern.md#known-inconsistencies--edge-cases).
+
+## Related
+
+- Shared pattern: [`_pattern.md`](./_pattern.md)
+- Sibling monitors: [`batteryMonitor`](./batteryMonitor.md), [`systemInfo`](./systemInfo.md), [`location`](./location.md)
diff --git a/docs-internal/node-logic-flows/android/screenControlAutomation.md b/docs-internal/node-logic-flows/android/screenControlAutomation.md
new file mode 100644
index 00000000..07d356e2
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/screenControlAutomation.md
@@ -0,0 +1,54 @@
+# Screen Control (`screenControlAutomation`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / automation |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/screen-control-skill/SKILL.md`](../../../server/skills/android_agent/screen-control-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Screen-focused subset of device state: brightness adjustment, wake screen,
+auto-brightness toggle, screen timeout.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[screenControlAutomation]` | `screen_control` |
+| Default action | `status` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'screen_control']
+ B --> C{action}
+ C -- status --> D[POST /api/screen_control]
+ C -- set_brightness --> D
+ C -- wake --> D
+ C -- auto_brightness --> D
+ C -- set_timeout --> D
+ D --> E[Flatten data: brightness, auto_brightness, timeout]
+```
+
+## Edge cases & known limits
+
+- Frontend hidden `service_id` is `screen_control_automation`; handler
+ rewrites to `screen_control` via `SERVICE_ID_MAP`. See
+ [`_pattern.md`](./_pattern.md#known-inconsistencies--edge-cases) item 1.
+- Brightness value range is device-dependent (0-255 on AOSP).
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`screen-control-skill/SKILL.md`](../../../server/skills/android_agent/screen-control-skill/SKILL.md)
+- Sibling: [`deviceStateAutomation`](./deviceStateAutomation.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/systemInfo.md b/docs-internal/node-logic-flows/android/systemInfo.md
new file mode 100644
index 00000000..c4d7c681
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/systemInfo.md
@@ -0,0 +1,43 @@
+# System Info (`systemInfo`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / monitoring |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+Device and OS metadata: Android version, API level, manufacturer, model,
+memory, storage, build fingerprint.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[systemInfo]` | `system_info` |
+| Default action | `info` |
+
+## Parameters
+
+Shared parameter set only. See [`_pattern.md`](./_pattern.md#shared-parameter-set).
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'system_info']
+ B --> C[POST /api/system_info]
+ C --> D[Flatten data: android_version, api_level,<br/>manufacturer, model, memory, storage]
+```
+
+## Edge cases & known limits
+
+- Shared edge cases only.
+
+## Related
+
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/android/wifiAutomation.md b/docs-internal/node-logic-flows/android/wifiAutomation.md
new file mode 100644
index 00000000..22586a27
--- /dev/null
+++ b/docs-internal/node-logic-flows/android/wifiAutomation.md
@@ -0,0 +1,55 @@
+# WiFi Automation (`wifiAutomation`)
+
+| Field | Value |
+|------|-------|
+| **Category** | android / automation |
+| **Frontend definition** | [`client/src/nodeDefinitions/androidServiceNodes.ts`](../../../client/src/nodeDefinitions/androidServiceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/android.py::handle_android_service`](../../../server/services/handlers/android.py) (shared) |
+| **Tests** | [`server/tests/nodes/test_android.py`](../../../server/tests/nodes/test_android.py) |
+| **Skill (if any)** | [`server/skills/android_agent/wifi-skill/SKILL.md`](../../../server/skills/android_agent/wifi-skill/SKILL.md) |
+| **Dual-purpose tool** | sub-node of `androidTool`; connectable directly to any agent's `input-tools` |
+
+## Purpose
+
+WiFi state control and scanning: enable, disable, get status, scan for
+networks.
+
+## Backend service mapping
+
+| Field | Value |
+|------|-------|
+| `SERVICE_ID_MAP[wifiAutomation]` | `wifi_automation` |
+| Default action | `status` |
+
+## Parameters
+
+Shared parameter set only.
+
+## Logic Flow (node-specific slice)
+
+```mermaid
+flowchart TD
+ A[Dispatch] --> B[service_id = 'wifi_automation']
+ B --> C{action}
+ C -- status --> D1[POST /api/wifi_automation {action: status}]
+ C -- enable --> D2[POST /api/wifi_automation {action: enable}]
+ C -- disable --> D3[POST /api/wifi_automation {action: disable}]
+ C -- scan --> D4[POST /api/wifi_automation {action: scan}]
+ D1 --> E[Flatten data]
+ D2 --> E
+ D3 --> E
+ D4 --> E
+```
+
+## Edge cases & known limits
+
+- Recent Android versions restrict programmatic WiFi state changes; the
+ service-side action may silently no-op on Android 10+ unless a system
+ signature app is used.
+- Shared edge cases only otherwise.
+
+## Related
+
+- Skill: [`wifi-skill/SKILL.md`](../../../server/skills/android_agent/wifi-skill/SKILL.md)
+- Siblings: [`bluetoothAutomation`](./bluetoothAutomation.md), [`airplaneModeControl`](./airplaneModeControl.md)
+- Shared pattern: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/chat_utility/chatHistory.md b/docs-internal/node-logic-flows/chat_utility/chatHistory.md
new file mode 100644
index 00000000..16a09ab0
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/chatHistory.md
@@ -0,0 +1,105 @@
+# Chat History (`chatHistory`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility |
+| **Frontend definition** | [`client/src/nodeDefinitions/chatNodes.ts`](../../../client/src/nodeDefinitions/chatNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_chat_history`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Retrieves chat history from an external chat backend via the JSON-RPC 2.0
+WebSocket `services.chat_client.get_chat_history`. Complements `chatSend` for
+workflows that need to read a conversation from a remote chat host.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream payload; template variables can populate params |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `host` | string | `localhost` | no | - | Chat backend host |
+| `port` | number | `8080` | no | - | Chat backend port |
+| `session_id` | string | `default` | no | - | Chat session identifier |
+| `api_key` | string | `""` | no | - | Auth token forwarded to the chat backend |
+| `limit` | number | `50` | no | - | Maximum messages to return |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `{ messages: Array<ChatMessage> }` |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ messages: Array<{
+ role: string; // e.g. "user" | "assistant"
+ message: string; // body
+ created_at: string;
+ [key: string]: unknown;
+ }>;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params] --> B[Call services.chat_client.get_chat_history]
+ B -- JSON-RPC error --> E[Return error envelope]
+ B -- RPC ok --> F{result.success?}
+ F -- false --> E
+ F -- true --> G[Wrap result.messages into envelope]
+```
+
+## Decision Logic
+
+- **Validation**: none; no parameter is required.
+- **Branches**: success vs error branch on RPC response `success` flag.
+- **Fallbacks**: `host`/`port`/`session_id`/`api_key`/`limit` all have defaults.
+- **Error paths**: every exception logged via `logger.error` and returned as
+ `{success: false, error: str(e)}`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: JSON-RPC 2.0 WebSocket to `ws://<host>:<port>` via
+ `services.chat_client.get_chat_history`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: optional `api_key` parameter, not looked up via
+ `auth_service`.
+- **Services**: external chat backend speaking the project chat JSON-RPC
+ protocol.
+- **Python packages**: `websockets` (via `services.chat_client`).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Any exception from `get_chat_history` is swallowed and surfaced as
+ `success=false`. No retry.
+- `port` and `limit` are coerced via `int()`; non-numeric strings raise
+ `ValueError` and surface as `success=false`.
+- The handler returns `{"messages": ...}` using `result.get('messages', [])`
+ from the RPC. If the chat backend returns messages nested under another key,
+ they will be dropped silently (returned as empty list).
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Other nodes that consume this output**: any node templating
+ `{{chatHistory.messages}}`.
+- **Architecture docs**: [`docs-internal/status_broadcaster.md`](../../status_broadcaster.md).
diff --git a/docs-internal/node-logic-flows/chat_utility/chatSend.md b/docs-internal/node-logic-flows/chat_utility/chatSend.md
new file mode 100644
index 00000000..12e25c59
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/chatSend.md
@@ -0,0 +1,114 @@
+# Chat Send (`chatSend`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility |
+| **Frontend definition** | [`client/src/nodeDefinitions/chatNodes.ts`](../../../client/src/nodeDefinitions/chatNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_chat_send`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Sends a single chat message to an external chat backend via the JSON-RPC 2.0
+WebSocket `services.chat_client.send_chat_message`. Used in workflows that need
+to forward agent output into a chat room, customer-support channel, or any
+external service that speaks the project's chat JSON-RPC protocol. Unlike the
+`chatTrigger` node (which receives messages from the built-in Console Panel
+chat), `chatSend` pushes into a remote chat host.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream payload used via template variables in `content` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `host` | string | `localhost` | no | - | Chat backend host |
+| `port` | number | `8080` | no | - | Chat backend port |
+| `session_id` | string | `default` | no | - | Chat session identifier |
+| `api_key` | string | `""` | no | - | Auth token forwarded to the chat backend |
+| `content` | string | `""` | yes | - | Message body |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | The `result` payload returned by the chat backend |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ // Pass-through of whatever the chat backend's send_message RPC returned,
+ // e.g. { message_id: string, timestamp: string, ... }
+ [key: string]: unknown;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params] --> B{content non-empty?}
+ B -- no --> E[Return error envelope: content required]
+ B -- yes --> C[Call services.chat_client.send_chat_message]
+ C -- JSON-RPC error --> E
+ C -- RPC ok --> F{result.success?}
+ F -- false --> E
+ F -- true --> G[Return success envelope with result.result]
+```
+
+## Decision Logic
+
+- **Validation**: empty `content` raises `ValueError("Message content is required")`
+ which is caught and returned as `success=false`.
+- **Branches**: success vs error branch on RPC response `success` flag.
+- **Fallbacks**: `host`/`port`/`session_id` default to `localhost:8080/default`,
+ `api_key` defaults to empty string.
+- **Error paths**: every exception is logged via `logger.error` and returned as
+ `{success: false, error: str(e)}` with `node_id`, `node_type`, timing fields.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none from this handler (the chat backend may broadcast on its
+ side but that is external to MachinaOs).
+- **External API calls**: JSON-RPC 2.0 WebSocket to `ws://<host>:<port>` via
+ `services.chat_client.send_chat_message`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: optional `api_key` parameter forwarded as the chat backend's
+ auth token. No lookup via `auth_service`.
+- **Services**: external chat backend speaking the project chat JSON-RPC
+ protocol (e.g. the chat mircoservice in `docs-internal/chat-service.md`).
+- **Python packages**: `websockets` (via `services.chat_client`).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Any exception from `send_chat_message` (connection refused, timeout, malformed
+ RPC response) is swallowed and surfaced as `success=false` with the stringified
+ error. No retry is performed.
+- `port` is coerced via `int(parameters.get('port', 8080))`; a non-numeric port
+ raises `ValueError` and is returned as `success=false`.
+- Templates in `content` (e.g. `{{aiAgent.response}}`) are resolved upstream by
+ `ParameterResolver`; this handler never sees unresolved `{{...}}`.
+- `session_id` here is the chat-backend session, not the MachinaOs workflow
+ `session_id` from `context`. They are unrelated.
+
+## Related
+
+- **Skills using this as a tool**: none (not a dual-purpose tool).
+- **Other nodes that consume this output**: any downstream node can consume the
+ RPC response via `{{chatSend.message_id}}` etc.
+- **Architecture docs**: [`docs-internal/status_broadcaster.md`](../../status_broadcaster.md)
+ (for comparison with WebSocket-first in-app chat), this node bypasses the
+ in-app WebSocket entirely.
diff --git a/docs-internal/node-logic-flows/chat_utility/console.md b/docs-internal/node-logic-flows/chat_utility/console.md
new file mode 100644
index 00000000..22527494
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/console.md
@@ -0,0 +1,142 @@
+# Console (`console`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility |
+| **Frontend definition** | [`client/src/nodeDefinitions/utilityNodes.ts`](../../../client/src/nodeDefinitions/utilityNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_console`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Debug/inspection node that logs the output of connected upstream nodes to the
+Console tab in the frontend Console Panel and to the backend logger. Mirrors
+n8n's "Debug / Log" node. Supports whole-object logging, single field
+extraction (dot-path with `field[index]`), or pre-resolved template expression
+logging. Passes the merged input through to downstream nodes so it can be
+spliced into a pipeline without breaking data flow.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Any number of upstream outputs merged into `input_data` |
+
+`console` is dispatched via `NodeExecutor._dispatch`'s special-handlers branch,
+which resolves upstream outputs via `_get_connected_outputs_with_info` and
+passes `connected_outputs` (keyed by source node type) and `source_nodes`
+(ids/types/labels of source nodes) to the handler.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `label` | string | `""` | no | - | Display label for this console entry |
+| `logMode` | string | `all` | no | - | `all`, `field`, or `expression` |
+| `format` | string | `json` | no | - | `json`, `json_compact`, `text`, or `table` |
+| `fieldPath` | string | `""` | no | `logMode=field` | Dot path like `data.items[0].name` |
+| `expression` | string | `""` | no | `logMode=expression` | Pre-resolved template output |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `{label, logged_at, format, data, formatted, ...input_data}` |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ label: string; // user label or "Console (<nodeid[:8]>)"
+ logged_at: string; // ISO timestamp
+ format: string; // format parameter (json/text/table/json_compact)
+ data: unknown; // the logged value (respects logMode)
+ formatted: string; // stringified representation for display
+ // plus every key from the merged upstream input so downstream nodes
+ // can keep templating against the upstream shape
+ [key: string]: unknown;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params + connected_outputs + source_nodes] --> B[Merge upstream dicts into input_data]
+ B --> C{logMode}
+ C -- all --> D[log_value = input_data]
+ C -- field --> E{fieldPath has curly braces OR key exists?}
+ E -- resolved template --> F[log_value = fieldPath as-is]
+ E -- literal path --> G[log_value = _navigate_field_path]
+ C -- expression --> H[log_value = expression or input_data]
+ C -- unknown --> D
+ D --> I[_format_console_output]
+ F --> I
+ G --> I
+ H --> I
+ I --> J[broadcast_console_log via StatusBroadcaster]
+ J --> K[Return envelope with log_value + input_data pass-through]
+```
+
+## Decision Logic
+
+- **Validation**: none; all parameters optional.
+- **Branches**:
+ - `logMode=all` - logs the full merged `input_data`.
+ - `logMode=field` + `fieldPath` without `{{` and not a key in `input_data` ->
+ treat `fieldPath` as a pre-resolved template value.
+ - `logMode=field` + valid literal path -> `_navigate_field_path` returns
+ nested value or `None` on mismatch.
+ - `logMode=expression` -> use resolved `expression` or fall back to
+ `input_data` when empty.
+ - Any other `logMode` falls through to `input_data` (via `match _`).
+- **Fallbacks**: non-dict upstream output is wrapped as `{"value": output}` in
+ `input_data`; label defaults to `Console (<first 8 chars of node_id>)`.
+- **Error paths**: top-level try/except returns `success=false` with the
+ stringified exception.
+
+## Side Effects
+
+- **Database writes**: none (console logs are transient; they are NOT persisted
+ via `database.add_console_log` in this handler - persistence happens via the
+ WebSocket broadcast consumer in the frontend/DB layer).
+- **Broadcasts**: `StatusBroadcaster.broadcast_console_log` with
+ `{node_id, label, timestamp, data, formatted, format, workflow_id,
+ source_node_id, source_node_type, source_node_label}`.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `StatusBroadcaster` (`services.status_broadcaster`).
+- **Python packages**: stdlib only (`json`, `re`).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `_navigate_field_path` returns `None` for any missing key or out-of-range
+ index, so `log_value` silently becomes `null` rather than raising.
+- `fieldPath` heuristic: the handler treats a field path as "already a resolved
+ template value" when it has no `{{` AND is not a key in `input_data`. This
+ can misfire if the user's literal path happens not to match a top-level key
+ even though the intent was to navigate.
+- `format=table` falls back to indented JSON for non-tabular data (not a list
+ of dicts).
+- JSON formatting uses `default=str` so non-JSON-serialisable types become
+ string reprs rather than failing.
+- `connected_outputs` is keyed by source *node type*, so two upstream nodes of
+ the same type will collide - only the last one processed ends up in
+ `input_data` per key.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Other nodes that consume this output**: any node downstream of the console
+ (pass-through shape matches the upstream input).
+- **Architecture docs**:
+ [`docs-internal/status_broadcaster.md`](../../status_broadcaster.md) -
+ `broadcast_console_log` is one of the broadcast methods defined there.
diff --git a/docs-internal/node-logic-flows/chat_utility/fileHandler.md b/docs-internal/node-logic-flows/chat_utility/fileHandler.md
new file mode 100644
index 00000000..a17bcb93
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/fileHandler.md
@@ -0,0 +1,107 @@
+# File Handler (`fileHandler`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility |
+| **Frontend definition** | not exposed in `client/src/nodeDefinitions/` (backend-only registry entry) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_file_handler`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Legacy file-shape wrapper retained from the Node.js-era engine. Does NOT touch
+the filesystem - it only composes a descriptive dict (`fileName`, `fileType`,
+`content`, `size`) around an already-in-memory string. For real filesystem
+access use the `fileRead`, `fileModify`, `fsSearch`, and `fileDownloader`
+nodes in the `code_fs_process` and `document` categories.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream text/JSON used via templates |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `fileType` | string | `generic` | no | - | Arbitrary tag stored in output |
+| `content` | string | `""` | no | - | In-memory file contents |
+| `fileName` | string | `untitled.txt` | no | - | Display file name |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `{ type: "file", data: {...}, nodeId, timestamp }` |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ type: "file";
+ data: {
+ fileName: string;
+ fileType: string;
+ content: string;
+ size: number; // len(content), bytes-of-str length
+ processed: true;
+ processingType: string; // === fileType
+ nodeId: string;
+ };
+ nodeId: string;
+ timestamp: string;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params] --> B[TextService.execute_file_handler]
+ B --> C[Compose result_data]
+ C --> D[Return success envelope]
+ B -- exception --> E[Return error envelope]
+```
+
+## Decision Logic
+
+- **Validation**: none.
+- **Branches**: none; the handler is effectively a pure data-shape wrapper.
+- **Fallbacks**: all three params have defaults.
+- **Error paths**: any exception inside `TextService.execute_file_handler` is
+ caught and returned as `success=false`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none (despite the name).
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `TextService` injected via `functools.partial` in
+ `NodeExecutor._build_handler_registry`.
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `processed` is hard-coded to `true` regardless of input.
+- `processingType` duplicates `fileType`; there is no actual processing logic.
+- `size` is `len(content)` on the string (character count, not byte count of
+ an encoded representation).
+- Not a real filesystem node; misleading name retained for backward
+ compatibility with older workflow JSON.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Other nodes that consume this output**: any templating downstream.
+- **Architecture docs**: see `docs-internal/node-logic-flows/code_fs_process/`
+ for the real filesystem nodes (`fileRead`, `fileModify`, `fsSearch`).
diff --git a/docs-internal/node-logic-flows/chat_utility/gmaps_create.md b/docs-internal/node-logic-flows/chat_utility/gmaps_create.md
new file mode 100644
index 00000000..b9923865
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/gmaps_create.md
@@ -0,0 +1,116 @@
+# Create Map (`gmaps_create`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility (grouping) / location (functional domain) |
+| **Frontend definition** | [`client/src/nodeDefinitions/locationNodes.ts`](../../../client/src/nodeDefinitions/locationNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_create_map`](../../../server/services/handlers/utility.py) -> [`server/services/maps.py::MapsService.create_map`](../../../server/services/maps.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no (display-only; `gmaps_locations` and `gmaps_nearby_places` are the dual-purpose pair) |
+
+## Purpose
+
+Builds a Google Maps configuration (center, zoom, map type) and a Static Maps
+URL for display on the canvas or downstream consumers. The node does NOT hit
+the Maps API - it assembles the URL from parameters and tracks a
+`static_map` usage cost of $0.002 per execution.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream lat/lng via templates |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `api_key` | string | - | yes (auto-injected) | - | Google Maps API key; auto-injected from `auth_service.get_api_key('google_maps')` or `settings.google_maps_api_key` |
+| `lat` | number | `40.7128` | no | - | Latitude, -90 .. 90 |
+| `lng` | number | `-74.0060` | no | - | Longitude, -180 .. 180 |
+| `zoom` | number | `13` | no | - | Zoom level, 0 .. 21 |
+| `map_type_id` | string | `ROADMAP` | no | - | One of `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Map config + static URL |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ map_config: {
+ center: { lat: number; lng: number };
+ zoom: number;
+ mapTypeId: "ROADMAP" | "SATELLITE" | "HYBRID" | "TERRAIN";
+ };
+ static_map_url: string; // https://maps.googleapis.com/maps/api/staticmap?...
+ status: "OK";
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params] --> B{api_key present?}
+ B -- no --> E[Return error: Google Maps API key is required]
+ B -- yes --> C[Validate lat/lng, zoom, map_type]
+ C -- invalid --> E
+ C -- ok --> D[Compose map_config + static_map_url]
+ D --> F[_track_maps_usage: static_map, 1]
+ F --> G[Return success envelope]
+```
+
+## Decision Logic
+
+- **Validation**:
+ - `api_key` required (from params, else `settings.google_maps_api_key`).
+ - `lat`/`lng` validated via `validate_coordinates`.
+ - `zoom` validated via `validate_zoom_level` (0-21).
+ - `map_type` restricted to the four Google Maps MapTypeId values.
+- **Branches**: success envelope vs error envelope.
+- **Fallbacks**: defaults centre the map on New York City.
+- **Error paths**: any raised `ValueError` bubbles into the generic
+ `except Exception` and returns `success=false`.
+
+## Side Effects
+
+- **Database writes**: `api_usage_metrics` row via `_track_maps_usage` with
+ `operation=static_map`, `resource_count=1`, `total_cost=0.002`.
+- **Broadcasts**: none.
+- **External API calls**: none. The URL is assembled locally and meant to be
+ fetched by the frontend or downstream `httpRequest` node.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: Google Maps API key via `auth_service.get_api_key('google_maps')`
+ or `settings.google_maps_api_key` (env `GOOGLE_MAPS_API_KEY`).
+- **Services**: `MapsService` injected via `functools.partial` in
+ `NodeExecutor._build_handler_registry`.
+- **Python packages**: stdlib only for this path (googlemaps is used by other
+ map handlers, not this one).
+- **Environment variables**: `GOOGLE_MAPS_API_KEY` (fallback).
+
+## Edge cases & known limits
+
+- The static map URL embeds the API key in plain text - any downstream node or
+ log that captures the output leaks the key. Treat the output as sensitive.
+- Size is hard-coded to `600x400`; there is no parameter to override.
+- `map_type` comparison is case-sensitive; `roadmap` (lowercase) is rejected as
+ invalid even though Google Maps accepts it.
+- Cost tracking is optimistic: the $0.002 is charged even if the frontend
+ never actually fetches the static map URL.
+
+## Related
+
+- **Skills using this as a tool**: none (display-only node).
+- **Other nodes that consume this output**: downstream map-display components
+ on the frontend, or `httpRequest` for server-side image fetch.
+- **Architecture docs**: [`docs-internal/pricing_service.md`](../../pricing_service.md)
+ for API cost tracking.
diff --git a/docs-internal/node-logic-flows/chat_utility/teamMonitor.md b/docs-internal/node-logic-flows/chat_utility/teamMonitor.md
new file mode 100644
index 00000000..89521c44
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/teamMonitor.md
@@ -0,0 +1,118 @@
+# Team Monitor (`teamMonitor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility |
+| **Frontend definition** | [`client/src/nodeDefinitions/utilityNodes.ts`](../../../client/src/nodeDefinitions/utilityNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_team_monitor`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Real-time monitoring window for Agent Team operations. Connects to the output
+of an AI Employee or Orchestrator node and surfaces the team's members, task
+counters, active tasks, and recent events for display. See
+[`docs-internal/agent_teams.md`](../../agent_teams.md) for the overall teams
+architecture.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | yes (for non-empty output) | Upstream team-lead node whose output carries `team_id` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `maxHistoryItems` | number | `50` | no | - | Cap on `recent_events` slice length |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Team status snapshot (see shape) |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ team_id: string | null;
+ members: Array<unknown>;
+ tasks: {
+ total: number;
+ completed: number;
+ active: number;
+ pending: number;
+ failed: number;
+ };
+ active_tasks: Array<unknown>;
+ recent_events: Array<unknown>;
+ // When no team_id is resolved:
+ message?: "No team connected";
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params + context] --> B{team_id in context?}
+ B -- yes --> E[team_service.get_team_status]
+ B -- no --> C[Scan context.outputs for dict with team_id]
+ C -- found --> E
+ C -- not found --> D[Return empty envelope with message=No team connected]
+ E --> F[Slice recent_events by maxHistoryItems]
+ F --> G[Return envelope with counters + lists]
+```
+
+## Decision Logic
+
+- **Validation**: none.
+- **Branches**:
+ - `team_id` resolved via `context['team_id']` first, else the first connected
+ output that is a dict containing `team_id`.
+ - When no `team_id` is found, returns an intentional success envelope with
+ zero counters - the node does not error.
+- **Fallbacks**: counters default to 0 for any missing key; `members`,
+ `active_tasks`, `recent_events` default to empty lists.
+- **Error paths**: any exception from `team_service.get_team_status` is caught
+ and returned as `success=false` with the stringified error.
+
+## Side Effects
+
+- **Database writes**: none (the service reads `agent_teams`, `team_members`,
+ `team_tasks`, `agent_messages` tables behind `get_team_status`, but this
+ handler only reads the returned status dict).
+- **Broadcasts**: none from this handler.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `AgentTeamService` via
+ `services.agent_team.get_agent_team_service()`.
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `maxHistoryItems` is used as a negative slice (`[-max:]`); passing a
+ non-integer triggers a `TypeError` which surfaces as `success=false`.
+- The "find team_id in outputs" loop stops at the first dict it sees containing
+ a truthy `team_id`; if two upstream outputs carry different team ids, behaviour
+ is order-dependent.
+- When the team disappears mid-run (`get_team_status` raises `TeamNotFound` or
+ similar) the envelope is `success=false` - the monitor does not gracefully
+ degrade.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Other nodes that consume this output**: downstream nodes can template on
+ `{{teamMonitor.tasks.total}}`, `{{teamMonitor.active_tasks}}` etc.
+- **Architecture docs**: [`docs-internal/agent_teams.md`](../../agent_teams.md).
diff --git a/docs-internal/node-logic-flows/chat_utility/textGenerator.md b/docs-internal/node-logic-flows/chat_utility/textGenerator.md
new file mode 100644
index 00000000..c032ee35
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/textGenerator.md
@@ -0,0 +1,105 @@
+# Text Generator (`textGenerator`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility |
+| **Frontend definition** | not exposed in `client/src/nodeDefinitions/` (backend-only registry entry) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_text_generator`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_chat_utility.py`](../../../server/tests/nodes/test_chat_utility.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Trivial text factory node retained from the original Node.js-era workflow
+engine. Emits a text string and its length (optionally with a timestamp). Used
+by legacy workflows and as a scaffolding node during tests. Not surfaced in the
+current React component palette but still reachable through the backend
+registry.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream value usable via templates in `text` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `text` | string | `Hello World` | no | - | Text payload to emit |
+| `includeTimestamp` | boolean | `true` | no | - | Include ISO timestamp in `data` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Wrapper containing `data` with the generated text |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ type: "text";
+ data: {
+ text: string;
+ length: number;
+ nodeId: string;
+ timestamp?: string; // only when includeTimestamp=true
+ };
+ nodeId: string;
+ timestamp: string;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[Receive params] --> B[TextService.execute_text_generator]
+ B --> C[Compose data with text/length/nodeId]
+ C --> D{includeTimestamp?}
+ D -- yes --> E[Attach isoformat timestamp]
+ D -- no --> F[Skip timestamp]
+ E --> G[Return success envelope]
+ F --> G
+```
+
+## Decision Logic
+
+- **Validation**: none; both params have defaults.
+- **Branches**: `includeTimestamp` toggles the nested timestamp.
+- **Fallbacks**: `text` defaults to `Hello World`.
+- **Error paths**: any exception inside `TextService.execute_text_generator`
+ is caught there and returned as `success=false`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `TextService` injected via `functools.partial` in
+ `NodeExecutor._build_handler_registry`.
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `length` is the Python `len(text)` which counts characters (not bytes), so
+ non-ASCII strings report their Unicode code-point count.
+- There is no upper bound on `text` length; the entire payload is stored in
+ the output store and broadcast to every WS client subscribed to the
+ execution run.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Other nodes that consume this output**: any downstream node that
+ templates `{{textGenerator.data.text}}`.
+- **Architecture docs**: none.
diff --git a/docs-internal/node-logic-flows/code_fs_process/fileModify.md b/docs-internal/node-logic-flows/code_fs_process/fileModify.md
new file mode 100644
index 00000000..d1489494
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/fileModify.md
@@ -0,0 +1,132 @@
+# File Modify (`fileModify`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / filesystem |
+| **Frontend definition** | [`client/src/nodeDefinitions/filesystemNodes.ts`](../../../client/src/nodeDefinitions/filesystemNodes.ts) |
+| **Backend handler** | [`server/services/handlers/filesystem.py::handle_file_modify`](../../../server/services/handlers/filesystem.py) |
+| **Backend** | [`deepagents.backends.LocalShellBackend`](https://github.com/langchain-ai/deepagents) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/coding_agent/file-modify-skill/SKILL.md`](../../../server/skills/coding_agent/file-modify-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `file_modify` |
+
+## Purpose
+
+Writes a new file or edits an existing one inside the per-workflow workspace.
+Two operations: `write` (create/overwrite) and `edit` (string find-and-replace).
+Delegates to `LocalShellBackend.write()` / `backend.edit()` with
+`virtual_mode=True` sandboxing, invoked through `asyncio.to_thread()`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Not consumed by the handler |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `operation` | options | `write` | no | - | `write` or `edit` |
+| `file_path` | string | `""` | yes | - | Target file path |
+| `content` | string | `""` | yes (when `operation=write`) | `operation=write` | File content |
+| `old_string` | string | `""` | yes (when `operation=edit`) | `operation=edit` | Text to find |
+| `new_string` | string | `""` | no | `operation=edit` | Replacement text |
+| `replace_all` | boolean | `false` | no | `operation=edit` | Replace every occurrence; when `false` the backend insists `old_string` is unique |
+| `working_directory` | string | `""` | no | - | Overrides context workspace |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+Write:
+```ts
+{ operation: "write"; file_path: string }
+```
+
+Edit:
+```ts
+{ operation: "edit"; file_path: string; occurrences: number }
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_file_modify] --> B{file_path empty?}
+ B -- yes --> E[Return error:<br/>file_path is required]
+ B -- no --> C[_get_backend root=workspace]
+ C --> D{operation?}
+ D -- write --> W[to_thread backend.write file_path, content]
+ W --> W1{result.error?}
+ W1 -- yes --> Eenv[Return error result.error]
+ W1 -- no --> Wok[Return success<br/>operation=write, file_path=result.path]
+ D -- edit --> Ei{old_string empty?}
+ Ei -- yes --> Ereq[Return error:<br/>old_string is required for edit]
+ Ei -- no --> Ed[to_thread backend.edit file_path,<br/>old_string, new_string, replace_all]
+ Ed --> Ed1{result.error?}
+ Ed1 -- yes --> Eenv
+ Ed1 -- no --> Edok[Return success<br/>occurrences=result.occurrences]
+ D -- other --> Unk[Return error:<br/>Unknown operation: <op>]
+```
+
+## Decision Logic
+
+- **Validation**:
+ - empty `file_path` -> `"file_path is required"`.
+ - `operation=edit` with empty `old_string` -> `"old_string is required for
+ edit"`.
+ - Anything other than `write` / `edit` -> `"Unknown operation: <op>"`.
+- **Backend-level errors**: both `backend.write()` and `backend.edit()`
+ return a result object with an `error` field. A non-empty `error` short-
+ circuits before the success envelope is built. Common backend errors:
+ non-unique `old_string` when `replace_all=False`, path escape with
+ `virtual_mode=True`.
+- **`operations.edit` uniqueness constraint**: when `replace_all=False`, the
+ backend REQUIRES `old_string` to appear exactly once. Zero or multiple
+ matches trigger a backend-level error.
+- **`file_path` echoed from `result.path`**: on success the returned
+ `file_path` comes from the backend's normalised path, falling back to the
+ user-supplied path only if `result.path` is empty.
+- **Broad `except Exception`**: catches unexpected backend or I/O errors.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**:
+ - `os.makedirs(root, exist_ok=True)` on the workspace root.
+ - Writes/edits `<root>/<file_path>`.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Python packages**: `deepagents`.
+- **Environment variables**: `WORKSPACE_BASE_DIR`.
+
+## Edge cases & known limits
+
+- **Silent overwrite on `write`**: there is no "fail if exists" flag - every
+ `write` call replaces the file.
+- **`edit` without a match**: returns an error envelope (backend surfaces the
+ message). The handler never distinguishes "not found" from "multiple
+ matches" - both are string errors.
+- **No encoding option**: the backend opens files in text mode with the
+ platform default encoding.
+- **`working_directory` escape**: as in `fileRead`, the node trusts the
+ parameter which can bypass the workspace sandbox.
+- **`replace_all=true` with empty `new_string`**: effectively deletes every
+ occurrence of `old_string`. No safeguard.
+- **Atomicity**: the backend does not do atomic writes - a crash mid-write
+ can leave a truncated file.
+
+## Related
+
+- **Skills using this as a tool**: [`file-modify-skill/SKILL.md`](../../../server/skills/coding_agent/file-modify-skill/SKILL.md)
+- **Sibling nodes**: [`fileRead`](./fileRead.md), [`fsSearch`](./fsSearch.md), [`shell`](./shell.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/fileRead.md b/docs-internal/node-logic-flows/code_fs_process/fileRead.md
new file mode 100644
index 00000000..dbe65069
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/fileRead.md
@@ -0,0 +1,122 @@
+# File Read (`fileRead`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / filesystem |
+| **Frontend definition** | [`client/src/nodeDefinitions/filesystemNodes.ts`](../../../client/src/nodeDefinitions/filesystemNodes.ts) |
+| **Backend handler** | [`server/services/handlers/filesystem.py::handle_file_read`](../../../server/services/handlers/filesystem.py) |
+| **Backend** | [`deepagents.backends.LocalShellBackend`](https://github.com/langchain-ai/deepagents) (third-party) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/coding_agent/file-read-skill/SKILL.md`](../../../server/skills/coding_agent/file-read-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `file_read` |
+
+## Purpose
+
+Reads a file within the per-workflow workspace. Delegates to
+`LocalShellBackend.read()` from the `deepagents` package. The backend is
+instantiated with `virtual_mode=True` and a `root_dir` pinned to
+`data/workspaces/<workflow_id>/` (or the node-level `working_directory`
+override), so path traversal outside the workspace is rejected by the
+backend itself.
+
+All calls run inside `asyncio.to_thread()` because the underlying backend
+APIs are synchronous file I/O.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Not consumed by the handler |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `file_path` | string | `""` | yes | - | File path relative to the workspace root |
+| `offset` | number | `0` | no | - | 0-indexed starting line |
+| `limit` | number | `100` | no | - | Max lines to read (1-10000 in UI) |
+| `working_directory` | string | `""` | no | - | Overrides the context workspace; resolved before backend creation |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+{
+ content: string; // File content returned by LocalShellBackend.read()
+ file_path: string; // Echo of the requested path
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_file_read] --> B{file_path empty?}
+ B -- yes --> E[Return error:<br/>file_path is required]
+ B -- no --> C[_get_backend:<br/>root = param.working_directory OR<br/>context.workspace_dir OR<br/>Settings().workspace_base_resolved/default]
+ C --> D[os.makedirs root, exist_ok=True]
+ D --> F[LocalShellBackend root_dir=root, virtual_mode=True]
+ F --> G[to_thread backend.read file_path, offset, limit]
+ G -- exception --> H[Return error envelope str e]
+ G -- ok --> I[Return success envelope<br/>content, file_path]
+```
+
+## Decision Logic
+
+- **Validation**: empty `file_path` -> `"file_path is required"` error.
+- **Workspace resolution precedence**: node param `working_directory` >
+ `context["workspace_dir"]` > `Settings().workspace_base_resolved/default`.
+- **Directory creation**: the resolved root is `os.makedirs(... exist_ok=True)`
+ BEFORE the backend is built, so read against a fresh workflow works.
+- **`virtual_mode=True`**: the backend rejects absolute paths and `..`
+ traversal that escape the root. Violations raise an exception which is
+ caught by the broad `except` and returned as a string.
+- **Broad `except Exception`**: missing files, permission errors, decoding
+ errors all collapse to the same shape - users must parse the `error` string
+ to distinguish them.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**:
+ - `os.makedirs(root, exist_ok=True)` on the resolved workspace root.
+ - Reads `<root>/<file_path>` via the backend.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none.
+- **Python packages**: `deepagents` (imported lazily inside `_get_backend`),
+ `asyncio`.
+- **Environment variables**: `WORKSPACE_BASE_DIR` (read by `core.config.Settings`).
+
+## Edge cases & known limits
+
+- **Errors are strings, not structured**: "file not found", "permission
+ denied", "path escapes workspace" all return `{success: false, error: <str>}`
+ with no error code.
+- **Binary files**: `LocalShellBackend.read()` decodes as text; a binary file
+ raises a `UnicodeDecodeError` that surfaces as a vague error string.
+- **`offset`/`limit` typed as numbers**: negative offsets are NOT validated by
+ the handler - they are forwarded to the backend which may return an empty
+ string or raise.
+- **`working_directory` can point outside the workspace root**: the handler
+ trusts it, so setting `working_directory="/"` effectively disables the
+ `virtual_mode` sandbox. Dangerous when the node is exposed as an AI tool.
+- **No line-count cap**: `limit` default is 100 but the UI allows up to
+ 10000; very large files with `limit=10000` block the thread longer.
+
+## Related
+
+- **Skills using this as a tool**: [`file-read-skill/SKILL.md`](../../../server/skills/coding_agent/file-read-skill/SKILL.md)
+- **Sibling nodes**: [`fileModify`](./fileModify.md), [`fsSearch`](./fsSearch.md), [`shell`](./shell.md)
+- **Architecture docs**: [DESIGN.md](../../DESIGN.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/fsSearch.md b/docs-internal/node-logic-flows/code_fs_process/fsSearch.md
new file mode 100644
index 00000000..8eae3700
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/fsSearch.md
@@ -0,0 +1,129 @@
+# FS Search (`fsSearch`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / filesystem |
+| **Frontend definition** | [`client/src/nodeDefinitions/filesystemNodes.ts`](../../../client/src/nodeDefinitions/filesystemNodes.ts) |
+| **Backend handler** | [`server/services/handlers/filesystem.py::handle_fs_search`](../../../server/services/handlers/filesystem.py) |
+| **Backend** | [`deepagents.backends.LocalShellBackend`](https://github.com/langchain-ai/deepagents) (`ls_info`, `glob_info`, `grep_raw`) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/coding_agent/fs-search-skill/SKILL.md`](../../../server/skills/coding_agent/fs-search-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `fs_search` |
+
+## Purpose
+
+Three-mode filesystem query node confined to the per-workflow workspace.
+Dispatches to `ls_info()`, `glob_info()`, or `grep_raw()` on
+`LocalShellBackend` (`virtual_mode=True`) depending on `mode`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Not consumed |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `mode` | options | `ls` | no | - | `ls`, `glob`, or `grep` |
+| `path` | string | `.` | no | - | Directory path to search in (workspace-relative) |
+| `pattern` | string | `""` | yes (when `mode != ls`) | `mode=glob`, `mode=grep` | Glob pattern or grep regex |
+| `file_filter` | string | `""` | no | `mode=grep` | Glob pattern restricting which files are searched |
+| `working_directory` | string | `""` | no | - | Overrides context workspace |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+// ls
+{ path: string; entries: Array<FileInfo>; count: number }
+// glob
+{ path: string; pattern: string; matches: Array<FileInfo>; count: number }
+// grep
+{ path: string; pattern: string; matches: Array<GrepMatch>; count: number }
+```
+
+`FileInfo` and `GrepMatch` are the dataclass shapes returned by the
+`deepagents` backend, converted via `dict(entry)`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_fs_search] --> C[_get_backend virtual_mode=True]
+ C --> D{mode?}
+ D -- ls --> L[to_thread backend.ls_info path]
+ L --> Lok[Return success entries, count]
+ D -- glob --> G{pattern empty?}
+ G -- yes --> Gp[Return error:<br/>pattern is required for glob mode]
+ G -- no --> Gr[to_thread backend.glob_info pattern, path]
+ Gr --> Grok[Return success matches, count]
+ D -- grep --> Gg{pattern empty?}
+ Gg -- yes --> Ggp[Return error:<br/>pattern is required for grep mode]
+ Gg -- no --> Gx[to_thread backend.grep_raw pattern, path, glob=file_filter]
+ Gx --> Gxt{result type?}
+ Gxt -- str error --> Gxerr[Return error<br/>error=result]
+ Gxt -- list --> Gxok[Return success matches, count]
+ D -- other --> U[Return error:<br/>Unknown mode: <mode>]
+```
+
+## Decision Logic
+
+- **`mode=ls`** requires nothing; defaults `path='.'`.
+- **`mode=glob`** requires `pattern`. Missing pattern -> error envelope.
+- **`mode=grep`** requires `pattern`. Optional `file_filter` is forwarded as
+ the backend's `glob` kwarg.
+- **`grep_raw` polymorphic return**: the backend returns either a list of
+ `GrepMatch` objects (success) OR a plain string (error description). The
+ handler checks `isinstance(result, str)` and turns a string into an error
+ envelope verbatim. This is the only place error details flow through as a
+ direct backend string rather than the generic `str(Exception)` path.
+- **`file_filter` empty-string handling**: `file_filter or None` -> empty
+ string is coerced to `None` before forwarding.
+- **Unknown modes**: returns error envelope `"Unknown mode: <mode>"`.
+- **Broad `except Exception`**: catches backend-level surprises.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**:
+ - `os.makedirs(root, exist_ok=True)` on the workspace root.
+ - Reads directory listings and file contents under `<root>/<path>`.
+- **Subprocess**: none (`grep_raw` is a Python regex walk in recent
+ `deepagents`; not a `grep(1)` exec).
+
+## External Dependencies
+
+- **Python packages**: `deepagents`.
+- **Environment variables**: `WORKSPACE_BASE_DIR`.
+
+## Edge cases & known limits
+
+- **`grep_raw` string-error path is unique**: unlike ls/glob which raise,
+ grep can "succeed" at the Python level but return a string. Frontends
+ expecting a consistent error shape across modes may miss this.
+- **Glob patterns match the backend's semantics**: `**` globs work, but
+ the backend's behaviour for symlinks, hidden files, and case sensitivity
+ is inherited from `pathlib`.
+- **No maxResults cap**: a `**/*` glob over a huge workspace returns every
+ match; the handler does not paginate. The caller must truncate.
+- **`path='.'` resolves against the workspace root, not the server CWD**.
+- **`working_directory` escape**: same caveat as other filesystem nodes -
+ a caller can bypass the sandbox.
+- **Dataclass `dict()` conversion**: relies on `FileInfo` / `GrepMatch`
+ being dataclasses (they implement `__iter__` via dataclass). A future
+ backend upgrade that returns `TypedDict`s could break this.
+
+## Related
+
+- **Skills using this as a tool**: [`fs-search-skill/SKILL.md`](../../../server/skills/coding_agent/fs-search-skill/SKILL.md)
+- **Sibling nodes**: [`fileRead`](./fileRead.md), [`fileModify`](./fileModify.md), [`shell`](./shell.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md b/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md
new file mode 100644
index 00000000..bfbef25d
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/javascriptExecutor.md
@@ -0,0 +1,151 @@
+# JavaScript Executor (`javascriptExecutor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / code |
+| **Frontend definition** | [`client/src/nodeDefinitions/codeNodes.ts`](../../../client/src/nodeDefinitions/codeNodes.ts) |
+| **Backend handler** | [`server/services/handlers/code.py::handle_javascript_executor`](../../../server/services/handlers/code.py) |
+| **Node.js client** | [`server/services/nodejs_client.py::NodeJSClient`](../../../server/services/nodejs_client.py) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/coding_agent/javascript-skill/SKILL.md`](../../../server/skills/coding_agent/javascript-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `javascript_code` |
+
+## Purpose
+
+Runs user JavaScript through the persistent Node.js executor server (Express +
+tsx) that the Python backend spawns on startup. The handler does **not** spawn
+`node` per call - it POSTs the code to `http://localhost:3020/execute` via an
+async `aiohttp` client. The Node.js server evaluates the script inside a VM
+sandbox and returns `{success, output, console_output, execution_time_ms}`.
+
+The handler merges the caller's upstream outputs into an `input_data` object,
+injects the workflow's `workspace_dir` as a key, then forwards the payload.
+
+Dispatched through the special-handlers branch at
+[`node_executor.py:367-381`](../../../server/services/node_executor.py) so it
+receives `connected_outputs`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream outputs merged into the Node-side `input_data` object |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `code` | string (code editor) | (boilerplate stub) | yes | - | JavaScript source. User must assign to `output` |
+| `timeout` | number | `30` | no | - | Seconds - multiplied by 1000 and forwarded as millisecond timeout to the Node server |
+
+## Handler-level kwargs (bound via partial at registry setup)
+
+| Name | Default | Description |
+|------|---------|-------------|
+| `nodejs_url` | `http://localhost:3020` | Overridable via `NODEJS_EXECUTOR_URL` at container wiring |
+| `nodejs_timeout` | `30` | Seconds; overridable via `NODEJS_EXECUTOR_TIMEOUT` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+{
+ output: any; // Value the Node.js server parsed from `output` in the script
+ console_output: string; // Captured console.log/.error etc.
+ timestamp: string; // ISO8601
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_javascript_executor] --> B{code strip empty?}
+ B -- yes --> E[Return error envelope:<br/>No code provided]
+ B -- no --> C[timeout_ms = int timeout * 1000]
+ C --> D[input_data = connected_outputs or {}<br/>inject workspace_dir]
+ D --> F[get_nodejs_client<br/>lazy singleton]
+ F --> G[client.execute<br/>POST /execute<br/>language=javascript]
+ G -- exception --> H[Return error envelope<br/>error=str e]
+ G -- ok + success=true --> I[Return success envelope<br/>output + console_output]
+ G -- ok + success=false --> J[Return error envelope<br/>preserve console_output]
+```
+
+## Decision Logic
+
+- **Validation**: `code.strip() == ""` -> immediate error envelope
+ `"No code provided"`.
+- **Timeout unit mismatch**: UI accepts seconds, handler multiplies by 1000
+ before forwarding. Default 30 -> 30000 ms. No upper cap enforced in Python.
+- **`workspace_dir` injection**: unconditionally sets
+ `input_data["workspace_dir"]`, shadowing any upstream node that happened to
+ produce a key with that name.
+- **Client reuse**: `_nodejs_client` is a **module-global** singleton. First
+ call fixes the `base_url` and `timeout`; subsequent calls with different
+ kwargs silently reuse the first one. See Edge cases.
+- **Node server error propagation**: if the Node.js server returns
+ `{success: false, error, console_output}`, the handler forwards the `error`
+ string and **keeps** `console_output` so users still see logs from the failed
+ run.
+- **Broad `except Exception`**: any networking error (aiohttp.ClientError,
+ TimeoutError, ConnectionRefusedError) is caught, logged at ERROR, and
+ surfaced as an error envelope with `console_output=""`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none from this handler.
+- **External API calls**: `POST http://localhost:3020/execute`
+ (configurable via `NODEJS_EXECUTOR_URL`). Body:
+ `{code, input_data, language: "javascript", timeout}`.
+- **File I/O**: none from Python; the Node.js server may read/write user
+ packages at `server/nodejs/user-packages/`.
+- **Subprocess**: none directly. The Node.js server itself is a long-lived
+ subprocess started by `main.py` lifespan.
+- **Module-level state**: the `_nodejs_client` module global is created on
+ first use and never reset.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: Persistent Node.js executor at `http://localhost:3020`.
+ Must be running - the backend start script boots it alongside uvicorn.
+- **Python packages**: `aiohttp`.
+- **Environment variables**: `NODEJS_EXECUTOR_URL`,
+ `NODEJS_EXECUTOR_TIMEOUT`, `NODEJS_EXECUTOR_PORT`, `NODEJS_EXECUTOR_HOST`,
+ `NODEJS_EXECUTOR_BODY_LIMIT` (all read by the Node server itself).
+
+## Edge cases & known limits
+
+- **Module-level client singleton**: `_nodejs_client` is cached on first call.
+ If the injected `nodejs_url` / `nodejs_timeout` kwargs change mid-process
+ (e.g., tests re-wiring the container), the cached instance keeps the
+ original values. Reset by `services.handlers.code._nodejs_client = None`.
+- **Node server down**: connection refused surfaces as
+ `error="Cannot connect to host localhost:3020 ssl:default [Connect call
+ failed]"` or similar aiohttp message. No automatic retry.
+- **`workspace_dir` key collision**: user code cannot read an upstream
+ `workspace_dir` from `input_data` - the handler always overwrites it.
+- **Timeout semantics**: the Python-side `timeout` is a ceiling on the
+ aiohttp request itself (set once at client creation); the
+ `timeout_ms` forwarded in the body is the Node server's script timeout.
+ These two can disagree - if the script timeout is longer than the aiohttp
+ timeout, the HTTP call fails before the script finishes.
+- **`console_output` may contain partial output**: Node server streams stdio
+ into a buffer and flushes at end-of-run, but on script timeout the server
+ returns whatever it captured up to the kill signal.
+- **JSON-only transport**: `output` must be JSON-serialisable on the Node
+ side. Functions, `undefined`, `BigInt`, circular refs are stripped or
+ rejected by `JSON.stringify` before return.
+
+## Related
+
+- **Skills using this as a tool**: [`javascript-skill/SKILL.md`](../../../server/skills/coding_agent/javascript-skill/SKILL.md)
+- **Sibling nodes**: [`typescriptExecutor`](./typescriptExecutor.md), [`pythonExecutor`](./pythonExecutor.md)
+- **Architecture docs**: [DESIGN.md](../../DESIGN.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/processManager.md b/docs-internal/node-logic-flows/code_fs_process/processManager.md
new file mode 100644
index 00000000..455c8879
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/processManager.md
@@ -0,0 +1,181 @@
+# Process Manager (`processManager`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / process |
+| **Frontend definition** | [`client/src/nodeDefinitions/processNodes.ts`](../../../client/src/nodeDefinitions/processNodes.ts) |
+| **Backend handler** | [`server/services/handlers/process.py::handle_process_manager`](../../../server/services/handlers/process.py) |
+| **Service** | [`server/services/process_service.py::ProcessService`](../../../server/services/process_service.py) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/terminal/process-manager-skill/SKILL.md`](../../../server/skills/terminal/process-manager-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `process_manager` |
+
+## Purpose
+
+Manages long-running subprocesses (dev servers, watchers, build tools) for a
+workflow. Unlike [`shell`](./shell.md), processes spawned here inherit the
+**full** system PATH and run asynchronously - their stdout/stderr streams into
+the Terminal tab via `broadcast_terminal_log()` and persists to per-process log
+files at `<workspace>/<agent_node_id>/.processes/<name>/{stdout,stderr}.log`.
+
+Six operations: `start`, `stop`, `restart`, `send_input`, `list`, `get_output`.
+The handler is a thin dispatcher over the `ProcessService` singleton; the
+singleton owns a `{(workflow_id, name): ManagedProcess}` dict, the streaming
+tasks, and the cleanup scheduler.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Not consumed |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `process_manager` | no | - | Tool name exposed to AI agents |
+| `toolDescription` | string | (see frontend) | no | - | Description shown to LLM |
+| `operation` | options | `start` | no | - | One of `start`, `stop`, `restart`, `send_input`, `list`, `get_output` |
+| `name` | string | `""` | yes (all except `list`) | `operation in [start, stop, restart, send_input, get_output]` | Unique process name within the workflow |
+| `command` | string | `""` | yes (`start` only) | `operation=start` | Shell command (parsed with `shlex.split`) |
+| `working_directory` | string | `""` | no | `operation=start` | Defaults to `<workspace>/<node_id>` |
+| `text` | string | `""` | yes (`send_input`) | `operation=send_input` | Text to write to stdin (newline auto-appended) |
+| `stream` | string | `"stdout"` | no | - (tool-only) | `stdout` or `stderr` for `get_output` |
+| `tail` | number | `50` | no | - (tool-only) | Tail lines; 0 means all lines from `offset` |
+| `offset` | number | `0` | no | - (tool-only) | Skip N lines (only when `tail=0`) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload per operation
+
+- `start` / `stop` / `restart`: `{name, command, pid, status, started_at,
+ exit_code, working_directory, stdout_lines, stderr_lines, log_dir}`.
+- `send_input`: `{sent: <text>}`.
+- `list`: `{processes: Array<ProcessInfo>}` for the current workflow.
+- `get_output`: `{lines: string[], total: number, file: string}`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_process_manager] --> B[Build tool_args:<br/>clean 'None' strings,<br/>default working_directory to workspace/node_id]
+ B --> C[execute_process_manager]
+ C --> D{operation}
+ D -- start --> S1{command blocked?<br/>rm, format, mkfs...}
+ S1 -- yes --> Sblk[Return error:<br/>Destructive commands blocked]
+ S1 -- no --> S2{process limit reached?}
+ S2 -- yes --> Slim[Return error:<br/>Process limit reached]
+ S2 -- no --> S3{name exists & running?}
+ S3 -- yes --> S3s[await self.stop]
+ S3 -- no --> S4
+ S3s --> S4[shlex.split command,<br/>cwd must be inside workspace_base]
+ S4 --> S5[mkdir log_dir, clear stdout.log/stderr.log]
+ S5 --> S6[create_subprocess_exec argv<br/>stdin/out/err=PIPE, PYTHONUNBUFFERED=1]
+ S6 --> S7[spawn stdout + stderr reader tasks]
+ S7 --> S8[Return success ProcessInfo]
+ D -- stop --> St1{process found & running?}
+ St1 -- no --> Sterr[Return error or idempotent success]
+ St1 -- yes --> St2[psutil kill tree, cancel reader tasks]
+ St2 --> St3[wait exit, schedule 60s cleanup]
+ St3 --> St4[Return success]
+ D -- restart --> R[stop then start with same cmd+cwd]
+ D -- send_input --> I1[write text+newline to stdin.drain]
+ D -- list --> L[return info for workflow_id processes]
+ D -- get_output --> O[read log file, tail or offset slice]
+ D -- unknown --> U[Return error:<br/>Unknown operation]
+```
+
+## Decision Logic
+
+- **`_clean_arg()`**: LLMs sometimes pass the literal string `"None"` for
+ missing fields; the handler coerces `""` and `"None"` to empty.
+- **`working_directory` fallback**: if the param is empty the handler uses
+ `<workspace>/<node_id>` (each agent node gets its own subfolder). If the
+ workspace is also empty, `ProcessService.start` falls back to
+ `<workspace_base>/default` and mkdir's it.
+- **Workspace guardrail**: `cwd` must resolve inside `workspace_base_resolved`
+ via `Path.is_relative_to()`. Violations return an error.
+- **Destructive-command block**: the service maintains a hard-coded list of
+ prefixes/tokens (`rm `, `rmdir`, `del `, `rd `, `remove-item`, `format `,
+ `mkfs`, `dd if=`, `shred`, `> /dev/`, `chmod 777`, `chmod -r`) and refuses
+ any command that matches. Users are told to use `shell_execute` instead.
+- **Process limit**: `max_processes` (default 10) caps the number of
+ concurrently-running processes. Stopped/error entries do not count. When
+ at the limit, a new `start` returns an error; restarting an existing entry
+ is still allowed.
+- **Duplicate name handling**: starting a name that already exists and is
+ running triggers an implicit `stop` first; the new process inherits the
+ same `log_dir` (cleared before spawn).
+- **PATH inheritance**: `env = {**os.environ, "PYTHONUNBUFFERED": "1"}`.
+ The full system PATH is available - this is the main distinction from the
+ sandboxed shell node.
+- **Exit code capture**: only the stdout reader task fulfils `exit_code` on
+ EOF via `process.wait()` with a 5s timeout. Status becomes `stopped`
+ (exit=0) or `error` (nonzero).
+- **Auto cleanup**: 60 seconds after a process exits, `_cleanup_completed`
+ removes its log directory and drops it from the tracking dict. Fast
+ consumers must call `get_output` before the grace window.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**:
+ - Every streamed stdout/stderr line fires
+ `broadcast_terminal_log({timestamp, level, message, source:
+ "process:<name>"})`.
+- **External API calls**: none.
+- **File I/O**:
+ - `<workspace>/<node_id>/.processes/<name>/stdout.log`
+ - `<workspace>/<node_id>/.processes/<name>/stderr.log`
+ - Appended line-by-line by the reader tasks; cleared on each `start` and
+ removed on `stop`/`shutdown`.
+- **Subprocess**:
+ - `asyncio.create_subprocess_exec(*argv, stdin/out/err=PIPE, cwd=..., env=...)`.
+ - `psutil.Process(pid).children(recursive=True)` + `.kill()` for tree
+ termination.
+
+## External Dependencies
+
+- **Python packages**: `asyncio`, `psutil`, `shlex`, `shutil`.
+- **Services**: `ProcessService` singleton (global). `set_broadcaster()` must
+ be called at startup for Terminal streaming to reach the frontend.
+- **OS utilities**: whatever the user command references - full PATH.
+
+## Edge cases & known limits
+
+- **`shlex.split` is POSIX-style even on Windows**: Windows-style
+ backslashes inside quotes may be mis-split. Complex PowerShell invocations
+ are fragile; users are guided toward a wrapper script or to use the
+ `bash`/`wsl` variants.
+- **Blocked-commands list is substring-based**: `"rm "` matching checks for
+ leading and mid-string occurrences, but a command like
+ `python -c "os.system('rm -rf ...')"` slips through because it does not
+ start with `rm ` and the word `rm ` does not appear with a leading space.
+- **60-second cleanup race**: if an agent polls `get_output` at 65s it may
+ hit `{lines: [], total: 0, file: ""}` with no hint that the process ever
+ existed.
+- **`send_input` requires trailing newline**: the handler appends `\n` only
+ if `text` does not already end with one.
+- **`exit_code=-1` on stop timeout**: if `process.wait()` does not return
+ within 3s after the kill, `exit_code=-1` is written - ambiguous with real
+ exit codes that happen to be negative (rare on POSIX, common on Windows).
+- **stdout-only exit capture**: if a process writes only to stderr and
+ closes stdout immediately, the stderr reader runs to completion but the
+ status stays `running` until the handler is asked again. This is a known
+ race in `_read_stream`.
+- **No resource limits**: CPU/memory caps are NOT applied; rogue processes
+ can exhaust the host.
+- **Log dir name collision**: two concurrent `start` calls with the same
+ `name` will serialise via the `stop` guard, but a partial cleanup from a
+ previous run can leave stale files if the server was killed mid-cleanup.
+
+## Related
+
+- **Skills using this as a tool**: [`process-manager-skill/SKILL.md`](../../../server/skills/terminal/process-manager-skill/SKILL.md)
+- **Sibling nodes**: [`shell`](./shell.md), [`fileRead`](./fileRead.md), [`fsSearch`](./fsSearch.md)
+- **Architecture docs**: [DESIGN.md](../../DESIGN.md), [Status Broadcaster](../../status_broadcaster.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/pythonExecutor.md b/docs-internal/node-logic-flows/code_fs_process/pythonExecutor.md
new file mode 100644
index 00000000..d726c103
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/pythonExecutor.md
@@ -0,0 +1,144 @@
+# Python Executor (`pythonExecutor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / code |
+| **Frontend definition** | [`client/src/nodeDefinitions/codeNodes.ts`](../../../client/src/nodeDefinitions/codeNodes.ts) |
+| **Backend handler** | [`server/services/handlers/code.py::handle_python_executor`](../../../server/services/handlers/code.py) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/coding_agent/python-skill/SKILL.md`](../../../server/skills/coding_agent/python-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `python_code` |
+
+## Purpose
+
+Executes user-supplied Python code in the backend process using `exec()` with a
+curated `__builtins__` whitelist. Intended for quick data transforms inside a
+workflow; input from upstream nodes lands in a local `input_data` dict and the
+code must set a module-level `output` variable to emit a result. Heavy libraries
+are intentionally excluded - only `math`, `json`, `datetime`, `re`, `random`,
+`Counter`, `defaultdict` are preloaded by the skill guide. `print()` is
+redirected to an `io.StringIO` buffer so stdout becomes the `console_output`
+return field.
+
+Dispatched through the special-handlers branch at
+[`node_executor.py:367-381`](../../../server/services/node_executor.py) so it
+receives `connected_outputs` (dict of upstream outputs keyed by source node id).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream outputs are exposed as `input_data` dict inside the exec namespace |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `code` | string (code editor) | (boilerplate stub) | yes | - | Python source. Must assign to the free variable `output` to emit a value |
+| `timeout` | number | `30` | no | - | Read and coerced to int but **not enforced** - `exec()` is synchronous with no wall-clock guard |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+{
+ output: any; // Value assigned to `output` in the user code (None by default)
+ console_output: string; // Captured stdout from redirected print()
+ timestamp: string; // ISO8601 local time
+}
+```
+
+On failure the envelope is `{success: false, error, console_output: "", ...}`.
+Note that `console_output` is **only** preserved on the success path; when an
+exception fires mid-execution the already-captured buffer is discarded because
+the `except` branch hard-codes `"console_output": console_output` but
+`console_output` is only assigned after `exec()` finishes. See Edge cases.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_python_executor] --> B{code strip empty?}
+ B -- yes --> E[Return error envelope:<br/>No code provided]
+ B -- no --> C[Read timeout<br/>int-coerce only, unused]
+ C --> D[Build safe_builtins dict:<br/>abs..zip, math, json, captured_print]
+ D --> F[Build namespace:<br/>input_data=connected_outputs or {},<br/>workspace_dir=context,<br/>output=None]
+ F --> G[exec code in namespace]
+ G -- exception --> H[Return error envelope<br/>error=str e, console_output=empty]
+ G -- ok --> I[output = namespace.get output<br/>console_output = StringIO.getvalue]
+ I --> J[Return success envelope<br/>output, console_output, timestamp]
+```
+
+## Decision Logic
+
+- **Validation**: `code.strip() == ""` -> immediate error envelope with message
+ `"No code provided"`.
+- **Namespace seeding**: `input_data` defaults to `{}` if `connected_outputs` is
+ None. `workspace_dir` is pulled from `context["workspace_dir"]` but never
+ validated; an empty string is fine.
+- **Print redirection**: `safe_builtins["print"]` is a wrapper that forces
+ `file=stdout_capture`, so any user-supplied `file=` kwarg is **overwritten**.
+- **Output extraction**: `namespace.get("output", None)` - the user writing
+ `output = <value>` is the only way to emit data. A top-level expression is
+ evaluated but not captured.
+- **No timeout enforcement**: the `timeout` parameter is int-coerced only as a
+ sanity check (raises on non-numeric strings) but never passed to a watchdog.
+ Long loops will block the async event loop for the whole backend.
+- **Error path**: broad `except Exception` catches everything, logs via
+ `logger.error`, and returns `{success: false, error: str(e)}`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none (the handler itself is silent; the executor does the
+ status broadcast around it).
+- **External API calls**: none.
+- **File I/O**: user code can freely read/write via Python stdlib - it is NOT
+ sandboxed by the `safe_builtins` dict because `open`, `eval`, `exec`,
+ `__import__` are still reachable through attribute lookups on imported
+ modules. `exec()` runs in the server process with its full OS privileges.
+- **Subprocess**: none from the handler; user code could spawn.
+- **Event loop blocking**: `exec()` is synchronous. A tight loop blocks every
+ other request/workflow until it returns.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none.
+- **Python packages**: stdlib only (`io`, `math`, `json`, `datetime`).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **`timeout` is cosmetic**: accepted and coerced to int but never enforced. A
+ hanging script hangs the entire FastAPI worker.
+- **No real sandbox**: the `safe_builtins` dict is not a security boundary -
+ `math` and `json` are module objects, and user code can re-import anything via
+ `().__class__.__base__.__subclasses__()` or similar well-known escapes. Treat
+ this node as trusted-input only.
+- **`console_output` swallowed on error**: the `except` path hard-codes
+ `"console_output": console_output`, but `console_output` is initialised to
+ `""` and only overwritten **after** `exec()` succeeds. Any print()s before an
+ exception are therefore lost.
+- **`output=None` is indistinguishable from a user explicitly returning
+ `None`**: both surface as `{"output": None}` in the envelope.
+- **`input_data` mutation is visible to later siblings**: the handler passes
+ the `connected_outputs` dict by reference, so user code mutating it mutates
+ the executor's cache. Downstream nodes in the same execution layer can see
+ the mutation.
+- **`print(..., file=...)`**: the captured_print wrapper unconditionally sets
+ `kwargs["file"] = stdout_capture`, overriding any user-provided file handle.
+- **No `await` support**: `exec()` cannot evaluate top-level `await`; the user
+ must wrap async code in `asyncio.run(...)` themselves.
+
+## Related
+
+- **Skills using this as a tool**: [`python-skill/SKILL.md`](../../../server/skills/coding_agent/python-skill/SKILL.md)
+- **Sibling nodes**: [`javascriptExecutor`](./javascriptExecutor.md), [`typescriptExecutor`](./typescriptExecutor.md), [`shell`](./shell.md), [`processManager`](./processManager.md)
+- **Architecture docs**: [DESIGN.md](../../DESIGN.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/shell.md b/docs-internal/node-logic-flows/code_fs_process/shell.md
new file mode 100644
index 00000000..7ee6e12a
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/shell.md
@@ -0,0 +1,134 @@
+# Shell (`shell`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / filesystem |
+| **Frontend definition** | [`client/src/nodeDefinitions/filesystemNodes.ts`](../../../client/src/nodeDefinitions/filesystemNodes.ts) |
+| **Backend handler** | [`server/services/handlers/filesystem.py::handle_shell`](../../../server/services/handlers/filesystem.py) |
+| **Backend** | [`deepagents.backends.LocalShellBackend.execute`](https://github.com/langchain-ai/deepagents) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | [`server/skills/terminal/shell-skill/SKILL.md`](../../../server/skills/terminal/shell-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `shell_execute` |
+
+## Purpose
+
+Runs a short-lived shell command inside the per-workflow workspace. Delegates
+to `LocalShellBackend.execute()`, which invokes the command via `subprocess`
+but intentionally **scrubs the system PATH**, so tools like `npm`, `node`,
+`python`, and `git` are NOT resolvable unless supplied with an absolute path.
+For long-running processes or tools that need the real PATH, users are
+directed to [`processManager`](./processManager.md).
+
+Runs synchronously under `asyncio.to_thread()` so the event loop keeps
+servicing other requests while the command executes.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Not consumed by the handler |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `command` | string | `""` | yes | - | Shell command |
+| `timeout` | number | `30` | no | - | Max seconds (UI clamps 1-300) |
+| `working_directory` | string | `""` | no | - | Overrides context workspace |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+{
+ stdout: string; // Combined output (backend merges stderr into stdout unless truncated)
+ exit_code: number; // 124 = timed out, else the process exit code
+ truncated: boolean; // Whether the backend truncated the output buffer
+ command: string; // Echo of the requested command
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_shell] --> B{command empty?}
+ B -- yes --> E[Return error:<br/>command is required]
+ B -- no --> C[_get_backend workspace root<br/>virtual_mode=True]
+ C --> D[to_thread backend.execute command, timeout]
+ D -- exception --> H[Return error envelope]
+ D -- ok --> I{exit_code?}
+ I -- 124 --> I1[Log warning:<br/>Timed out]
+ I -- nonzero --> I2[Log warning:<br/>Non-zero exit]
+ I -- 0 --> I3[Log info: Completed]
+ I1 & I2 & I3 --> J[Return success envelope<br/>stdout, exit_code, truncated, command]
+```
+
+## Decision Logic
+
+- **Validation**: empty `command` -> `"command is required"` error.
+- **Sandbox PATH**: `LocalShellBackend` strips the system PATH before spawn,
+ so by default only built-ins and absolute paths work. This is a deliberate
+ safety choice; AI agents are steered toward `process_manager` for any
+ install/build tool invocation.
+- **Timeout handling**: `timeout` is forwarded to
+ `backend.execute(command, timeout=timeout)`. On timeout the backend kills
+ the process and sets `exit_code=124` (POSIX convention). Logged at WARNING.
+- **Non-zero exit still returns `success: true`**: the envelope-level success
+ reflects whether the handler itself finished, not whether the command
+ succeeded. Users must inspect `exit_code` in the payload.
+- **Truncation**: the backend caps output size internally; when capped
+ `truncated=true` surfaces to the caller. The exact cap lives in
+ `deepagents`.
+- **Broad `except Exception`**: backend failures (missing binary,
+ `virtual_mode` violations) become an error envelope.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none (but the process stdout/stderr is NOT streamed to
+ Terminal - only `processManager` does that).
+- **External API calls**: none.
+- **File I/O**: `os.makedirs(root, exist_ok=True)` on the workspace root. The
+ command itself may read/write under that root.
+- **Subprocess**: one per call, via the backend's `subprocess.run`
+ (synchronous, scrubbed PATH). Finished before the handler returns.
+
+## External Dependencies
+
+- **Python packages**: `deepagents`.
+- **Environment variables**: `WORKSPACE_BASE_DIR`.
+- **OS utilities**: whatever the command references - but PATH is empty, so
+ absolute paths only.
+
+## Edge cases & known limits
+
+- **Missing binaries masquerade as command failures**: because PATH is
+ scrubbed, a plain `npm test` gives "command not found" rather than a
+ permissions error. Users often confuse this for a broken node.
+- **Truncation corrupts JSON output**: if a command prints JSON and the
+ backend truncates, the `stdout` string becomes invalid JSON with no
+ trailing marker beyond `truncated=true`.
+- **`exit_code=124` is exit-code polysemy**: real programs can legitimately
+ exit 124; the handler does not distinguish those from a backend-side
+ SIGTERM-on-timeout.
+- **`timeout` is best-effort**: the backend uses `subprocess.run(..., timeout=)`.
+ A child process that ignores SIGTERM may keep running until SIGKILL.
+- **Stdin is empty**: the handler exposes no way to pipe data into the
+ command - `input_data` from upstream nodes does not reach it.
+- **No environment variable override**: users cannot inject env vars via
+ parameters; the backend sets its own minimal env.
+- **Windows path traversal check is string-based**: `virtual_mode=True`
+ normalises paths but trust-boundary violations depend on the backend
+ implementation.
+
+## Related
+
+- **Skills using this as a tool**: [`shell-skill/SKILL.md`](../../../server/skills/terminal/shell-skill/SKILL.md), [`bash-skill/SKILL.md`](../../../server/skills/terminal/bash-skill/SKILL.md), [`powershell-skill/SKILL.md`](../../../server/skills/terminal/powershell-skill/SKILL.md), [`wsl-skill/SKILL.md`](../../../server/skills/terminal/wsl-skill/SKILL.md)
+- **Sibling nodes**: [`processManager`](./processManager.md), [`fileRead`](./fileRead.md), [`fsSearch`](./fsSearch.md)
diff --git a/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md b/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md
new file mode 100644
index 00000000..421736dc
--- /dev/null
+++ b/docs-internal/node-logic-flows/code_fs_process/typescriptExecutor.md
@@ -0,0 +1,117 @@
+# TypeScript Executor (`typescriptExecutor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | code_fs_process / code |
+| **Frontend definition** | [`client/src/nodeDefinitions/codeNodes.ts`](../../../client/src/nodeDefinitions/codeNodes.ts) |
+| **Backend handler** | [`server/services/handlers/code.py::handle_typescript_executor`](../../../server/services/handlers/code.py) |
+| **Node.js client** | [`server/services/nodejs_client.py::NodeJSClient`](../../../server/services/nodejs_client.py) |
+| **Tests** | [`server/tests/nodes/test_code_fs_process.py`](../../../server/tests/nodes/test_code_fs_process.py) |
+| **Skill (if any)** | - (shared with `javascript-skill`) |
+| **Dual-purpose tool** | yes - tool name `typescript_code` |
+
+## Purpose
+
+Identical to [`javascriptExecutor`](./javascriptExecutor.md) except the
+`language` field in the POST payload is `"typescript"`, so the Node.js server
+runs the script through `tsx` (TypeScript runner) instead of plain `node`.
+All inputs, outputs, and error paths match the JS variant - the only
+user-facing difference is that TypeScript type annotations parse without
+error.
+
+Dispatched through the special-handlers branch at
+[`node_executor.py:367-381`](../../../server/services/node_executor.py) so it
+receives `connected_outputs`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream outputs merged into the Node-side `input_data` object |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `code` | string (code editor) | (boilerplate stub with `interface Result { ... }`) | yes | - | TypeScript source. User must assign to `output` |
+| `timeout` | number | `30` | no | - | Seconds - multiplied by 1000 before forwarding to the Node server |
+
+## Handler-level kwargs
+
+| Name | Default | Description |
+|------|---------|-------------|
+| `nodejs_url` | `http://localhost:3020` | |
+| `nodejs_timeout` | `30` | |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+{
+ output: any;
+ console_output: string;
+ timestamp: string;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_typescript_executor] --> B{code strip empty?}
+ B -- yes --> E[Return error envelope:<br/>No code provided]
+ B -- no --> C[timeout_ms = int timeout * 1000]
+ C --> D[input_data = connected_outputs or {}<br/>inject workspace_dir]
+ D --> F[get_nodejs_client<br/>lazy singleton]
+ F --> G[client.execute<br/>POST /execute<br/>language=typescript]
+ G -- exception --> H[Return error envelope]
+ G -- ok + success=true --> I[Return success envelope]
+ G -- ok + success=false --> J[Return error envelope<br/>preserve console_output]
+```
+
+## Decision Logic
+
+Matches [`javascriptExecutor`](./javascriptExecutor.md#decision-logic). The only
+wire-level difference is the POST body's `language` field.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: `POST http://localhost:3020/execute` with body
+ `{code, input_data, language: "typescript", timeout}`.
+- **Subprocess**: none directly.
+- **Module-level state**: shares the `_nodejs_client` singleton with the JS
+ executor.
+
+## External Dependencies
+
+- **Services**: Persistent Node.js executor at `http://localhost:3020`.
+ The server must have `tsx` available (pinned in `server/nodejs/package.json`).
+- **Python packages**: `aiohttp`.
+- **Environment variables**: `NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_TIMEOUT`.
+
+## Edge cases & known limits
+
+- **Shared singleton with `javascriptExecutor`**: a TS call after a JS call
+ (or vice versa) reuses the same `NodeJSClient` instance. Changing
+ `nodejs_url` / `nodejs_timeout` mid-process has no effect.
+- **No TypeScript compile errors at HTTP layer**: if `tsx` emits compile
+ errors the Node server returns `{success: false, error: "<tsc message>"}`;
+ the Python handler surfaces this verbatim.
+- **Type erasure**: runtime output is still JSON; interfaces and type aliases
+ are compile-time only.
+- **Inherits every JS caveat**: module-level client, aiohttp-vs-script timeout
+ mismatch, `workspace_dir` overwrite, JSON-only transport. See
+ [`javascriptExecutor.md`](./javascriptExecutor.md#edge-cases--known-limits).
+
+## Related
+
+- **Shared skill**: [`javascript-skill/SKILL.md`](../../../server/skills/coding_agent/javascript-skill/SKILL.md)
+- **Sibling nodes**: [`javascriptExecutor`](./javascriptExecutor.md), [`pythonExecutor`](./pythonExecutor.md)
diff --git a/docs-internal/node-logic-flows/document/documentParser.md b/docs-internal/node-logic-flows/document/documentParser.md
new file mode 100644
index 00000000..b34eff51
--- /dev/null
+++ b/docs-internal/node-logic-flows/document/documentParser.md
@@ -0,0 +1,125 @@
+# Document Parser (`documentParser`)
+
+| Field | Value |
+|------|-------|
+| **Category** | document |
+| **Frontend definition** | [`client/src/nodeDefinitions/documentNodes.ts`](../../../client/src/nodeDefinitions/documentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/document.py::handle_document_parser`](../../../server/services/handlers/document.py) |
+| **Tests** | [`server/tests/nodes/test_document.py`](../../../server/tests/nodes/test_document.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Parse a batch of files into plain/Markdown text documents via one of four
+parsers: `pypdf` (default, fast), `marker` (GPU OCR for scanned PDFs),
+`unstructured` (multi-format - DOCX, PPTX, HTML, ...), `beautifulsoup` (HTML).
+Parsing runs in a thread pool (`asyncio.to_thread`) so the event loop stays
+responsive. Inputs can be a list of file dicts/strings, or a directory +
+glob pattern.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Provides `files[]` upstream (e.g. from `fileDownloader`) |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `files` | array | `[]` | no | - | List of `{path: string}` or raw path strings |
+| `inputDir` | string | `""` | no | - | Directory to glob for files |
+| `filePattern` | string | `*.pdf` | no | - | Glob pattern applied inside `inputDir` |
+| `parser` | options | `pypdf` | no | - | `pypdf` / `marker` / `unstructured` / `beautifulsoup` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `documents`, `parsed_count`, `failed` |
+
+### Output payload
+
+```ts
+{
+ documents: Array<{
+ source: string; // full path
+ filename: string; // basename
+ content: string; // extracted text / markdown
+ length: number;
+ parser: string; // echoed
+ }>;
+ parsed_count: number;
+ failed: Array<{ file: string; error: string }>;
+}
+```
+
+Wrapped in standard envelope: `{ success, result, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_document_parser] --> B[Normalize files param<br/>dict -> path, str -> path]
+ B --> C{inputDir exists?}
+ C -- yes --> C1[extend paths with inputDir.glob(filePattern)]
+ C -- no --> D{paths empty?}
+ C1 --> D
+ D -- yes --> Ret0[Return success=true<br/>documents=[], parsed_count=0]
+ D -- no --> E[For each path: asyncio.to_thread _parse_file_sync]
+ E --> F{parser branch}
+ F -- pypdf --> Fp[pypdf.PdfReader -> join page.extract_text]
+ F -- marker --> Fm[marker.PdfConverter -> markdown]
+ F -- unstructured --> Fu[unstructured.partition.auto -> join elements]
+ F -- beautifulsoup --> Fb[BeautifulSoup + decompose script/style -> get_text]
+ F -- other --> Fx[raise ValueError Unknown parser]
+ Fp --> G[append to documents]
+ Fm --> G
+ Fu --> G
+ Fb --> G
+ Fx --> Gx[append to failed]
+ G --> H[Return success=true with documents + failed]
+ Gx --> H
+```
+
+## Decision Logic
+
+- **No paths**: returns success with empty `documents[]`, no error.
+- **Per-file failure**: any exception inside `_parse_file_sync` is captured into `failed` with `{file, error}`; other files continue.
+- **Unknown parser**: raised by `_parse_file_sync`, recorded per-file in `failed` (NOT a top-level failure - every file fails identically).
+- **Lazy imports**: each parser imports its backend only when selected, so unused heavy deps (marker CUDA stack, unstructured) are not loaded.
+- **BeautifulSoup special handling**: strips `<script>` and `<style>` tags before extracting text.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: reads every input file (text or binary depending on parser). BeautifulSoup branch uses `path.read_text(errors='ignore')`.
+- **Subprocess**: none (parsers run in-process via `asyncio.to_thread`).
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Python packages** (lazy-imported per parser):
+ - `pypdf>=4.0.0` for `pypdf`
+ - `marker-pdf` + CUDA runtime for `marker`
+ - `unstructured>=0.16.0` for `unstructured`
+ - `beautifulsoup4>=4.12.0` for `beautifulsoup`
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `pypdf`: `page.extract_text()` can return `None` for scanned pages - coerced to empty string via `or ''`.
+- `marker`: downloads models on first call and requires CUDA; will fail on CPU-only hosts.
+- `unstructured`: classifies file type from extension/content; no explicit type param.
+- BeautifulSoup branch is the only one that handles HTML via `read_text`, so passing a binary `.pdf` there returns garbled `get_text`.
+- `files` and `inputDir` can be combined - directory glob is appended to the explicit list.
+- `filePattern` is applied via `Path.glob` (non-recursive). Use `**/*.pdf` for recursive.
+- The handler returns `success=true` even when every file failed - consumers must inspect `failed` and `parsed_count`.
+
+## Related
+
+- **Upstream producer**: [`fileDownloader`](./fileDownloader.md) drops files into a directory consumed here via `inputDir`.
+- **Downstream consumer**: [`textChunker`](./textChunker.md) consumes the `documents[]` array directly.
diff --git a/docs-internal/node-logic-flows/document/embeddingGenerator.md b/docs-internal/node-logic-flows/document/embeddingGenerator.md
new file mode 100644
index 00000000..59640e3d
--- /dev/null
+++ b/docs-internal/node-logic-flows/document/embeddingGenerator.md
@@ -0,0 +1,120 @@
+# Embedding Generator (`embeddingGenerator`)
+
+| Field | Value |
+|------|-------|
+| **Category** | document |
+| **Frontend definition** | [`client/src/nodeDefinitions/documentNodes.ts`](../../../client/src/nodeDefinitions/documentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/document.py::handle_embedding_generator`](../../../server/services/handlers/document.py) |
+| **Tests** | [`server/tests/nodes/test_document.py`](../../../server/tests/nodes/test_document.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Generate vector embeddings from a list of text chunks using one of three
+backends: HuggingFace (local sentence-transformers, default), OpenAI
+(API-hosted), or Ollama (local server). The heavy embedding call runs in a
+thread pool via `asyncio.to_thread` so the event loop is not blocked.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Provides `chunks[]` upstream |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `chunks` | array | `[]` | yes | - | List of `{content, source, chunk_index}` dicts |
+| `provider` | options | `huggingface` | no | - | `huggingface` / `openai` / `ollama` |
+| `model` | string | `BAAI/bge-small-en-v1.5` | no | - | Model name for the chosen provider |
+| `apiKey` | string | `""` | no (required for openai) | - | OpenAI API key |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Embeddings + original chunks + metadata |
+
+### Output payload
+
+```ts
+{
+ embeddings: number[][]; // one vector per chunk
+ embedding_count: number;
+ dimensions: number; // len(embeddings[0])
+ chunks: any[]; // echoed back for pairing
+ provider: string;
+ model: string;
+}
+```
+
+Empty-input variant:
+
+```ts
+{ embeddings: [], embedding_count: 0, dimensions: 0, chunks: [] }
+```
+
+Wrapped in standard envelope: `{ success, result, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_embedding_generator] --> B{chunks empty?}
+ B -- yes --> Ret0[Return success=true<br/>zero-valued payload]
+ B -- no --> C[Extract text list: dict.content or str(chunk)]
+ C --> D{provider}
+ D -- huggingface --> Dh[Import langchain_huggingface<br/>raise ImportError with install hint if missing]
+ D -- openai --> Do[Import langchain_openai.OpenAIEmbeddings]
+ D -- ollama --> Dl[Import langchain_ollama.OllamaEmbeddings]
+ D -- other --> Dx[raise ValueError Unknown provider]
+ Dh --> E[HuggingFaceEmbeddings(model_name=model)]
+ Do --> F[OpenAIEmbeddings(model=model, api_key=apiKey)]
+ Dl --> G[OllamaEmbeddings(model=model)]
+ E --> H[asyncio.to_thread embedder.embed_documents(texts)]
+ F --> H
+ G --> H
+ H --> I[Compute dimensions from len(embeddings[0])]
+ I --> J[Return success=true with embeddings + echoed chunks]
+```
+
+## Decision Logic
+
+- **Empty chunks**: short-circuits to the empty-payload success envelope.
+- **Provider dispatch**: string match on `provider`, else `ValueError`.
+- **Embedding call**: always runs in a worker thread via `asyncio.to_thread`.
+- **Dimensions**: inferred from first embedding; `0` if the call returned `[]`.
+- **Unknown provider**: raised inside the try block -> caught by outer `except` -> `success=false`.
+- **Missing huggingface package**: re-raised with an install hint (`pip install langchain-huggingface sentence-transformers`).
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**:
+ - `openai`: HTTPS call to OpenAI embeddings endpoint.
+ - `ollama`: HTTP call to local Ollama server (default `localhost:11434`).
+ - `huggingface`: no network after the model is cached; first run downloads model to `~/.cache/huggingface`.
+- **File I/O**: HuggingFace model cache on first run.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `apiKey` param (OpenAI only). Not fetched from `auth_service` - must be passed as a node parameter.
+- **Python packages**: `langchain-huggingface` + `sentence-transformers` (HF), `langchain-openai` (OpenAI), `langchain-ollama` (Ollama).
+- **Environment variables**: `OLLAMA_HOST` respected by `langchain_ollama`.
+
+## Edge cases & known limits
+
+- OpenAI `apiKey` is read from the node parameter, NOT from `auth_service.get_api_key('openai')`. This is inconsistent with other OpenAI-using nodes (documented gotcha).
+- No batching controls - everything is passed in one `embed_documents` call; provider-side batch limits apply.
+- HF first-run model download can take minutes; the node will appear to hang.
+- Model name default (`BAAI/bge-small-en-v1.5`) is HF-specific; you must override `model` when switching provider.
+- No cost tracking (unlike LLM chat nodes).
+
+## Related
+
+- **Upstream producer**: [`textChunker`](./textChunker.md) supplies `chunks[]`.
+- **Downstream consumer**: [`vectorStore`](./vectorStore.md) consumes `embeddings` + `chunks` together.
diff --git a/docs-internal/node-logic-flows/document/fileDownloader.md b/docs-internal/node-logic-flows/document/fileDownloader.md
new file mode 100644
index 00000000..2eeb26aa
--- /dev/null
+++ b/docs-internal/node-logic-flows/document/fileDownloader.md
@@ -0,0 +1,119 @@
+# File Downloader (`fileDownloader`)
+
+| Field | Value |
+|------|-------|
+| **Category** | document |
+| **Frontend definition** | [`client/src/nodeDefinitions/documentNodes.ts`](../../../client/src/nodeDefinitions/documentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/document.py::handle_file_downloader`](../../../server/services/handlers/document.py) |
+| **Tests** | [`server/tests/nodes/test_document.py`](../../../server/tests/nodes/test_document.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Download a batch of URLs in parallel to a local directory using a bounded
+`asyncio.Semaphore`. Typically consumes the `items` array produced by
+`httpScraper`. Output directory defaults to `<workspace_dir>/downloads/` so
+downloaded files land in the per-workflow workspace and can be picked up by
+`documentParser` or the Deep Agent filesystem tools.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data - provides `items` via parameter resolution |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `items` | array | `[]` | yes | - | List of `{url: string, ...}` dicts or raw URL strings |
+| `outputDir` | string | `""` | no | - | Falls back to `<workspace_dir>/downloads` or `downloads` |
+| `maxWorkers` | number | `8` | no | - | Semaphore width, 1-32 |
+| `skipExisting` | boolean | `true` | no | - | Skip when destination file already exists |
+| `timeout` | number | `60` | no | - | Per-request timeout (seconds) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Counts plus downloaded file metadata |
+
+### Output payload
+
+```ts
+{
+ downloaded: number;
+ skipped: number;
+ failed: number;
+ files: Array<{
+ status: 'downloaded';
+ path: string;
+ url: string;
+ size: number; // bytes
+ filename: string;
+ }>;
+ output_dir: string;
+}
+```
+
+Wrapped in standard envelope: `{ success, result, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_file_downloader] --> B{items empty?}
+ B -- yes --> Ret0[Return success=true<br/>counts all zero]
+ B -- no --> C[Resolve output_dir from outputDir or context.workspace_dir or ./downloads]
+ C --> D[mkdir parents exist_ok]
+ D --> E[Build semaphore(maxWorkers)]
+ E --> F[asyncio.gather over items<br/>each inside semaphore slot]
+ F --> G{Per-item}
+ G -- empty url --> Gx[status=failed]
+ G -- skip_existing + exists --> Gs[status=skipped]
+ G -- fetch --> Gf[GET with timeout, follow_redirects=True]
+ Gf -- HTTPStatusError/Exception --> Ge[status=failed]
+ Gf -- ok --> Gw[write_bytes, status=downloaded]
+ G --> H[Collect Exception results into failed]
+ H --> I[Return success=true with totals + downloaded files list]
+```
+
+## Decision Logic
+
+- **Empty items**: short-circuits to a zero-count success envelope before any directory work.
+- **Output dir resolution**: `outputDir` param -> `<context.workspace_dir>/downloads` -> literal `downloads` relative to CWD.
+- **Filename**: `unquote(basename(urlparse(url).path))` or literal `"download"` when URL has no path. Collisions silently overwrite unless `skipExisting=true`.
+- **Skip logic**: path-existence check, not size/hash check.
+- **Per-URL failure**: appended to `failed` list, envelope remains `success=true`.
+- **Gather exceptions**: wrapped tasks may raise - `return_exceptions=True` collects them and they are normalized into `failed` entries with only an `error` field.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: `GET <url>` per item with user-supplied timeout, follow redirects.
+- **File I/O**: creates `output_dir` (recursive), writes each download via `Path.write_bytes`.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: uses `context["workspace_dir"]` injected by the executor.
+- **Python packages**: `httpx`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Each download opens its own `httpx.AsyncClient` inside the semaphore - overhead per file, not a shared client/session.
+- No retry on failure; one HTTP error per URL means one `failed` entry.
+- Filename collisions are not deduplicated across URLs that share a basename - later writes overwrite earlier ones.
+- `maxWorkers` is cast via `int(...)` with no clamping; out-of-range values pass through.
+- `skipExisting` checks the target file path only; a partially downloaded file from a previous crashed run will be treated as complete.
+- The top-level `files` array contains ONLY successfully downloaded items; skipped files are counted but not listed.
+
+## Related
+
+- **Upstream producer**: [`httpScraper`](./httpScraper.md) produces the expected `items[]` shape.
+- **Downstream consumer**: [`documentParser`](./documentParser.md) can glob files from `output_dir`.
+- **Architecture docs**: [Workspace directory](../../../CLAUDE.md#per-workflow-workspace-directory) (per-workflow workspace concept).
diff --git a/docs-internal/node-logic-flows/document/httpScraper.md b/docs-internal/node-logic-flows/document/httpScraper.md
new file mode 100644
index 00000000..5b4e5a7b
--- /dev/null
+++ b/docs-internal/node-logic-flows/document/httpScraper.md
@@ -0,0 +1,127 @@
+# HTTP Scraper (`httpScraper`)
+
+| Field | Value |
+|------|-------|
+| **Category** | document |
+| **Frontend definition** | [`client/src/nodeDefinitions/documentNodes.ts`](../../../client/src/nodeDefinitions/documentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/document.py::handle_http_scraper`](../../../server/services/handlers/document.py) |
+| **Tests** | [`server/tests/nodes/test_document.py`](../../../server/tests/nodes/test_document.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Scrape links from one or more web pages into a normalized `items[]` array
+suitable for the `fileDownloader` node. Supports three iteration modes:
+single URL, date-range iteration with a `{date}` placeholder, and page
+pagination with a `{page}` placeholder. A CSS selector picks which anchor-like
+elements become items. Typically the first stage of an ingestion pipeline:
+`httpScraper -> fileDownloader -> documentParser -> textChunker -> ...`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Trigger / upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `url` | string | `""` | **yes** | - | URL with optional `{date}` / `{page}` placeholder |
+| `iterationMode` | options | `single` | no | - | `single` / `date` / `page` |
+| `startDate` | string | `""` | yes (date mode) | `iterationMode=date` | `YYYY-MM-DD` |
+| `endDate` | string | `""` | yes (date mode) | `iterationMode=date` | `YYYY-MM-DD`, inclusive |
+| `datePlaceholder` | string | `{date}` | no | `iterationMode=date` | Substring replaced with formatted date |
+| `startPage` | number | `1` | no | `iterationMode=page` | Inclusive |
+| `endPage` | number | `10` | no | `iterationMode=page` | Inclusive; `{page}` literal replaced |
+| `linkSelector` | string | `a[href$=".pdf"]` | no | - | BeautifulSoup CSS selector |
+| `headers` | string (JSON) | `{}` | no | - | Extra HTTP headers as JSON object |
+| `useProxy` | boolean | `false` | no | - | Route through proxy service if enabled |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `items`, `item_count`, `errors` |
+
+### Output payload
+
+```ts
+{
+ items: Array<{
+ url: string; // urljoin(fetch_url, href)
+ text: string; // anchor text, stripped
+ source_url: string; // page the link was found on
+ date?: string; // ISO date, present in date mode
+ page?: number; // present in page mode
+ }>;
+ item_count: number;
+ errors: string[]; // "<url>: <error str>" per failed fetch
+}
+```
+
+Wrapped in standard envelope: `{ success, result, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_http_scraper] --> B{url provided?}
+ B -- no --> Eret[Return success=false<br/>error: URL is required]
+ B -- yes --> C[Parse headers JSON]
+ C --> D{iterationMode}
+ D -- date --> D1[Iterate start_date..end_date days<br/>replace datePlaceholder per URL]
+ D -- page --> D2[Iterate startPage..endPage<br/>replace `{page}` literal per URL]
+ D -- single --> D3[Single URL, meta=`{}`]
+ D1 --> E[Build urls_to_fetch list]
+ D2 --> E
+ D3 --> E
+ E --> F{useProxy?}
+ F -- yes --> F1[Lookup proxy URL via proxy_service<br/>swallow errors, continue without proxy]
+ F -- no --> G[httpx.AsyncClient timeout=30 follow_redirects=True]
+ F1 --> G
+ G --> H[For each URL: GET + BeautifulSoup parse]
+ H -- HTTPStatusError / Exception --> I[Append to errors, keep going]
+ H -- ok --> J[Select by linkSelector, build item dict with urljoin + meta]
+ I --> K[Return success=true with items/errors]
+ J --> K
+```
+
+## Decision Logic
+
+- **Validation**: missing `url` raises `ValueError("URL is required")`; caught by outer `except` -> `success=false`.
+- **Date mode**: missing `startDate` or `endDate` raises `ValueError` -> `success=false`.
+- **Iteration mode fallback**: any value other than `date` or `page` takes the single-URL branch (no validation of unknown modes).
+- **Per-URL errors**: collected into `errors` list; the handler still returns `success=true` even if every URL failed (only top-level setup errors fail the envelope).
+- **Proxy failure**: logged at warning, request proceeds without proxy.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: `GET <fetch_url>` for each expanded URL, timeout 30s, `follow_redirects=True`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: optional `services.proxy.service.get_proxy_service()` when `useProxy=true`.
+- **Python packages**: `httpx`, `beautifulsoup4`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `datePlaceholder` is a plain `str.replace`, not a token boundary - a URL containing the placeholder substring twice is replaced twice.
+- Date mode formats dates as `YYYY-MM-DD`; placeholder in URL is replaced with this exact format regardless of what the user wrote.
+- `{page}` in page mode is hard-coded, not configurable (unlike the date placeholder).
+- `headers` is parsed with `json.loads` with no try/except - invalid JSON raises at the top level and fails the envelope.
+- Per-URL failures are silently aggregated into `errors` but the envelope is still `success=true`; downstream nodes must check `errors`.
+- `endPage`/`endDate` are inclusive.
+
+## Related
+
+- **Skills using this as a tool**: none (not a dual-purpose tool).
+- **Downstream nodes**: [`fileDownloader`](./fileDownloader.md) consumes the `items` array directly.
+- **Architecture docs**: [Proxy Service](../../proxy_service.md).
diff --git a/docs-internal/node-logic-flows/document/textChunker.md b/docs-internal/node-logic-flows/document/textChunker.md
new file mode 100644
index 00000000..effe2722
--- /dev/null
+++ b/docs-internal/node-logic-flows/document/textChunker.md
@@ -0,0 +1,108 @@
+# Text Chunker (`textChunker`)
+
+| Field | Value |
+|------|-------|
+| **Category** | document |
+| **Frontend definition** | [`client/src/nodeDefinitions/documentNodes.ts`](../../../client/src/nodeDefinitions/documentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/document.py::handle_text_chunker`](../../../server/services/handlers/document.py) |
+| **Tests** | [`server/tests/nodes/test_document.py`](../../../server/tests/nodes/test_document.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Split documents into overlapping text chunks suitable for embedding. Uses
+LangChain's `RecursiveCharacterTextSplitter` (default) or
+`MarkdownTextSplitter` for structure-aware splitting of Markdown content.
+Typically sits between `documentParser` and `embeddingGenerator` in a RAG
+pipeline.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Provides `documents[]` upstream |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `documents` | array | `[]` | yes | - | List of `{content, source}` dicts (or raw strings) |
+| `chunkSize` | number | `1024` | no | - | Max chars per chunk (100-8000) |
+| `chunkOverlap` | number | `200` | no | - | Char overlap between adjacent chunks (0-1000) |
+| `strategy` | options | `recursive` | no | - | `recursive` / `markdown` (token strategy is documented but falls through to recursive) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `chunks`, `chunk_count` |
+
+### Output payload
+
+```ts
+{
+ chunks: Array<{
+ source: string; // 'input' when doc was a bare string
+ chunk_index: number; // 0-based within the source doc
+ content: string;
+ length: number;
+ }>;
+ chunk_count: number;
+}
+```
+
+Wrapped in standard envelope: `{ success, result, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_text_chunker] --> B{documents empty?}
+ B -- yes --> Ret0[Return success=true<br/>chunks=[], chunk_count=0]
+ B -- no --> C{strategy}
+ C -- markdown --> Cm[MarkdownTextSplitter]
+ C -- other --> Cr[RecursiveCharacterTextSplitter]
+ Cm --> D[For each doc: extract content + source]
+ Cr --> D
+ D --> E{content truthy?}
+ E -- no --> Eskip[Skip]
+ E -- yes --> F[splitter.split_text -> enumerate chunks]
+ F --> G[Append chunk with source, chunk_index, content, length]
+ G --> H[Return success=true chunks + count]
+ Eskip --> H
+```
+
+## Decision Logic
+
+- **Empty documents**: short-circuits to success with empty `chunks[]`.
+- **Strategy dispatch**: only `markdown` gets the Markdown splitter; anything else (including `token`, `recursive`, typos) uses the recursive splitter.
+- **Doc normalization**: dict -> `(content, source)`; string -> `(str(doc), 'input')`.
+- **Empty content skip**: docs with falsy `content` are silently dropped (not counted, not listed).
+- **Exception path**: any splitter error bubbles to the outer `except` -> `success=false` with the error string.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Python packages**: `langchain-text-splitters>=0.3.0`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `token` strategy is mentioned in the frontend options/description but there is no branch for it; it currently falls through to recursive. Documented gotcha.
+- `chunkSize`/`chunkOverlap` are cast via `int(...)` without clamping - out-of-range values pass through to LangChain and may raise if `overlap >= chunkSize`.
+- Pure function, no randomness - deterministic given the same inputs.
+- Chunks preserve order per-document but there is no global index across documents.
+
+## Related
+
+- **Upstream producer**: [`documentParser`](./documentParser.md) supplies `documents[]`.
+- **Downstream consumer**: [`embeddingGenerator`](./embeddingGenerator.md) consumes `chunks[]`.
diff --git a/docs-internal/node-logic-flows/document/vectorStore.md b/docs-internal/node-logic-flows/document/vectorStore.md
new file mode 100644
index 00000000..ff01c721
--- /dev/null
+++ b/docs-internal/node-logic-flows/document/vectorStore.md
@@ -0,0 +1,141 @@
+# Vector Store (`vectorStore`)
+
+| Field | Value |
+|------|-------|
+| **Category** | document |
+| **Frontend definition** | [`client/src/nodeDefinitions/documentNodes.ts`](../../../client/src/nodeDefinitions/documentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/document.py::handle_vector_store`](../../../server/services/handlers/document.py) |
+| **Tests** | [`server/tests/nodes/test_document.py`](../../../server/tests/nodes/test_document.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Store, query, or delete embedding vectors in one of three vector database
+backends: ChromaDB (local persistent, default), Qdrant (self-hosted or cloud),
+or Pinecone (managed cloud). Acts as the final stage of the RAG indexing
+pipeline and/or the retrieval stage at query time.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Provides `embeddings` + `chunks` from `embeddingGenerator` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `operation` | options | `store` | no | - | `store` / `query` / `delete` |
+| `backend` | options | `chroma` | no | - | `chroma` / `qdrant` / `pinecone` |
+| `collectionName` | string | `documents` | no | - | Collection / index name |
+| `embeddings` | array | `[]` | yes (store) | `operation=store` | Vectors from `embeddingGenerator` |
+| `chunks` | array | `[]` | no (store) | `operation=store` | Metadata pairs for the vectors |
+| `queryEmbedding` | array | `[]` | yes (query) | `operation=query` | Single vector to query |
+| `topK` | number | `5` | no | `operation=query` | Max matches to return |
+| `ids` | array | `[]` | yes (delete) | `operation=delete` | Vector IDs to delete |
+| `persistDir` | string | `./data/vectors` | no | `backend=chroma` | ChromaDB persistence dir |
+| `qdrantUrl` | string | `http://localhost:6333` | no | `backend=qdrant` | Qdrant URL |
+| `pineconeApiKey` | string | `""` | yes | `backend=pinecone` | Pinecone API key |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation-specific payload + `backend` + `collection_name` |
+
+### Output payload
+
+Store:
+```ts
+{ stored_count: number; collection_count?: number; backend: string; collection_name: string; }
+```
+
+Query:
+```ts
+{
+ matches: Array<{
+ id: string;
+ document: string; // extracted content
+ metadata: object;
+ distance?: number; // chroma
+ score?: number; // qdrant, pinecone
+ }>;
+ backend: string;
+ collection_name: string;
+}
+```
+
+Delete:
+```ts
+{ deleted: true; count: number; backend: string; collection_name: string; }
+```
+
+Wrapped in standard envelope: `{ success, result, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_vector_store] --> B{backend}
+ B -- chroma --> C1[_chroma_op]
+ B -- qdrant --> C2[_qdrant_op]
+ B -- pinecone --> C3[_pinecone_op]
+ B -- other --> Ex[raise ValueError Unknown backend]
+ C1 --> D{operation}
+ C2 --> D
+ C3 --> D
+ D -- store --> Ds[Auto-create collection if needed<br/>generate uuid ids + metas<br/>upsert via asyncio.to_thread]
+ D -- query --> Dq[query / search with queryEmbedding + topK<br/>normalize matches across backends]
+ D -- delete --> Dd[delete by ids, count = len(ids)]
+ Ds --> E[Return partial result]
+ Dq --> E
+ Dd --> E
+ E --> F[Attach backend + collection_name]
+ F --> G[Return success=true envelope]
+```
+
+## Decision Logic
+
+- **Backend dispatch**: `chroma` / `qdrant` / `pinecone` - anything else raises `ValueError` caught as `success=false`.
+- **Empty embeddings (store)**: returns `stored_count=0` without raising; for Chroma also returns current `collection_count`.
+- **Empty queryEmbedding (query)**: returns `matches=[]` without hitting the backend.
+- **Empty ids (delete)**: returns `deleted=true, count=0` without hitting the backend.
+- **Collection auto-creation**:
+ - Chroma: `get_or_create_collection` always.
+ - Qdrant: existence check via `get_collections()`; created with `Distance.COSINE` and vector size inferred from first embedding.
+ - Pinecone: assumed pre-existing; `pc.Index(collection)` is called unconditionally.
+- **Metadata padding (Chroma)**: `docs` and `metas` are right-padded when `chunks` is shorter than `embeddings` so `coll.add` gets matching lengths.
+- **ID generation**: random `uuid.uuid4()` per vector. Store is not idempotent; re-running a store op writes duplicates.
+
+## Side Effects
+
+- **Database writes**: writes into the selected vector DB (Chroma files, Qdrant collection, Pinecone index).
+- **Broadcasts**: none.
+- **External API calls**:
+ - Chroma: none (local).
+ - Qdrant: HTTP to `qdrantUrl`.
+ - Pinecone: HTTPS to Pinecone API.
+- **File I/O**: Chroma persists to `persistDir` (SQLite + parquet by default).
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `pineconeApiKey` node parameter (Pinecone only). Not fetched from `auth_service`.
+- **Python packages**: `chromadb>=0.5.0`, `qdrant-client>=1.12.0`, `pinecone` (all lazy-imported per backend).
+- **Environment variables**: none (Qdrant URL is a param, Pinecone key is a param).
+
+## Edge cases & known limits
+
+- Every `store` call generates fresh UUIDs - there is no upsert-by-key; re-indexing the same chunk creates duplicates.
+- Chroma is the only backend that returns `collection_count` after a store.
+- Qdrant collection creation infers the vector size from the first embedding; mixed-size batches will be rejected by Qdrant on upsert.
+- Pinecone `pc.Index(collection)` does not create the index - it must exist, or the op fails with Pinecone's own error.
+- Pinecone `apiKey` is a node parameter, inconsistent with other cloud services that pull from `auth_service`.
+- Delete is by ID only - no metadata-filter delete.
+- Query match shape differs per backend: Chroma returns `distance`, Qdrant and Pinecone return `score`. Downstream consumers must handle both.
+
+## Related
+
+- **Upstream producer**: [`embeddingGenerator`](./embeddingGenerator.md) supplies `embeddings` + `chunks`.
+- **Architecture docs**: none (there is no dedicated RAG architecture doc yet).
diff --git a/docs-internal/node-logic-flows/email/emailRead.md b/docs-internal/node-logic-flows/email/emailRead.md
new file mode 100644
index 00000000..2030c48e
--- /dev/null
+++ b/docs-internal/node-logic-flows/email/emailRead.md
@@ -0,0 +1,146 @@
+# Email Read (`emailRead`)
+
+| Field | Value |
+|------|-------|
+| **Category** | email / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/emailNodes.ts`](../../../client/src/nodeDefinitions/emailNodes.ts) |
+| **Backend handler** | [`server/services/handlers/email.py::handle_email_read`](../../../server/services/handlers/email.py) |
+| **Tests** | [`server/tests/nodes/test_email.py`](../../../server/tests/nodes/test_email.py) |
+| **Skill (if any)** | none shipped |
+| **Dual-purpose tool** | yes - connect to `input-tools` as the node's own name |
+
+## Purpose
+
+Read and manage IMAP mail via the `himalaya` CLI: list envelopes, search,
+fetch a full message, list folders, move/delete, and add/remove flags. One
+node exposes seven operations selected by the `operation` parameter.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `provider` | options | `gmail` | no | - | Preset key in `email_providers.json` |
+| `operation` | options | `list` | **yes** | - | `list` / `search` / `read` / `folders` / `move` / `delete` / `flag` |
+| `folder` | string | `INBOX` | no | show for all except `folders` | IMAP folder name |
+| `query` | string | `""` | **yes** (`search`) | `operation: ['search']` | Himalaya search expression, e.g. `from:x subject:y` |
+| `message_id` | string | `""` | **yes** for `read`/`move`/`delete`/`flag` | `operation: ['read','move','delete','flag']` | IMAP message UID |
+| `target_folder` | string | `""` | **yes** (`move`) | `operation: ['move']` | Destination folder for `move` |
+| `flag` | options | `Seen` | no | `operation: ['flag']` | One of `Seen` / `Answered` / `Flagged` / `Draft` / `Deleted` |
+| `flag_action` | options | `add` | no | `operation: ['flag']` | `add` or `remove` |
+| `page` | number | `1` | no | `operation: ['list']` | 1-based page number |
+| `page_size` | number | `20` | no | `operation: ['list']` | 1-100 envelopes per page |
+
+Credential params (`email`, `password`, `imap_host`, etc.) follow the same
+resolution rules as [`emailSend`](./emailSend.md#decision-logic).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation result |
+| `output-tool` | object | Same payload, used when wired as an AI tool |
+
+### Output payload
+
+```ts
+{
+ operation: string; // echoed from params
+ folder: string; // echoed from params
+ // When Himalaya returns a JSON object, its keys are merged in:
+ ...dictFromHimalaya;
+ // When Himalaya returns a list (e.g. list/search envelopes), it's wrapped:
+ data?: unknown;
+ // When stdout isn't JSON, HimalayaService falls back to:
+ raw_output?: string;
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_email_read] --> B[EmailService.read params]
+ B --> C[resolve_credentials]
+ C -->|missing email/password| Ec[ValueError -> error envelope]
+ C --> D{operation in router?}
+ D -- no --> En[ValueError: Unknown operation -> error envelope]
+ D -- yes --> E[Dispatch to HimalayaService method]
+ E --> F[ensure_binary + write TOML config tempfile]
+ F -->|missing| Eb[RuntimeError -> error envelope]
+ F --> G[subprocess: himalaya -c cfg -a acct --output json ...<br/>timeout 60s]
+ G -->|returncode != 0| Er[RuntimeError: himalaya error ... -> error envelope]
+ G --> H[json.loads stdout; fallback {raw_output: str}]
+ H --> I[Merge operation + folder into result]
+ I --> J[Return success envelope]
+```
+
+## Decision Logic
+
+- **Operation router** in `EmailService.read` maps each operation to a
+ `HimalayaService` method + kwargs. See the table in the handler:
+
+ | operation | Himalaya subcommand |
+ |-----------|---------------------|
+ | `list` | `envelope list -f <folder> --page <page> --page-size <n>` |
+ | `search` | `envelope list -f <folder> --query <query>` |
+ | `read` | `message read <id> -f <folder>` |
+ | `folders` | `folder list` |
+ | `move` | `message move <id> <target_folder> -f <folder>` |
+ | `delete` | `message delete <id> -f <folder>` |
+ | `flag` | `flag add|remove <id> --flag <flag> -f <folder>` |
+
+- **Unknown operation** raises `ValueError("Unknown operation: ...")` before
+ any subprocess is spawned.
+- **Missing required params for an operation are not pre-validated** - e.g.
+ calling `read` without `message_id` passes an empty string to Himalaya,
+ which returns a non-zero exit code and produces a generic error envelope.
+- **Result shape depends on Himalaya output**:
+ - Dict stdout (most commands) -> merged into `{operation, folder, ...}`.
+ - List stdout -> wrapped as `{operation, folder, data: [...]}`.
+ - Non-JSON stdout -> `HimalayaService.execute` returns `{raw_output: str}`
+ which is then merged into `{operation, folder, raw_output}`.
+- **`folders` operation** ignores `folder`, but the echoed value will still be
+ whatever the caller passed (defaulting to `INBOX`).
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none direct - IMAP traffic flows through Himalaya.
+- **File I/O**: one `himalaya_*.toml` tempfile per call (containing the
+ plaintext password), deleted in `finally`.
+- **Subprocess**: one `himalaya` invocation per call with 60s timeout.
+
+## External Dependencies
+
+- **Binary**: `himalaya` on `PATH`.
+- **Credentials**: same as [`emailSend`](./emailSend.md#external-dependencies).
+- **Config**: `server/config/email_providers.json`.
+- **Python packages**: stdlib only.
+
+## Edge cases & known limits
+
+- **Page-size clamp is frontend-only**: the node def caps `page_size` at 100,
+ but the backend passes whatever value arrives. Requesting 10000 will hit
+ the IMAP server's own limits.
+- **No pagination metadata**: `list` returns whatever Himalaya gives; there
+ is no `has_more` / `total` helper.
+- **Deletion is permanent** (no undo), and the handler does not prompt or
+ double-check. This is particularly load-bearing when used as an AI tool.
+- **Search syntax** is Himalaya's, not RFC 3501 IMAP SEARCH; queries are
+ passed through verbatim.
+- **Plaintext password on disk** for the tempfile window (inherited from
+ `HimalayaService.execute`).
+
+## Related
+
+- **Companion nodes**: [`emailSend`](./emailSend.md), [`emailReceive`](./emailReceive.md)
+- **Architecture docs**: [Email Service](../../email_service.md)
diff --git a/docs-internal/node-logic-flows/email/emailReceive.md b/docs-internal/node-logic-flows/email/emailReceive.md
new file mode 100644
index 00000000..839a0a25
--- /dev/null
+++ b/docs-internal/node-logic-flows/email/emailReceive.md
@@ -0,0 +1,146 @@
+# Email Receive (`emailReceive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | email / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/emailNodes.ts`](../../../client/src/nodeDefinitions/emailNodes.ts) |
+| **Backend handler** | [`server/services/handlers/email.py::handle_email_receive`](../../../server/services/handlers/email.py) |
+| **Tests** | [`server/tests/nodes/test_email.py`](../../../server/tests/nodes/test_email.py) |
+| **Skill (if any)** | none shipped |
+| **Dual-purpose tool** | no (trigger only) |
+
+## Purpose
+
+Polling-based trigger that fires when a new email lands in a watched IMAP
+folder. The first poll establishes a baseline (so existing mail is not
+replayed), then subsequent polls diff message IDs to detect arrivals.
+Mirrors the `gmailReceive` pattern but works against any IMAP provider via
+Himalaya.
+
+## Inputs (handles)
+
+None. Triggers have no inputs.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `provider` | options | `gmail` | no | - | Preset key in `email_providers.json` |
+| `folder` | string | `INBOX` | no | - | IMAP folder to watch |
+| `poll_interval` | number | `60` | no | - | Seconds between polls. Clamped to `[min_interval, max_interval]` from config (30-3600) |
+| `filter_query` | string | `""` | no | - | Reserved, currently not applied during polling |
+| `mark_as_read` | boolean | `false` | no | - | When true, adds the `Seen` flag to the new message after fetch |
+
+Credential params (`email`, `password`, `imap_*`, `smtp_*`) follow the same
+resolution rules as [`emailSend`](./emailSend.md#decision-logic).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Details of the first new message detected |
+
+### Output payload
+
+```ts
+{
+ message_id: string;
+ folder: string;
+ // plus any keys returned by `himalaya message read <id>`:
+ // from, to, subject, date, body, ...
+ raw?: unknown; // set if Himalaya output was a list/non-dict
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_email_receive] --> B[resolve_credentials]
+ B -->|ValueError| Ec[error envelope]
+ B --> C[resolve_poll_params]
+ C --> D[broadcaster.update_node_status waiting]
+ D --> E[poll_ids baseline -> seen set]
+ E --> F[Sleep poll_interval seconds]
+ F --> G[poll_ids again -> new = current - seen]
+ G -->|empty| F
+ G -->|non-empty| H[pick first new id<br/>update seen]
+ H --> I[fetch_detail: himalaya message read id]
+ I --> J{mark_as_read?}
+ J -- yes --> K[himalaya flag add Seen id]
+ J -- no --> L[skip]
+ K --> M[event_waiter.dispatch email_received]
+ L --> M
+ M --> N[Return success envelope]
+```
+
+## Decision Logic
+
+- **Baseline-before-poll** prevents existing emails from triggering the
+ workflow on first run. The baseline is an in-memory `set` of envelope IDs
+ (via `EmailService.poll_ids` -> Himalaya `envelope list`, `baseline_page_size=50`).
+- **Interval clamping** in `EmailService.resolve_poll_params`:
+ `max(min_interval, min(max_interval, requested))`. Defaults come from
+ `email_providers.json -> polling` block.
+- **One event per handler run**: as soon as any new IDs are seen, the handler
+ fetches the *first* of them, dispatches a single `email_received` event,
+ and returns. Remaining new IDs are added to `seen` but not processed;
+ they will be skipped on the next run because they are now considered
+ baseline.
+- **`filter_query` is unused in polling**: the parameter appears in the UI
+ and is documented in the node description, but `poll_ids` does not pass
+ it to `list_envelopes`. This is a known gap; see Edge cases.
+- **`mark_as_read` flagging**: uses `defaults.flag` (`Seen`) +
+ `defaults.flag_action` (`add`) - the UI exposes per-node flag/flag_action
+ parameters on `emailRead`, but `emailReceive` does not.
+- **Cancellation**: `asyncio.CancelledError` is caught and returned as a
+ "Cancelled by user" error envelope.
+
+## Side Effects
+
+- **Database writes**: none directly. (The `event_waiter.dispatch` side is
+ in-memory only - no DB row is written for the event.)
+- **Broadcasts**: one `update_node_status(..., "waiting", ...)` when polling
+ starts, with `workflow_id` from context.
+- **Event bus**: `event_waiter.dispatch("email_received", email_data)` fires
+ once per handler run. Downstream trigger consumers (e.g. another
+ `emailReceive` listener) receive this payload.
+- **External API calls**: none direct - IMAP traffic flows through Himalaya.
+- **File I/O**: one `himalaya_*.toml` tempfile per subprocess call (baseline,
+ each poll, fetch, flag). Each is deleted in `finally`.
+- **Subprocess**: multiple `himalaya` invocations per run: 1 baseline + N
+ poll cycles (one per `poll_interval`) + 1 message-read + optional 1 flag.
+
+## External Dependencies
+
+- **Binary**: `himalaya` on `PATH`.
+- **Credentials**: same as [`emailSend`](./emailSend.md#external-dependencies).
+- **Services**: `StatusBroadcaster` (for the waiting status),
+ `event_waiter` (for dispatch).
+- **Config**: `server/config/email_providers.json -> polling`.
+
+## Edge cases & known limits
+
+- **`filter_query` parameter is a no-op**: it is collected but never passed
+ to Himalaya during polling. Users expecting filtering at the IMAP level
+ will be surprised.
+- **Missed messages when > 1 arrive per poll**: only the *first* new ID is
+ fetched and emitted; others are absorbed into `seen` and never processed.
+ If a workflow needs to process every incoming mail it must run fast
+ enough that each poll sees at most one new message, or be rebuilt to loop.
+- **No persistence of `seen`**: restarting the process resets the baseline,
+ so any mail that arrived while offline is treated as pre-existing.
+- **IMAP UID reuse**: `poll_ids` uses `id` or `uid` from the envelope.
+ Some servers recycle UIDs across folders; moving a message between
+ folders can theoretically present a new ID that was `seen` elsewhere.
+- **Plaintext password on disk** per subprocess call (inherited from
+ `HimalayaService.execute`).
+- **Poll timeout pressure**: each Himalaya call has a 60s hard timeout; a
+ slow IMAP server can stall the loop. There is no per-call retry.
+
+## Related
+
+- **Companion nodes**: [`emailSend`](./emailSend.md), [`emailRead`](./emailRead.md)
+- **Architecture docs**: [Email Service](../../email_service.md), [Event Waiter System](../../event_waiter_system.md)
diff --git a/docs-internal/node-logic-flows/email/emailSend.md b/docs-internal/node-logic-flows/email/emailSend.md
new file mode 100644
index 00000000..52fa9bd0
--- /dev/null
+++ b/docs-internal/node-logic-flows/email/emailSend.md
@@ -0,0 +1,152 @@
+# Email Send (`emailSend`)
+
+| Field | Value |
+|------|-------|
+| **Category** | email / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/emailNodes.ts`](../../../client/src/nodeDefinitions/emailNodes.ts) |
+| **Backend handler** | [`server/services/handlers/email.py::handle_email_send`](../../../server/services/handlers/email.py) |
+| **Tests** | [`server/tests/nodes/test_email.py`](../../../server/tests/nodes/test_email.py) |
+| **Skill (if any)** | none shipped |
+| **Dual-purpose tool** | yes - connect to `input-tools` as the node's own name |
+
+## Purpose
+
+Send an email over SMTP via the bundled [Himalaya](https://github.com/pimalaya/himalaya)
+CLI. Works with any IMAP/SMTP provider; Gmail, Outlook/O365, Yahoo, iCloud,
+ProtonMail (Bridge), Fastmail and custom/self-hosted are provided as built-in
+presets (see `server/config/email_providers.json`). When wired to an AI agent's
+`input-tools` handle the LLM fills the same parameter schema.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `provider` | options | `gmail` | no | - | One of `gmail` / `outlook` / `yahoo` / `icloud` / `protonmail` / `fastmail` / `custom`. Picks the preset in `email_providers.json` |
+| `to` | string | `""` | **yes** | - | Comma-separated recipient list |
+| `subject` | string | `""` | **yes** | - | Email subject line |
+| `body` | string | `""` | **yes** | - | Email body (plain text or HTML, see `body_type`) |
+| `cc` | string | `""` | no | - | CC recipients, only added if truthy |
+| `bcc` | string | `""` | no | - | BCC recipients, only added if truthy |
+| `body_type` | options | `text` | no | - | `text` or `html`. HTML sends a `multipart/alternative` MIME message |
+
+Also resolved at runtime (not node-exposed):
+- `email` / `password` / `display_name` - from node params OR stored `email_address` / `email_password` / `email_display_name` API keys.
+- `imap_*` / `smtp_*` - from node params OR preset OR stored custom keys (see Decision Logic).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Himalaya send result merged with `from` (sender address) |
+| `output-tool` | object | Same payload, used when wired as an AI tool |
+
+### Output payload
+
+```ts
+{
+ from: string; // resolved sender address from credentials
+ // plus whatever keys Himalaya's `message send` command returns (often {} on success)
+ raw_output?: string; // present when Himalaya stdout is non-JSON
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time: number, node_id, node_type, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_email_send] --> B[EmailService.send params]
+ B --> C[resolve_credentials]
+ C -->|no email/password| Ee[ValueError -> error envelope]
+ C --> D[Merge with provider preset from email_providers.json]
+ D --> E[HimalayaService.send_email]
+ E --> F[Build MIME message text or multipart/alternative]
+ F --> G[ensure_binary: which himalaya]
+ G -->|missing| Eb[RuntimeError -> error envelope]
+ G --> H[Write TOML config to tempfile]
+ H --> I[subprocess: himalaya -c cfg -a acct message send<br/>stdin = MIME bytes, timeout 60s]
+ I -->|returncode != 0| Er[RuntimeError -> error envelope]
+ I --> J[Parse JSON stdout or wrap as raw_output]
+ J --> K[tempfile unlinked in finally]
+ K --> L[Merge from into result]
+ L --> M[Return success envelope]
+```
+
+## Decision Logic
+
+- **Credential precedence (per field)** in `EmailService.resolve_credentials`:
+ 1. Node parameter (e.g. `imap_host` on the node).
+ 2. Provider preset from `email_providers.json` (e.g. `gmail` -> `imap.gmail.com`).
+ 3. Stored custom API key (`email_imap_host`, `email_imap_port`, etc.). Only
+ reached when the preset field is empty, which in practice means
+ `provider == 'custom'`.
+- **Port coercion**: stored ports are strings in the API-key store; `_coerce_port`
+ casts them to `int` and silently returns `None` on invalid values.
+- **Missing email/password**: `resolve_credentials` raises `ValueError` before
+ any subprocess is spawned -> `handle_email_send` catches and returns
+ `success=false`.
+- **HTML vs plain**: `body_type == 'html'` -> `multipart/alternative` with an
+ HTML part (no plain-text fallback part is attached). Anything else -> a
+ single `text/plain` part.
+- **CC/BCC headers**: only set when the parameter is truthy. BCC is added as a
+ header (visible in the composed MIME) - Himalaya is responsible for stripping
+ it before sending.
+- **Account name**: derived from the email local-part via
+ `HimalayaService._account_name` (`[email protected]` -> `john_doe`). Dots and
+ `+` are replaced with `_`.
+- **Subprocess errors**: non-zero returncode raises `RuntimeError("himalaya
+ error: <stderr>")`; the handler's `except Exception` catches and emits an
+ error envelope.
+
+## Side Effects
+
+- **Database writes**: none (no API usage tracking for email).
+- **Broadcasts**: none.
+- **External API calls**: none direct - SMTP traffic is handled entirely by
+ the `himalaya` binary.
+- **File I/O**:
+ - Writes a Himalaya TOML config (containing the plaintext password) to a
+ `NamedTemporaryFile` prefixed `himalaya_` in the OS temp dir.
+ - Unlinks the tempfile in the `finally` block of `HimalayaService.execute`.
+- **Subprocess**: spawns `himalaya -c <tmpfile> -a <account> --output json message send`
+ with the composed MIME message on stdin; timeout 60s.
+
+## External Dependencies
+
+- **Binary**: `himalaya` must be on `PATH`. Detected via `shutil.which` and
+ cached on `HimalayaService._binary_path`.
+- **Credentials**: `auth_service.get_api_key('email_address')`,
+ `get_api_key('email_password')`, and (for `provider='custom'`) the six
+ custom host/port/encryption keys. All optional if their values are passed
+ directly as node parameters.
+- **Config**: `server/config/email_providers.json` for presets and defaults.
+- **Python packages**: stdlib only (`asyncio`, `email.mime.*`, `tempfile`, `shutil`).
+
+## Edge cases & known limits
+
+- **Credentials hit the filesystem**: the generated TOML contains the raw
+ password in plaintext on disk for the duration of the subprocess call. Best-
+ effort cleanup happens in `finally`, but a crash between `tmp.flush()` and
+ `unlink` can leave it behind.
+- **No retry / idempotency**: a transient SMTP failure returns `success=false`
+ and the caller must re-run the node; there is no queue.
+- **Body escaping**: values are not escaped when formatted into the TOML
+ config. A password or host containing `"` would produce invalid TOML and a
+ confusing `himalaya error` string.
+- **60s hard timeout**: SMTP sends that exceed 60 seconds raise
+ `asyncio.TimeoutError` from `HimalayaService.execute` (not caught as a
+ special case) and surface as a generic error envelope.
+- **No attachments**: the current handler only composes a single text or HTML
+ part; attachments are not supported.
+
+## Related
+
+- **Companion nodes**: [`emailRead`](./emailRead.md), [`emailReceive`](./emailReceive.md)
+- **Architecture docs**: [Email Service](../../email_service.md), [Credentials Encryption](../../credentials_encryption.md)
diff --git a/docs-internal/node-logic-flows/google_workspace/calendar.md b/docs-internal/node-logic-flows/google_workspace/calendar.md
new file mode 100644
index 00000000..6509fe01
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/calendar.md
@@ -0,0 +1,155 @@
+# Calendar (`calendar`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/calendar.py::handle_google_calendar`](../../../server/services/handlers/calendar.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | [`server/skills/productivity_agent/calendar-skill/SKILL.md`](../../../server/skills/productivity_agent/calendar-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `calendar` |
+
+## Purpose
+
+Consolidated Google Calendar node covering create, list, update, delete
+operations on calendar events. Uses Google Calendar API v3. One node, four
+operations switched via the `operation` parameter.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+Top-level dispatcher: `operation` (one of `create`, `list`, `update`, `delete`).
+
+### `operation = create`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `title` | string | `""` | **yes** | Event summary |
+| `start_time` | string | `""` | **yes** | ISO 8601 datetime |
+| `end_time` | string | `""` | **yes** | ISO 8601 datetime |
+| `description` | string | `""` | no | Event description |
+| `location` | string | `""` | no | Location text |
+| `attendees` | string | `""` | no | Comma-separated emails |
+| `reminder_minutes` | number | `30` | no | Popup reminder lead time |
+| `calendar_id` | string | `primary` | no | Target calendar |
+| `timezone` | string | `UTC` | no | Event timezone |
+
+### `operation = list`
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `start_date` | string | today 00:00Z | ISO or `today` |
+| `end_date` | string | now+7d | ISO, `today+Nd`, or ISO string |
+| `max_results` | number | `10` | Clamped to `min(value, 250)` |
+| `calendar_id` | string | `primary` | - |
+| `single_events` | boolean | `true` | Expand recurrences |
+| `order_by` | options | `startTime` | `startTime` or `updated` |
+
+### `operation = update`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `event_id` | string | `""` | **yes** | Event to update |
+| `title` / `start_time` / `end_time` / `description` / `location` | string | `""` | no | Patch fields |
+| `calendar_id` | string | `primary` | no | - |
+
+Also accepts `update_title`, `update_start_time`, etc. which the dispatcher
+aliases onto the standard names.
+
+### `operation = delete`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `event_id` | string | `""` | **yes** | Event to delete |
+| `calendar_id` | string | `primary` | no | - |
+| `send_updates` | options | `all` | no | `all` or `none` - cancellation emails |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation-specific payload |
+| `output-tool` | object | Same, for AI tool wiring |
+
+- `create` / `update`: `{event_id, title, start, end, html_link, status, created?/updated?}`
+- `list`: `{events: [{event_id, title, start, end, description, location, status, html_link, attendees}], count, time_range: {start, end}}`
+- `delete`: `{deleted: true, event_id}`
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_google_calendar] --> AL{operation == update?}
+ AL -- yes --> AM[Alias update_* params<br/>to standard names]
+ AL -- no --> B
+ AM --> B{operation?}
+ B -- create --> C1[handle_calendar_create]
+ B -- list --> C2[handle_calendar_list]
+ B -- update --> C3[handle_calendar_update]
+ B -- delete --> C4[handle_calendar_delete]
+ B -- unknown --> Eret[success=false<br/>Unknown Calendar operation]
+ C1 --> G[get_google_credentials + build v3]
+ C2 --> G
+ C3 --> G
+ C4 --> G
+ G -- ValueError --> Eret
+ C1 --> V1{title & start & end present?}
+ V1 -- no --> Eret
+ V1 -- yes --> R1[events.insert sendUpdates=all]
+ C2 --> DP[Parse date shortcuts:<br/>today / today+Nd]
+ DP --> R2[events.list timeMin/timeMax]
+ C3 --> V3{event_id?}
+ V3 -- no --> Eret
+ V3 -- yes --> G3[events.get -> merge updates -> events.update]
+ C4 --> V4{event_id?}
+ V4 -- no --> Eret
+ V4 -- yes --> R4[events.delete sendUpdates]
+ R1 --> T[_track_calendar_usage]
+ R2 --> T
+ G3 --> T
+ R4 --> T
+ T --> OUT[Return success envelope]
+```
+
+## Decision Logic
+
+- **Date shortcut parsing** (list): `start_date` of `today` or empty -> today 00:00 UTC; `end_date` starting with `today+` is `today + Nd`; otherwise the raw string is used and `Z` is appended if missing.
+- **Timezone fallback** (update): when updating start/end, the existing event's `timeZone` is reused; if absent falls back to `UTC`.
+- **Update parameter aliasing**: the dispatcher copies `update_title`, `update_start_time`, `update_end_time`, `update_description`, `update_location` onto their plain names before delegating - this is irreversible mutation of the incoming `parameters` dict.
+- **Description / location**: treated as `is not None` rather than truthy - empty string is a valid clear.
+- **Attendees**: empty strings after `split(',')` are filtered; the whole `attendees` field is omitted if the list is empty.
+- **`order_by`**: only sent when `single_events=True`; otherwise `None`, which the Google client library strips.
+
+## Side Effects
+
+- **Database writes**: `api_usage_metrics` row per call via `save_api_usage_metric` with `service='google_calendar'`.
+- **Broadcasts**: none.
+- **External API calls**: Calendar API v3 - `events().insert/list/update/delete/get`. `sendUpdates='all'` on create/update sends email invitations to attendees.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth via `auth_service.get_oauth_tokens("google")`.
+- **Services**: Google Calendar API, `PricingService`, `Database`.
+- **Python packages**: `google-api-python-client`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `max_results` clamped to 250 silently.
+- `update` performs a read-modify-write cycle: two API calls per update. A concurrent modification between the `get` and `update` is overwritten without ETag checking.
+- `delete` with an invalid event_id will surface the `HttpError 404` message into the envelope as a string.
+- The dispatcher mutates the incoming `parameters` dict for update aliasing; callers that reuse the dict will see the aliased fields.
+- `description=""` is treated as a real clear; `description=None` or missing leaves the field untouched. Subtle but load-bearing for update callers.
+
+## Related
+
+- **Skills using this as a tool**: [`calendar-skill/SKILL.md`](../../../server/skills/productivity_agent/calendar-skill/SKILL.md)
+- **Companion nodes**: [`gmail`](./gmail.md), [`drive`](./drive.md), [`sheets`](./sheets.md), [`tasks`](./tasks.md), [`contacts`](./contacts.md)
+- **Architecture docs**: `CLAUDE.md` -> "Google Workspace Nodes".
diff --git a/docs-internal/node-logic-flows/google_workspace/contacts.md b/docs-internal/node-logic-flows/google_workspace/contacts.md
new file mode 100644
index 00000000..473e7546
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/contacts.md
@@ -0,0 +1,193 @@
+# Contacts (`contacts`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/contacts.py::handle_google_contacts`](../../../server/services/handlers/contacts.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | [`server/skills/productivity_agent/contacts-skill/SKILL.md`](../../../server/skills/productivity_agent/contacts-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `contacts` |
+
+## Purpose
+
+Consolidated Google Contacts node backed by the People API v1. One node, six
+operations switched via the `operation` parameter. All payloads are flattened
+through `_format_contact()` into a consistent simplified shape.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+Top-level dispatcher: `operation` (one of `create`, `list`, `search`, `get`, `update`, `delete`).
+
+### `operation = create`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `first_name` | string | `""` | **yes** | Given name |
+| `last_name` | string | `""` | no | Family name |
+| `email` | string | `""` | no | - |
+| `phone` | string | `""` | no | - |
+| `company` | string | `""` | no | Organization name |
+| `job_title` | string | `""` | no | - |
+| `notes` | string | `""` | no | Stored as `biographies` with `contentType: TEXT_PLAIN` |
+
+### `operation = list`
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `page_size` | number | `100` | - |
+| `page_token` | string | `""` | Pagination cursor |
+| `sort_order` | options | `LAST_MODIFIED_DESCENDING` | also `LAST_MODIFIED_ASCENDING`, `FIRST_NAME_ASCENDING`, `LAST_NAME_ASCENDING` |
+
+### `operation = search`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `query` | string | `""` | **yes** | Name/email/phone fragment |
+| `page_size` | number | `30` | no | - |
+
+### `operation = get`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `resource_name` | string | `""` | **yes** | e.g. `people/c12345678` |
+
+### `operation = update`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `resource_name` | string | `""` | **yes** | - |
+| `first_name` / `last_name` / `email` / `phone` / `company` / `job_title` | string | `""` | no | Any provided field triggers its person field group to be replaced. **At least one patch field required.** |
+
+Also accepts `update_first_name`, `update_last_name`, `update_email`,
+`update_phone`, `update_company`, `update_job_title` aliases.
+
+### `operation = delete`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `resource_name` | string | `""` | **yes** | - |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Formatted contact(s) payload |
+| `output-tool` | object | Same, for AI tool wiring |
+
+### Formatted contact shape (`_format_contact`)
+
+```ts
+{
+ resource_name: string;
+ display_name: string;
+ given_name: string;
+ family_name: string;
+ email: string; // primary
+ phone: string; // primary
+ company: string;
+ job_title: string;
+ photo_url: string;
+ emails: string[];
+ phones: string[];
+}
+```
+
+- `list`: `{contacts: [...], count, total_people, next_page_token}`
+- `search`: `{contacts: [...], count}`
+- `delete`: `{deleted: true, resource_name}`
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_google_contacts] --> AL{operation == update?}
+ AL -- yes --> AM[Alias update_* params<br/>to plain names]
+ AL -- no --> B
+ AM --> B{operation?}
+ B -- create --> C1[handle_contacts_create]
+ B -- list --> C2[handle_contacts_list]
+ B -- search --> C3[handle_contacts_search]
+ B -- get --> C4[handle_contacts_get]
+ B -- update --> C5[handle_contacts_update]
+ B -- delete --> C6[handle_contacts_delete]
+ B -- unknown --> Eret[success=false<br/>Unknown Contacts operation]
+ C1 --> G[get_google_credentials + build people v1]
+ C2 --> G
+ C3 --> G
+ C4 --> G
+ C5 --> G
+ C6 --> G
+ G -- ValueError --> Eret
+ C1 --> V1{first_name?}
+ V1 -- no --> Eret
+ V1 -- yes --> BB[Build names/emails/phones<br/>organizations/biographies]
+ BB --> R1[people.createContact]
+ C2 --> R2[people.connections.list<br/>personFields names emails phones<br/>organizations photos biographies]
+ C3 --> V3{query?}
+ V3 -- no --> Eret
+ V3 -- yes --> R3[people.searchContacts]
+ C4 --> V4{resource_name?}
+ V4 -- no --> Eret
+ V4 -- yes --> R4[people.get]
+ C5 --> V5{resource_name?}
+ V5 -- no --> Eret
+ V5 -- yes --> G5[people.get etag -> build update body -> check updatePersonFields non-empty]
+ G5 -- no fields --> Eret2[raise<br/>At least one field to update required]
+ G5 -- ok --> R5[people.updateContact updatePersonFields=csv]
+ C6 --> V6{resource_name?}
+ V6 -- no --> Eret
+ V6 -- yes --> R6[people.deleteContact]
+ R1 --> T[_track_contacts_usage]
+ R2 --> T
+ R3 --> T
+ R4 --> T
+ R5 --> T
+ R6 --> T
+ T --> OUT[Return success envelope]
+```
+
+## Decision Logic
+
+- **Dispatcher aliasing**: `update_*` params are copied over their plain counterparts (mutating input) before delegation.
+- **Update requires etag**: `update` does a `people.get` first to fetch the current etag, then submits `updateContact` with `updatePersonFields` set to the comma-joined list of person field groups touched. If no field group was modified, raises `ValueError("At least one field to update is required")`.
+- **Search requires query**: empty query -> `ValueError` captured by outer except.
+- **Notes field on create**: non-empty `notes` writes a `biographies[0]` entry; empty notes skip the field. Cannot be cleared via update (not wired).
+- **Format fallbacks**: `_format_contact` returns `""` for missing headers rather than `None`, so callers should not distinguish absence from empty.
+- **`list` resource_name** is hard-coded to `people/me` - this node cannot list another user's contacts.
+
+## Side Effects
+
+- **Database writes**: `api_usage_metrics` row per call via `save_api_usage_metric` with `service='google_contacts'`. `list` DOES call `_track_contacts_usage`.
+- **Broadcasts**: none.
+- **External API calls**: People API v1 - `people().createContact/get/updateContact/deleteContact/searchContacts`, `people().connections().list`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth via `auth_service.get_oauth_tokens("google")`.
+- **Services**: Google People API, `PricingService`, `Database`.
+- **Python packages**: `google-api-python-client`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Primary email/phone detection uses `metadata.primary` - contacts with no explicit primary fall back to the first entry in the list, which may not match Google UI's primary.
+- Update replaces entire field groups: passing `email` wipes any additional emails on the contact. The handler does not merge.
+- `search` returns at most `page_size` results; there is no pagination wrapper.
+- `delete` does not prompt or verify - the deletion is immediate and final on Google's side.
+- An unused local statement `person.get('addresses', [])` exists in `_format_contact` without assignment - noted as dead code, not a bug.
+- `update` requires at least one patch field; however the handler only treats first_name/last_name/email/phone/company/job_title. Notes and other fields cannot be updated here.
+
+## Related
+
+- **Skills using this as a tool**: [`contacts-skill/SKILL.md`](../../../server/skills/productivity_agent/contacts-skill/SKILL.md)
+- **Companion nodes**: [`gmail`](./gmail.md), [`calendar`](./calendar.md), [`drive`](./drive.md), [`sheets`](./sheets.md), [`tasks`](./tasks.md)
+- **Architecture docs**: `CLAUDE.md` -> "Google Workspace Nodes".
diff --git a/docs-internal/node-logic-flows/google_workspace/drive.md b/docs-internal/node-logic-flows/google_workspace/drive.md
new file mode 100644
index 00000000..721e9b00
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/drive.md
@@ -0,0 +1,158 @@
+# Drive (`drive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/drive.py::handle_google_drive`](../../../server/services/handlers/drive.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | [`server/skills/productivity_agent/drive-skill/SKILL.md`](../../../server/skills/productivity_agent/drive-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `drive` |
+
+## Purpose
+
+Consolidated Google Drive node for file upload, download, listing, and
+sharing. Uses Drive API v3. One node, four operations switched via the
+`operation` parameter. Handles both remote URL sources (HTTP download then
+re-upload) and base64-inlined content.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+Top-level dispatcher: `operation` (one of `upload`, `download`, `list`, `share`).
+
+### `operation = upload`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `filename` | string | `""` | **yes** | Target filename in Drive |
+| `file_url` | string | `""` | cond. | Source URL (either this or `file_content` required) |
+| `file_content` | string | `""` | cond. | Base64-encoded file bytes |
+| `folder_id` | string | `""` | no | Parent folder; empty = root |
+| `mime_type` | string | `application/octet-stream` | no | MIME type |
+| `description` | string | `""` | no | File description |
+
+### `operation = download`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `file_id` | string | `""` | **yes** | Drive file ID |
+| `output_format` | options | `base64` | no | `base64` returns bytes inline; `url` returns only metadata + download link |
+
+### `operation = list`
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `folder_id` | string | `""` | Parent folder filter |
+| `query` | string | `""` | Drive query DSL |
+| `max_results` | number | `20` | Clamped to `min(value, 1000)` |
+| `file_types` | options | `all` | `all` / `folder` / `document` / `spreadsheet` / `image` |
+| `order_by` | string | `modifiedTime desc` | - |
+
+### `operation = share`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `file_id` | string | `""` | **yes** | File to share |
+| `email` | string | `""` | **yes** | Grantee email |
+| `role` | options | `reader` | no | `reader` / `writer` / `commenter` |
+| `send_notification` | boolean | `true` | no | Send email notification |
+| `message` | string | `""` | no | Custom notification message |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation-specific payload |
+| `output-tool` | object | Same, for AI tool wiring |
+
+- `upload`: `{file_id, name, mime_type, size, web_link, download_link, created_time}`
+- `download` (base64): `{file_id, name, mime_type, size, content_base64}`
+- `download` (url): `{file_id, name, mime_type, size, download_url, web_link}`
+- `list`: `{files: [...], count, next_page_token}`
+- `share`: `{permission_id, file_id, file_name, shared_with, role, web_link}`
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_google_drive] --> B{operation?}
+ B -- upload --> U[handle_drive_upload]
+ B -- download --> D[handle_drive_download]
+ B -- list --> L[handle_drive_list]
+ B -- share --> S[handle_drive_share]
+ B -- unknown --> Eret[success=false<br/>Unknown Drive operation]
+ U --> G[get_google_credentials + build v3]
+ D --> G
+ L --> G
+ S --> G
+ G -- ValueError --> Eret
+ U --> V1{filename &<br/>file_url OR file_content?}
+ V1 -- no --> Eret
+ V1 -- yes --> SRC{file_url set?}
+ SRC -- yes --> H1[httpx.AsyncClient.get<br/>timeout 60s<br/>raise_for_status]
+ SRC -- no --> H2[base64.b64decode file_content]
+ H1 --> M[MediaIoBaseUpload BytesIO<br/>resumable=True]
+ H2 --> M
+ M --> R1[files.create body+media]
+ D --> V2{file_id?}
+ V2 -- no --> Eret
+ V2 -- yes --> M2[files.get metadata]
+ M2 --> OF{output_format == url?}
+ OF -- yes --> OUT[Return metadata + download_url]
+ OF -- no --> DL[MediaIoBaseDownload chunks<br/>base64 encode]
+ L --> QB[Build q from folder_id,<br/>query, file_type filter,<br/>trashed=false]
+ QB --> R3[files.list pageSize]
+ S --> V3{file_id & email?}
+ V3 -- no --> Eret
+ V3 -- yes --> R4[permissions.create +<br/>files.get for name/link]
+ R1 --> T[_track_drive_usage]
+ DL --> T
+ OUT --> T
+ R3 --> T
+ R4 --> T
+ T --> OE[Return success envelope]
+```
+
+## Decision Logic
+
+- **Source dispatch on upload**: `file_url` wins over `file_content`. When using `file_url` and `mime_type` is still the default, the HTTP `Content-Type` header (first token before `;`) is adopted.
+- **Query composition on list**: `q` parts are joined with ` and `; always includes `trashed = false`. File type filters are hard-coded MIME mappings (Docs, Sheets, folders, `image/` prefix).
+- **Download format**: `output_format=='url'` returns metadata only (`webContentLink`) and skips the `MediaIoBaseDownload` chunk loop.
+- **Share**: permission created AND a second `files.get` is issued to fetch the human-readable name + link for the response. Two API calls per share.
+- **HTTP fetch errors**: `httpx.get(...).raise_for_status()` is called - any HTTP error on the source URL propagates into the generic `except Exception` and becomes `error: <str>` in the envelope.
+
+## Side Effects
+
+- **Database writes**: `api_usage_metrics` row per call via `save_api_usage_metric` with `service='google_drive'`.
+- **Broadcasts**: none.
+- **External API calls**: Drive API v3 - `files().create/get/list`, `permissions().create`, `files().get_media`. Plus `httpx.AsyncClient.get(file_url)` on upload-from-URL.
+- **File I/O**: in-memory `io.BytesIO` buffers only; no disk writes.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth via `auth_service.get_oauth_tokens("google")`.
+- **Services**: Google Drive API, `PricingService`, `Database`.
+- **Python packages**: `google-api-python-client`, `httpx`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `max_results` clamped to 1000 silently.
+- Upload downloads `file_url` fully into memory before uploading - not streamed. Large files will OOM the worker.
+- Download with `output_format=url` returns `webContentLink` which requires the caller to authenticate independently; it is NOT a public link.
+- File type filter is a closed list - `file_types='video'` for example is silently ignored (falls through).
+- `share` permission role `owner` is not accepted (People API requires ownership transfer semantics).
+- No ETag or If-Match header on any write - concurrent edits are last-write-wins.
+
+## Related
+
+- **Skills using this as a tool**: [`drive-skill/SKILL.md`](../../../server/skills/productivity_agent/drive-skill/SKILL.md)
+- **Companion nodes**: [`gmail`](./gmail.md), [`calendar`](./calendar.md), [`sheets`](./sheets.md), [`tasks`](./tasks.md), [`contacts`](./contacts.md)
+- **Architecture docs**: `CLAUDE.md` -> "Google Workspace Nodes".
diff --git a/docs-internal/node-logic-flows/google_workspace/gmail.md b/docs-internal/node-logic-flows/google_workspace/gmail.md
new file mode 100644
index 00000000..05e7543b
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/gmail.md
@@ -0,0 +1,142 @@
+# Gmail (`gmail`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/gmail.py::handle_google_gmail`](../../../server/services/handlers/gmail.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | [`server/skills/productivity_agent/gmail-skill/SKILL.md`](../../../server/skills/productivity_agent/gmail-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `gmail` |
+
+## Purpose
+
+Consolidated Gmail node covering send, search, and read operations. Uses the
+Google Gmail API v1 via the official `google-api-python-client`. One node, three
+operations switched via the `operation` parameter. Authenticates through the
+shared `get_google_credentials()` helper that reads OAuth tokens stored via
+`auth_service.store_oauth_tokens("google", ...)`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+Top-level dispatcher: `operation` (one of `send`, `search`, `read`).
+
+### `operation = send`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `to` | string | `""` | **yes** | Recipient email(s), comma-separated |
+| `cc` | string | `""` | no | CC recipients |
+| `bcc` | string | `""` | no | BCC recipients |
+| `subject` | string | `""` | **yes** | Email subject |
+| `body` | string | `""` | **yes** | Email body content |
+| `body_type` | options | `text` | no | `text` or `html` |
+
+### `operation = search`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `query` | string | `""` | **yes** | Gmail search query (same syntax as Gmail web) |
+| `max_results` | number | `10` | no | Clamped to `min(value, 100)` |
+| `include_body` | boolean | `false` | no | If true, fetches `format=full` per message |
+
+### `operation = read`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `message_id` | string | `""` | **yes** | Gmail message ID |
+| `format` | options | `full` | no | `full` / `minimal` / `raw` / `metadata` |
+
+Shared: `account_mode` (default `owner`), `customer_id` (required when
+`account_mode == 'customer'`).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation-specific payload (see below) |
+| `output-tool` | object | Same payload, used when wired to an AI agent `input-tools` |
+
+### Output payloads
+
+- `send`: `{message_id, thread_id, label_ids, to, subject}`
+- `search`: `{messages: [...], count, query, result_size_estimate}` where each
+ message is `{message_id, thread_id, from, to, cc, subject, date, snippet,
+ labels, size_estimate, body?, attachments?}`
+- `read`: formatted message (same shape as a single entry in `search`)
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_google_gmail] --> B{operation?}
+ B -- send --> S1[handle_gmail_send]
+ B -- search --> S2[handle_gmail_search]
+ B -- read --> S3[handle_gmail_read]
+ B -- unknown --> Eret[Return success=false<br/>Unknown Gmail operation: X]
+ S1 --> C1[get_google_credentials]
+ S2 --> C2[get_google_credentials]
+ S3 --> C3[get_google_credentials]
+ C1 -- ValueError --> Eret
+ C2 -- ValueError --> Eret
+ C3 -- ValueError --> Eret
+ C1 --> V1{to/subject/body<br/>all present?}
+ V1 -- no --> Eret
+ V1 -- yes --> B1[Build MIMEText/MIMEMultipart<br/>base64 urlsafe encode]
+ B1 --> R1[service.users.messages.send<br/>run_in_executor]
+ C2 --> V2{query non-empty?}
+ V2 -- no --> Eret
+ V2 -- yes --> R2[service.users.messages.list q=query]
+ R2 --> L2[Loop: users.messages.get per id<br/>format=full if include_body else metadata]
+ C3 --> V3{message_id?}
+ V3 -- no --> Eret
+ V3 -- yes --> R3[service.users.messages.get id=message_id]
+ R1 --> T[_track_gmail_usage -> save_api_usage_metric]
+ L2 --> T
+ R3 --> T
+ T --> OUT[Return success envelope]
+```
+
+## Decision Logic
+
+- **Operation dispatch**: `if/elif` chain in `handle_google_gmail`. Unknown operation returns an error envelope (does NOT raise).
+- **Credential resolution** (`get_google_credentials`): owner mode reads from `auth_service.get_oauth_tokens("google", customer_id="owner")`; customer mode reads from `google_connections` table. Raises `ValueError` if no tokens found.
+- **Proactive refresh**: if the Credentials object reports `expired and not valid` and a `refresh_token` is present, a refresh is attempted in a thread executor; result is persisted via `auth_service.store_oauth_tokens`. Refresh failures are swallowed to DEBUG.
+- **Search body fetching**: `include_body=False` uses `format=metadata` with a fixed header list (`From`, `To`, `Subject`, `Date`); `True` uses `format=full`. Body extraction recurses into multipart payloads; prefers `text/plain` over `text/html`.
+- **Send body type**: `body_type=='html'` -> `MIMEMultipart('alternative')` with an HTML part; otherwise `MIMEText(body, 'plain')`. Message is `urlsafe_b64encode`d to base64.
+- **Error paths**: every sub-handler wraps the whole body in `try/except Exception` and returns `{success: false, error: str(e), execution_time: ...}`.
+
+## Side Effects
+
+- **Database writes**: one row per API call in `api_usage_metrics` via `database.save_api_usage_metric` with `service='gmail'`, `operation=<action>`, `endpoint=<action>`, `resource_count`, `cost` (always 0 for Google APIs).
+- **Broadcasts**: none from the handler itself; `NodeExecutor` emits standard `node_status`.
+- **External API calls**: Gmail API v1 via `googleapiclient.discovery.build("gmail", "v1", creds)` - `users().messages().send/list/get`. Proactive token refresh hits `https://oauth2.googleapis.com/token`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth tokens via `auth_service.get_oauth_tokens("google", customer_id="owner")`; `google_client_id` / `google_client_secret` via `auth_service.get_api_key(...)`.
+- **Services**: Google Gmail API, `PricingService`, `Database`.
+- **Python packages**: `google-auth`, `google-auth-oauthlib`, `google-api-python-client`.
+- **Environment variables**: none (OAuth redirect URI derived from request at auth time).
+
+## Edge cases & known limits
+
+- `max_results` is silently clamped to 100 (hard ceiling).
+- Search fetches every matching message individually in sequence - with `max_results=100` this is 100 round trips. No batching.
+- The proactive refresh path swallows exceptions - if the refresh token has been revoked the handler continues and subsequently fails with a 401-shaped error surfaced as `"<status>"` in the envelope.
+- `_format_message` returns empty strings for missing headers rather than omitting them; callers should not treat `""` as "header was present and empty".
+- `body` is returned as a UTF-8 decoded string with `errors='ignore'` - binary parts may produce partial output without raising.
+
+## Related
+
+- **Skills using this as a tool**: [`gmail-skill/SKILL.md`](../../../server/skills/productivity_agent/gmail-skill/SKILL.md)
+- **Companion nodes**: [`gmailReceive`](./gmailReceive.md), [`calendar`](./calendar.md), [`drive`](./drive.md), [`sheets`](./sheets.md), [`tasks`](./tasks.md), [`contacts`](./contacts.md)
+- **Architecture docs**: `CLAUDE.md` -> "Google Workspace Nodes" and "Encrypted Credentials System".
diff --git a/docs-internal/node-logic-flows/google_workspace/gmailReceive.md b/docs-internal/node-logic-flows/google_workspace/gmailReceive.md
new file mode 100644
index 00000000..278823e3
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/gmailReceive.md
@@ -0,0 +1,129 @@
+# Gmail Receive (`gmailReceive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / trigger (polling) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/gmail.py::handle_gmail_receive`](../../../server/services/handlers/gmail.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Polling-based trigger that fires when a new Gmail message matching a filter
+query arrives. Unlike push-based triggers (webhook, WhatsApp, Telegram) Gmail
+has no official push without extra Pub/Sub setup, so this handler polls
+`users.messages.list` at a configurable interval, diffs IDs against a
+baseline, fetches full details for new messages, and optionally marks them
+as read.
+
+Dispatches a `gmail_email_received` event via `event_waiter.dispatch` so
+deployment-mode listeners can react in parallel.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Not read - this is a trigger |
+
+## Parameters
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `filter_query` | string | `is:unread` | no | Gmail search query (same syntax as Gmail web) |
+| `label_filter` | string | `INBOX` | no | Label name or `all`. When set and not `all`, prepended to query as `label:<name>` |
+| `mark_as_read` | boolean | `false` | no | If true, remove `UNREAD` label from matched message after fetching |
+| `poll_interval` | number | `60` | no | Seconds between polls; clamped to `[10, 3600]` |
+| `account_mode` | options | `owner` | no | Owner or customer OAuth store |
+| `customer_id` | string | `""` | cond. | Required when `account_mode == 'customer'` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Formatted message envelope (the new email) |
+
+### Output payload
+
+```ts
+{
+ message_id: string;
+ thread_id: string;
+ from: string;
+ to: string;
+ cc: string;
+ subject: string;
+ date: string;
+ snippet: string;
+ body: string; // included because format='full'
+ labels: string[];
+ size_estimate: number;
+ attachments?: Array<{ filename, mime_type, size, attachment_id }>;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_gmail_receive] --> B[_get_gmail_service<br/>get_google_credentials + build]
+ B -- ValueError --> Eret[Return success=false<br/>error: str]
+ B -- ok --> C[Clamp poll_interval to 10-3600]
+ C --> D[Compose query:<br/>label:X filter_query]
+ D --> E[broadcaster.update_node_status waiting]
+ E --> F[_poll_gmail_ids -> baseline seen_ids]
+ F -- Exception --> F2[Log warning; treat all as new]
+ F --> L[Loop forever]
+ L --> S[asyncio.sleep poll_interval]
+ S --> P[_poll_gmail_ids -> current_ids]
+ P -- Exception --> P2[Log error; retry next tick]
+ P --> D2{new_ids empty?}
+ D2 -- yes --> S
+ D2 -- no --> N[Pick first new id<br/>seen_ids.update new_ids]
+ N --> F3[_fetch_email_details format=full]
+ F3 --> MAR{mark_as_read?}
+ MAR -- yes --> M1[_mark_email_as_read<br/>removeLabelIds UNREAD]
+ MAR -- no --> M2
+ M1 --> M2[_track_gmail_usage receive]
+ M2 --> EV[event_waiter.dispatch<br/>gmail_email_received email_data]
+ EV --> OUT[Return success=true email_data]
+ L -.-> CX[CancelledError -> return success=false<br/>error: Cancelled by user]
+```
+
+## Decision Logic
+
+- **Query composition**: `label_filter` is only prepended when set AND not equal to the literal `all`. There is no validation that the label exists.
+- **Baseline on startup**: the first `_poll_gmail_ids` call seeds `seen_ids`. If it raises, the set stays empty and the very next poll will treat the entire history as new - the handler logs this as a warning but does not short-circuit.
+- **Per-tick error recovery**: the inner `except Exception` around `_poll_gmail_ids` just logs; the loop keeps running. The outer `except Exception` catches anything leaking out of `_get_gmail_service` / the `while True` and returns an error envelope.
+- **Cancellation**: `asyncio.CancelledError` is caught at both levels. The inner handler re-raises; the outer returns `{success: false, error: "Cancelled by user"}`.
+- **Single-email-per-trigger**: only the first element of `new_ids` (arbitrary `set` iteration order) is processed per invocation - the remaining new IDs are marked seen but not returned. In deployment mode, subsequent events arriving on the same cycle are lost until the next poll.
+
+## Side Effects
+
+- **Database writes**: one `api_usage_metrics` row via `save_api_usage_metric` per email processed (operation `receive`).
+- **Broadcasts**: initial `update_node_status(node_id, "waiting", {...}, workflow_id=...)` via `get_status_broadcaster()`. Event dispatch via `event_waiter.dispatch('gmail_email_received', email_data)`.
+- **External API calls**: repeated `users().messages().list(q=query, maxResults=20)`, one `users().messages().get(format=full)` per new email, optional `users().messages().modify(removeLabelIds=['UNREAD'])`. Token refresh path as per shared helper.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth via `auth_service.get_oauth_tokens("google")`.
+- **Services**: Gmail API v1, `StatusBroadcaster`, `event_waiter`, `PricingService`, `Database`.
+- **Python packages**: `google-auth`, `google-api-python-client`, `asyncio`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `set(new_ids)` iteration order is non-deterministic - if two emails arrive in the same tick, the handler picks one arbitrarily. The others are marked seen and never surfaced by this trigger node (deployment listeners may still see the dispatched event, but only one dispatch is emitted).
+- Baseline is in-memory only - restarting the handler re-walks the latest 20 unread messages as the baseline, so messages that arrived during downtime will not fire this trigger.
+- `mark_as_read` failures are logged and swallowed.
+- `poll_interval` is clamped to `[10, 3600]` - values outside this range are silently coerced.
+- The `maxResults=20` in `_poll_gmail_ids` is hard-coded. Very busy inboxes may see the baseline constantly rolling forward without triggering if more than 20 unread emails arrive between polls (an email that falls off the first page is never seen).
+- Deployment-mode polling (via `POLLING_TRIGGER_TYPES` in `constants.py`) uses a separate coroutine; this handler is the single-run path.
+
+## Related
+
+- **Companion nodes**: [`gmail`](./gmail.md) (send/search/read operations)
+- **Architecture docs**: `CLAUDE.md` -> "Polling Triggers (Gmail, Twitter)" and "Event-Driven Trigger Node System".
diff --git a/docs-internal/node-logic-flows/google_workspace/sheets.md b/docs-internal/node-logic-flows/google_workspace/sheets.md
new file mode 100644
index 00000000..ca64485d
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/sheets.md
@@ -0,0 +1,130 @@
+# Sheets (`sheets`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/sheets.py::handle_google_sheets`](../../../server/services/handlers/sheets.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | [`server/skills/productivity_agent/sheets-skill/SKILL.md`](../../../server/skills/productivity_agent/sheets-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `sheets` |
+
+## Purpose
+
+Consolidated Google Sheets node for reading, writing, and appending cell
+values. Uses Sheets API v4 (`spreadsheets.values` collection). One node,
+three operations switched via the `operation` parameter.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+Top-level dispatcher: `operation` (one of `read`, `write`, `append`).
+
+### `operation = read`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `spreadsheet_id` | string | `""` | **yes** | Sheet ID (from URL) |
+| `range` | string | `""` | **yes** | A1 notation, e.g. `Sheet1!A1:D10` |
+| `value_render_option` | options | `FORMATTED_VALUE` | no | `FORMATTED_VALUE` / `UNFORMATTED_VALUE` / `FORMULA` |
+| `major_dimension` | options | `ROWS` | no | `ROWS` / `COLUMNS` |
+
+### `operation = write`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `spreadsheet_id` | string | `""` | **yes** | - |
+| `range` | string | `""` | **yes** | e.g. `Sheet1!A1` |
+| `values` | array/string | `[]` | **yes** | 2D array, or JSON string that parses to 2D array, or 1D auto-wrapped to 2D |
+| `value_input_option` | options | `USER_ENTERED` | no | `RAW` or `USER_ENTERED` |
+
+### `operation = append`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `spreadsheet_id` | string | `""` | **yes** | - |
+| `range` | string | `""` | **yes** | e.g. `Sheet1!A:D` |
+| `values` | array/string | `[]` | **yes** | Same coercion as write |
+| `value_input_option` | options | `USER_ENTERED` | no | - |
+| `insert_data_option` | options | `INSERT_ROWS` | no | `INSERT_ROWS` / `OVERWRITE` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation-specific payload |
+| `output-tool` | object | Same, for AI tool wiring |
+
+- `read`: `{values: [[...],...], range, rows, columns, major_dimension}`
+- `write` / `append`: `{updated_range, updated_rows, updated_columns, updated_cells, table_range?}`
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_google_sheets] --> B{operation?}
+ B -- read --> R[handle_sheets_read]
+ B -- write --> W[handle_sheets_write]
+ B -- append --> AP[handle_sheets_append]
+ B -- unknown --> Eret[success=false<br/>Unknown Sheets operation]
+ R --> G[get_google_credentials + build v4]
+ W --> G
+ AP --> G
+ G -- ValueError --> Eret
+ R --> V1{spreadsheet_id & range?}
+ V1 -- no --> Eret
+ V1 -- yes --> R1[spreadsheets.values.get<br/>valueRenderOption majorDimension]
+ W --> V2{spreadsheet_id & range & values?}
+ V2 -- no --> Eret
+ V2 -- yes --> C2[Coerce values:<br/>str -> json.loads<br/>1D -> wrap to 2D]
+ C2 --> R2[spreadsheets.values.update<br/>valueInputOption body]
+ AP --> V3{spreadsheet_id & range & values?}
+ V3 -- no --> Eret
+ V3 -- yes --> C3[Same coercion as write]
+ C3 --> R3[spreadsheets.values.append<br/>valueInputOption insertDataOption]
+ R1 --> T[_track_sheets_usage]
+ R2 --> T
+ R3 --> T
+ T --> OUT[Return success envelope]
+```
+
+## Decision Logic
+
+- **Values coercion**: if `values` is a `str`, parsed via `json.loads`. If the (possibly parsed) sequence's first element is not a list, the whole thing is wrapped into `[values]` to guarantee 2D.
+- **Required fields**: each operation has its own validation block; all three require `spreadsheet_id` and `range`, write/append additionally require a non-empty `values`.
+- **Usage tracking count**: read reports `len(values)` rows; write reports `updatedCells`; append reports `updates.updatedCells`. If any field is missing in the response, usage count is 0 (no exception).
+- **JSON parse errors** on `values` propagate into the outer `except Exception` and become `error: "<ValueError str>"`.
+
+## Side Effects
+
+- **Database writes**: `api_usage_metrics` row per call via `save_api_usage_metric` with `service='google_sheets'`.
+- **Broadcasts**: none.
+- **External API calls**: Sheets API v4 - `spreadsheets().values().get/update/append`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth via `auth_service.get_oauth_tokens("google")`.
+- **Services**: Google Sheets API, `PricingService`, `Database`.
+- **Python packages**: `google-api-python-client`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `value_input_option='USER_ENTERED'` means strings like `=SUM(A1:A5)` are evaluated as formulas. Use `RAW` to write literal text that may otherwise be coerced.
+- No row-count validation - writing a 10,000-row block will attempt it in a single call; Sheets API rejects bodies over the limit with a 413 surfaced as `HttpError`.
+- `append` with `insert_data_option='OVERWRITE'` can clobber existing rows below the header; callers commonly want `INSERT_ROWS`.
+- `range` for write is a start cell (e.g. `Sheet1!A1`); the API automatically expands to fit `values`. A too-small range is silently widened.
+- `FORMULA` rendering returns formulas as-is for read; `UNFORMATTED_VALUE` returns native types (int/float/bool), `FORMATTED_VALUE` returns the user-visible string.
+
+## Related
+
+- **Skills using this as a tool**: [`sheets-skill/SKILL.md`](../../../server/skills/productivity_agent/sheets-skill/SKILL.md)
+- **Companion nodes**: [`gmail`](./gmail.md), [`calendar`](./calendar.md), [`drive`](./drive.md), [`tasks`](./tasks.md), [`contacts`](./contacts.md)
+- **Architecture docs**: `CLAUDE.md` -> "Google Workspace Nodes".
diff --git a/docs-internal/node-logic-flows/google_workspace/tasks.md b/docs-internal/node-logic-flows/google_workspace/tasks.md
new file mode 100644
index 00000000..76f889bf
--- /dev/null
+++ b/docs-internal/node-logic-flows/google_workspace/tasks.md
@@ -0,0 +1,159 @@
+# Tasks (`tasks`)
+
+| Field | Value |
+|------|-------|
+| **Category** | google_workspace / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/googleWorkspaceNodes.ts`](../../../client/src/nodeDefinitions/googleWorkspaceNodes.ts) |
+| **Backend handler** | [`server/services/handlers/tasks.py::handle_google_tasks`](../../../server/services/handlers/tasks.py) |
+| **Tests** | [`server/tests/nodes/test_google_workspace.py`](../../../server/tests/nodes/test_google_workspace.py) |
+| **Skill (if any)** | [`server/skills/productivity_agent/tasks-skill/SKILL.md`](../../../server/skills/productivity_agent/tasks-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `tasks` |
+
+## Purpose
+
+Consolidated Google Tasks node for managing personal to-do items. Uses Google
+Tasks API v1 (`tasklists` + `tasks` collections). One node, five operations
+switched via the `operation` parameter.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+Top-level dispatcher: `operation` (one of `create`, `list`, `complete`, `update`, `delete`).
+
+### `operation = create`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `title` | string | `""` | **yes** | Task title |
+| `notes` | string | `""` | no | Task description |
+| `due_date` | string | `""` | no | RFC 3339; date-only is upgraded to `T00:00:00.000Z` |
+| `tasklist_id` | string | `@default` | no | Which tasklist |
+
+### `operation = list`
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `tasklist_id` | string | `@default` | - |
+| `show_completed` | boolean | `false` | - |
+| `show_hidden` | boolean | `false` | - |
+| `max_results` | number | `100` | No clamp |
+
+### `operation = complete`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `task_id` | string | `""` | **yes** | - |
+| `tasklist_id` | string | `@default` | no | - |
+
+### `operation = update`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `task_id` | string | `""` | **yes** | - |
+| `tasklist_id` | string | `@default` | no | - |
+| `title` / `notes` / `due_date` / `status` | string | `""` | no | Patch fields |
+
+Also accepts `update_title`, `update_notes`, `update_due_date`, `update_status`
+aliases (the dispatcher rewrites them before delegating).
+
+### `operation = delete`
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `task_id` | string | `""` | **yes** | - |
+| `tasklist_id` | string | `@default` | no | - |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Operation-specific payload |
+| `output-tool` | object | Same, for AI tool wiring |
+
+- `create` / `complete` / `update`: `{task_id, title, notes?, due, status, completed?, self_link?}`
+- `list`: `{tasks: [{task_id, title, notes, due, status, completed, position}], count}`
+- `delete`: `{deleted: true, task_id}`
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_google_tasks] --> AL{operation == update?}
+ AL -- yes --> AM[Alias update_* params<br/>to plain names]
+ AL -- no --> B
+ AM --> B{operation?}
+ B -- create --> C1[handle_tasks_create]
+ B -- list --> C2[handle_tasks_list]
+ B -- complete --> C3[handle_tasks_complete]
+ B -- update --> C4[handle_tasks_update]
+ B -- delete --> C5[handle_tasks_delete]
+ B -- unknown --> Eret[success=false<br/>Unknown Tasks operation]
+ C1 --> G[get_google_credentials + build v1]
+ C2 --> G
+ C3 --> G
+ C4 --> G
+ C5 --> G
+ G -- ValueError --> Eret
+ C1 --> V1{title?}
+ V1 -- no --> Eret
+ V1 -- yes --> DF[Normalize due_date<br/>append T00:00:00.000Z if missing]
+ DF --> R1[tasks.insert]
+ C2 --> R2[tasks.list]
+ C3 --> V3{task_id?}
+ V3 -- no --> Eret
+ V3 -- yes --> G3[tasks.get -> set status=completed -> tasks.update]
+ C4 --> V4{task_id?}
+ V4 -- no --> Eret
+ V4 -- yes --> G4[tasks.get -> merge patch -> tasks.update]
+ C5 --> V5{task_id?}
+ V5 -- no --> Eret
+ V5 -- yes --> R5[tasks.delete]
+ R1 --> T[_track_tasks_usage]
+ R2 --> T
+ G3 --> T
+ G4 --> T
+ R5 --> T
+ T --> OUT[Return success envelope]
+```
+
+## Decision Logic
+
+- **Update parameter aliasing** (dispatcher): the dispatcher mutates the incoming `parameters` dict to promote `update_*` keys onto their plain counterparts BEFORE delegating. Irreversible.
+- **Due-date upgrade**: any `due_date` that lacks a `T` gets `T00:00:00.000Z` appended. There is no strict ISO validation otherwise.
+- **Complete** is a convenience op - it does a read-modify-write (`tasks.get` then `tasks.update`) with `status='completed'`. Two API calls per completion.
+- **Update** merges only truthy fields (uses `parameters.get('title')` etc. which skips empty strings). Callers cannot clear `notes` via the update path - use an explicit `status='needsAction'` or direct API.
+- **`tasks.list`** does NOT reject `max_results > 100` - the API itself caps silently.
+
+## Side Effects
+
+- **Database writes**: `api_usage_metrics` row per API call via `save_api_usage_metric` with `service='google_tasks'`. `list` records one row with `resource_count = len(tasks)`, but `_track_tasks_usage` is NOT called on the list path (see bug below).
+- **Broadcasts**: none.
+- **External API calls**: Tasks API v1 - `tasks().insert/list/get/update/delete`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth via `auth_service.get_oauth_tokens("google")`.
+- **Services**: Google Tasks API, `PricingService`, `Database`.
+- **Python packages**: `google-api-python-client`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **`handle_tasks_list` does not call `_track_tasks_usage`** (all other operations do). The list operation therefore skips the `api_usage_metrics` row. Handler bug noted, not fixed.
+- Update cannot clear a field - empty strings are filtered out by truthiness. To clear notes or title you must bypass this node.
+- Complete is non-idempotent on the server side: re-completing a completed task overwrites the `completed` timestamp.
+- Dispatcher mutates `parameters` in place - callers that reuse the dict will see `title`/`notes`/`due_date`/`status` filled in from `update_*` aliases.
+- `tasklist_id='@default'` only resolves for authenticated users who have created at least one list; freshly authenticated users may get a 404 until Google Tasks provisions their default list.
+
+## Related
+
+- **Skills using this as a tool**: [`tasks-skill/SKILL.md`](../../../server/skills/productivity_agent/tasks-skill/SKILL.md)
+- **Companion nodes**: [`gmail`](./gmail.md), [`calendar`](./calendar.md), [`drive`](./drive.md), [`sheets`](./sheets.md), [`contacts`](./contacts.md)
+- **Architecture docs**: `CLAUDE.md` -> "Google Workspace Nodes".
diff --git a/docs-internal/node-logic-flows/http_proxy/httpRequest.md b/docs-internal/node-logic-flows/http_proxy/httpRequest.md
new file mode 100644
index 00000000..6990eb1c
--- /dev/null
+++ b/docs-internal/node-logic-flows/http_proxy/httpRequest.md
@@ -0,0 +1,130 @@
+# HTTP Request (`httpRequest`)
+
+| Field | Value |
+|------|-------|
+| **Category** | utility / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/utilityNodes.ts`](../../../client/src/nodeDefinitions/utilityNodes.ts) |
+| **Backend handler** | [`server/services/handlers/http.py::handle_http_request`](../../../server/services/handlers/http.py) |
+| **Tests** | [`server/tests/nodes/test_http_proxy.py`](../../../server/tests/nodes/test_http_proxy.py) |
+| **Skill (if any)** | [`server/skills/web_agent/http-request-skill/SKILL.md`](../../../server/skills/web_agent/http-request-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - exposed to agents as a generic HTTP tool |
+
+## Purpose
+
+General-purpose outbound HTTP client used in workflows to call third-party
+REST APIs. Supports all common methods, custom headers, JSON/text bodies,
+and a transparent `useProxy` flag that routes the request through the
+configured residential proxy provider via `ProxyService`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger; parameters template-resolved before the handler runs |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `method` | options | `GET` | no | - | One of `GET` / `POST` / `PUT` / `DELETE` / `PATCH` |
+| `url` | string | `""` | **yes** | - | Target URL; empty value short-circuits with `URL is required` |
+| `headers` | string (JSON) | `"{}"` | no | - | JSON object; invalid JSON silently falls back to `{}` |
+| `body` | string | `""` | no | `method in [POST, PUT, PATCH]` | Sent as JSON when parseable, else as raw content |
+| `timeout` | number | `30` | no | - | Seconds; coerced via `float(...)` |
+| `useProxy` | boolean | `false` | no | - | Route through `ProxyService.get_proxy_url` |
+| `proxyProvider` | string | `""` | no | `useProxy=true` | Specific provider name (empty -> auto-select) |
+| `proxyCountry` | string | `""` | no | `useProxy=true` | ISO country code for geo-targeting |
+| `sessionType` | options | `rotating` | no | `useProxy=true` | `rotating` or `sticky` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Response envelope (see below) |
+
+### Output payload
+
+```ts
+{
+ status: number; // HTTP status code
+ data: any; // Parsed JSON body if possible, else text string
+ headers: Record<string, string>;
+ url: string; // Final URL after redirects (httpx default follows them)
+ method: string; // Echo of request method
+ proxied: boolean; // true iff a proxy URL was applied
+}
+```
+
+Wrapped in the standard envelope: `{ success: <status<400>, node_id, node_type: 'httpRequest', result, execution_time, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_http_request] --> B[Read method/url/headers/body/timeout]
+ B --> C{url truthy?}
+ C -- no --> Eerr[Return success=false<br/>error: URL is required]
+ C -- yes --> D[Parse headers JSON<br/>fallback {} on JSONDecodeError]
+ D --> E{useProxy?}
+ E -- no --> G[httpx.AsyncClient timeout=timeout]
+ E -- yes --> F[_get_proxy_url_if_enabled<br/>-> proxy_svc.get_proxy_url]
+ F -- returns None --> G
+ F -- returns url --> G2[httpx.AsyncClient proxy=proxy_url timeout=timeout]
+ F -- raises --> G3[Log warning, proceed without proxy -> G]
+ G --> H{method in POST/PUT/PATCH<br/>and body truthy?}
+ G2 --> H
+ G3 --> H
+ H -- yes JSON parseable --> I[kwargs.json = parsed]
+ H -- yes non-JSON --> I2[kwargs.content = body]
+ H -- no --> I3[no body]
+ I --> J[await client.request]
+ I2 --> J
+ I3 --> J
+ J -- response --> K[response.json fallback text]
+ K --> L[Return success=(status<400)<br/>with status/data/headers/url/method/proxied]
+ J -- TimeoutException --> T[Return success=false<br/>error: Request timed out]
+ J -- Exception --> Z[Return success=false<br/>error: str(e)]
+```
+
+## Decision Logic
+
+- **Validation**: `url` empty -> raises `ValueError('URL is required')` caught by outer `try`.
+- **Branches**:
+ - `useProxy=true` -> attempt proxy lookup; swallow proxy errors and fall back to direct call.
+ - Body handling depends on `method` and JSON-parseability of `body`.
+- **Fallbacks**:
+ - Invalid headers JSON -> `{}`.
+ - Proxy service disabled / `get_proxy_url` raises -> proceed without proxy.
+ - Non-JSON response body -> plain `text` string in `data`.
+- **Error paths**:
+ - `TimeoutException` (class name match) -> user-friendly `Request timed out after N seconds`.
+ - Any other exception -> `str(e)` verbatim in envelope.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none (only `logger.info` / `logger.error`).
+- **External API calls**: `client.request(method, url, ...)` to whatever URL the user supplied; optionally routed through a proxy URL provided by `ProxyService`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none directly; `ProxyService` may load proxy credentials via the auth service when `useProxy=true`.
+- **Services**: `ProxyService` (optional, only when `useProxy=true`).
+- **Python packages**: `httpx`.
+- **Environment variables**: none (timeout comes from node params).
+
+## Edge cases & known limits
+
+- Proxy lookup errors are **swallowed** (`_get_proxy_url_if_enabled` logs a warning and returns `None`); the request then proceeds directly, silently losing the proxy. Downstream nodes can detect this by checking `result.proxied`.
+- Timeout detection is by `type(e).__name__ == 'TimeoutException'` (string match) rather than `isinstance`; subclass hierarchy changes in httpx could bypass this branch.
+- `success` in the envelope reflects `status < 400`, so non-2xx 3xx responses (e.g. unfollowed 302) count as success.
+- The handler always wraps with `execution_time = time.time() - start_time`; no caching, no retry (retry is only implemented in `proxyRequest`).
+- `response.url` (final URL) is stringified; for non-proxied requests with redirects disabled this equals the request URL.
+
+## Related
+
+- **Skills using this as a tool**: [`http-request-skill/SKILL.md`](../../../server/skills/web_agent/http-request-skill/SKILL.md)
+- **Companion nodes**: [`proxyRequest`](./proxyRequest.md), [`proxyConfig`](./proxyConfig.md), [`proxyStatus`](./proxyStatus.md)
+- **Architecture docs**: [Proxy Service](../../proxy_service.md)
diff --git a/docs-internal/node-logic-flows/http_proxy/proxyConfig.md b/docs-internal/node-logic-flows/http_proxy/proxyConfig.md
new file mode 100644
index 00000000..cffdf81b
--- /dev/null
+++ b/docs-internal/node-logic-flows/http_proxy/proxyConfig.md
@@ -0,0 +1,169 @@
+# Proxy Config (`proxyConfig`)
+
+| Field | Value |
+|------|-------|
+| **Category** | proxy / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/proxyNodes.ts`](../../../client/src/nodeDefinitions/proxyNodes.ts) |
+| **Backend handler** | [`server/services/handlers/proxy.py::handle_proxy_config`](../../../server/services/handlers/proxy.py) (delegates to [`services/handlers/tools.py::_execute_proxy_config`](../../../server/services/handlers/tools.py)) |
+| **Tests** | [`server/tests/nodes/test_http_proxy.py`](../../../server/tests/nodes/test_http_proxy.py) |
+| **Skill (if any)** | [`server/skills/web_agent/proxy-config-skill/SKILL.md`](../../../server/skills/web_agent/proxy-config-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `proxy_config` |
+
+## Purpose
+
+Admin-style CRUD node for managing proxy providers, credentials, and routing
+rules. Dispatches on the `operation` param. Works the same as both a workflow
+node and an AI-agent tool: the node handler simply forwards its parameters as
+both `args` and `node_params` to the tool handler `_execute_proxy_config`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `operation` | options | `list_providers` | **yes** | - | One of the 10 operations below |
+| `name` | string | `""` | (most ops) | `operation in [add/update/remove/set_credentials/test_provider]` | Provider name |
+| `gateway_host` | string | `""` | no | `operation in [add/update]` | Proxy hostname |
+| `gateway_port` | number | `0` | no | `operation in [add/update]` | Proxy port |
+| `url_template` | string (JSON) | `"{}"` | no | `operation in [add/update]` | JSON template config |
+| `cost_per_gb` | number | `0` | no | `operation in [add/update]` | USD per GB |
+| `priority` | number | `50` | no | `operation in [add/update]` | Lower = preferred |
+| `enabled` | boolean | `true` | no | `operation in [add/update]` | Provider enabled |
+| `username` | string | `""` | yes (op=set_credentials) | `operation=set_credentials` | Proxy username |
+| `password` | string | `""` | yes (op=set_credentials) | `operation=set_credentials` | Proxy password |
+| `domain_pattern` | string | `""` | yes (op=add_routing_rule) | `operation=add_routing_rule` | Glob like `*.linkedin.com` |
+| `preferred_providers` | string (JSON array) | `"[]"` | no | `operation=add_routing_rule` | `["provider1"]` |
+| `required_country` | string | `""` | no | `operation=add_routing_rule` | ISO country |
+| `session_type` | options | `rotating` | no | `operation=add_routing_rule` | `rotating` or `sticky` |
+| `rule_id` | number | `0` | yes (op=remove_routing_rule) | `operation=remove_routing_rule` | Rule PK |
+
+### Operation index
+
+| `operation` | Effect |
+|-------------|--------|
+| `list_providers` | `proxy_svc.get_providers()` -> `[ProviderStats]` |
+| `get_stats` | `proxy_svc.get_stats()` -> dict |
+| `list_routing_rules` | `proxy_svc.get_routing_rules()` -> `[RoutingRule]` |
+| `add_provider` | `db.save_proxy_provider(...)` + `proxy_svc.reload_providers()` |
+| `update_provider` | merge existing row + save + reload |
+| `remove_provider` | `db.delete_proxy_provider(name)` + reload |
+| `set_credentials` | `auth_svc.store_api_key('proxy_<name>_username', ...)` + `..._password` + reload |
+| `test_provider` | `get_proxy_url` for `https://httpbin.org/ip` + real GET to httpbin (30s timeout) |
+| `add_routing_rule` | `db.save_proxy_routing_rule(...)` + reload |
+| `remove_routing_rule` | `db.delete_proxy_routing_rule(int(rule_id))` + reload |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope; `result` field carries op-specific payload |
+
+### Output payload (success)
+
+```ts
+// The node handler wraps the tool result under result = {...}
+{
+ success: true,
+ operation: string,
+ // op-specific fields: providers / rules / stats / name / rule_id / ip+latency_ms / updated_fields
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_proxy_config] --> B[_execute_proxy_config args=params node_params=params]
+ B --> C{operation}
+ C -- list_providers --> LP[proxy_svc.get_providers -> model_dump list]
+ C -- get_stats --> GS[proxy_svc.get_stats]
+ C -- list_routing_rules --> LR[proxy_svc.get_routing_rules]
+ C -- add_provider --> AP{name truthy?}
+ AP -- no --> Ename[success=false error: Provider name is required]
+ AP -- yes --> AP2[parse url_template JSON fallback error]
+ AP2 --> AP3[db.save_proxy_provider + reload_providers]
+ C -- update_provider --> UP{name truthy?}
+ UP -- no --> Ename
+ UP -- yes --> UP2[db.get_proxy_provider existing?]
+ UP2 -- not found --> Enf[success=false error not found]
+ UP2 -- found --> UP3[merge updates + save + reload]
+ C -- remove_provider --> RP[db.delete_proxy_provider + reload]
+ C -- set_credentials --> SC{username+password?}
+ SC -- no --> Ecred[success=false]
+ SC -- yes --> SC2[auth_svc.store_api_key user + pass + reload]
+ C -- test_provider --> TP{proxy_svc enabled?}
+ TP -- no --> Etp[success=false]
+ TP -- yes --> TP2[get_proxy_url for httpbin.org/ip<br/>httpx GET httpbin.org/ip 30s timeout]
+ TP2 -- ok --> TP3[return ip + latency_ms + status_code]
+ TP2 -- raises --> TP4[success=false error str(e)]
+ C -- add_routing_rule --> AR{domain_pattern?}
+ AR -- no --> Erule[success=false]
+ AR -- yes --> AR2[parse preferred_providers JSON fallback []]
+ AR2 --> AR3[db.save_proxy_routing_rule + reload]
+ C -- remove_routing_rule --> RR{rule_id?}
+ RR -- no --> Erid[success=false]
+ RR -- yes --> RR2[db.delete_proxy_routing_rule int(rule_id) + reload]
+ C -- unknown --> Eunk[success=false error Unknown operation]
+ LP --> W[handle_proxy_config wraps tool_result<br/>under result=]
+ GS --> W
+ LR --> W
+ AP3 --> W
+ UP3 --> W
+ RP --> W
+ SC2 --> W
+ TP3 --> W
+ TP4 --> W
+ AR3 --> W
+ RR2 --> W
+ Ename --> W
+ Enf --> W
+ Ecred --> W
+ Etp --> W
+ Erule --> W
+ Erid --> W
+ Eunk --> W
+```
+
+## Decision Logic
+
+- **Validation**: each op checks its own required fields before any service call.
+- **Branches**: 10 operations dispatched by string match; unknown op returns `Unknown operation: <op>`.
+- **Fallbacks**: `preferred_providers` JSON parse error -> `[]`; `url_template` JSON parse error -> early return with error (no fallback).
+- **Error paths**: validation failures return `{success: false, error: "..."}` *without* setting `operation`. The node handler wraps the tool result in its own envelope and copies the tool's `success` into the outer envelope, so validation errors look like `{success: false, result: {success: false, error: "..."}}`.
+
+## Side Effects
+
+- **Database writes**: `proxy_providers` table via `save_proxy_provider` / `delete_proxy_provider`; `proxy_routing_rules` table via `save_proxy_routing_rule` / `delete_proxy_routing_rule`.
+- **Credential writes**: `EncryptedAPIKey` rows for keys `proxy_<name>_username` and `proxy_<name>_password` (on `set_credentials`).
+- **In-memory writes**: `proxy_svc.reload_providers()` reinitialises `_providers` / `_routing_rules` dicts on every successful mutation.
+- **Broadcasts**: none.
+- **External API calls**: `GET https://httpbin.org/ip` through the proxy on `operation=test_provider` (30s timeout).
+- **File I/O**: none directly (DB only).
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.store_api_key(...)` for proxy username/password.
+- **Services**: `ProxyService`, `Database`, `auth_service` (via `container`).
+- **Python packages**: `httpx`, `json`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `handle_proxy_config` passes the same dict for both `args` and `node_params`, so the `args.get(..., node_params.get(...))` fallback resolves to the same source. This is harmless but tautological.
+- The outer node handler copies the tool's `success` into the envelope, yet still wraps the tool payload under `result`; tests must inspect both `result["success"]` AND `result["result"]["success"]`.
+- `test_provider` does a **real** HTTP call to `httpbin.org/ip` when the handler is invoked - there is no offline / dry-run path; this call is un-mocked in production.
+- `update_provider` silently returns `success=true` with `updated_fields=[]` if no fields were changed.
+- `remove_provider` / `remove_routing_rule` do not verify the row existed before issuing the delete; they always return `success=true` unless the DB raises.
+- `url_template` is re-serialized via `json.dumps(...)` before being saved, so whitespace in the caller's JSON is normalised.
+
+## Related
+
+- **Skills using this as a tool**: [`proxy-config-skill/SKILL.md`](../../../server/skills/web_agent/proxy-config-skill/SKILL.md)
+- **Companion nodes**: [`proxyRequest`](./proxyRequest.md), [`proxyStatus`](./proxyStatus.md), [`httpRequest`](./httpRequest.md)
+- **Architecture docs**: [Proxy Service](../../proxy_service.md)
diff --git a/docs-internal/node-logic-flows/http_proxy/proxyRequest.md b/docs-internal/node-logic-flows/http_proxy/proxyRequest.md
new file mode 100644
index 00000000..24001e71
--- /dev/null
+++ b/docs-internal/node-logic-flows/http_proxy/proxyRequest.md
@@ -0,0 +1,143 @@
+# Proxy Request (`proxyRequest`)
+
+| Field | Value |
+|------|-------|
+| **Category** | proxy / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/proxyNodes.ts`](../../../client/src/nodeDefinitions/proxyNodes.ts) |
+| **Backend handler** | [`server/services/handlers/proxy.py::handle_proxy_request`](../../../server/services/handlers/proxy.py) |
+| **Tests** | [`server/tests/nodes/test_http_proxy.py`](../../../server/tests/nodes/test_http_proxy.py) |
+| **Skill (if any)** | [`server/skills/web_agent/http-request-skill/SKILL.md`](../../../server/skills/web_agent/http-request-skill/SKILL.md) (covers useProxy + proxyRequest) |
+| **Dual-purpose tool** | yes - workflow node and AI tool |
+
+## Purpose
+
+Proxy-aware HTTP client with explicit retry / failover and per-attempt health
+reporting. Unlike `httpRequest` (where `useProxy` is an optional flag),
+`proxyRequest` is unconditional: it requires `ProxyService` to be enabled and
+short-circuits if no provider is available. It additionally tracks cost and
+latency per attempt and feeds them back into the provider's health score.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `method` | options | `GET` | no | - | `GET` / `POST` / `PUT` / `DELETE` / `PATCH` |
+| `url` | string | `""` | **yes** | - | Target URL |
+| `headers` | string (JSON) | `"{}"` | no | - | JSON object, falls back to `{}` on parse error |
+| `body` | string | `""` | no | `method in [POST, PUT, PATCH]` | JSON if parseable else raw content |
+| `timeout` | number | `30` | no | - | Seconds |
+| `proxyProvider` | string | `""` | no | - | Specific provider name, empty for auto-select |
+| `proxyCountry` | string | `""` | no | - | ISO country code |
+| `sessionType` | options | `rotating` | no | - | `rotating` or `sticky` |
+| `stickyDuration` | number | `300` | no | `sessionType=sticky` | Seconds (30-3600) |
+| `maxRetries` | number | `3` | no | - | Number of retry attempts (`proxyMaxRetries` is also read) |
+| `proxyFailover` | boolean | `true` | no | - | On failure, request a new proxy URL and retry |
+| `followRedirects` | boolean | `true` | no | - | Declared in frontend; handler does not currently forward to httpx |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Proxy response envelope (see below) |
+
+### Output payload (success)
+
+```ts
+{
+ status: number;
+ data: any; // JSON if parseable, else text
+ headers: Record<string, string>;
+ url: string;
+ method: string;
+ proxy_provider: string; // echo of proxyProvider param (may be empty when auto-selected)
+ latency_ms: number; // round-trip time of the winning attempt
+ bytes_transferred: number; // len(response.content)
+ attempt: number; // 1-indexed attempt that succeeded
+}
+```
+
+### Output payload (failure)
+
+`{ success: false, error: "All N attempts failed. Last error: <str>", ... }` or a short-circuit error if proxy service is unavailable.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_proxy_request] --> B{proxy_svc.is_enabled?}
+ B -- no --> Edis[Return success=false<br/>error: Proxy service not initialized]
+ B -- yes --> C[Read method/url/headers/body/timeout/maxRetries/failover]
+ C --> D{url truthy?}
+ D -- no --> Eval[Return success=false<br/>error: URL is required]
+ D -- yes --> E[Parse headers JSON; fallback {}]
+ E --> F[await proxy_svc.get_proxy_url]
+ F -- None --> Enop[Return success=false<br/>error: No proxy provider available]
+ F -- url --> G[attempt = 0]
+ G --> H[httpx.AsyncClient proxy=proxy_url timeout=timeout]
+ H --> I{method in POST/PUT/PATCH and body?}
+ I -- yes JSON --> J[kwargs.json]
+ I -- yes non-JSON --> J2[kwargs.content]
+ I -- no --> J3[no body]
+ J --> K[await client.request]
+ J2 --> K
+ J3 --> K
+ K -- response --> L[proxy_svc.report_result success=status<400]
+ L --> M[_track_proxy_usage -> db.save_api_usage_metric]
+ M --> N[Return success=(status<400) with status/data/headers/url/method/provider/latency_ms/bytes/attempt]
+ K -- Exception --> R[proxy_svc.report_result success=False<br/>log warning]
+ R --> S{failover and attempt<maxRetries?}
+ S -- yes --> T[await get_proxy_url again<br/>on exception break]
+ T --> H
+ S -- no --> U[Return success=false<br/>error: All N attempts failed]
+```
+
+## Decision Logic
+
+- **Validation**:
+ - Service disabled -> short-circuit error envelope.
+ - Empty `url` -> `ValueError` caught -> error envelope.
+ - `get_proxy_url` returns `None` -> `No proxy provider available` error.
+- **Branches**:
+ - Retry loop runs up to `maxRetries + 1` times; `failover=false` breaks after first failure.
+ - Body JSON-parseable -> `kwargs.json`, else `kwargs.content`.
+- **Fallbacks**: invalid headers JSON -> `{}`.
+- **Error paths**:
+ - Per-attempt exception logged at `warning` and reported via `ProxyResult(success=False, error=...)`.
+ - Final error string: `All <maxRetries+1> attempts failed. Last error: <last_error>`.
+ - Outer unexpected exception -> `error: str(e)`.
+
+## Side Effects
+
+- **Database writes**: one row per successful attempt in `api_usage_metrics` via `database.save_api_usage_metric`, with `service=proxy_<provider_name>`, `operation=proxy_request`, `cost` computed as `bytes / 1GB * cost_per_gb` from `config/pricing.json`.
+- **In-memory writes**: `proxy_svc.report_result(...)` mutates the provider's rolling history deque (length 100), which feeds `compute_score()`. The service also increments `_daily_spend_usd`.
+- **Broadcasts**: none.
+- **External API calls**: the target URL, tunneled through the selected proxy URL.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service` stores proxy username/password under keys `proxy_<name>_username` / `proxy_<name>_password` (read by ProxyService when loading providers).
+- **Services**: `ProxyService` (must be enabled), `PricingService` (read through `_track_proxy_usage` -> `pricing._config["proxy"]`), `Database`.
+- **Python packages**: `httpx`.
+- **Environment variables**: none directly; ProxyService reads daily budget from `Settings.proxy_budget_daily_usd`.
+
+## Edge cases & known limits
+
+- Failed attempts are **not** tracked in `api_usage_metrics` - only successful requests that returned a response. If every attempt raises, the DB sees nothing for that call.
+- `followRedirects` is defined in the frontend but never forwarded to `httpx`; httpx default follows redirects.
+- `provider_name` in the result echoes the `proxyProvider` param verbatim; when left empty (auto-select), the envelope shows `""` even though a specific provider was used.
+- Retry loop re-requests a new proxy URL via `get_proxy_url` on each retry; if that call raises (e.g. `BudgetExceededError`), the retry loop silently `break`s and the envelope reports the previous network error rather than the budget exception.
+- Cost tracking reads `pricing._config["proxy"]` directly - touching a private attribute. If the pricing config is missing a `proxy` section, `cost_per_gb` falls back to `0.0` and cost rows are still written with `cost=0`.
+
+## Related
+
+- **Skills using this as a tool**: [`http-request-skill/SKILL.md`](../../../server/skills/web_agent/http-request-skill/SKILL.md), [`proxy-config-skill/SKILL.md`](../../../server/skills/web_agent/proxy-config-skill/SKILL.md)
+- **Companion nodes**: [`httpRequest`](./httpRequest.md), [`proxyConfig`](./proxyConfig.md), [`proxyStatus`](./proxyStatus.md)
+- **Architecture docs**: [Proxy Service](../../proxy_service.md), [Pricing Service](../../pricing_service.md)
diff --git a/docs-internal/node-logic-flows/http_proxy/proxyStatus.md b/docs-internal/node-logic-flows/http_proxy/proxyStatus.md
new file mode 100644
index 00000000..99f8c27d
--- /dev/null
+++ b/docs-internal/node-logic-flows/http_proxy/proxyStatus.md
@@ -0,0 +1,97 @@
+# Proxy Status (`proxyStatus`)
+
+| Field | Value |
+|------|-------|
+| **Category** | proxy / tool |
+| **Frontend definition** | [`client/src/nodeDefinitions/proxyNodes.ts`](../../../client/src/nodeDefinitions/proxyNodes.ts) |
+| **Backend handler** | [`server/services/handlers/proxy.py::handle_proxy_status`](../../../server/services/handlers/proxy.py) |
+| **Tests** | [`server/tests/nodes/test_http_proxy.py`](../../../server/tests/nodes/test_http_proxy.py) |
+| **Skill (if any)** | [`server/skills/web_agent/proxy-config-skill/SKILL.md`](../../../server/skills/web_agent/proxy-config-skill/SKILL.md) |
+| **Dual-purpose tool** | yes |
+
+## Purpose
+
+Read-only snapshot of the `ProxyService` runtime state: per-provider health
+stats (score, success rate, latency, bytes transferred) and aggregate stats.
+Used by the dashboard and by AI agents that need to reason about which
+provider to target.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `providerFilter` | string | `""` | no | - | Declared in frontend; handler currently **ignores** it and returns all providers |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Status envelope (see below) |
+
+### Output payload
+
+```ts
+{
+ enabled: boolean; // proxy_svc.is_enabled()
+ providers: Array<ProviderStats>; // [] when disabled
+ stats: Record<string, any>; // {} when disabled
+}
+```
+
+`ProviderStats` is produced by `ProviderStats.model_dump()` and includes
+`name`, `enabled`, `priority`, `score`, `success_rate`, `avg_latency_ms`,
+`total_requests`, `total_bytes`, etc. (see `services/proxy/models.py`).
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_proxy_status] --> B{proxy_svc and<br/>proxy_svc.is_enabled?}
+ B -- no --> C[Return success=true<br/>result = enabled:false providers:[] stats:{}]
+ B -- yes --> D[stats = proxy_svc.get_stats]
+ D --> E[providers = proxy_svc.get_providers -> model_dump each]
+ E --> F[Return success=true<br/>result = enabled:true providers stats]
+ A -- Exception --> Eerr[Return success=false<br/>error: str(e)]
+```
+
+## Decision Logic
+
+- **Validation**: none - no required params.
+- **Branches**: service-disabled short-circuit returns `enabled=false` with empty collections; still `success=true`.
+- **Fallbacks**: `providerFilter` is ignored - the handler always returns the full list.
+- **Error paths**: only the outer `Exception` catch; returns `{success: false, error: str(e)}`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+- **In-memory reads**: `ProxyService._providers` and rolling history deques.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `ProxyService` (optional; handler tolerates disabled state).
+- **Python packages**: none.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Even when proxy is disabled, the handler returns `success=true` with empty collections - callers need to inspect `result.enabled` rather than `success`.
+- `providerFilter` is defined in the frontend UI but never applied in the backend; filtering must happen in the consumer.
+- `ProviderStats.model_dump()` exposes every field including computed `score`; the shape is governed by `services/proxy/models.py::ProviderStats`.
+- No locking around the read: if another request is mutating `ProxyService._providers` (e.g. `reload_providers` mid-flight), the returned list may reflect a partial state.
+
+## Related
+
+- **Skills using this as a tool**: [`proxy-config-skill/SKILL.md`](../../../server/skills/web_agent/proxy-config-skill/SKILL.md)
+- **Companion nodes**: [`proxyConfig`](./proxyConfig.md), [`proxyRequest`](./proxyRequest.md), [`httpRequest`](./httpRequest.md)
+- **Architecture docs**: [Proxy Service](../../proxy_service.md)
diff --git a/docs-internal/node-logic-flows/search/braveSearch.md b/docs-internal/node-logic-flows/search/braveSearch.md
new file mode 100644
index 00000000..4cc321a6
--- /dev/null
+++ b/docs-internal/node-logic-flows/search/braveSearch.md
@@ -0,0 +1,107 @@
+# Brave Search (`braveSearch`)
+
+| Field | Value |
+|------|-------|
+| **Category** | search / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/searchNodes.ts`](../../../client/src/nodeDefinitions/searchNodes.ts) |
+| **Backend handler** | [`server/services/handlers/search.py::handle_brave_search`](../../../server/services/handlers/search.py) |
+| **Tests** | [`server/tests/nodes/test_search.py`](../../../server/tests/nodes/test_search.py) |
+| **Skill (if any)** | [`server/skills/web_agent/brave-search-skill/SKILL.md`](../../../server/skills/web_agent/brave-search-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `brave_search` |
+
+## Purpose
+
+Free-text web search via the Brave Search REST API. Returns ranked web results
+with title, snippet, and URL. Used both as a workflow node (drag onto canvas)
+and as an AI agent tool (connect to `input-tools`); when invoked as a tool
+the LLM fills the same parameter schema documented below.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `brave_search` | no | - | Name of this node when exposed as an AI tool |
+| `toolDescription` | string | (see frontend) | no | - | Description shown to LLM in tool schema |
+| `query` | string | `""` | **yes** | - | Search query |
+| `maxResults` | number | `10` | no | - | 1-100; clamped via `min(maxResults, 100)` before API call |
+| `country` | string | `""` | no | - | ISO country code, e.g. `US` - only sent when truthy |
+| `searchLang` | string | `""` | no | - | ISO language code, e.g. `en` - only sent when truthy |
+| `safeSearch` | options | `moderate` | no | - | One of `off` / `moderate` / `strict` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard search payload (see below) |
+| `output-tool` | object | Same payload, used when this node is wired to an AI agent's `input-tools` |
+
+### Output payload
+
+```ts
+{
+ query: string;
+ results: Array<{ title: string; snippet: string; url: string }>;
+ result_count: number;
+ provider: 'brave_search';
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time: number }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_brave_search] --> B{query stripped<br/>non-empty?}
+ B -- no --> Eret[Return success=false<br/>error: Search query is required]
+ B -- yes --> C[Read maxResults / country / searchLang / safeSearch from params]
+ C --> D[await _get_api_key brave_search]
+ D -- ValueError --> Eapi[Return success=false<br/>error: API key not configured]
+ D -- ok --> E[Build params dict; only include country/searchLang/safeSearch if truthy]
+ E --> F[GET api.search.brave.com/res/v1/web/search<br/>headers X-Subscription-Token + Accept: application/json<br/>timeout 30s]
+ F -- HTTPStatusError --> Estat[Return success=false<br/>error: Brave Search API error STATUS]
+ F -- other Exception --> Egen[Return success=false<br/>error: Brave Search failed STR]
+ F -- 2xx --> G[data.web.results -> map first maxResults to title/snippet/url]
+ G --> H[await _track_search_usage<br/>service=brave_search action=web_search count=1]
+ H --> I[Return success=true with query / results / result_count / provider]
+```
+
+## Decision Logic
+
+- **Empty query**: `query.strip() == ""` -> immediate failure envelope, no API call.
+- **Param trimming**: `country`, `searchLang`, `safeSearch` only added to the request when truthy. Note: `safeSearch` defaults to `'moderate'` in the frontend so it is effectively always sent.
+- **maxResults clamp**: API receives `min(maxResults, 100)` regardless of the requested value; the response is then sliced to the original `maxResults` again before mapping.
+- **Result mapping**: missing fields fall back to empty string (`title`, `snippet`, `url`).
+
+## Side Effects
+
+- **Database writes**: one row in `api_usage_metrics` (via `database.save_api_usage_metric`) with `service='brave_search'`, `operation` from PricingService, `cost` from PricingService, plus `session_id` / `node_id` / `workflow_id`.
+- **Broadcasts**: none.
+- **External API calls**: `GET https://api.search.brave.com/res/v1/web/search` (timeout 30s).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('brave_search')` - looked up at execution time; stored under `EncryptedAPIKey` table.
+- **Services**: `PricingService` for cost calc, `Database` for usage row.
+- **Python packages**: `httpx`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- API hard-caps `count` at 100; values above 100 are silently capped.
+- Network errors are caught by the generic `Exception` handler and returned as `Brave Search failed: <str>` - i.e. the handler never raises; downstream nodes always see an envelope.
+- The handler does *not* validate `safeSearch` values - the API rejects unknown values with 4xx, which becomes the `Brave Search API error: 400` envelope.
+
+## Related
+
+- **Skills using this as a tool**: [`brave-search-skill/SKILL.md`](../../../server/skills/web_agent/brave-search-skill/SKILL.md)
+- **Companion nodes**: [`serperSearch`](./serperSearch.md), [`perplexitySearch`](./perplexitySearch.md), [`duckduckgoSearch`](../tools/duckduckgoSearch.md)
+- **Architecture docs**: [Pricing Service](../../pricing_service.md), [Credentials Encryption](../../credentials_encryption.md)
diff --git a/docs-internal/node-logic-flows/search/perplexitySearch.md b/docs-internal/node-logic-flows/search/perplexitySearch.md
new file mode 100644
index 00000000..536aeccf
--- /dev/null
+++ b/docs-internal/node-logic-flows/search/perplexitySearch.md
@@ -0,0 +1,120 @@
+# Perplexity Search (`perplexitySearch`)
+
+| Field | Value |
+|------|-------|
+| **Category** | search / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/searchNodes.ts`](../../../client/src/nodeDefinitions/searchNodes.ts) |
+| **Backend handler** | [`server/services/handlers/search.py::handle_perplexity_search`](../../../server/services/handlers/search.py) |
+| **Tests** | [`server/tests/nodes/test_search.py`](../../../server/tests/nodes/test_search.py) |
+| **Skill (if any)** | [`server/skills/web_agent/perplexity-search-skill/SKILL.md`](../../../server/skills/web_agent/perplexity-search-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `perplexity_search` |
+
+## Purpose
+
+AI-generated answer with inline citations from Perplexity Sonar models. The
+node returns an LLM completion *plus* the citation URLs Perplexity used so
+downstream nodes can render references or follow the sources.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `perplexity_search` | no | - | Tool name when exposed to AI |
+| `toolDescription` | string | (see frontend) | no | - | Tool description for AI |
+| `query` | string | `""` | **yes** | - | Question for the model |
+| `model` | options | `sonar` | no | - | One of `sonar` / `sonar-pro` / `sonar-reasoning` / `sonar-reasoning-pro` |
+| `searchRecencyFilter` | options | `""` | no | - | One of `""` / `month` / `week` / `day` / `hour` |
+| `returnImages` | boolean | `false` | no | - | When true, include images array in payload |
+| `returnRelatedQuestions` | boolean | `false` | no | - | When true, include related_questions array |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Answer + citations payload |
+| `output-tool` | object | Same payload, AI-tool wiring |
+
+### Output payload
+
+```ts
+{
+ query: string;
+ answer: string; // markdown content from choices[0].message.content
+ citations: string[]; // URLs the model cited
+ results: Array<{ url: string }>; // citations remapped as result objects
+ model: string; // echoes the model param
+ provider: 'perplexity';
+ images?: string[]; // present only if requested AND returned
+ related_questions?: string[]; // present only if requested AND returned
+}
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_perplexity_search] --> B{query stripped<br/>non-empty?}
+ B -- no --> Eret[Return error: Search query is required]
+ B -- yes --> C[Read model, searchRecencyFilter, returnImages,<br/>returnRelatedQuestions]
+ C --> D[await _get_api_key 'perplexity']
+ D -- ValueError --> Eapi[Return error: API key not configured]
+ D -- ok --> E[Build body:<br/>model + messages role=user content=query]
+ E --> F{searchRecencyFilter truthy?}
+ F -- yes --> G[Add search_recency_filter to body]
+ F -- no --> H{returnImages?}
+ G --> H
+ H -- yes --> I[body.return_images=true]
+ H -- no --> J{returnRelatedQuestions?}
+ I --> J
+ J -- yes --> K[body.return_related_questions=true]
+ J -- no --> L[POST api.perplexity.ai/chat/completions<br/>headers Authorization Bearer + JSON<br/>timeout 60s]
+ K --> L
+ L -- HTTPStatusError --> Estat[Return error: Perplexity API error STATUS]
+ L -- other Exception --> Egen[Return error: Perplexity search failed STR]
+ L -- 2xx --> M[answer = data.choices 0 .message.content or empty]
+ M --> N[citations = data.citations or empty list]
+ N --> O[results = list of url-only objects]
+ O --> P[await _track_search_usage 'perplexity' 'sonar_search' 1]
+ P --> Q[Return success with query / answer / citations / results / model / provider<br/>plus images and related_questions when present]
+```
+
+## Decision Logic
+
+- **Empty query**: short-circuit failure envelope.
+- **Optional body fields** (`search_recency_filter`, `return_images`, `return_related_questions`) only added when the corresponding param is truthy. `searchRecencyFilter=''` is the explicit "off" value.
+- **Empty `choices`**: `answer` falls back to `''` rather than raising.
+- **Optional response fields** (`images`, `related_questions`) only added to the output payload when present *and non-empty* (`if images:` / `if related_questions:`).
+
+## Side Effects
+
+- **Database writes**: one `api_usage_metrics` row per call (`service='perplexity'`, `operation='sonar_search'`).
+- **Broadcasts**: none.
+- **External API calls**: `POST https://api.perplexity.ai/chat/completions` (timeout 60s - longer than the other search nodes because Sonar Reasoning models can be slow).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('perplexity')`.
+- **Services**: `PricingService`, `Database`.
+- **Python packages**: `httpx`.
+
+## Edge cases & known limits
+
+- 60s timeout - reasoning-pro models can occasionally exceed this and surface as `Perplexity search failed: ReadTimeout`.
+- Citations field shape can vary across Perplexity response versions (`list[str]` historically). The handler assumes `list[str]`; a list-of-objects response will pass through to the output unchanged but break the `results` mapping (`{'url': <obj>}`).
+- The `results` list is purely a citations remap; downstream nodes expecting `title` / `snippet` will not find them - use `braveSearch` or `serperSearch` for those.
+
+## Related
+
+- **Skills using this as a tool**: [`perplexity-search-skill/SKILL.md`](../../../server/skills/web_agent/perplexity-search-skill/SKILL.md)
+- **Companion nodes**: [`braveSearch`](./braveSearch.md), [`serperSearch`](./serperSearch.md)
+- **Architecture docs**: [Pricing Service](../../pricing_service.md)
diff --git a/docs-internal/node-logic-flows/search/serperSearch.md b/docs-internal/node-logic-flows/search/serperSearch.md
new file mode 100644
index 00000000..8b7695ad
--- /dev/null
+++ b/docs-internal/node-logic-flows/search/serperSearch.md
@@ -0,0 +1,122 @@
+# Serper Search (`serperSearch`)
+
+| Field | Value |
+|------|-------|
+| **Category** | search / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/searchNodes.ts`](../../../client/src/nodeDefinitions/searchNodes.ts) |
+| **Backend handler** | [`server/services/handlers/search.py::handle_serper_search`](../../../server/services/handlers/search.py) |
+| **Tests** | [`server/tests/nodes/test_search.py`](../../../server/tests/nodes/test_search.py) |
+| **Skill (if any)** | [`server/skills/web_agent/serper-search-skill/SKILL.md`](../../../server/skills/web_agent/serper-search-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `serper_search` |
+
+## Purpose
+
+Google SERP scraping via the Serper API. Supports four search verticals
+(web, news, images, places) and optional knowledge-graph enrichment for the
+default web search. Used as a workflow node and as an AI agent tool.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `serper_search` | no | - | Tool name when exposed to AI |
+| `toolDescription` | string | (see frontend) | no | - | Tool description for AI |
+| `query` | string | `""` | **yes** | - | Search query |
+| `searchType` | options | `search` | no | - | One of `search` / `news` / `images` / `places` |
+| `maxResults` | number | `10` | no | - | 1-100; clamped via `min(maxResults, 100)` before API call |
+| `country` | string | `""` | no | - | Sent as `gl` only when truthy |
+| `language` | string | `""` | no | - | Sent as `hl` only when truthy |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Search payload (shape varies by `searchType`) |
+| `output-tool` | object | Same payload, AI-tool wiring |
+
+### Output payload
+
+```ts
+{
+ query: string;
+ results: Array<SearchResult | NewsResult | ImageResult | PlaceResult>;
+ result_count: number;
+ search_type: 'search' | 'news' | 'images' | 'places';
+ provider: 'serper';
+ knowledge_graph?: object; // only when API returns it
+}
+
+type SearchResult = { title: string; snippet: string; url: string; position?: number };
+type NewsResult = { title: string; snippet: string; url: string; date: string; source: string };
+type ImageResult = { title: string; imageUrl: string; url: string };
+type PlaceResult = { title: string; address: string; rating?: number; url: string };
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_serper_search] --> B{query stripped non-empty?}
+ B -- no --> Eret[Return error: Search query is required]
+ B -- yes --> C[Read maxResults, searchType, country, language]
+ C --> D[await _get_api_key 'serper']
+ D -- ValueError --> Eapi[Return error: API key not configured]
+ D -- ok --> E[Build body q + num; add gl/hl when truthy]
+ E --> F[Pick endpoint by searchType<br/>fallback to /search]
+ F --> G[POST endpoint headers X-API-KEY + Content-Type: application/json<br/>timeout 30s]
+ G -- HTTPStatusError --> Estat[Return error: Serper API error STATUS]
+ G -- other Exception --> Egen[Return error: Serper search failed STR]
+ G -- 2xx --> H{searchType branch}
+ H -- search --> J1[Map data.organic -> title/snippet/url/position]
+ H -- news --> J2[Map data.news -> title/snippet/url/date/source]
+ H -- images --> J3[Map data.images -> title/imageUrl/url]
+ H -- places --> J4[Map data.places -> title/address/rating/url]
+ J1 --> K[knowledge_graph = data.knowledgeGraph or None]
+ J2 --> K
+ J3 --> K
+ J4 --> K
+ K --> L[await _track_search_usage 'serper' 'web_search' 1]
+ L --> M[Return success with query results result_count search_type provider plus knowledge_graph if present]
+```
+
+## Decision Logic
+
+- **Empty query**: short-circuit failure envelope.
+- **searchType dispatch**: hard-coded `endpoint_map`; unknown values fall through to `https://google.serper.dev/search` *and* take the `if search_type == 'search'` branch... wait no - they hit the default endpoint but skip every branch in the result loop, returning `results: []`. Document this as a known gotcha.
+- **knowledge_graph**: only added to the payload when the API includes a non-falsy `knowledgeGraph` field.
+- **maxResults clamp**: API receives `min(maxResults, 100)`; results list is then sliced again to `maxResults`.
+- **gl/hl trimming**: `country` -> `gl`, `language` -> `hl`. Only sent when truthy.
+
+## Side Effects
+
+- **Database writes**: one `api_usage_metrics` row per call (`service='serper'`, `operation` from PricingService).
+- **Broadcasts**: none.
+- **External API calls**: `POST` to one of `https://google.serper.dev/{search,news,images,places}` (timeout 30s).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key('serper')`.
+- **Services**: `PricingService`, `Database`.
+- **Python packages**: `httpx`.
+
+## Edge cases & known limits
+
+- An unrecognised `searchType` value silently returns `results: []` (no error). Refactors must preserve this or update the test to assert the new behaviour.
+- 4xx/5xx API errors are translated into `Serper API error: <status>` - the response body is logged but not exposed.
+- The handler trusts the API to return the expected nested keys (`organic`, `news`, etc.); a malformed response yields an empty results list rather than an exception.
+
+## Related
+
+- **Skills using this as a tool**: [`serper-search-skill/SKILL.md`](../../../server/skills/web_agent/serper-search-skill/SKILL.md)
+- **Companion nodes**: [`braveSearch`](./braveSearch.md), [`perplexitySearch`](./perplexitySearch.md)
+- **Architecture docs**: [Pricing Service](../../pricing_service.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/_pattern.md b/docs-internal/node-logic-flows/specialized_agents/_pattern.md
new file mode 100644
index 00000000..8015f157
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/_pattern.md
@@ -0,0 +1,183 @@
+# Generic Specialized Agent Pattern (`handle_chat_agent`)
+
+This document describes the shared behavioural contract for the 13 specialized
+agent nodes that route to the same backend handler:
+
+`android_agent`, `coding_agent`, `web_agent`, `task_agent`, `social_agent`,
+`travel_agent`, `tool_agent`, `productivity_agent`, `payments_agent`,
+`consumer_agent`, `autonomous_agent`, `orchestrator_agent`, `ai_employee`.
+
+All 13 nodes use the `handle_chat_agent` handler wired in
+`server/services/node_executor.py` (lines 134-146). They differ only in
+frontend presentation (icon, theme color, default skills) and intended use
+case. The three agents with **dedicated** handlers (`deep_agent`, `rlm_agent`,
+`claude_code_agent`) are documented separately.
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Registry binding** | `partial(handle_chat_agent, ai_service=..., database=...)` |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+| **Architecture docs** | [Agent Architecture](../../agent_architecture.md), [Agent Delegation](../../agent_delegation.md), [Agent Teams](../../agent_teams.md) |
+
+## Purpose
+
+A specialized agent is an `aiAgent` pre-configured for a specific domain
+(Android control, coding, web automation, etc.). From the backend's
+perspective it is identical to `chatAgent`: same handler, same inputs, same
+output envelope, same delegation semantics. The specialization is conveyed
+only through:
+
+1. Connected skills (usually via a Master Skill node seeded with the
+ domain-specific folder in `server/skills/`).
+2. Connected tools (e.g. `coding_agent` typically has `pythonExecutor` wired
+ to `input-tools`).
+3. Frontend cosmetics (icon, theme color, AGENT_CONFIGS label).
+
+## Inputs (handles)
+
+All 13 agents share these input handles.
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; auto-prompt fallback when `prompt` param is empty |
+| `input-skill` | main | no | Skill node(s) providing SKILL.md context |
+| `input-memory` | main | no | `simpleMemory` node for conversation history |
+| `input-tools` | main | no | Tool nodes exposed to the LLM via LangGraph |
+| `input-task` | main | no | `taskTrigger` events from delegated child agents |
+| `input-teammates` | main | no | **Only on `orchestrator_agent` and `ai_employee`** -- connected agents become `delegate_to_*` tools |
+
+## Parameters
+
+All specialized agents share the `AI_AGENT_PROPERTIES` schema from
+`specializedAgentNodes.ts` plus node-specific extras (e.g. orchestrator has
+`teamMode`, `ai_employee` has `teamMode` + `maxConcurrent`).
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `provider` | options | `openai` | AI provider (openai / anthropic / gemini / ...) |
+| `model` | string | `""` | Model ID; required |
+| `prompt` | string | `""` | User prompt; falls back to upstream output when empty |
+| `systemMessage` | string | `""` | Additional system instructions (prepended to skill content) |
+| `options.temperature` | number | `0.7` | Sampling temperature |
+| `options.maxTokens` | number | `4096` | Max response tokens |
+| `options.thinkingEnabled` | boolean | `false` | Extended thinking / reasoning |
+| `options.thinkingBudget` | number | `2048` | Thinking budget tokens (Claude/Gemini) |
+| `options.reasoningEffort` | options | `medium` | For OpenAI o-series and GPT-5 |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` / `output-top` / `output-0` | object | Standard agent envelope |
+
+### Output payload
+
+```ts
+{
+ response: string; // Final agent message
+ thinking?: string; // Extended thinking content (when enabled)
+ model: string;
+ provider: string;
+ finish_reason?: string;
+ timestamp: string;
+}
+```
+
+Wrapped in the standard envelope:
+`{ success: true, result: <payload>, execution_time: number }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_chat_agent] --> B[_collect_agent_connections]
+ B --> B1[memory_data from input-memory]
+ B --> B2[skill_data from input-skill<br/>masterSkill expanded to N skills]
+ B --> B3[tool_data from input-tools<br/>androidTool sub-nodes discovered]
+ B --> B4[input_data from input-main]
+ B --> B5[task_data from input-task]
+ B1 --> C{task_data present?}
+ B2 --> C
+ B3 --> C
+ B4 --> C
+ B5 --> C
+ C -- yes + completed/error --> D[_format_task_context<br/>prepend to prompt<br/>STRIP ALL tools]
+ C -- no --> E{prompt empty<br/>and input_data?}
+ D --> E
+ E -- yes --> F[prompt = input_data.message/text/content/str]
+ E -- no --> G{team lead?<br/>orchestrator / ai_employee}
+ F --> G
+ G -- yes --> H[_collect_teammate_connections<br/>append as delegate_to_* tools]
+ G -- no --> I[ai_service.execute_chat_agent]
+ H --> I
+ I --> J[Return envelope]
+```
+
+## Decision Logic
+
+- **Task completion short-circuit**: if `task_data.status in {completed,
+ error}`, the handler strips **all** tools from `tool_data`. This prevents
+ Gemini from hallucinating a delegate call when the original prompt says
+ "just report the result".
+- **Auto-prompt fallback**: when `parameters.prompt` is empty and an
+ upstream node is connected to `input-main`, the handler pulls
+ `input_data.message` -> `text` -> `content` -> `str(input_data)` in that
+ order.
+- **Team-lead detection**: `TEAM_LEAD_TYPES = {'orchestrator_agent',
+ 'ai_employee'}`. Teammates are collected only for these two node types
+ and appended to `tool_data` as delegation targets.
+- **Master Skill expansion**: `masterSkill` source nodes are expanded in
+ `_collect_agent_connections` - each enabled entry in `skillsConfig`
+ becomes a separate skill entry with `node_id = f"{source_id}_{skill_key}"`.
+
+## Side Effects
+
+- **Database reads**: `database.get_node_parameters(source_id)` for every
+ connected skill, memory, tool, and teammate node.
+- **Database writes**: `TokenUsageMetric` and potentially `CompactionEvent`
+ rows (via `CompactionService` invoked inside `ai_service.execute_chat_agent`).
+- **Broadcasts**: `StatusBroadcaster.update_node_status` events for the
+ agent's execution phase (`executing`, `executing_tool`, `success`,
+ `error`), plus `executing_tool` fired on connected tool nodes when the LLM
+ invokes them.
+- **External API calls**: one or more calls to the configured LLM provider
+ (see `services/ai.py::execute_chat_agent` -> LangChain / LangGraph).
+- **Subprocess / file I/O**: none directly in the handler; tools invoked by
+ the LLM may trigger those themselves.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key(<provider>)` for the
+ configured LLM provider.
+- **Services**: `AIService.execute_chat_agent`, `CompactionService`,
+ `PricingService`, `StatusBroadcaster`.
+- **Python packages**: `langchain-core`, `langgraph`, plus provider SDKs.
+
+## Edge cases & known limits
+
+- Empty `prompt` with no `input-main` connection still calls
+ `execute_chat_agent` -- the LLM may produce a generic response. There is
+ no early-return error envelope for missing prompts in this handler.
+- When a `masterSkill` has zero enabled skills, no skill context is
+ injected and the agent runs without domain-specific instructions.
+- `input-teammates` is silently ignored for all non-team-lead node types
+ (the edge is collected but never expanded).
+- Token tracking and compaction happen inside `execute_chat_agent`; if the
+ configured provider is unknown, tracking is skipped without an error.
+
+## Related
+
+- **Dedicated-handler siblings**: [`deepAgent`](./deepAgent.md), [`rlmAgent`](./rlmAgent.md), [`claudeCodeAgent`](./claudeCodeAgent.md)
+- **Per-node variants** (short link-style docs):
+ [`androidAgent`](./androidAgent.md), [`codingAgent`](./codingAgent.md),
+ [`webAgent`](./webAgent.md), [`taskAgent`](./taskAgent.md),
+ [`socialAgent`](./socialAgent.md), [`travelAgent`](./travelAgent.md),
+ [`toolAgent`](./toolAgent.md), [`productivityAgent`](./productivityAgent.md),
+ [`paymentsAgent`](./paymentsAgent.md), [`consumerAgent`](./consumerAgent.md),
+ [`autonomousAgent`](./autonomousAgent.md),
+ [`orchestratorAgent`](./orchestratorAgent.md), [`aiEmployee`](./aiEmployee.md)
+- **Architecture docs**: [Memory Compaction](../../memory_compaction.md),
+ [Pricing Service](../../pricing_service.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/aiEmployee.md b/docs-internal/node-logic-flows/specialized_agents/aiEmployee.md
new file mode 100644
index 00000000..8af49294
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/aiEmployee.md
@@ -0,0 +1,47 @@
+# AI Employee (`ai_employee`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `ai_employee`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.purple` |
+| **Icon** | people / briefcase (U+1F465) |
+| **Team lead** | **yes** -- `input-teammates` handle enabled |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+Team-lead agent identical in behaviour to `orchestrator_agent`. Distinct
+only in frontend presentation (different icon, theme color, default
+labels) and an extra `maxConcurrent` parameter. Backend routing is the
+same: `handle_chat_agent` -> `_collect_teammate_connections` ->
+teammates appended to `tool_data` as `delegate_to_*` tools.
+
+## What is unique to this node
+
+- **`input-teammates` handle** (same as `orchestrator_agent`).
+- **`teamMode` parameter** (`parallel` / `sequential`, default `parallel`;
+ no `""` option).
+- **`maxConcurrent` parameter** (number, default `5`, range 1-20)
+ controlling max concurrent task executions.
+- **Frontend theming**: purple dracula accent.
+
+## Behaviour
+
+See **[Orchestrator Agent](./orchestratorAgent.md)** for the teammate
+expansion details, and **[Generic Specialized Agent Pattern](./_pattern.md)**
+for the shared contract.
+
+## Edge cases
+
+- Same as `orchestrator_agent`: non-agent teammates are silently skipped,
+ and `maxConcurrent` / `teamMode` are passed through as parameters but
+ not enforced by `handle_chat_agent` itself -- the `delegate_to_*`
+ implementation owns concurrency.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Sibling team lead**: [`orchestratorAgent`](./orchestratorAgent.md)
+- **Architecture**: [Agent Teams](../../agent_teams.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/androidAgent.md b/docs-internal/node-logic-flows/specialized_agents/androidAgent.md
new file mode 100644
index 00000000..ac80b9ee
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/androidAgent.md
@@ -0,0 +1,39 @@
+# Android Control Agent (`android_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `android_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) (routed via registry) |
+| **Theme color** | `dracula.green` |
+| **Icon** | phone (U+1F4F1) |
+| **AGENT_CONFIGS entry** | `AIAgentNode.tsx` key `android_agent` |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for Android device control. Users typically connect
+Android service nodes (`batteryMonitor`, `wifiAutomation`, `appLauncher`,
+etc.) directly to `input-tools`, or wire an `androidTool` toolkit, or attach
+the `android_agent` folder via a Master Skill.
+
+## What is unique to this node
+
+- **Intended tool set**: Android service nodes (16 total) and the
+ `androidTool` aggregator.
+- **Intended skills**: `server/skills/android_agent/` (12 skills:
+ personality, battery, wifi, bluetooth, location, etc.).
+- **Frontend theming**: green dracula accent, phone emoji in component
+ palette.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)** for the full
+contract: inputs, parameters, outputs, logic flow, decision logic, side
+effects, edge cases. This node routes to `handle_chat_agent` with no
+behavioural differences from the other 12 variants.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/android_agent/`](../../../server/skills/android_agent/)
diff --git a/docs-internal/node-logic-flows/specialized_agents/autonomousAgent.md b/docs-internal/node-logic-flows/specialized_agents/autonomousAgent.md
new file mode 100644
index 00000000..c2eb4ea4
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/autonomousAgent.md
@@ -0,0 +1,38 @@
+# Autonomous Agent (`autonomous_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `autonomous_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.purple` |
+| **Icon** | target (U+1F3AF) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for autonomous multi-step operations using the
+Code Mode patterns (agentic loops, progressive discovery, error recovery,
+multi-tool orchestration). Claims 81-98% token savings when paired with
+the autonomous skill pack.
+
+## What is unique to this node
+
+- **Intended tool set**: code executors + filesystem + HTTP, typically
+ combined so the agent writes code to orchestrate other tools.
+- **Intended skills**: `server/skills/autonomous/` (code-mode-skill,
+ agentic-loop-skill, progressive-discovery-skill, error-recovery-skill,
+ multi-tool-orchestration-skill).
+- **Frontend theming**: purple dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**. Routes to the
+same `handle_chat_agent` -- the "autonomous" behaviour comes entirely from
+the attached skill content, not a different execution engine.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/autonomous/`](../../../server/skills/autonomous/)
+- **Architecture**: [Autonomous Agent Creation](../../autonomous_agent_creation.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.md b/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.md
new file mode 100644
index 00000000..2d131b65
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.md
@@ -0,0 +1,133 @@
+# Claude Code Agent (`claude_code_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `claude_code_agent`) |
+| **Backend handler** | [`server/services/handlers/claude_code.py::handle_claude_code_agent`](../../../server/services/handlers/claude_code.py) |
+| **Backend service** | [`server/services/claude_code_service.py::ClaudeCodeService.execute`](../../../server/services/claude_code_service.py) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py::TestClaudeCodeAgent`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+Runs a Claude Code CLI subprocess (`claude -p <prompt> --output-format json
+...`) and returns the parsed JSON. Keeps a per-`node_id` session map so
+follow-up invocations resume with `--resume <session_id>`. This is the
+only specialized-agent node that shells out; the others stay in-process.
+
+## Inputs (handles)
+
+| Handle | Purpose |
+|--------|---------|
+| `input-main` | Auto-prompt fallback (reads `source.message / text / content`) |
+| `input-skill` | Skill instructions appended to `--append-system-prompt` |
+
+All other handles (`input-memory`, `input-tools`, `input-task`,
+`input-teammates`) are **ignored** by this handler.
+
+## Parameters
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `prompt` | string | `""` | User prompt passed via `-p` |
+| `systemPrompt` | string | `""` | Prepended to any skill content for `--append-system-prompt` |
+| `model` | string | `claude-sonnet-4-6` | Passed via `--model` |
+| `workingDirectory` | string | (default workspace) | `cwd` for the subprocess |
+| `allowedTools` | string | `Read,Edit,Bash,Glob,Grep,Write` | Passed via `--allowedTools` |
+| `maxTurns` | number | `10` | `--max-turns` |
+| `maxBudgetUsd` | number | `5.0` | **`--max-budget-usd`** (note: historical bug fixed to use this exact flag name) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `{ response, model, provider: 'anthropic', session_id, usage, timestamp }` |
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_claude_code_agent] --> B[broadcast executing]
+ B --> C{prompt param set?}
+ C -- no --> D[Scan input-main edges<br/>pull source.message/text/content]
+ C -- yes --> E[_collect_agent_connections for skills]
+ D --> F{prompt still empty?}
+ F -- yes --> G[Return envelope success=false<br/>error: No prompt provided]
+ F -- no --> E
+ E --> H[Build system_parts<br/>systemPrompt + skill.instructions]
+ H --> I[get_claude_code_service]
+ I --> J[service.execute<br/>spawns claude subprocess<br/>300s timeout]
+ J -- returncode != 0 --> K[RuntimeError<br/>caught by outer try/except<br/>returns success=false envelope]
+ J -- returncode == 0 --> L[Parse JSON stdout<br/>or fallback to raw text]
+ L --> M[Store session_id in service._session_map]
+ M --> N[broadcast success]
+ N --> O[Return envelope success=true]
+```
+
+## Decision Logic
+
+- **Prompt resolution**: explicit `prompt` param wins; otherwise scans
+ `input-main` edges and reads `source.message / text / content / str`.
+- **Skill collection**: uses `_collect_agent_connections` only to gather
+ skills. Memory, tools, teammates, task triggers are all discarded.
+- **System prompt assembly**: `systemPrompt` param + every enabled skill's
+ `instructions`, joined by `\n\n`, passed as
+ `--append-system-prompt`.
+- **Session resume**: `ClaudeCodeService._session_map[node_id]` is
+ consulted; when set, `--resume <session_id>` is added to argv.
+- **Working directory**: if `workingDirectory` is empty, the service
+ defaults to `{workspace_base_resolved}/default` and creates it if
+ missing.
+
+## Side Effects
+
+- **Subprocess spawn**: `asyncio.create_subprocess_exec('claude', '-p',
+ <prompt>, '--output-format', 'json', '--model', <model>, '--max-turns',
+ N, '--allowedTools', <list>, '--max-budget-usd', <usd>, [--resume
+ <session_id>,] [--append-system-prompt <system>,] ...)` with a 300s
+ `asyncio.wait_for` timeout. Falls back to `npx -y @anthropic-ai/claude-code`
+ when the `claude` binary is not on PATH.
+- **Broadcasts**: `StatusBroadcaster.update_node_status` -- executing
+ ("Starting Claude Code..." and "Running Claude Code (<model>)..."),
+ then success on completion.
+- **Database**: none directly; usage tracking happens only if the caller
+ wires it in (handler signature accepts `database=None` and never uses
+ it).
+- **File I/O**: creates `{workspace_base_resolved}/default` when the
+ default cwd does not exist.
+- **External API**: indirect -- the CLI calls Anthropic internally.
+
+## External Dependencies
+
+- **Binaries**: `claude` on PATH, or `npx` fallback.
+- **Python packages**: standard library only
+ (`asyncio.create_subprocess_exec`).
+- **Credentials**: Claude Code handles its own authentication via
+ `~/.claude-machina` (see [Claude OAuth](../../claude_code_agent_architecture.md));
+ MachinaOs does not inject an API key.
+
+## Edge cases & known limits
+
+- **No prompt -> early failure**: unlike `handle_chat_agent`, this
+ handler explicitly returns an error envelope when neither `prompt`
+ nor a connected `input-main` output yields text.
+- **`max_budget_usd <= 0`**: the `--max-budget-usd` flag is omitted
+ entirely (see `claude_code_service.py:50-51`). This silently disables
+ budget enforcement rather than passing `0`.
+- **Non-zero exit**: `ClaudeCodeService.execute` raises `RuntimeError`,
+ the handler's outer `except Exception` converts it to
+ `success=false` with the error message as the envelope's `error` field.
+- **300-second timeout**: `asyncio.wait_for(proc.communicate(),
+ timeout=300)` is hard-coded. Long CLI runs beyond 5 minutes abort and
+ surface as `TimeoutError` in the envelope.
+- **Tools/memory/teammates ignored**: connecting memory, tools, or
+ teammates has no effect. The CLI's own tool set is controlled by
+ `allowedTools`.
+- **JSON parsing fallback**: if stdout is not valid JSON, the service
+ returns `{"result": <raw text>}` -- the handler still reports
+ `success=true` and `response` contains the raw text.
+
+## Related
+
+- **Pattern siblings**: [`deepAgent`](./deepAgent.md), [`rlmAgent`](./rlmAgent.md)
+- **Architecture**: [Claude Code Agent](../../claude_code_agent_architecture.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/codingAgent.md b/docs-internal/node-logic-flows/specialized_agents/codingAgent.md
new file mode 100644
index 00000000..499cce88
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/codingAgent.md
@@ -0,0 +1,33 @@
+# Coding Agent (`coding_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `coding_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.cyan` |
+| **Icon** | laptop (U+1F4BB) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for code execution workflows. Typical tool
+connections: `pythonExecutor`, `javascriptExecutor`, `typescriptExecutor`,
+`shell`, `fileRead`, `fileModify`, `fsSearch`, `processManager`.
+
+## What is unique to this node
+
+- **Intended tool set**: code executors, filesystem tools, shell, process
+ manager.
+- **Intended skills**: `server/skills/coding_agent/` (python-skill,
+ javascript-skill, file-read-skill, file-modify-skill, fs-search-skill).
+- **Frontend theming**: cyan dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/coding_agent/`](../../../server/skills/coding_agent/)
diff --git a/docs-internal/node-logic-flows/specialized_agents/consumerAgent.md b/docs-internal/node-logic-flows/specialized_agents/consumerAgent.md
new file mode 100644
index 00000000..21c23213
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/consumerAgent.md
@@ -0,0 +1,32 @@
+# Consumer Agent (`consumer_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `consumer_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.purple` |
+| **Icon** | shopping cart (U+1F6D2) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for customer support and consumer interactions
+(order status, product recommendations). Like `payments_agent`, this is a
+naming / theming shell around `handle_chat_agent`.
+
+## What is unique to this node
+
+- **Intended tool set**: `httpRequest` against product / order APIs,
+ messaging nodes for customer replies.
+- **Intended skills**: no dedicated `server/skills/consumer_agent/` folder
+ ships today.
+- **Frontend theming**: purple dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/deepAgent.md b/docs-internal/node-logic-flows/specialized_agents/deepAgent.md
new file mode 100644
index 00000000..393b7ab5
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/deepAgent.md
@@ -0,0 +1,129 @@
+# Deep Agent (`deep_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `deep_agent`) |
+| **Backend handler** | [`server/services/handlers/deep_agent.py::handle_deep_agent`](../../../server/services/handlers/deep_agent.py) |
+| **Backend service** | [`server/services/agents/service.py::DeepAgentService.execute`](../../../server/services/agents/service.py) |
+| **Theme color** | `dracula.green` |
+| **Icon** | brain (U+1F9E0) |
+| **Team lead** | yes -- teammates become deepagents `SubAgent` dicts |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py::TestDeepAgent`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent backed by LangChain [DeepAgents](https://github.com/langchain-ai/deepagents)
+rather than the stock LangGraph loop. Provides built-in filesystem tools
+(read, write, edit, glob, grep, execute), sub-agent delegation,
+auto-summarization, and todo planning, all operating on a sandboxed
+per-workflow workspace (`data/workspaces/<workflow_id>/`).
+
+## Inputs (handles)
+
+Same 5 shared handles as the generic specialized agents plus an
+`input-teammates` handle used to seed deepagents sub-agents.
+
+| Handle | Purpose |
+|--------|---------|
+| `input-main` | Auto-prompt fallback |
+| `input-skill` | Skill instructions merged into system prompt |
+| `input-memory` | `simpleMemory` conversation history |
+| `input-tools` | Tools exposed to the deep-agent graph |
+| `input-task` | `taskTrigger` completion events |
+| `input-teammates` | Teammate agents converted to `SubAgent` dicts |
+
+## Parameters
+
+Standard `AI_AGENT_PROPERTIES` plus deepagents-specific options read by
+`DeepAgentService` (`recursionLimit`, etc.).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard agent envelope with `response`, `model`, `provider` |
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_deep_agent] --> B[_collect_agent_connections]
+ B --> C{task_data present?}
+ C -- completed/error --> D[prepend task context<br/>strip tools]
+ C -- no --> E{prompt empty<br/>and input_data?}
+ D --> E
+ E -- yes --> F[prompt = input_data.message/text/content]
+ E -- no --> G[_collect_teammate_connections]
+ F --> G
+ G --> H[workspace_dir from context<br/>injected into parameters]
+ H --> I[ai_service.deep_agent_service.execute]
+ I --> J[FilesystemBackend root=workspace_dir<br/>virtual_mode=True]
+ J --> K[DeepAgentService builds LangGraph<br/>via create_deep_agent]
+ K --> L[Graph invocation]
+ L --> M[Return envelope]
+```
+
+## Decision Logic
+
+- **Same connection-collection short-circuits** as `handle_chat_agent`:
+ task completion strips tools; empty prompt falls back to upstream
+ message/text/content.
+- **Workspace injection**: `context['workspace_dir']` is copied into
+ `parameters['workspace_dir']` so `DeepAgentService` can pass it to
+ `FilesystemBackend(root_dir=workspace_dir, virtual_mode=True)`.
+- **Teammates become deepagents sub-agents**: passed as a list to
+ `service.execute(..., teammates=teammates)`; the service constructs
+ deepagents `SubAgent` dicts and injects them into
+ `create_deep_agent(subagents=...)`.
+- **Tool building**: the handler passes `build_tool_fn=ai_service._build_tool_from_node`
+ so the service layer can convert raw `tool_data` into LangChain
+ `StructuredTool` instances inside the deepagents graph.
+
+## Side Effects
+
+- **Database reads**: `database.get_node_parameters(source_id)` for every
+ connected skill, memory, tool, and teammate node.
+- **Database writes**: token usage and compaction rows via
+ `DeepAgentService` -> `AIService` helpers.
+- **Broadcasts**: `StatusBroadcaster.update_node_status` (executing,
+ success, error), plus `executing_tool` for tools invoked during the
+ deepagents run.
+- **File I/O**: reads and writes within `data/workspaces/<workflow_id>/`
+ via the sandboxed `FilesystemBackend`.
+- **External API calls**: LLM provider calls inside the deepagents graph
+ (one per planning / tool / summarization step).
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key(<provider>)`.
+- **Services**: `DeepAgentService`, `StatusBroadcaster`,
+ `PricingService`, `CompactionService`, `FilesystemBackend`.
+- **Python packages**: `deepagents`, `langchain-core`, `langgraph`,
+ provider SDKs.
+- **Filesystem**: writable `data/workspaces/<workflow_id>/` directory.
+
+## Edge cases & known limits
+
+- **Missing workspace**: if `context['workspace_dir']` is absent
+ (`None`), no injection happens; `DeepAgentService` falls back to
+ `Settings().workspace_base_dir`. The handler logs `workspace_dir from
+ context: None` at INFO but does not short-circuit.
+- **Missing `deepagents` package**: `DeepAgentService.execute` raises an
+ `ImportError` which the handler's surrounding `NodeExecutor.execute`
+ wrapper converts into a failure envelope. There is no explicit
+ preflight check in the handler itself.
+- **Teammate filtering**: uses `_collect_teammate_connections` which
+ filters to `AI_AGENT_TYPES`; non-agent nodes on `input-teammates` are
+ silently skipped.
+- **No task-context tool rename**: unlike `handle_chat_agent` where the
+ stripped tools are replaced by delegate_to_* tools for team leads, the
+ deep_agent task-completion branch strips all tools outright. A
+ subsequent user turn must re-trigger a fresh execution to restore them.
+
+## Related
+
+- **Pattern siblings**: [`rlmAgent`](./rlmAgent.md), [`claudeCodeAgent`](./claudeCodeAgent.md)
+- **Generic pattern**: [`_pattern.md`](./_pattern.md) (for the shared
+ `_collect_agent_connections` helper)
+- **Architecture**: [Deep Agent](../../deep_agent.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.md b/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.md
new file mode 100644
index 00000000..3fa709fd
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/orchestratorAgent.md
@@ -0,0 +1,65 @@
+# Orchestrator Agent (`orchestrator_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `orchestrator_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.cyan` |
+| **Icon** | musical score (U+1F3BC) |
+| **Team lead** | **yes** -- `input-teammates` handle enabled |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+Team-lead agent that coordinates multiple specialized agents. Teammates
+are wired via the extra `input-teammates` handle and become
+`delegate_to_<agent_type>` tools the orchestrator can call.
+
+## What is unique to this node
+
+- **`input-teammates` handle** (extra input beyond the shared 5).
+- **`teamMode` parameter** (`""` / `parallel` / `sequential`) controlling
+ how delegate_to_* calls are executed.
+- **Team lead detection**: `handle_chat_agent` checks `node_type in
+ TEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}` and calls
+ `_collect_teammate_connections` to expand teammates into tools.
+- **Frontend theming**: cyan dracula accent.
+
+## Teammate collection
+
+`_collect_teammate_connections(node_id, context, database)` in
+`handlers/ai.py`:
+
+1. Scans `context.edges` for `edge.target == node_id` and
+ `edge.targetHandle == 'input-teammates'`.
+2. Resolves the source node in `context.nodes`.
+3. Filters to `node_type in AI_AGENT_TYPES`.
+4. Loads `database.get_node_parameters(source_id)` for each teammate.
+5. Returns a list of `{node_id, node_type, label, parameters}` dicts.
+
+The teammates are then appended to `tool_data` before
+`execute_chat_agent` is called, so the LLM sees them as ordinary tools.
+
+## Behaviour
+
+Inputs, parameters, outputs, logic flow -- see **[Generic Specialized
+Agent Pattern](./_pattern.md)**. The only difference is the teammate
+expansion above.
+
+## Edge cases
+
+- Non-`AI_AGENT_TYPES` nodes wired to `input-teammates` are silently
+ skipped.
+- `teamMode` is collected by `execute_chat_agent` but the actual
+ parallel / sequential scheduling is not enforced at this layer -- it
+ depends on how the downstream `delegate_to_*` tool implementation handles
+ concurrent invocations.
+- When zero teammates are connected, the node behaves identically to any
+ other specialized agent.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Sibling team lead**: [`aiEmployee`](./aiEmployee.md)
+- **Architecture**: [Agent Teams](../../agent_teams.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/paymentsAgent.md b/docs-internal/node-logic-flows/specialized_agents/paymentsAgent.md
new file mode 100644
index 00000000..3e5912bc
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/paymentsAgent.md
@@ -0,0 +1,32 @@
+# Payments Agent (`payments_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `payments_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.green` |
+| **Icon** | credit card (U+1F4B3) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for payment processing and financial workflows.
+No first-party payment tools ship with MachinaOs yet, so users typically
+wire `httpRequest` against a payment provider (Stripe, Razorpay) as a tool.
+
+## What is unique to this node
+
+- **Intended tool set**: `httpRequest` against payment APIs.
+- **Intended skills**: no dedicated `server/skills/payments_agent/` folder
+ ships today -- the node is a naming / theming shell around
+ `handle_chat_agent`.
+- **Frontend theming**: green dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/productivityAgent.md b/docs-internal/node-logic-flows/specialized_agents/productivityAgent.md
new file mode 100644
index 00000000..2c9af553
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/productivityAgent.md
@@ -0,0 +1,32 @@
+# Productivity Agent (`productivity_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `productivity_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.cyan` |
+| **Icon** | clock (U+23F0) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for Google Workspace productivity flows: email,
+calendar, drive, sheets, tasks, contacts.
+
+## What is unique to this node
+
+- **Intended tool set**: `gmail`, `calendar`, `drive`, `sheets`, `tasks`,
+ `contacts`, plus scheduling tools (`timer`, `cronScheduler`).
+- **Intended skills**: `server/skills/productivity_agent/` (gmail-skill,
+ calendar-skill, drive-skill, sheets-skill, tasks-skill, contacts-skill).
+- **Frontend theming**: cyan dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/productivity_agent/`](../../../server/skills/productivity_agent/)
diff --git a/docs-internal/node-logic-flows/specialized_agents/rlmAgent.md b/docs-internal/node-logic-flows/specialized_agents/rlmAgent.md
new file mode 100644
index 00000000..51f98362
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/rlmAgent.md
@@ -0,0 +1,104 @@
+# RLM Agent (`rlm_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `rlm_agent`) |
+| **Backend handler** | [`server/services/handlers/rlm.py::handle_rlm_agent`](../../../server/services/handlers/rlm.py) |
+| **Backend service** | `AIService.rlm_service` -> `RLMService.execute` |
+| **Theme color** | `dracula.orange` |
+| **Icon** | brain (U+1F9E0) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py::TestRLMAgent`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+Recursive Language Model agent. Instead of LangGraph tool-calling, the
+LLM is prompted to emit Python code that is executed in a REPL and may
+recursively call `llm_query()` or `rlm_query()` and end with `FINAL(...)`
+to return a result. See [RLM Service](../../rlm_service.md).
+
+## Inputs (handles)
+
+Same 5 shared handles as the generic specialized agents. **No
+`input-teammates` handle** -- RLM does not support team-lead expansion.
+
+## Parameters
+
+Standard `AI_AGENT_PROPERTIES` plus RLM extras:
+
+| Name | Type | Default | Description |
+|------|------|---------|-------------|
+| `maxIterations` | number | `30` | Hard cap on REPL iterations before forcing `FINAL(...)` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `{ response, model, provider, iterations, timestamp }` |
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_rlm_agent] --> B[_collect_agent_connections]
+ B --> C{task_data present?}
+ C -- completed/error --> D[prepend task context<br/>strip tools]
+ C -- no --> E{prompt empty<br/>and input_data?}
+ D --> E
+ E -- yes --> F[prompt = input_data.message/text/content]
+ E -- no --> G[ai_service.rlm_service.execute]
+ F --> G
+ G --> H[RLMService REPL loop<br/>llm_query / rlm_query / FINAL]
+ H --> I[Return envelope]
+```
+
+## Decision Logic
+
+- **Same preprocessing as `handle_chat_agent`**: task-completion tool
+ strip, auto-prompt fallback.
+- **No teammate expansion**: `_collect_teammate_connections` is not
+ called.
+- **No workspace injection**: RLM executes code in an in-memory REPL
+ (`exec()`), not on a real filesystem; the handler does not pass
+ `workspace_dir`.
+
+## Side Effects
+
+- **Database reads**: `database.get_node_parameters` for each connected
+ skill/memory/tool node.
+- **Database writes**: token usage metrics via `RLMService` ->
+ `AIService` helpers.
+- **Broadcasts**: `StatusBroadcaster.update_node_status` (executing,
+ success, error); `executing_tool` for connected tools invoked during
+ REPL calls.
+- **External API calls**: one call to the big LM per REPL turn, plus
+ nested `llm_query()` calls to the small LM provider when configured.
+- **File I/O / subprocess**: none directly; REPL `exec()` may import
+ libraries and run computation in-process.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key(<provider>)` for big LM, and
+ optionally the small-LM provider wired as a connected chat-model node.
+- **Services**: `RLMService`, `StatusBroadcaster`, `PricingService`.
+- **Python packages**: standard library + LangChain core; no special
+ deepagents dependency.
+
+## Edge cases & known limits
+
+- **REPL exec() is in-process**: user code runs in the backend Python
+ process with no sandboxing. The skill prompt is expected to constrain
+ the LLM, but nothing prevents a misbehaving LLM from importing
+ `subprocess` or `os` and doing I/O.
+- **No per-step timeout**: `maxIterations` is the only bound; a single
+ REPL step can hang the handler if user code blocks.
+- **No team-lead support**: `input-teammates` is not read. Connecting
+ agents there has no effect.
+- **LLM output parsing**: the REPL parser expects a specific fenced-code
+ format. If the big LM ignores formatting instructions, the loop
+ aborts early and returns whatever partial result it collected.
+
+## Related
+
+- **Pattern siblings**: [`deepAgent`](./deepAgent.md), [`claudeCodeAgent`](./claudeCodeAgent.md)
+- **Architecture**: [RLM Service](../../rlm_service.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/socialAgent.md b/docs-internal/node-logic-flows/specialized_agents/socialAgent.md
new file mode 100644
index 00000000..36e74aec
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/socialAgent.md
@@ -0,0 +1,33 @@
+# Social Media Agent (`social_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `social_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.green` |
+| **Icon** | phone (U+1F4F1) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for social messaging across WhatsApp, Telegram,
+Twitter/X, and the unified `socialSend` node.
+
+## What is unique to this node
+
+- **Intended tool set**: `whatsappSend`, `whatsappDb`, `telegramSend`,
+ `twitterSend`, `twitterSearch`, `twitterUser`, `socialSend`.
+- **Intended skills**: `server/skills/social_agent/` (whatsapp-send-skill,
+ whatsapp-db-skill, twitter-send-skill, twitter-search-skill,
+ twitter-user-skill).
+- **Frontend theming**: green dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/social_agent/`](../../../server/skills/social_agent/)
diff --git a/docs-internal/node-logic-flows/specialized_agents/taskAgent.md b/docs-internal/node-logic-flows/specialized_agents/taskAgent.md
new file mode 100644
index 00000000..8adbf027
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/taskAgent.md
@@ -0,0 +1,31 @@
+# Task Management Agent (`task_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `task_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.purple` |
+| **Icon** | clipboard (U+1F4CB) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for task scheduling and planning. Typical tool
+connections: `timer`, `cronScheduler`, `taskManager`, `writeTodos`.
+
+## What is unique to this node
+
+- **Intended tool set**: scheduling, reminders, todo planning.
+- **Intended skills**: `server/skills/task_agent/` (timer-skill,
+ cron-scheduler-skill, task-manager-skill, write-todos-skill).
+- **Frontend theming**: purple dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/task_agent/`](../../../server/skills/task_agent/)
diff --git a/docs-internal/node-logic-flows/specialized_agents/toolAgent.md b/docs-internal/node-logic-flows/specialized_agents/toolAgent.md
new file mode 100644
index 00000000..203d2561
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/toolAgent.md
@@ -0,0 +1,29 @@
+# Tool Agent (`tool_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `tool_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.yellow` |
+| **Icon** | wrench (U+1F527) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+Domain-agnostic AI agent for mixing arbitrary tools. Use when the intended
+tool set spans multiple categories and no other specialized agent fits.
+
+## What is unique to this node
+
+- **Intended tool set**: any combination of workflow tool nodes.
+- **Intended skills**: none pre-assigned; user wires whatever fits.
+- **Frontend theming**: yellow dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
diff --git a/docs-internal/node-logic-flows/specialized_agents/travelAgent.md b/docs-internal/node-logic-flows/specialized_agents/travelAgent.md
new file mode 100644
index 00000000..797e1a32
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/travelAgent.md
@@ -0,0 +1,31 @@
+# Travel Agent (`travel_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `travel_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.orange` |
+| **Icon** | airplane (U+2708) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for travel planning. Typical tool connections:
+`gmaps_locations`, `gmaps_nearby_places`, `calendar`, `braveSearch`.
+
+## What is unique to this node
+
+- **Intended tool set**: Google Maps, calendar, search.
+- **Intended skills**: `server/skills/travel_agent/` (geocoding-skill,
+ nearby-places-skill).
+- **Frontend theming**: orange dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/travel_agent/`](../../../server/skills/travel_agent/)
diff --git a/docs-internal/node-logic-flows/specialized_agents/webAgent.md b/docs-internal/node-logic-flows/specialized_agents/webAgent.md
new file mode 100644
index 00000000..acc45625
--- /dev/null
+++ b/docs-internal/node-logic-flows/specialized_agents/webAgent.md
@@ -0,0 +1,34 @@
+# Web Control Agent (`web_agent`)
+
+| Field | Value |
+|------|-------|
+| **Category** | specialized_agents |
+| **Frontend definition** | [`client/src/nodeDefinitions/specializedAgentNodes.ts`](../../../client/src/nodeDefinitions/specializedAgentNodes.ts) (search `web_agent`) |
+| **Backend handler** | [`server/services/handlers/ai.py::handle_chat_agent`](../../../server/services/handlers/ai.py) |
+| **Theme color** | `dracula.pink` |
+| **Icon** | globe (U+1F310) |
+| **Tests** | [`server/tests/nodes/test_specialized_agents.py`](../../../server/tests/nodes/test_specialized_agents.py) |
+
+## Purpose
+
+AI agent pre-configured for web automation. Typical tool connections:
+`httpRequest`, `browser`, `crawleeScraper`, `apifyActor`, `proxyRequest`,
+and any of the search nodes (`braveSearch`, `serperSearch`,
+`perplexitySearch`, `duckduckgoSearch`).
+
+## What is unique to this node
+
+- **Intended tool set**: HTTP, browser, scrapers, proxies, search.
+- **Intended skills**: `server/skills/web_agent/` (http-request-skill,
+ browser-skill, crawlee-scraper-skill, apify-skill, proxy-config-skill,
+ duckduckgo/brave/serper/perplexity search skills).
+- **Frontend theming**: pink dracula accent.
+
+## Behaviour
+
+See **[Generic Specialized Agent Pattern](./_pattern.md)**.
+
+## Related
+
+- **Pattern doc**: [`_pattern.md`](./_pattern.md)
+- **Skills**: [`server/skills/web_agent/`](../../../server/skills/web_agent/)
diff --git a/docs-internal/node-logic-flows/telegram_social/socialReceive.md b/docs-internal/node-logic-flows/telegram_social/socialReceive.md
new file mode 100644
index 00000000..3022e010
--- /dev/null
+++ b/docs-internal/node-logic-flows/telegram_social/socialReceive.md
@@ -0,0 +1,212 @@
+# Social Receive (`socialReceive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social |
+| **Frontend definition** | [`client/src/nodeDefinitions/socialNodes.ts`](../../../client/src/nodeDefinitions/socialNodes.ts) |
+| **Backend handler** | [`server/services/handlers/social.py::handle_social_receive`](../../../server/services/handlers/social.py) |
+| **Tests** | [`server/tests/nodes/test_telegram_social.py`](../../../server/tests/nodes/test_telegram_social.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Normalizes messages from any platform-specific trigger (WhatsApp, Telegram,
+Chat, Webchat, Discord, Slack, ...) into the unified "inbound message" schema.
+Applies channel / message-type / sender / keyword filters, then fans the
+result out across four dedicated handles (`message`, `media`, `contact`,
+`metadata`) so downstream agents can grab just the slice they need.
+
+The dispatcher in `NodeExecutor._dispatch` special-cases `socialReceive`
+(node_executor.py:367-374) to collect upstream outputs via
+`_get_connected_outputs_with_info` and inject them as `outputs` / `source_nodes`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | yes | Upstream trigger output (`whatsappReceive`, `telegramReceive`, `chatTrigger`, ...) - this is what gets normalized |
+
+The executor resolves upstream outputs keyed by source node **type**, so the
+handler walks `source_nodes` and looks up `outputs[source_type]`.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `channelFilter` | options | `all` | no | - | Only allow messages whose detected `channel` matches |
+| `messageTypeFilter` | options | `all` | no | - | Filter by `message_type` |
+| `senderFilter` | options | `all` | no | - | `all` / `any_contact` / `contact` / `group` / `keywords` |
+| `contactPhone` | string | `""` | yes when `senderFilter=contact` | `senderFilter: ['contact']` | Exact phone compare |
+| `groupId` | string | `""` | yes when `senderFilter=group` | `senderFilter: ['group']` | Exact chat_id compare |
+| `keywords` | string | `""` | no | `senderFilter: ['keywords']` | Comma-separated, lower-case substring match |
+| `ignoreOwnMessages` | boolean | `true` | no | - | Drop messages where `is_from_me=True` |
+| `ignoreBots` | boolean | `false` | no | - | Drop messages where `is_bot=True` |
+
+## Outputs (handles)
+
+`NodeExecutor` stores the handler's `result.result` under `output_main`
+**and** splits it into four additional output-store keys so different
+downstream handles can consume different slices (node_executor.py:292-296):
+
+| Handle / key | Shape | Description |
+|--------------|-------|-------------|
+| `output_main` | object | Full unified message (backwards-compatible) |
+| `output_message` | string | `result.message` - plain text for LLM input |
+| `output_media` | object | `result.media` - `{ url, type, mimetype, caption, size, thumbnail, filename }` (empty `{}` when no media) |
+| `output_contact` | object | `result.contact` - `{ sender, sender_phone, sender_name, sender_username, channel, is_group, group_info, chat_title }` |
+| `output_metadata` | object | `result.metadata` - `{ message_id, chat_id, timestamp, message_type, is_from_me, is_forwarded, reply_to, thread_id }` |
+
+### Output payload (`result`)
+
+```ts
+{
+ // Per-handle slices (also written to dedicated output keys):
+ message: string;
+ media: { url, type, mimetype, caption, size, thumbnail, filename } | {};
+ contact: { sender, sender_phone, sender_name, sender_username, channel, is_group, group_info, chat_title };
+ metadata: { message_id, chat_id, timestamp, message_type, is_from_me, is_forwarded, reply_to, thread_id };
+
+ // Plus the full unified message at the top level (spread):
+ message_id: string;
+ channel: string;
+ sender: string;
+ sender_phone: string;
+ sender_name: string;
+ sender_username: string;
+ chat_id: string;
+ chat_title: string;
+ chat_type: 'dm' | 'group' | string;
+ message_type: string;
+ text: string;
+ timestamp: string;
+ is_group: boolean;
+ is_from_me: boolean;
+ is_forwarded: boolean;
+ is_bot: boolean;
+ is_admin: boolean;
+ thread_id?: any;
+ account_id?: any;
+ session_id?: any;
+ group_info?: any;
+ location?: any;
+ contact?: any;
+ poll?: any;
+ reaction?: any;
+ reply_to?: any;
+ mentions?: any;
+ raw: object;
+}
+```
+
+When a message is filtered out the handler returns
+`{ success: true, result: null, filtered: true, reason: "Message did not pass filters" }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[_dispatch specialcase] --> A1[_get_connected_outputs_with_info]
+ A1 --> B[handle_social_receive]
+ B --> C[Scan source_nodes,<br/>pick first output with<br/>message_id / text / message]
+ C -- none --> C2[Fallback: iterate outputs dict]
+ C2 -- still none --> Efail[Return success=false<br/>error: No message data]
+ C -- found --> D[Detect source_channel from node type<br/>or output.channel / sender suffix]
+ C2 -- found --> D
+ D --> E[_normalize_to_unified_format]
+ E --> F{_apply_filters}
+ F -- fail --> Ffilt[Return success=true<br/>result=null, filtered=true]
+ F -- pass --> G[Build 4-slice result dict +<br/>spread full unified message]
+ G --> H[Return success=true]
+
+ subgraph Executor post-processing
+ H --> H1[output_main = result]
+ H1 --> H2[output_message = result.message]
+ H2 --> H3[output_media = result.media]
+ H3 --> H4[output_contact = result.contact]
+ H4 --> H5[output_metadata = result.metadata]
+ end
+```
+
+## Decision Logic
+
+- **Source resolution (primary path)**: Loop over `source_nodes`, look up
+ `outputs[source_type]`, accept the first dict that has any of
+ `message_id` / `text` / `message`.
+- **Source resolution (fallback)**: If the primary path fails, iterate
+ `outputs.items()` and apply the same detection. Channel detection here also
+ sniffs `sender.endswith('@s.whatsapp.net')` to tag WhatsApp.
+- **Channel detection** (case-insensitive substring on node type or key):
+ `whatsapp`/`telegram`/`discord`/`slack`/`chat` (-> `webchat`). Falls back to
+ `output.channel` if present, else `"unknown"`.
+- **Chat type**: `_determine_chat_type` returns `data.chat_type` if set, else
+ `"group"` if `is_group` else `"dm"`.
+- **Filters** (`_apply_filters`):
+ - `channelFilter`: exact match against normalized `channel`.
+ - `messageTypeFilter`: exact match against `message_type`.
+ - `senderFilter=any_contact`: rejects group messages only.
+ - `senderFilter=contact`: rejects when `sender_phone != contactPhone` (only
+ if `contactPhone` is truthy).
+ - `senderFilter=group`: rejects when `chat_id != groupId` (only if `groupId` is truthy).
+ - `senderFilter=keywords`: lower-cased substring match on the `text`; empty
+ `keywords` accepts all.
+ - `ignoreOwnMessages` (default `true`): drops `is_from_me`.
+ - `ignoreBots`: drops `is_bot`.
+- **Message id synthesis**: If upstream omits `message_id`, a random 8-char
+ hex (`uuid4().hex[:8]`) is assigned.
+- **Webchat defaults**: When `source_channel == 'webchat'`, missing `sender` is
+ set to `webchat_<session_id>`, `chat_id` defaults to the session id, and
+ `sender_name` defaults to `"User"`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none from the handler; executor writes the five output-store
+ keys.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none directly; relies on upstream trigger nodes feeding
+ `outputs` via the executor.
+- **Python packages**: stdlib only (`uuid`, `time`, `datetime`, `typing`).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **First-match wins**: When multiple upstream triggers feed `socialReceive`
+ in the same execution, only the first candidate (by `source_nodes` iteration
+ order) is normalized; the others are silently ignored.
+- **Channel heuristic is fragile**: Detection uses `.lower() in source_type`
+ and `sender.endswith('@s.whatsapp.net')`. A node type named `chatty_*`
+ becomes `webchat`, and a Telegram message without a matching node type
+ falls back to `"unknown"`.
+- **Filtered messages still succeed**: When filters reject a message, the
+ envelope is `success=true, result=null, filtered=true`. Downstream nodes
+ receive `null` via the output store - anything that expects a dict must
+ handle this.
+- **`_apply_filters` default for `ignoreOwnMessages` is `True`**: Loopback
+ messages (echo bots, self-tests) are silently dropped unless explicitly
+ turned off in the UI.
+- **Top-level spread**: `{ ...unified_message }` overwrites the dedicated
+ `contact` / `media` keys the handler just built, with the raw versions from
+ the upstream message. Code that reads `result.contact` via the output-store
+ key `output_contact` sees the handler's structured slice; code that reads
+ `result['contact']` from `output_main` may see the upstream raw contact
+ dict instead (they are not the same shape).
+- **UUID `message_id` on fallback**: Not cryptographically unique across
+ sessions; two workflows receiving chatTrigger messages at the same time
+ can generate colliding ids.
+- **`source_nodes` parameter typo risk**: Handler accepts `outputs=None` and
+ `source_nodes=None` and falls back to `context['outputs']` / `[]` - useful
+ for direct unit tests but also means a broken executor path would silently
+ return "No message data received" instead of failing fast.
+
+## Related
+
+- **Sibling nodes**: [`socialSend`](./socialSend.md), [`telegramReceive`](./telegramReceive.md)
+- **Upstream triggers**: [`telegramReceive`](./telegramReceive.md); WhatsApp/Chat triggers live in other categories
+- **Dispatcher special-case**: `server/services/node_executor.py:287-296, 367-374`
diff --git a/docs-internal/node-logic-flows/telegram_social/socialSend.md b/docs-internal/node-logic-flows/telegram_social/socialSend.md
new file mode 100644
index 00000000..a86fc5d0
--- /dev/null
+++ b/docs-internal/node-logic-flows/telegram_social/socialSend.md
@@ -0,0 +1,156 @@
+# Social Send (`socialSend`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/socialNodes.ts`](../../../client/src/nodeDefinitions/socialNodes.ts) |
+| **Backend handler** | [`server/services/handlers/social.py::handle_social_send`](../../../server/services/handlers/social.py) |
+| **Tests** | [`server/tests/nodes/test_telegram_social.py`](../../../server/tests/nodes/test_telegram_social.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | yes - works as a workflow node and as an AI Agent tool |
+
+## Purpose
+
+Platform-agnostic outbound messaging. Routes the payload to the platform
+identified by `channel` - currently only `whatsapp` is implemented; every
+other value (`telegram`, `discord`, `slack`, `signal`, `sms`, `webchat`,
+`email`, `matrix`, `teams`) falls through to an "not yet implemented" stub
+and surfaces as a failed envelope.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; consumed only via template resolution on individual params (e.g. `message`) |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `channel` | options | `whatsapp` | no | - | Destination platform - only `whatsapp` is wired today |
+| `recipientType` | options | `phone` | no | - | `phone` / `group` / `channel` / `user` / `chat` |
+| `phone` | string | `""` | yes when `recipientType=phone` | `recipientType: ['phone']` | Destination phone (WhatsApp style incl. country code) |
+| `groupId` | string | `""` | yes when `recipientType=group` | `recipientType: ['group']` | Group JID |
+| `channelId` | string | `""` | yes when `recipientType=channel` | `recipientType: ['channel']` | Newsletter/channel JID |
+| `userId` | string | `""` | yes when `recipientType=user` | `recipientType: ['user']` | Platform user id |
+| `chatId` | string | `""` | yes when `recipientType=chat` | `recipientType: ['chat']` | Generic chat id |
+| `messageType` | options | `text` | no | - | `text`/`image`/`video`/`audio`/`document`/`sticker`/`location`/`contact`/`poll`/`buttons`/`list` |
+| `message` | string | `""` | yes when `messageType=text` | `messageType: ['text']` | Message body |
+| `mediaSource` | options | `url` | no | `messageType: ['image','video','audio','document','sticker']` | One of `url`/`base64`/`file` |
+| `mediaUrl` / `mediaData` / `filePath` | string | `""` | depends on `mediaSource` | (see above) | Media payload |
+| `mimeType`, `caption`, `filename` | string | `""` | no | media types | Extra media fields |
+| `latitude`, `longitude`, `locationName`, `address` | mixed | - | yes for location | `messageType: ['location']` | Location fields |
+| `contactName`, `vcard` | string | `""` | yes for contact | `messageType: ['contact']` | vCard fields |
+| `replyToMessage` | boolean | `false` | no | - | Send as reply |
+| `replyMessageId` | string | `""` | yes when `replyToMessage=true` | - | Message id to reply to |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Send result envelope |
+| `output-tool` | object | Same payload, emitted when wired to an AI agent's `input-tools` |
+
+### Output payload
+
+```ts
+{
+ success: true;
+ message_id: string | null;
+ channel: string; // e.g. 'whatsapp'
+ recipient: string; // resolved phone / groupId / channelId / userId / chatId
+ recipient_type: string;
+ message_type: string;
+ timestamp: string; // ISO
+}
+```
+
+Wrapped in the standard envelope `{ success, node_id, node_type, result, execution_time, timestamp }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_social_send] --> B[Read channel / recipientType / messageType]
+ B --> C{recipientType}
+ C -- phone --> C1[recipient = params.phone]
+ C -- group --> C2[recipient = params.groupId]
+ C -- channel --> C3[recipient = params.channelId]
+ C -- user --> C4[recipient = params.userId]
+ C -- chat --> C5[recipient = params.chatId]
+ C1 & C2 & C3 & C4 & C5 --> D{recipient truthy?}
+ D -- no --> Eval[raise ValueError<br/>caught -> success=false]
+ D -- yes --> E{channel}
+ E -- whatsapp --> W[_send_via_whatsapp<br/>-> routers.whatsapp.handle_whatsapp_send]
+ E -- other --> Stub[Return success=false stub<br/>'Platform X is not yet implemented']
+ W --> F{result.success?}
+ Stub --> F
+ F -- false --> Eraise[raise Exception<br/>caught -> success=false envelope]
+ F -- true --> Ok[Return success=true<br/>with message_id / channel / recipient]
+```
+
+## Decision Logic
+
+- **Recipient resolution**: Hard-coded mapping from `recipientType` to a
+ specific parameter key. An unknown `recipientType` leaves `recipient = None`
+ and the handler raises `ValueError("Recipient (<type>) is required")`.
+- **Channel dispatch**: Python `if/elif` on `channel`. Only `"whatsapp"` is
+ wired. Every other value returns
+ `{"success": False, "error": "Platform '<x>' is not yet implemented"}`
+ which is then re-raised as a generic `Exception` and becomes the envelope's
+ `error` string.
+- **Message type branching**: `_send_via_whatsapp` converts the social-send
+ parameter shape into the whatsapp-send shape (camelCase -> snake_case,
+ media sources, reply flags). Unknown `messageType` values fall through
+ without setting any media/content fields - the downstream WhatsApp handler
+ is responsible for rejecting them.
+- **Reply handling**: Only set when `replyToMessage` is truthy; sets
+ `is_reply=True` and copies `replyMessageId -> reply_message_id`.
+
+## Side Effects
+
+- **Database writes**: none directly. The WhatsApp handler this delegates
+ to may record usage.
+- **Broadcasts**: none from `handle_social_send` itself; broadcasts originate
+ in the underlying platform handler.
+- **External API calls**: delegated to `routers.whatsapp.handle_whatsapp_send`
+ for the `whatsapp` channel, which hits the WhatsApp RPC service
+ (default `http://localhost:9400`).
+- **File I/O**: none from this handler. `mediaSource=file` reads are delegated.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none at this layer - the WhatsApp handler manages its own
+ RPC connection.
+- **Services**: `routers.whatsapp.handle_whatsapp_send` (imported lazily
+ inside `_send_via_whatsapp`).
+- **Python packages**: stdlib only (`time`, `datetime`, `typing`).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Only WhatsApp is implemented**: The node advertises 10 channels but silently
+ degrades to `"Platform '<x>' is not yet implemented"` for the other 9.
+- **Lossy exception surface**: A failed WhatsApp call returns
+ `{"success": False, "error": "..."}`, which the outer code re-raises as a
+ generic `Exception(result.get('error', 'Send failed'))`. The traceback is
+ swallowed; only the string survives.
+- **Recipient defaults**: When `recipientType` is something the code does not
+ handle, `recipient` stays `None` and the ValueError message reports the
+ received `recipient_type` string back to the user. Good for debugging, bad
+ for LLM tool use (the LLM then retries with a different type).
+- **`groupId` used for non-phone `recipient_type`**: Inside `_send_via_whatsapp`,
+ anything that is not `phone` maps onto `group_id` in the WhatsApp params,
+ including `channel`/`user`/`chat`. This means channels/users/chats end up
+ being sent as WhatsApp groups, which the RPC will likely reject.
+- **camelCase vs snake_case drift**: Node parameters are mostly camelCase
+ (`recipientType`, `messageType`, `mediaUrl`) while the WhatsApp handler
+ expects snake_case; the conversion in `_send_via_whatsapp` is manual and
+ easy to drift from new parameters added on either side.
+
+## Related
+
+- **Sibling nodes**: [`socialReceive`](./socialReceive.md), [`telegramSend`](./telegramSend.md)
+- **Downstream handler**: `routers.whatsapp.handle_whatsapp_send`
+- **Architecture docs**: WhatsApp Integration section in the root [`CLAUDE.md`](../../../CLAUDE.md)
diff --git a/docs-internal/node-logic-flows/telegram_social/telegramReceive.md b/docs-internal/node-logic-flows/telegram_social/telegramReceive.md
new file mode 100644
index 00000000..23e14646
--- /dev/null
+++ b/docs-internal/node-logic-flows/telegram_social/telegramReceive.md
@@ -0,0 +1,158 @@
+# Telegram Receive (`telegramReceive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/telegramNodes.ts`](../../../client/src/nodeDefinitions/telegramNodes.ts) |
+| **Backend handler** | [`server/services/handlers/triggers.py::handle_trigger_node`](../../../server/services/handlers/triggers.py) (generic) + [`server/services/event_waiter.py::build_telegram_filter`](../../../server/services/event_waiter.py) |
+| **Tests** | [`server/tests/nodes/test_telegram_social.py`](../../../server/tests/nodes/test_telegram_social.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no (trigger only) |
+
+## Purpose
+
+Wait for an incoming Telegram message and emit it as the workflow trigger
+event. Implementation is split between the generic `handle_trigger_node`
+(registers a waiter and blocks on `event_waiter.wait_for_event`) and the
+Telegram-specific filter builder that pre-compiles a `matches()` closure
+from the node parameters. Events are produced by the `TelegramService`
+long-polling loop inside `_on_message_received` and dispatched via
+`event_waiter.dispatch("telegram_message_received", <event_data>)`.
+
+## Inputs (handles)
+
+Trigger node - no inputs.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `contentTypeFilter` | options | `all` | no | - | One of `all`/`text`/`photo`/`video`/`audio`/`voice`/`document`/`sticker`/`location`/`contact`/`poll` |
+| `senderFilter` | options | `all` | no | - | `all`/`self`/`private`/`group`/`supergroup`/`channel`/`specific_chat`/`specific_user`/`keywords` |
+| `chat_id` | string | `""` | yes when `senderFilter=specific_chat` | `senderFilter: ['specific_chat']` | Numeric chat id or `@username` |
+| `from_user` | string | `""` | yes when `senderFilter=specific_user` | `senderFilter: ['specific_user']` | Numeric user id |
+| `keywords` | string | `""` | yes when `senderFilter=keywords` | `senderFilter: ['keywords']` | Comma-separated, matched case-insensitively |
+| `ignoreBots` | boolean | `true` | no | - | Skip messages where `is_bot=True` (ignored when `senderFilter=self`) |
+
+Legacy alias: `chatTypeFilter` is still read when `senderFilter` is absent and
+reconstructs the new-style value.
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Formatted event from `TelegramService._format_message` |
+
+### Output payload
+
+```ts
+{
+ message_id: number;
+ chat_id: number;
+ chat_type: 'private' | 'group' | 'supergroup' | 'channel';
+ chat_title: string | null;
+ from_id: number | null;
+ from_username: string | null;
+ from_first_name: string | null;
+ from_last_name: string | null;
+ is_bot: boolean;
+ text: string; // msg.text or msg.caption or ''
+ content_type: 'text' | 'photo' | 'video' | 'audio' | 'voice'
+ | 'document' | 'sticker' | 'location' | 'contact' | 'poll';
+ date: string; // ISO timestamp
+ reply_to_message_id: number | null;
+ photo?: { file_id; file_unique_id; width; height; file_size };
+ document?: { file_id; file_name; mime_type; file_size };
+ location?: { latitude; longitude };
+ contact?: { phone_number; first_name; last_name; user_id };
+}
+```
+
+Wrapped in the standard success envelope when an event is received.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_trigger_node] --> B{TelegramService.connected?}
+ B -- no --> Eoff[Return success=false<br/>error: bot not connected]
+ B -- yes --> C[event_waiter.register<br/>-> build_telegram_filter]
+ C --> D[broadcaster.update_node_status waiting]
+ D --> E[await event_waiter.wait_for_event]
+ E -- CancelledError --> Ecx[Return success=false<br/>error: Cancelled by user]
+ E -- event resolved --> F[Return success=true<br/>result = event_data]
+
+ subgraph Producer
+ P1[TelegramService polling loop] --> P2[_on_message_received]
+ P2 --> P3[_format_message -> event_data]
+ P3 --> P4[event_waiter.dispatch<br/>'telegram_message_received']
+ P4 --> P5[matches filter<br/>per waiter]
+ P5 -- match --> P6[Waiter.future.set_result]
+ end
+```
+
+## Decision Logic
+
+- **Pre-check**: Handler inspects `TelegramService.connected` before registering
+ a waiter. Prevents hanging forever when the bot token was never added.
+- **Sender filter branches** (inside `build_telegram_filter.matches`):
+ - `self`: compares `m.from_id` to a lazily-resolved `owner_chat_id`. If no
+ owner is known, the message is rejected (but no error surfaces to the
+ user).
+ - `private`/`group`/`supergroup`/`channel`: direct `m.chat_type` comparison.
+ - `specific_chat` / `specific_user`: string-compared to `chat_id` / `from_user`.
+ - `keywords`: lower-cased substring match against `m.text`.
+ - `all`: accepts everything (subject to `ignore_bots`).
+- **Content type filter**: Always applied first; if set and not `all`, rejects
+ anything with a non-matching `content_type`.
+- **`ignore_bots`**: Applied last; silently skipped when `senderFilter == 'self'`.
+- **Legacy fallback**: If `senderFilter` is unset the code reconstructs it
+ from `chat_id`/`from_user`/`keywords`/`chatTypeFilter` so old workflows keep
+ working.
+
+## Side Effects
+
+- **Database writes**: none from the trigger path. (First private message to
+ the bot causes `TelegramService._on_message_received` to call
+ `auth_service.store_api_key("telegram_owner_chat_id", ...)`, but that is
+ producer-side, not trigger-side.)
+- **Broadcasts**: `status_broadcaster.update_node_status(node_id, "waiting", {...}, workflow_id=...)`
+ when the waiter is registered.
+- **External API calls**: none from the handler. Producer makes continuous
+ `getUpdates` calls via python-telegram-bot long polling.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: bot token via `auth_service.get_api_key("telegram_bot_token")`
+ (read by the service on connect, not by the handler).
+- **Services**: `TelegramService`, `event_waiter`, `StatusBroadcaster`.
+- **Python packages**: `python-telegram-bot` v22.x.
+- **Environment variables**: `TELEGRAM_OWNER_CHAT_ID` (service fallback).
+
+## Edge cases & known limits
+
+- **`self` filter with no owner**: Until the bot receives a private message (or
+ `TELEGRAM_OWNER_CHAT_ID` is set), every message is rejected. There is no
+ user-visible error; the node just stays in "waiting".
+- **Keyword matching**: Case-insensitive substring, no word boundaries. `"hi"`
+ matches `"chicken"`. Empty `keywords` accepts all messages.
+- **String comparison for IDs**: `specific_chat`/`specific_user` compare via
+ `str(...)`. A leading `@` or whitespace difference will silently mismatch.
+- **`ignore_bots` override**: Hard-coded to be bypassed for `senderFilter=self`
+ so bot-owners who are themselves bots still match.
+- **Cancellation path**: If the trigger is cancelled mid-wait, the handler
+ returns `success=false, error="Cancelled by user"` rather than swallowing.
+- **Handler accepts unknown trigger types**: `handle_trigger_node` has a guard
+ for missing `TriggerConfig`, but because the registry entry for
+ `telegramReceive` is hard-coded this branch is unreachable in practice.
+- **No timeout**: The node waits indefinitely. The only exit routes are an
+ event match, an explicit `cancel_event_wait` WebSocket call, or the server
+ restarting.
+
+## Related
+
+- **Sibling nodes**: [`telegramSend`](./telegramSend.md), [`socialReceive`](./socialReceive.md)
+- **Event waiter architecture**: [Event Waiter System](../../event_waiter_system.md)
+- **Service**: [`server/services/telegram_service.py`](../../../server/services/telegram_service.py)
diff --git a/docs-internal/node-logic-flows/telegram_social/telegramSend.md b/docs-internal/node-logic-flows/telegram_social/telegramSend.md
new file mode 100644
index 00000000..5f740b0f
--- /dev/null
+++ b/docs-internal/node-logic-flows/telegram_social/telegramSend.md
@@ -0,0 +1,176 @@
+# Telegram Send (`telegramSend`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/telegramNodes.ts`](../../../client/src/nodeDefinitions/telegramNodes.ts) |
+| **Backend handler** | [`server/services/handlers/telegram.py::handle_telegram_send`](../../../server/services/handlers/telegram.py) |
+| **Tests** | [`server/tests/nodes/test_telegram_social.py`](../../../server/tests/nodes/test_telegram_social.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | yes - group is `['social', 'tool']`; exposed to AI agents via the unified send path |
+
+## Purpose
+
+Send text, photo, document, location, or contact messages through a connected
+Telegram bot (python-telegram-bot v22.x). The node leans on the `TelegramService`
+singleton for the actual Bot API calls; the handler only does recipient
+resolution, parameter validation, and envelope packaging. When used as an AI
+tool, the LLM fills the same snake_case parameter schema documented below.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data - not read directly by the handler; parent nodes typically resolve templates into `text` / `caption` via ParameterResolver before the call. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `recipient_type` | options | `self` | no | - | One of `self` / `user` / `group` |
+| `chat_id` | string | `""` | yes when `recipient_type != self` | `recipient_type: ['user','group']` | Numeric chat id or `@username` |
+| `message_type` | options | `text` | no | - | `text` / `photo` / `document` / `location` / `contact` |
+| `text` | string | `""` | yes when `message_type=text` | `message_type: ['text']` | Message text |
+| `media_url` | string | `""` | yes when `message_type` in `photo`/`document` | `message_type: ['photo','document']` | Remote URL or `file_id` |
+| `caption` | string | `""` | no | `message_type: ['photo','document']` | Optional caption |
+| `latitude` | number | `0` | yes when `message_type=location` | `message_type: ['location']` | Latitude |
+| `longitude` | number | `0` | yes when `message_type=location` | `message_type: ['location']` | Longitude |
+| `phone_number` | string | `""` | yes when `message_type=contact` | `message_type: ['contact']` | Contact phone |
+| `first_name` | string | `""` | yes when `message_type=contact` | `message_type: ['contact']` | Contact first name |
+| `last_name` | string | `""` | no | `message_type: ['contact']` | Contact last name |
+| `parse_mode` | options | `Auto` | no | `message_type: ['text','photo','document']` | `Auto` / `""` / `HTML` / `Markdown` / `MarkdownV2` |
+| `silent` | boolean | `false` | no | - | Sends without notification (`disable_notification=True`) |
+| `reply_to_message_id` | number | `0` | no | - | If truthy, coerced to `int` and passed as `reply_to_message_id` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope containing Bot API message metadata |
+| `output-tool` | object | Same payload, emitted when wired into an AI agent's `input-tools` |
+
+### Output payload
+
+```ts
+{
+ message_id: number;
+ chat_id: number;
+ message_type: 'text' | 'photo' | 'document' | 'location' | 'contact';
+ date: string; // ISO timestamp from Telegram
+}
+```
+
+Wrapped in `{ success: true, result: <payload>, execution_time, timestamp, node_id, node_type }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_telegram_send] --> B{TelegramService<br/>connected?}
+ B -- no --> Efail[Return success=false<br/>error: bot not connected]
+ B -- yes --> C{recipient_type?}
+ C -- self --> D[chat_id = service.owner_chat_id]
+ D --> D2{owner set?}
+ D2 -- no --> D3[Fetch 'telegram_owner_chat_id'<br/>via auth_service.get_api_key]
+ D3 -- ok --> D4[service.set_owner + use]
+ D3 -- missing --> Efail
+ C -- user/group --> E{chat_id truthy?}
+ E -- no --> Efail
+ E -- yes --> F[Read message_type / parse_mode / silent / reply_to]
+ F --> G{message_type}
+ G -- text --> T{text set?}
+ T -- no --> Efail
+ T -- yes --> Tsend[service.send_message]
+ G -- photo --> P{media_url set?}
+ P -- no --> Efail
+ P -- yes --> Psend[service.send_photo]
+ G -- document --> Doc{media_url set?}
+ Doc -- no --> Efail
+ Doc -- yes --> Dsend[service.send_document]
+ G -- location --> L{lat and lng set?}
+ L -- no --> Efail
+ L -- yes --> Lsend[service.send_location]
+ G -- contact --> Ct{phone + first_name?}
+ Ct -- no --> Efail
+ Ct -- yes --> Ctsend[service.send_contact]
+ G -- other --> Efail
+ Tsend --> Ok
+ Psend --> Ok
+ Dsend --> Ok
+ Lsend --> Ok
+ Ctsend --> Ok
+ Ok[Return success=true<br/>with message_id, chat_id, message_type, date]
+```
+
+## Decision Logic
+
+- **Connection gate**: If `service.connected` is False the handler short-circuits with
+ `"Telegram bot not connected. Add bot token in Credentials."` No retry is attempted.
+- **Self recipient**: Uses `service.owner_chat_id` (auto-captured on the first
+ private message). If not set, the handler tries
+ `auth_service.get_api_key("telegram_owner_chat_id")` and restores the owner by
+ calling `service.set_owner(int(saved_owner))`. Any exception during restore is
+ logged at WARNING and swallowed - the handler continues and ultimately returns
+ the "Bot owner not detected" error envelope when the chat_id is still falsy.
+- **Parse mode**: Passed through to the service. The service itself implements
+ `Auto` (GFM -> Telegram HTML via `markdown_formatter.to_telegram_html`) plus the
+ `BadRequest "can't parse entities"` fallback that retries with `parse_mode=None`
+ and the original unescaped text.
+- **Message type dispatch**: Uses a Python `match` statement. An unknown
+ `message_type` falls into the `_` arm and returns
+ `"Unsupported message type: <x>"`.
+- **Reply-to coercion**: `reply_to_message_id` is cast via `int(...)` only when
+ truthy. A non-numeric string here raises `ValueError`, which is caught by the
+ outer `except Exception` and returned as an error envelope.
+
+## Side Effects
+
+- **Database writes**: none from the handler directly. `handle_telegram_send`
+ can call `auth_service.store_api_key("telegram_owner_chat_id", ...)` indirectly
+ only through `TelegramService._on_message_received`, not from the send path.
+- **Broadcasts**: none from the send handler. The service broadcasts
+ `update_telegram_status` on connect / disconnect only.
+- **External API calls**: Telegram Bot API via `python-telegram-bot` (`bot.send_message`,
+ `bot.send_photo`, `bot.send_document`, `bot.send_location`, `bot.send_contact`).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key("telegram_owner_chat_id")` when
+ restoring the self-owner. Bot token comes from `auth_service.store_api_key("telegram_bot_token", ...)`
+ and is consumed by `TelegramService.connect()` elsewhere, not by this handler.
+- **Services**: `TelegramService` singleton (`services.telegram_service.get_telegram_service`).
+- **Python packages**: `python-telegram-bot` (v22.x), `markdown-it-py` (via
+ `markdown_formatter`).
+- **Environment variables**: `TELEGRAM_OWNER_CHAT_ID` (read by the service as a
+ fallback for `owner_chat_id`).
+
+## Edge cases & known limits
+
+- **Swallowed owner-restore exceptions**: Any error looking up
+ `telegram_owner_chat_id` is logged at WARNING and continues; the user only
+ sees the downstream "Bot owner not detected" error.
+- **Silent ValueError on `reply_to_message_id`**: A non-numeric value raises
+ and the outer `except Exception` returns `str(e)` as the error message.
+- **`recipient_type` spelling**: The handler treats anything that is not
+ literally `"self"` as needing a `chat_id`, including unexpected values -
+ this means a typo like `"slf"` falls through to the user/group branch and
+ the user sees `"chat_id is required"` instead of a recipient-type error.
+- **Markdown fallback leaks unescaped text**: If `send_message` raises
+ `BadRequest("can't parse entities ...")`, the service retries with the
+ ORIGINAL (unescaped) text at `parse_mode=None`, not the escaped copy. If the
+ original contains markup, it is visible to the recipient as literal characters.
+- **`reply_to_message_id=0`**: Falsy, so the handler does NOT pass it through -
+ the node silently drops the reply reference.
+- **`parse_mode='None'` (string)**: Not treated as "no parse mode"; passed
+ through to Telegram, which will reject it. The frontend uses empty string
+ `""` for "None" so this is a misconfiguration hazard only for manual JSON
+ imports.
+
+## Related
+
+- **Sibling nodes**: [`telegramReceive`](./telegramReceive.md), [`socialSend`](./socialSend.md)
+- **Service**: [`server/services/telegram_service.py`](../../../server/services/telegram_service.py)
+- **Markdown formatter**: [`server/services/markdown_formatter.py`](../../../server/services/markdown_formatter.py)
+- **Architecture docs**: [Credentials Encryption](../../credentials_encryption.md), [Status Broadcaster](../../status_broadcaster.md)
diff --git a/docs-internal/node-logic-flows/twitter/twitterReceive.md b/docs-internal/node-logic-flows/twitter/twitterReceive.md
new file mode 100644
index 00000000..07d2c92b
--- /dev/null
+++ b/docs-internal/node-logic-flows/twitter/twitterReceive.md
@@ -0,0 +1,161 @@
+# Twitter Receive (`twitterReceive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/twitterNodes.ts`](../../../client/src/nodeDefinitions/twitterNodes.ts) |
+| **Backend handler** | [`server/services/handlers/triggers.py::handle_trigger_node`](../../../server/services/handlers/triggers.py) (generic) + [`server/services/event_waiter.py::build_twitter_filter`](../../../server/services/event_waiter.py) |
+| **Tests** | [`server/tests/nodes/test_twitter.py`](../../../server/tests/nodes/test_twitter.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no (trigger only) |
+
+## Purpose
+
+Wait for a Twitter/X event (mention, search match, or timeline update) and emit
+it as the workflow trigger payload. The trigger is polling-based (X API v2 has
+no push webhooks on the free tier); polling is driven by the deployment layer
+(`server/services/deployment/`) while the *execution* side reuses the same
+`handle_trigger_node` path that WhatsApp/Webhook/Telegram triggers use -
+register a waiter, block on `event_waiter.wait_for_event`, and surface the
+matching event.
+
+Filtering is done by the closure returned from `build_twitter_filter` in
+`event_waiter.py`.
+
+## Inputs (handles)
+
+Trigger node - no inputs.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `trigger_type` | options | `mentions` | yes | - | One of `mentions` / `search` / `timeline`. Filter compares against the event's `trigger_type` field. |
+| `search_query` | string | `""` | yes when `trigger_type=search` | `trigger_type: ['search']` | Substring-matched (case-insensitive) against event `query`. |
+| `user_id` | string | `""` | no | `trigger_type: ['timeline']` | When set, must exactly match event `user_id`. Empty -> authenticated user (resolved by the poller, not the filter). |
+| `filter_retweets` | boolean | `true` | no | - | Accepted by frontend; **not consumed** by the execution-side filter. Any effect must be implemented by the poller. |
+| `filter_replies` | boolean | `false` | no | - | Same as above - frontend-only hint. |
+| `poll_interval` | number | `60` | no | - | Seconds between polls (15-3600). Consumed by `deployment/` when deploying the workflow, not by `handle_trigger_node`. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Raw event data returned by `event_waiter.wait_for_event` |
+
+### Output payload (contract)
+
+The event shape is produced by whichever polling loop dispatches
+`twitter_event_received`. Documented fields the filter and downstream nodes
+rely on:
+
+```ts
+{
+ trigger_type: 'mentions' | 'search' | 'user_timeline';
+ tweet_id: string;
+ text: string;
+ author_id: string;
+ author_username?: string;
+ created_at: string;
+ // search-specific:
+ query?: string;
+ // timeline-specific:
+ user_id?: string;
+ // optionally: metrics, referenced_tweets, entities
+}
+```
+
+The handler wraps this in `{ success: true, result: <event_data>, execution_time }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_trigger_node] --> B[event_waiter.get_trigger_config twitterReceive]
+ B -- None --> E1[Return success=false<br/>error: Unknown trigger type]
+ B -- config --> C[event_waiter.register<br/>build_twitter_filter]
+ C --> D[broadcaster.update_node_status waiting]
+ D --> E[await event_waiter.wait_for_event]
+ E -- CancelledError --> Ecx[Return success=false<br/>error: Cancelled by user]
+ E -. any other Exception .-> EG[Return success=false<br/>error: str e]
+ E -- event --> F[Return success=true<br/>result = event_data]
+
+ subgraph Producer
+ P1[Deployment polling task] --> P2[Fetch via XDK<br/>mentions/search/user_timeline]
+ P2 --> P3[event_waiter.dispatch<br/>twitter_event_received]
+ P3 --> P4[build_twitter_filter.matches]
+ P4 -- match --> P5[Waiter.future.set_result]
+ end
+```
+
+## Decision Logic (filter)
+
+`build_twitter_filter(params)` returns a `matches(data)` closure that rejects
+non-matching events:
+
+- `trigger_type != 'all'` and `data['trigger_type'] != trigger_type` -> reject.
+ (Frontend only exposes `mentions` / `search` / `timeline`; there is no way to
+ select `all` from the UI.)
+- **search branch**: if `trigger_type == 'search'` and `search_query` set,
+ compare lowercase-substring against `data['query']`. Empty `search_query`
+ accepts any search event.
+- **user_timeline branch**: if `trigger_type == 'user_timeline'` and `user_id`
+ is set, require `data['user_id'] == user_id` (exact). Empty `user_id`
+ accepts any timeline event.
+- No `filter_retweets` / `filter_replies` logic exists in `build_twitter_filter`.
+
+### Execution-side handler branches
+
+- Unknown `trigger_type`: `handle_trigger_node` looks up the config and returns
+ an error envelope if missing. For `twitterReceive` the config is hard-coded in
+ `TRIGGER_REGISTRY`, so this branch is unreachable in practice.
+- `asyncio.CancelledError` from `wait_for_event` -> success=false,
+ `error="Cancelled by user"`.
+- Any other exception -> success=false, `error=str(e)`.
+
+## Side Effects
+
+- **Database writes**: none from the handler. The poller in `deployment/` may
+ write independently.
+- **Broadcasts**: `status_broadcaster.update_node_status(node_id, "waiting", {message, event_type: "twitter_event_received", waiter_id}, workflow_id=...)` when the waiter is registered.
+- **External API calls**: none from the handler. The polling loop makes
+ periodic `GET /2/users/:id/mentions`, `GET /2/tweets/search/recent`, or
+ `GET /2/users/:id/tweets` requests.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth tokens via `auth_service.get_oauth_tokens("twitter")`
+ (read by the poller, not by the handler).
+- **Services**: `event_waiter`, `StatusBroadcaster`, `deployment/` polling
+ infrastructure.
+- **Python packages**: `xdk`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **`filter_retweets` / `filter_replies` ignored**: despite the UI toggles, the
+ execution-side filter does nothing with them. Unless the poller honours them
+ downstream, retweets and replies will surface.
+- **Frontend <-> filter mismatch**: frontend offers `trigger_type='timeline'`
+ but the filter compares against `event_type == 'user_timeline'`. The poller
+ must dispatch events tagged `trigger_type: 'user_timeline'` (note the prefix)
+ or matching will fail silently.
+- **Substring match on `search_query`**: case-insensitive substring - no
+ boolean operators, no token-awareness. `"AI"` inside `query="raid"` matches.
+- **`user_id` comparison is exact**: leading `@` or whitespace mismatches
+ silently.
+- **No timeout on wait**: the handler waits indefinitely. Only exits on event,
+ cancellation, or server restart.
+- **Polling latency**: `poll_interval` default is 60s - expect up to a minute
+ between a tweet being created and the node firing.
+- **No dedup at the filter**: consecutive polls producing the same `tweet_id`
+ rely on the poller for deduplication. The filter will happily match the same
+ tweet twice.
+
+## Related
+
+- **Sibling nodes**: [`twitterSend`](./twitterSend.md), [`twitterSearch`](./twitterSearch.md), [`twitterUser`](./twitterUser.md)
+- **Event waiter architecture**: [Event Waiter System](../../event_waiter_system.md)
+- **Deployment / polling triggers**: [`server/services/deployment/`](../../../server/services/deployment/)
diff --git a/docs-internal/node-logic-flows/twitter/twitterSearch.md b/docs-internal/node-logic-flows/twitter/twitterSearch.md
new file mode 100644
index 00000000..6945e4e5
--- /dev/null
+++ b/docs-internal/node-logic-flows/twitter/twitterSearch.md
@@ -0,0 +1,189 @@
+# Twitter Search (`twitterSearch`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/twitterNodes.ts`](../../../client/src/nodeDefinitions/twitterNodes.ts) |
+| **Backend handler** | [`server/services/handlers/twitter.py::handle_twitter_search`](../../../server/services/handlers/twitter.py) |
+| **Tests** | [`server/tests/nodes/test_twitter.py`](../../../server/tests/nodes/test_twitter.py) |
+| **Skill (if any)** | [`server/skills/social_agent/twitter-search-skill/SKILL.md`](../../../server/skills/social_agent/twitter-search-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `twitter_search` |
+
+## Purpose
+
+Search recent tweets via `GET /2/tweets/search/recent` using the official `xdk`
+SDK. Returns enriched tweet objects: URLs are expanded out of the `entities`
+block, author profile is joined in from the `includes.users` expansion, media
+objects are joined in from `includes.media`, referenced tweets (quoted / replied
+to) are joined in from `includes.tweets`, and long-form `note_tweet` content
+replaces the 280-char `text` when present. This is the tool LLMs get when a
+`twitterSearch` node is wired to `input-tools`.
+
+The first result page is returned - pagination is not surfaced to the user.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `query` | string | `""` | yes | - | X search query. Supports full operator set (`from:`, `lang:`, `-is:retweet`, ...). |
+| `max_results` | number | `10` | no | - | Clamped to `max(10, min(requested, 100))` - API minimum is 10. |
+| `sort_order` | options | `recency` | no | - | Accepted by frontend but **ignored by the handler** (not passed to the SDK call). |
+| `start_time`, `end_time` | string (ISO8601) | `""` | no | - | Accepted by frontend but **ignored by the handler**. |
+| `include_metrics`, `include_author` | boolean | `true` | no | - | Accepted by frontend but **ignored** - the handler unconditionally requests the full field set. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when invoked via `input-tools` |
+
+### Output payload
+
+```ts
+{
+ tweets: Array<{
+ id: string;
+ text: string; // note_tweet.text if present, else tweet.text
+ display_text: string; // text with t.co URLs replaced by expanded_url
+ author_id: string | null;
+ created_at: string; // str(...) - may be '' if missing
+ lang: string | null;
+ source: string | null;
+ conversation_id: string | null;
+ in_reply_to_user_id: string | null;
+ possibly_sensitive: boolean;
+ public_metrics: { // {} if the API omitted them
+ retweet_count?: number;
+ reply_count?: number;
+ like_count?: number;
+ quote_count?: number;
+ bookmark_count?: number;
+ impression_count?: number;
+ };
+ author?: { // from includes.users[author_id]
+ id: string;
+ username: string;
+ name: string;
+ profile_image_url?: string;
+ // + any other user_fields returned
+ };
+ urls?: Array<{ // only present when entities.urls non-empty
+ url: string; // t.co shortlink
+ expanded_url: string;
+ display_url: string;
+ }>;
+ media?: Array<{ // from includes.media via attachments.media_keys
+ media_key: string;
+ type: 'photo' | 'video' | 'animated_gif';
+ url?: string;
+ preview_image_url?: string;
+ alt_text?: string;
+ variants?: any[];
+ }>;
+ referenced_tweets?: Array<{
+ type: 'quoted' | 'replied_to' | 'retweeted';
+ id: string;
+ text: string | null; // null when includes.tweets lacked the referenced id
+ author_id: string | null;
+ }>;
+ }>;
+ count: number; // len(tweets)
+ query: string;
+}
+```
+
+Wrapped in `{ success, result, execution_time }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_twitter_search] --> B[_get_twitter_client]
+ B -- no tokens --> Eauth[Return success=false<br/>error: Twitter not connected]
+ B --> C{query non-empty?}
+ C -- no --> Eq[Return success=false<br/>error: Search query is required]
+ C -- yes --> D[max_results clamp<br/>max 10, min requested, 100]
+ D --> E[to_thread _sync_search_recent<br/>tweet_fields + expansions + media + user]
+ E -. 401/403 .-> R[_refresh_and_get_client] --> E
+ E -. other Exception .-> EGEN[Return success=false<br/>error: str e]
+ E --> F[Build users_by_id, media_by_key, tweets_by_id<br/>from includes]
+ F --> G[Map raw tweets -> _format_tweet]
+ G --> H{tweets non-empty?}
+ H -- yes --> K[_track_twitter_usage search count=len tweets]
+ H -- no --> OK
+ K --> OK[Return success=true<br/>result={tweets, count, query}]
+```
+
+## Decision Logic
+
+- **Validation**: missing/empty `query` -> error envelope, no API call.
+- **max_results clamp**: `max(10, min(params.max_results, 100))`. Requests below
+ 10 are silently raised; above 100 are silently capped.
+- **SDK call**: `_sync_search_recent` iterates `client.posts.search_recent(...)`
+ once and returns `{tweets, includes}` for the first page. Subsequent pages
+ are discarded.
+- **Expansions assembled**:
+ - `users_by_id[author_id]` from `includes.users`
+ - `media_by_key[media_key]` from `includes.media`
+ - `tweets_by_id[referenced.id]` from `includes.tweets`
+- **`_format_tweet` enrichment**:
+ - Replaces every `t.co` shortlink in `text` with `expanded_url` in `display_text`.
+ - If `note_tweet.text` exists, it replaces both `text` and `display_text`.
+ - Attaches `author`, `urls`, `media`, `referenced_tweets` as optional keys
+ (only set when data is non-empty).
+ - Coerces Pydantic objects -> dicts via `model_dump()` where needed.
+- **Auth refresh**: same lazy-refresh loop as `twitterSend` - a single retry
+ via `_refresh_and_get_client` on `_is_auth_error(e)`.
+- **Usage tracking**: `resource_count` equals the number of tweets returned,
+ not 1. Skipped entirely when results are empty.
+
+## Side Effects
+
+- **Database writes**: one `api_usage_metrics` row per non-empty search (op
+ `search`, `resource_count=len(tweets)`) via `database.save_api_usage_metric`.
+- **Broadcasts**: none.
+- **External API calls**:
+ - `GET https://api.twitter.com/2/tweets/search/recent` with `expansions=author_id,attachments.media_keys,referenced_tweets.id,referenced_tweets.id.author_id`, `tweet_fields=author_id,created_at,entities,public_metrics,possibly_sensitive,lang,source,conversation_id,in_reply_to_user_id,referenced_tweets,note_tweet`, `media_fields=url,preview_image_url,type,alt_text,variants`, `user_fields=username,name,profile_image_url`.
+ - Optional refresh: `POST https://api.twitter.com/2/oauth2/token`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth tokens via `auth_service.get_oauth_tokens("twitter")`.
+- **Services**: `PricingService`, `Database`, `TwitterOAuth` (refresh path).
+- **Python packages**: `xdk`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **`max_results < 10`**: silently bumped to 10.
+- **Unused frontend params**: `sort_order`, `start_time`, `end_time`,
+ `include_metrics`, `include_author` are wired in the UI but the handler
+ does not forward any of them to the SDK.
+- **Only first page returned**: `_sync_search_recent` breaks out of the
+ generator after the first page regardless of `next_token`.
+- **Empty-includes tolerance**: when the API returns no `includes`, `author`,
+ `media`, `urls`, and `referenced_tweets` are simply omitted from each tweet -
+ consumers must treat them as optional.
+- **Referenced tweet id not in includes**: `referenced_tweets[].text` is
+ `null` rather than raising.
+- **Object/dict duality in `includes`**: `_format_tweet` handles both Pydantic
+ objects and raw dicts - changes to XDK's model shapes may silently drop
+ fields.
+- **Long-form tweets**: `note_tweet.text` replaces the 280-char `text`; callers
+ expecting always-short `text` will see the full note-tweet body.
+- **No streaming**: whole response is read into memory before returning.
+
+## Related
+
+- **Skills using this as a tool**: [`twitter-search-skill/SKILL.md`](../../../server/skills/social_agent/twitter-search-skill/SKILL.md)
+- **Sibling nodes**: [`twitterSend`](./twitterSend.md), [`twitterUser`](./twitterUser.md), [`twitterReceive`](./twitterReceive.md)
+- **Architecture docs**: [Pricing Service](../../pricing_service.md)
diff --git a/docs-internal/node-logic-flows/twitter/twitterSend.md b/docs-internal/node-logic-flows/twitter/twitterSend.md
new file mode 100644
index 00000000..f255fd37
--- /dev/null
+++ b/docs-internal/node-logic-flows/twitter/twitterSend.md
@@ -0,0 +1,185 @@
+# Twitter Send (`twitterSend`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/twitterNodes.ts`](../../../client/src/nodeDefinitions/twitterNodes.ts) |
+| **Backend handler** | [`server/services/handlers/twitter.py::handle_twitter_send`](../../../server/services/handlers/twitter.py) |
+| **Tests** | [`server/tests/nodes/test_twitter.py`](../../../server/tests/nodes/test_twitter.py) |
+| **Skill (if any)** | [`server/skills/social_agent/twitter-send-skill/SKILL.md`](../../../server/skills/social_agent/twitter-send-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `twitter_send` |
+
+## Purpose
+
+Perform write actions against the authenticated user's Twitter/X account via the
+official `xdk` Python SDK. Supports creating an original tweet, replying, native
+retweeting, liking, unliking, and deleting. Runs both as a workflow node and as
+an AI agent tool when connected to `input-tools`.
+
+All SDK calls are synchronous (`requests`-based) inside the XDK; the handler
+wraps every call in `asyncio.to_thread(...)` so the event loop is never blocked.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `action` | options | `tweet` | yes | - | One of `tweet` / `reply` / `retweet` / `quote` / `like` / `unlike` / `delete`. Backend only implements `tweet`, `reply`, `retweet`, `like`, `unlike`, `delete`; `quote` falls through to the `Unknown action` branch. |
+| `text` | string | `""` | yes (tweet/reply/quote) | `action: ['tweet','reply','quote']` | Tweet content. Handler truncates to 280 chars via slice. |
+| `tweet_id` | string | `""` | yes (reply/retweet/quote/like/unlike/delete) | `action: ['reply','retweet','quote','like','unlike','delete']` | Target tweet ID. |
+| `reply_to_id` | string | `""` | yes (reply) | - | ID of the tweet being replied to. Passed in `reply.in_reply_to_tweet_id`. Note the parameter name mismatch vs. frontend `tweet_id` for other actions. |
+| `include_media`, `media_urls` | boolean/string | - | no | tweet/reply/quote | **Accepted by frontend but ignored by backend** - the handler never attaches media. |
+| `include_poll`, `poll_options`, `poll_duration` | bool/string/number | - | no | tweet | **Accepted by frontend but ignored by backend.** |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope with XDK response payload |
+| `output-tool` | object | Same payload when invoked via `input-tools` |
+
+### Output payload
+
+Handler wraps the XDK response via `_format_response` then via `_success`:
+
+```ts
+// On success (tweet/reply):
+{
+ success: true,
+ result: {
+ id: string; // new tweet id
+ text: string;
+ // ...any additional fields returned by POST /2/tweets (edit_history_tweet_ids, etc.)
+ },
+ execution_time: number
+}
+// On success (retweet/like): { retweeted: boolean } or { liked: boolean }
+// On success (unlike): { liked: false }
+// On success (delete): { deleted: boolean }
+// On error: { success: false, error: string, execution_time: number }
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_twitter_send] --> B[_get_twitter_client<br/>auth_service.get_oauth_tokens twitter]
+ B -- no tokens --> Eauth[Return success=false<br/>error: Twitter not connected]
+ B -- ok --> C[_do_twitter_send]
+ C --> Dswitch{action}
+ Dswitch -- tweet --> T1{text non-empty?}
+ T1 -- no --> Eval[raise ValueError]
+ T1 -- yes --> T2[asyncio.to_thread _sync_create_post<br/>body=text 0..280]
+ Dswitch -- reply --> R1{text AND reply_to_id?}
+ R1 -- no --> Eval
+ R1 -- yes --> R2[to_thread _sync_create_post<br/>reply.in_reply_to_tweet_id]
+ Dswitch -- retweet/like --> L1[to_thread _get_my_user_id<br/>client.users.get_me]
+ L1 --> L2[to_thread _sync_repost or _sync_like]
+ Dswitch -- unlike --> U1[to_thread _get_my_user_id]
+ U1 --> U2[to_thread _sync_unlike]
+ Dswitch -- delete --> D1[to_thread _sync_delete_post]
+ Dswitch -- _ --> Eunk[raise ValueError Unknown action]
+ T2 --> K[_track_twitter_usage -> DB]
+ R2 --> K
+ L2 --> K
+ U2 --> K
+ D1 --> K
+ K --> OK[Return success=true envelope]
+
+ C -. raises .-> AuthErr{_is_auth_error?<br/>401/403/Unauthorized/Forbidden}
+ AuthErr -- yes --> REF[_refresh_and_get_client<br/>TwitterOAuth.refresh_access_token]
+ REF -. new tokens .-> STORE[auth_service.store_oauth_tokens twitter]
+ STORE --> C
+ AuthErr -- no --> EGEN[Return success=false<br/>error: str e]
+```
+
+## Decision Logic
+
+- **Client acquisition**: `_get_twitter_client()` reads OAuth tokens via
+ `auth_service.get_oauth_tokens("twitter", customer_id="owner")`. Raises
+ `ValueError("Twitter not connected. Please authenticate via Credentials.")`
+ when tokens are missing.
+- **No eager validation**: Handler never calls `get_me()` up-front to verify the
+ token; it jumps straight into the action call to conserve rate limits.
+- **Lazy refresh**: Any exception bubbling out of `_do_twitter_send` is inspected
+ by `_is_auth_error` (substring match on `401`, `403`, `Unauthorized`,
+ `Forbidden`). On match, a new client is built via `_refresh_and_get_client()`
+ which calls `TwitterOAuth.refresh_access_token`, re-stores tokens via
+ `store_oauth_tokens`, and the action is retried once. Non-auth errors surface
+ as an error envelope.
+- **Validation**:
+ - `tweet`: requires non-empty `text`, sliced to 280 chars.
+ - `reply`: requires both `text` and `reply_to_id`.
+ - `retweet`/`like`/`unlike`/`delete`: require `tweet_id`.
+- **User id fetch**: `retweet`/`like`/`unlike` need the authenticated user id;
+ `_get_my_user_id` calls `client.users.get_me()` via `asyncio.to_thread`.
+- **Unknown action**: `quote` (present in frontend) and any other value fall
+ into the default match arm and raise `ValueError(f"Unknown action: {action}")`
+ which is converted to an error envelope.
+
+## Side Effects
+
+- **Database writes**: one row per successful action in `api_usage_metrics` via
+ `database.save_api_usage_metric(...)` with `service='twitter'` and
+ `operation` from `PricingService.calculate_api_cost`. Action -> op name:
+ `tweet`, `reply`, `retweet`, `like`, `unlike`, `delete`.
+- **Broadcasts**: none from the handler.
+- **External API calls**:
+ - `POST https://api.twitter.com/2/tweets` (tweet, reply)
+ - `POST https://api.twitter.com/2/users/{id}/retweets` (retweet)
+ - `POST https://api.twitter.com/2/users/{id}/likes` (like)
+ - `DELETE https://api.twitter.com/2/users/{id}/likes/{tweet_id}` (unlike)
+ - `DELETE https://api.twitter.com/2/tweets/{id}` (delete)
+ - `GET https://api.twitter.com/2/users/me` (implicit, on retweet/like/unlike)
+ - `POST https://api.twitter.com/2/oauth2/token` (refresh path, via
+ `TwitterOAuth`).
+- **File I/O**: none.
+- **Subprocess**: none.
+- **Token store writes**: on refresh, `auth_service.store_oauth_tokens("twitter", ...)`
+ updates the encrypted OAuth credentials row.
+
+## External Dependencies
+
+- **Credentials**: OAuth access + refresh token via
+ `auth_service.get_oauth_tokens("twitter", customer_id="owner")`. Stored via
+ System 1 (`EncryptedOAuthToken` table); NOT via `get_api_key("twitter_access_token")`.
+ Client id + secret are stored via `get_api_key("twitter_client_id")` /
+ `get_api_key("twitter_client_secret")` and only consulted on refresh.
+- **Services**: `TwitterOAuth` (`server/services/twitter_oauth.py`) for token
+ refresh. `PricingService` for cost calculation. `Database` for metric row.
+- **Python packages**: `xdk` (X SDK), `httpx` (used transitively inside
+ `TwitterOAuth`).
+- **Environment variables**: none at runtime (OAuth flow uses stored creds).
+
+## Edge cases & known limits
+
+- **`quote` action is broken**: frontend exposes `Quote Tweet` but backend has no
+ handler branch; it falls through to the default arm and surfaces as
+ `Unknown action: quote`.
+- **Media and polls ignored**: the `include_media` / `include_poll` /
+ `media_urls` / `poll_options` / `poll_duration` parameters are never read by
+ the handler - the node silently sends a text-only tweet.
+- **280-char silent truncation**: `text[:280]` is applied without warning; the
+ emitted tweet may be shorter than the user typed.
+- **Single retry on auth error**: refresh + retry happens at most once; a
+ second 401 surfaces as an error envelope.
+- **Refresh failure message**: If `refresh_access_token` fails, the user sees
+ `Twitter token expired and refresh failed. Please re-authenticate.` - the
+ original upstream error message is lost.
+- **`_is_auth_error` uses substring matching**: any error whose `str(e)`
+ contains `401`, `403`, `Unauthorized`, or `Forbidden` triggers the refresh
+ path, even if the real cause is something else (e.g. a log message quoting
+ those strings).
+- **Usage tracking only on success**: the `_track_twitter_usage` call happens
+ after the SDK call returns; raised errors skip tracking entirely.
+
+## Related
+
+- **Skills using this as a tool**: [`twitter-send-skill/SKILL.md`](../../../server/skills/social_agent/twitter-send-skill/SKILL.md)
+- **Sibling nodes**: [`twitterSearch`](./twitterSearch.md), [`twitterUser`](./twitterUser.md), [`twitterReceive`](./twitterReceive.md)
+- **Architecture docs**: [Pricing Service](../../pricing_service.md), [Credentials Encryption](../../credentials_encryption.md)
diff --git a/docs-internal/node-logic-flows/twitter/twitterUser.md b/docs-internal/node-logic-flows/twitter/twitterUser.md
new file mode 100644
index 00000000..29095203
--- /dev/null
+++ b/docs-internal/node-logic-flows/twitter/twitterUser.md
@@ -0,0 +1,181 @@
+# Twitter User (`twitterUser`)
+
+| Field | Value |
+|------|-------|
+| **Category** | social / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/twitterNodes.ts`](../../../client/src/nodeDefinitions/twitterNodes.ts) |
+| **Backend handler** | [`server/services/handlers/twitter.py::handle_twitter_user`](../../../server/services/handlers/twitter.py) |
+| **Tests** | [`server/tests/nodes/test_twitter.py`](../../../server/tests/nodes/test_twitter.py) |
+| **Skill (if any)** | [`server/skills/social_agent/twitter-user-skill/SKILL.md`](../../../server/skills/social_agent/twitter-user-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `twitter_user` |
+
+## Purpose
+
+Look up Twitter users and their social graph via `GET /2/users/me`,
+`GET /2/users/by/username/:username`, `GET /2/users/:id`,
+`GET /2/users/:id/followers`, and `GET /2/users/:id/following`. Works as a
+workflow node and an AI agent tool. Every SDK call is wrapped in
+`asyncio.to_thread(...)` since XDK is sync-only.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `operation` | options | `me` | yes | - | `me` / `by_username` / `by_id` / `followers` / `following` |
+| `username` | string | `""` | yes (by_username) | `operation: ['by_username']` | Handle without `@`. |
+| `user_id` | string | `""` | yes (by_id), optional (followers/following) | `operation: ['by_id','followers','following']` | If omitted for followers/following, the authenticated user is used via `_get_my_user_id`. |
+| `max_results` | number | `100` | no | `operation: ['followers','following']` | Clamped `max(1, min(requested, 1000))`. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when invoked via `input-tools` |
+
+### Output payload
+
+`me` / `by_username` / `by_id`:
+
+```ts
+{
+ id: string;
+ username: string;
+ name: string;
+ profile_image_url: string | null;
+ verified: boolean; // defaults to false when API omits it
+ description: string | null;
+ created_at: string; // str(...) - empty string when missing
+}
+```
+
+`followers` / `following`:
+
+```ts
+{
+ users: Array<UserData>; // same shape as above
+ count: number;
+}
+```
+
+All wrapped in `{ success, result, execution_time }`. `me` / `by_username` /
+`by_id` additionally take the `_success` path that wraps the dict as
+`result` directly (no `action` field leaks through when the payload is already
+a dict, thanks to `_success`'s dict-shortcut).
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_twitter_user] --> B[_get_twitter_client]
+ B -- no tokens --> Eauth[Return success=false<br/>error: Twitter not connected]
+ B --> C[_do_twitter_user]
+ C --> Dswitch{operation}
+ Dswitch -- me --> M1[to_thread _sync_get_me<br/>user_fields=created_at, description]
+ Dswitch -- by_username --> U1{username?}
+ U1 -- no --> EV[raise ValueError Username is required]
+ U1 -- yes --> U2[to_thread _sync_get_by_usernames]
+ U2 --> U3{data list empty?}
+ U3 -- yes --> EVn[raise ValueError User @handle not found]
+ Dswitch -- by_id --> I1{user_id?}
+ I1 -- no --> EV
+ I1 -- yes --> I2[to_thread _sync_get_by_ids]
+ I2 --> I3{data list empty?}
+ I3 -- yes --> EVn
+ Dswitch -- followers --> F1{user_id present?}
+ F1 -- no --> F0[to_thread _get_my_user_id]
+ F0 --> F2[to_thread _sync_get_followers]
+ F1 -- yes --> F2
+ Dswitch -- following --> G1{user_id present?}
+ G1 -- no --> G0[to_thread _get_my_user_id]
+ G0 --> G2[to_thread _sync_get_following]
+ G1 -- yes --> G2
+ Dswitch -- _ --> Eunk[raise ValueError Unknown operation]
+ M1 --> K1[_format_user_data + _track_twitter_usage me 1]
+ U2 --> K2[_format_user_data users 0 + _track_twitter_usage by_username 1]
+ I2 --> K3[_format_user_data + _track_twitter_usage by_id 1]
+ F2 --> K4[map _format_user_data + _track_twitter_usage followers len users]
+ G2 --> K5[same for following]
+ K1 --> OK[Return success envelope]
+ K2 --> OK
+ K3 --> OK
+ K4 --> OK
+ K5 --> OK
+
+ C -. raises 401/403 .-> REF[_refresh_and_get_client] --> C
+ C -. other Exception .-> EGEN[Return success=false<br/>error: str e]
+```
+
+## Decision Logic
+
+- **Operation dispatch** uses a Python 3.10+ `match` / `case` block. Any value
+ other than the five documented operations raises `ValueError(f"Unknown operation: {operation}")`.
+- **Validation**:
+ - `by_username`: empty `username` -> `ValueError("Username is required")`.
+ - `by_id`: empty `user_id` -> `ValueError("User ID is required")`.
+ - `followers` / `following`: missing `user_id` is **not** an error - handler
+ falls back to `_get_my_user_id`.
+- **Not-found handling**: `by_username` / `by_id` raise `ValueError` when the
+ SDK returns an empty `data` list; the string is propagated as the envelope
+ `error`.
+- **Lazy auth refresh**: identical to `twitterSend` - any exception whose
+ `str(e)` contains `401`/`403`/`Unauthorized`/`Forbidden` triggers one
+ refresh-and-retry.
+- **max_results clamping**: `max(1, min(requested, 1000))` for followers /
+ following. Anything else is ignored.
+- **Usage tracking**:
+ - `me`/`by_username`/`by_id`: 1 resource.
+ - `followers`/`following`: `len(users)` resources; skipped when the result
+ list is empty.
+
+## Side Effects
+
+- **Database writes**: one `api_usage_metrics` row per successful operation
+ (when at least one resource was returned).
+- **Broadcasts**: none.
+- **External API calls**:
+ - `GET https://api.twitter.com/2/users/me` (always on `me`; also on
+ followers/following when `user_id` omitted).
+ - `GET https://api.twitter.com/2/users/by?usernames=...` (by_username).
+ - `GET https://api.twitter.com/2/users?ids=...` (by_id).
+ - `GET https://api.twitter.com/2/users/:id/followers` (followers).
+ - `GET https://api.twitter.com/2/users/:id/following` (following).
+ - Optional refresh: `POST https://api.twitter.com/2/oauth2/token`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: OAuth tokens via `auth_service.get_oauth_tokens("twitter")`.
+- **Services**: `PricingService`, `Database`, `TwitterOAuth` (refresh).
+- **Python packages**: `xdk`.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **`max_results < 1`**: silently clamped to 1.
+- **`max_results > 1000`**: silently clamped to 1000. The SDK may still paginate
+ internally; only the first page is returned regardless.
+- **Only first page for followers/following**: `_sync_get_followers` /
+ `_sync_get_following` break after the first page - `next_token` is discarded.
+- **Not-found vs. empty**: when the target user exists but has zero
+ followers/following, the handler returns `{users: [], count: 0}` - it does
+ NOT raise. `by_username` / `by_id` treat empty data as an error.
+- **`_get_my_user_id` cost not tracked**: the implicit `users/me` call made on
+ followers/following with empty `user_id` is not reflected in
+ `api_usage_metrics`.
+- **`verified` default is `False`**: even when the API omits the field the
+ output will claim the user is not verified. Treat as unreliable unless
+ expansions guaranteed.
+
+## Related
+
+- **Skills using this as a tool**: [`twitter-user-skill/SKILL.md`](../../../server/skills/social_agent/twitter-user-skill/SKILL.md)
+- **Sibling nodes**: [`twitterSend`](./twitterSend.md), [`twitterSearch`](./twitterSearch.md), [`twitterReceive`](./twitterReceive.md)
+- **Architecture docs**: [Pricing Service](../../pricing_service.md)
diff --git a/docs-internal/node-logic-flows/web_automation/apifyActor.md b/docs-internal/node-logic-flows/web_automation/apifyActor.md
new file mode 100644
index 00000000..380ad706
--- /dev/null
+++ b/docs-internal/node-logic-flows/web_automation/apifyActor.md
@@ -0,0 +1,172 @@
+# Apify Actor (`apifyActor`)
+
+| Field | Value |
+|------|-------|
+| **Category** | web_automation / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/apifyNodes.ts`](../../../client/src/nodeDefinitions/apifyNodes.ts) |
+| **Backend handler** | [`server/services/handlers/apify.py::handle_apify_actor`](../../../server/services/handlers/apify.py) |
+| **Tests** | [`server/tests/nodes/test_web_automation.py`](../../../server/tests/nodes/test_web_automation.py) |
+| **Skill (if any)** | [`server/skills/web_agent/apify-skill/SKILL.md`](../../../server/skills/web_agent/apify-skill/SKILL.md) |
+| **Dual-purpose tool** | yes |
+
+## Purpose
+
+Run an Apify actor (pre-built scraper / automation) via the official
+`apify-client` async SDK, wait for it to finish, and return the dataset
+items. Used for platforms that have no first-class integration in MachinaOs
+(Instagram, TikTok, Twitter/X, LinkedIn, Facebook, YouTube, Google Search /
+Maps, website content crawlers).
+
+The handler merges two input sources into the actor's run-input dict: a raw
+JSON string (`actorInput`) plus "quick helpers" specific to a handful of
+curated actor ids (e.g. `instagramUrls` for `apify/instagram-scraper`).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `actorId` | options/string | `""` | **yes** | - | Actor id (e.g. `apify/instagram-scraper`) or `custom` |
+| `customActorId` | string | `""` | yes if `actorId=custom` | `actorId=custom` | Used when `actorId=custom` |
+| `actorInput` | string (JSON) | `"{}"` | no | - | Raw JSON run-input; invalid JSON silently becomes `{}` |
+| `timeout` | number | `300` | no | - | Run timeout in seconds (SDK forwards as `timeout_secs`) |
+| `maxResults` | number | `100` | no | - | Forwarded to `dataset.list_items(limit=...)` |
+| `memory` | number | `1024` | no | - | Actor memory in MB (`memory_mbytes`) |
+| `instagramUrls` | string | `""` | no | `actorId=apify/instagram-scraper` | Comma-separated -> `directUrls[]` |
+| `tiktokProfiles` | string | `""` | no | `actorId=clockworks/tiktok-scraper` | Comma-separated -> `profiles[]` |
+| `tiktokHashtags` | string | `""` | no | `actorId=clockworks/tiktok-scraper` | Comma-separated -> `hashtags[]` |
+| `twitterSearchTerms` | string | `""` | no | `actorId=apidojo/tweet-scraper` | Comma-separated -> `searchTerms[]` |
+| `twitterHandles` | string | `""` | no | `actorId=apidojo/tweet-scraper` | Comma-separated -> `twitterHandles[]` |
+| `googleSearchQuery` | string | `""` | no | `actorId=apify/google-search-scraper` | -> `searchQuery` |
+| `googleSearchPages` | number | `1` | no | `actorId=apify/google-search-scraper` | -> `maxPagesPerQuery` |
+| `crawlerStartUrls` | string | `""` | no | `actorId=apify/website-content-crawler` | Comma-separated -> `startUrls[{url}]` |
+| `crawlerMaxDepth` | number | `2` | no | `actorId=apify/website-content-crawler` | -> `maxCrawlDepth` |
+| `crawlerMaxPages` | number | `50` | no | `actorId=apify/website-content-crawler` | -> `maxCrawlPages` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload (success)
+
+```ts
+{
+ run_id: string;
+ actor_id: string;
+ status: string; // 'SUCCEEDED' / 'FAILED' / 'TIMED-OUT' / 'ABORTED' / other
+ items: any[]; // dataset items up to maxResults
+ item_count: number;
+ dataset_id: string;
+ compute_units: number; // mapped from usageTotalUsd on the run
+ started_at: string;
+ finished_at: string;
+}
+```
+
+On `FAILED` / `TIMED-OUT` / `ABORTED` the envelope is `success: false` with a
+human error message AND a trimmed `result` dict carrying `run_id`, `actor_id`,
+and `status` so downstream nodes can still diagnose.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_apify_actor] --> B[await _get_apify_client<br/>via container.auth_service.get_api_key 'apify']
+ B -- token missing --> Enotk[Return error:<br/>Apify API token not configured]
+ B -- token ok --> C[Read actorId, swap to customActorId if 'custom']
+ C --> C1{actor_id empty?}
+ C1 -- yes --> Eaid[Return error: Actor ID is required]
+ C1 -- no --> D[_build_actor_input<br/>parse actorInput JSON else {}<br/>merge per-actor quick helpers]
+ D --> E[Read timeout, maxResults, memory_mbytes]
+ E --> F[client.actor id .call<br/>run_input, timeout_secs, memory_mbytes]
+ F -- run_info None --> Enone[Return error:<br/>no result returned]
+ F -- ok --> G{run_status?}
+ G -- FAILED --> Gf[Return success=false<br/>error=errorMessage, result={run_id, actor_id, status}]
+ G -- TIMED-OUT --> Gt[Return success=false<br/>error=Actor timed out]
+ G -- ABORTED --> Ga[Return success=false<br/>error=Actor run was aborted]
+ G -- other --> H{dataset_id truthy?}
+ H -- yes --> H1[client.dataset id .list_items limit=maxResults<br/>items = list_result.items]
+ H -- no --> H2[items = empty list]
+ H1 & H2 --> I[Build result dict:<br/>run_id, actor_id, status, items, item_count,<br/>dataset_id, compute_units=usageTotalUsd,<br/>started_at, finished_at]
+ I --> J[Return success envelope]
+ F -- Exception --> K[Catch all:<br/>rewrite 401/Unauthorized -> 'Invalid API token'<br/>rewrite 404/not found -> 'Actor not found']
+ K --> Eexc[Return error envelope]
+```
+
+## Decision Logic
+
+- **Auth lookup**: `auth_service.get_api_key("apify", "default")` - a None
+ return short-circuits with `Apify API token not configured`.
+- **Actor id swap**: literal string `"custom"` triggers replacement with
+ `customActorId` BEFORE the empty check. An empty `customActorId` still
+ triggers the `Actor ID is required` error.
+- **Run-input merge**:
+ - `actorInput` parsed as JSON; string input that fails `json.loads` (or is
+ empty/blank) silently becomes `{}`. Non-dict, non-string input becomes `{}`.
+ - Quick helpers run even when `actorInput` already contains those keys -
+ they OVERWRITE any existing value.
+ - Quick helpers only fire for the five hard-coded actor ids.
+- **Run statuses**: three status strings (`FAILED`, `TIMED-OUT`, `ABORTED`)
+ produce `success=false` envelopes with specific error messages. Every other
+ status (including `SUCCEEDED`, `RUNNING`, `READY`, etc.) proceeds to dataset
+ fetch. Runs that stay `RUNNING` past the SDK's internal polling are expected
+ to be handled by the SDK and should not reach here.
+- **Empty dataset id**: `items = []`, no API call to the dataset endpoint.
+- **Error string rewriting**: `str(e)` is pattern-matched for `401`,
+ `Unauthorized`, `404`, and `not found` (case-insensitive for the last one)
+ to produce friendlier user errors. All other exceptions bubble up as their
+ `str(e)` text.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**:
+ - `POST https://api.apify.com/v2/acts/<actor_id>/runs` (via SDK `actor.call`)
+ - `GET https://api.apify.com/v2/datasets/<dataset_id>/items?limit=<n>` (via SDK `dataset.list_items`)
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `auth_service.get_api_key("apify", "default")` -> stored in
+ the `EncryptedAPIKey` table under provider `apify`.
+- **Services**: Apify platform (api.apify.com).
+- **Python packages**: `apify-client` (>= async variant `ApifyClientAsync`).
+- **Environment variables**: none (token lives in credentials DB).
+
+## Edge cases & known limits
+
+- **Invalid `actorInput` JSON is silent**: the run is sent with `{}` and may
+ succeed unexpectedly (actor uses defaults) or fail with a validation error
+ that surfaces in `errorMessage`.
+- **Quick helpers overwrite raw input**: setting both `actorInput` JSON AND
+ the per-actor helper means the helper wins. This is not documented in the
+ frontend.
+- **No streaming**: the handler blocks until the actor finishes or the SDK
+ raises. `timeout` is the hard cap.
+- **`compute_units` is misleading**: the value returned is `run.usageTotalUsd`
+ (USD), not compute units. The key name is preserved for backward compat.
+- **Error rewriting is substring-based**: an actor's genuine error message
+ that contains the word "Unauthorized" or "not found" will be replaced with
+ the generic MachinaOs error, masking the real cause.
+- **No usage tracking**: unlike search / HTTP nodes, there is no
+ `api_usage_metrics` row written for Apify calls.
+- **Stale dataset on repeat runs**: `dataset.list_items(limit=maxResults)`
+ always reads the run's default dataset; concurrent runs on the same actor
+ use separate datasets per run (handled by Apify), but a user who supplies
+ a custom `datasetId` via `actorInput` cannot influence which dataset the
+ handler reads from.
+
+## Related
+
+- **Skills using this as a tool**: [`apify-skill/SKILL.md`](../../../server/skills/web_agent/apify-skill/SKILL.md)
+- **Companion nodes**: [`browser`](./browser.md), [`crawleeScraper`](./crawleeScraper.md)
+- **Architecture docs**: [Credentials Encryption](../../credentials_encryption.md)
diff --git a/docs-internal/node-logic-flows/web_automation/browser.md b/docs-internal/node-logic-flows/web_automation/browser.md
new file mode 100644
index 00000000..f87786a7
--- /dev/null
+++ b/docs-internal/node-logic-flows/web_automation/browser.md
@@ -0,0 +1,202 @@
+# Browser (`browser`)
+
+| Field | Value |
+|------|-------|
+| **Category** | web_automation / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/browserNodes.ts`](../../../client/src/nodeDefinitions/browserNodes.ts) |
+| **Backend handler** | [`server/services/handlers/browser.py::handle_browser`](../../../server/services/handlers/browser.py) |
+| **Service** | [`server/services/browser_service.py::BrowserService`](../../../server/services/browser_service.py) |
+| **Tests** | [`server/tests/nodes/test_web_automation.py`](../../../server/tests/nodes/test_web_automation.py) |
+| **Skill (if any)** | [`server/skills/web_agent/browser-skill/SKILL.md`](../../../server/skills/web_agent/browser-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `browser` |
+
+## Purpose
+
+Interactive browser automation via the `agent-browser` CLI (a pinned npm dependency
+invoked through `npx --no-install`). Exposes 14 discrete operations (navigate,
+click, type, fill, screenshot, snapshot, get_text, get_html, eval, wait, scroll,
+select, console, errors) plus a `batch` meta-op. The preferred workflow for an
+AI agent is `navigate` -> `snapshot` -> `click`/`fill` using the stable `@eN`
+element refs returned by snapshot -> `snapshot` again to verify.
+
+Session state (cookies, open tabs, auth) persists across sequential operations
+that share the same `session` value. If no session is provided the handler
+derives `machina_<execution_id>` from the current execution context, so every
+workflow run gets its own isolated browser.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `toolName` | string | `browser` | no | - | Tool name exposed to the AI agent |
+| `toolDescription` | string | (see frontend) | no | - | Tool description shown to LLM |
+| `operation` | options | `navigate` | no | - | One of `navigate`, `click`, `type`, `fill`, `screenshot`, `snapshot`, `get_text`, `get_html`, `eval`, `wait`, `scroll`, `select`, `console`, `errors`, `batch` |
+| `session` | string | `""` | no | - | Session id; if empty, handler uses `machina_<execution_id>` |
+| `timeout` | number | `30` | no | - | Per-operation timeout in seconds |
+| `headed` | boolean | `true` | no | - | Passes `--headed` to agent-browser |
+| `autoConnect` | boolean | `false` | no | - | Passes `--auto-connect` |
+| `browser` | options | `chrome` | no | - | `chrome` / `edge` / `chromium` / `custom` / `bundled` / `bundled_explicit`. Legacy `bundled` silently upgraded to `chrome` |
+| `executablePath` | string | `""` | no | `browser=custom` | Explicit browser path when `browser=custom` |
+| `newWindow` | boolean | `true` | no | - | Appended as `--args --new-window`; only honoured when an explicit `executable_path` resolved |
+| `chromeProfile` | string | `""` | no | - | Chrome user-data-dir profile |
+| `userAgent` | string | `""` | no | - | Custom UA string |
+| `proxy` | string | `""` | no | - | `host:port` or `user:pass@host:port` |
+| `actionDelay` | number | `0` | no | - | Seconds to wait before the real op (a pre-command `wait` is issued first) |
+| `url` | string | `""` | yes (op=navigate) | `operation=navigate` | Target URL |
+| `selector` | string | `""` | yes (ops that act on an element) | see below | CSS selector or `@eN` ref from snapshot |
+| `text` | string | `""` | no | `operation=type` | Text to type |
+| `value` | string | `""` | no | `operation in [fill, select]` | Value to fill / dropdown value |
+| `expression` | string | `""` | yes (op=eval) | `operation=eval` | JS expression to evaluate |
+| `direction` | options | `down` | no | `operation=scroll` | `up` / `down` / `left` / `right` |
+| `amount` | number | `500` | no | `operation=scroll` | Pixels to scroll |
+| `fullPage` | boolean | `false` | no | `operation=screenshot` | Passes `--full` |
+| `annotate` | boolean | `false` | no | `operation=screenshot` | Passes `--annotate` |
+| `screenshotFormat` | options | `png` | no | `operation=screenshot` | `png` / `jpeg` / `webp` |
+| `screenshotQuality` | number | - | no | `operation=screenshot, screenshotFormat=jpeg` | 1-100, only forwarded for jpeg |
+| `commands` | string (JSON array) | `"[]"` | yes (op=batch) | `operation=batch` | JSON array of command dicts piped to stdin |
+
+Operations that **require** `selector`: `click`, `type`, `fill`, `get_text`,
+`get_html`, `wait`, `select`.
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+| `output-tool` | object | Same payload when wired to an AI agent |
+
+### Output payload
+
+```ts
+{
+ operation: string; // echoes the requested op
+ data: any; // Parsed JSON from agent-browser's first stdout line
+ session: string; // Resolved session id
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time: number }`.
+On failure: `{ success: false, error: <string>, execution_time: number }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_browser] --> B{BrowserService<br/>available?}
+ B -- no --> Einst[Return error:<br/>agent-browser not installed]
+ B -- yes --> C[Resolve session, timeout, headed, browser,<br/>executable_path, proxy, userAgent,<br/>newWindow, chromeProfile, actionDelay]
+ C --> C1[Upgrade legacy 'bundled' -> 'chrome'<br/>_resolve_browser looks up shutil.which or Win registry]
+ C1 --> D{actionDelay > 0?}
+ D -- yes --> D1[svc.run wait actionDelay first]
+ D -- no --> E{op == batch?}
+ D1 --> E
+ E -- batch --> E1[json.loads commands -> stdin]
+ E1 --> F[svc.run batch --json + stdin=json]
+ E -- other --> G[_build_args op, params]
+ G --> Gsw{operation switch}
+ Gsw -- navigate --> Gn[args: open URL<br/>URL required]
+ Gsw -- click / wait --> Gc[args: op SELECTOR<br/>selector required]
+ Gsw -- type --> Gt[args: type SELECTOR TEXT]
+ Gsw -- fill / select --> Gf[args: op SELECTOR VALUE]
+ Gsw -- screenshot --> Gs[args: screenshot + --full/--annotate/--screenshot-format/--screenshot-quality]
+ Gsw -- snapshot --> Gsn[args: snapshot -i]
+ Gsw -- get_text / get_html --> Gg[args: get text-or-html SELECTOR]
+ Gsw -- eval --> Gev[args: eval EXPRESSION<br/>expression required]
+ Gsw -- scroll --> Gsc[args: scroll DIR AMOUNT]
+ Gsw -- console / errors --> Gco[args: op]
+ Gsw -- unknown --> Gx[raise ValueError<br/>Unknown operation]
+ Gn & Gc & Gt & Gf & Gs & Gsn & Gg & Gev & Gsc & Gco --> H[svc.run args, session, timeout, run_kw]
+ F --> H
+ H --> H1[Popen argv via npx --no-install agent-browser<br/>shell=False, reads first JSON line of stdout]
+ H1 --> H2{first line<br/>parseable JSON?}
+ H2 -- yes --> H3[data = parsed JSON]
+ H2 -- no --> H4[data = output: raw string]
+ H3 & H4 --> I{length > 100KB?}
+ I -- yes --> I1[truncate + append '...truncated']
+ I -- no --> J[finally: psutil kill process tree]
+ I1 --> J
+ J --> K[Return success envelope<br/>operation, data, session]
+ Gx --> Eval[ValueError caught:<br/>return error envelope]
+ H --> Eother[TimeoutError / RuntimeError caught<br/>return error envelope]
+```
+
+## Decision Logic
+
+- **Service missing**: `get_browser_service()` returns `None` when `npx` is not on
+ PATH -> immediate `agent-browser not installed` error envelope.
+- **Session resolution**: empty `session` -> `machina_<execution_id>`. Only the
+ stripped value is considered empty; whitespace triggers the fallback.
+- **Browser upgrade**: `""` or `bundled` both normalised to `chrome`. Users who
+ specifically want the bundled Chromium must pick `bundled_explicit`.
+- **Executable resolution**: `shutil.which()` against Linux/macOS PATH names,
+ then Windows `HKLM/HKCU\\SOFTWARE\\...\\App Paths\\<exe>` registry. If neither
+ resolves, `executable_path=None` and agent-browser uses its own bundled Chrome.
+- **`newWindow`**: gated on `executable_path` actually resolving - if a user
+ requests new-window while `browser=bundled_explicit`, the flag is silently
+ dropped.
+- **`actionDelay > 0`**: issues a `wait <seconds>` command to agent-browser
+ BEFORE the real operation. Failures in the delay call propagate as errors.
+- **`batch`**: reads `commands` JSON string (defaults to `"[]"`) and pipes
+ `json.dumps(cmds).encode()` to the subprocess' stdin with flags `batch --json`.
+- **Required params**: `_req(p, "url")` and `_req(p, "expression")` raise
+ `ValueError` on empty strings; `_req_sel(s)` does the same for `selector`.
+ These surface as the error envelope via the outer `except (ValueError, ...)`.
+- **Unknown operation**: `_build_args` raises `ValueError("Unknown operation: <op>")`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: none (all work happens via subprocess).
+- **File I/O**: agent-browser itself may write screenshots or a profile dir to
+ its own cache - not under this handler's control.
+- **Subprocess**: spawns `npx --no-install agent-browser ...` via
+ `subprocess.Popen` with `shell=False`. Reads only the FIRST stdout line
+ (daemon holds stdout open), caps at 100 KB, then force-kills the entire
+ process tree via `psutil.Process.children(recursive=True) -> kill()`.
+ Always calls `proc.wait()` in a finally block.
+- **Long-lived daemon**: agent-browser spawns a persistent daemon between
+ calls. `shutdown_browser_service()` (registered in FastAPI lifespan) runs
+ `agent-browser close --all` to stop it.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `BrowserService` singleton; `npx` on PATH; `agent-browser`
+ pinned in the project's `package.json` and installed under `node_modules`.
+- **Python packages**: `psutil` (for process-tree kill).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Output truncation**: responses > 100 KB are truncated with a literal
+ `...(truncated)` suffix appended BEFORE `json.loads`, so a truncated JSON
+ payload falls through the `JSONDecodeError` path and returns
+ `{"output": "<raw truncated string>"}` instead of structured data.
+- **Empty first line**: if agent-browser writes nothing to stdout the service
+ reads stderr and raises `RuntimeError` with the stderr content (or the
+ literal fallback `agent-browser returned empty output`).
+- **Silent `bundled` -> `chrome` upgrade**: a user who saved a workflow when
+ `bundled` was the default will now actually use system Chrome on execution.
+- **`newWindow` silently disabled**: see Decision Logic.
+- **Only `ValueError`, `TimeoutError`, `RuntimeError` are caught**: other
+ exceptions (e.g. `OSError` from subprocess, `psutil.Error`) propagate and
+ the executor wraps them in its generic envelope.
+- **Process tree kill race**: `psutil.NoSuchProcess` is swallowed for both the
+ parent and every child, so a fast-exiting daemon never leaks an exception
+ but may leave orphaned Chromium processes if the tree changed shape between
+ the `children()` call and the `kill()` call.
+- **`actionDelay` is billable**: the preliminary `wait` call consumes part of
+ `timeout` because each subprocess invocation resets the timer.
+
+## Related
+
+- **Skills using this as a tool**: [`browser-skill/SKILL.md`](../../../server/skills/web_agent/browser-skill/SKILL.md)
+- **Companion nodes**: [`crawleeScraper`](./crawleeScraper.md), [`apifyActor`](./apifyActor.md)
+- **Architecture docs**: [Proxy Service](../../proxy_service.md)
diff --git a/docs-internal/node-logic-flows/web_automation/crawleeScraper.md b/docs-internal/node-logic-flows/web_automation/crawleeScraper.md
new file mode 100644
index 00000000..9758537d
--- /dev/null
+++ b/docs-internal/node-logic-flows/web_automation/crawleeScraper.md
@@ -0,0 +1,180 @@
+# Crawlee Scraper (`crawleeScraper`)
+
+| Field | Value |
+|------|-------|
+| **Category** | web_automation / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/crawleeNodes.ts`](../../../client/src/nodeDefinitions/crawleeNodes.ts) |
+| **Backend handler** | [`server/services/handlers/crawlee.py::handle_crawlee_scraper`](../../../server/services/handlers/crawlee.py) |
+| **Tests** | [`server/tests/nodes/test_web_automation.py`](../../../server/tests/nodes/test_web_automation.py) |
+| **Skill (if any)** | [`server/skills/web_agent/crawlee-scraper-skill/SKILL.md`](../../../server/skills/web_agent/crawlee-scraper-skill/SKILL.md) |
+| **Dual-purpose tool** | yes |
+
+## Purpose
+
+Python-based web scraping on top of the `crawlee` library. Supports two runtime
+engines:
+
+- `beautifulsoup` - fast static HTML scraping via `BeautifulSoupCrawler`.
+- `playwright` - full headless browser for JS-rendered pages via `PlaywrightCrawler`.
+- `adaptive` - currently aliased to `beautifulsoup` in this handler.
+
+Two modes control how many URLs are visited: `single` (only the seed URL, hard
+caps `max_pages=1` / `max_depth=0`) and `crawl` (follow links matching
+`linkSelector` + optional `urlPattern` up to `maxPages` / `maxDepth`).
+
+Unlike `httpRequest` or `browser`, Crawlee manages concurrency, retry
+back-off, request queues, and storage internally; the handler only feeds in
+config and collects a page list from the route handler closure.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream trigger; not consumed directly |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `url` | string | `""` | **yes** | - | Seed URL |
+| `crawlerType` | options | `beautifulsoup` | no | - | `beautifulsoup` / `playwright` / `adaptive` |
+| `mode` | options | `single` | no | - | `single` or `crawl` |
+| `cssSelector` | string | `""` | no | - | CSS selector used for text/HTML extraction. Empty -> whole page |
+| `extractLinks` | boolean | `false` | no | - | Include `links[]` on each page |
+| `outputFormat` | options | `text` | no | - | `text` / `html` / `markdown`. `markdown` falls back to text if `html2text` not installed |
+| `maxPages` | number | `10` | no | `mode=crawl` | Ignored and clamped to 1 when `mode=single` |
+| `maxDepth` | number | `2` | no | `mode=crawl` | Ignored and set to 0 when `mode=single` |
+| `maxConcurrency` | number | `5` | no | - | Forwarded as `max_concurrency`; `desired_concurrency = min(maxConcurrency, 10)` |
+| `timeout` | number | `60` | no | - | Per-request handler timeout AND outer `asyncio.wait_for` timeout |
+| `linkSelector` | string | `""` | no | `mode=crawl` | Defaults to `a[href]` when empty |
+| `urlPattern` | string | `""` | no | `mode=crawl` | `fnmatch`-style pattern compiled with `fnmatch.translate` -> passed to `enqueue_links(include=[regex])` |
+| `browserType` | options | `chromium` | no | `crawlerType=playwright` | `chromium` / `firefox` / `webkit` |
+| `waitForSelector` | string | `""` | no | `crawlerType=playwright` | Awaits selector before extracting |
+| `waitTimeout` | number | `30000` | no | `crawlerType=playwright` | Milliseconds for `wait_for_selector` |
+| `screenshot` | boolean | `false` | no | `crawlerType=playwright` | Capture base64 PNG per page |
+| `useProxy` | boolean | `false` | no | - | Route through `ProxyService` (see Decision Logic) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope payload |
+
+### Output payload
+
+```ts
+{
+ pages: Array<{
+ url: string;
+ title: string;
+ content: string;
+ links?: string[]; // when extractLinks=true
+ screenshot?: string; // base64 PNG, playwright + screenshot=true
+ }>;
+ page_count: number;
+ crawler_type: 'beautifulsoup' | 'playwright' | 'adaptive';
+ mode: 'single' | 'crawl';
+ proxied: boolean;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_crawlee_scraper] --> B{url stripped<br/>non-empty?}
+ B -- no --> Eurl[Return error: URL is required]
+ B -- yes --> C[Read crawlerType, mode, cssSelector,<br/>extractLinks, outputFormat, maxPages,<br/>maxDepth, maxConcurrency, timeout]
+ C --> C1{mode == 'single'?}
+ C1 -- yes --> C2[Force maxPages=1, maxDepth=0]
+ C1 -- no --> C3[Use provided max_pages / max_depth]
+ C2 & C3 --> D[await _get_proxy_config parameters, url]
+ D --> D1{useProxy AND<br/>ProxyService.get_proxy_url<br/>returned URL?}
+ D1 -- yes --> D2[ProxyConfiguration proxy_urls=url]
+ D1 -- no / exception --> D3[proxy_config = None]
+ D2 & D3 --> E{crawlerType?}
+ E -- beautifulsoup / adaptive --> F1[_run_beautifulsoup]
+ E -- playwright --> F2[_run_playwright]
+ E -- other --> Ebad[Return error:<br/>Unknown crawler type]
+ F1 --> G[BeautifulSoupCrawler<br/>max_requests_per_crawl=maxPages<br/>max_crawl_depth=maxDepth if crawl else 0<br/>request_handler_timeout=timeout<br/>ConcurrencySettings<br/>MemoryStorageClient<br/>proxy_configuration=proxy_config]
+ F2 --> H[PlaywrightCrawler<br/>browser_type, headless=True, proxy_configuration]
+ G & H --> I[register default_handler closure]
+ I --> I1[handler: extract title/content<br/>via _extract_text+_extract_links<br/>append to pages list<br/>if mode=crawl: ctx.enqueue_links<br/>with optional fnmatch-compiled include regex]
+ I1 --> J[asyncio.wait_for crawler.run URL, timeout=timeout]
+ J -- ImportError --> Eimp[Return error with install hint<br/>playwright vs crawlee]
+ J -- other Exception --> Egen[Return error: str e]
+ J -- ok --> K[Return success<br/>pages, page_count, crawler_type, mode, proxied]
+```
+
+## Decision Logic
+
+- **Empty URL**: `url.strip() == ""` -> immediate failure envelope, no crawler
+ is constructed.
+- **`mode='single'`**: hard clamps `max_pages=1` and `max_depth=0`, regardless
+ of what the user set. In `crawl` mode the requested values are forwarded.
+- **`crawlerType='adaptive'`**: routed to `_run_beautifulsoup` - there is no
+ true adaptive detection in this handler today.
+- **Proxy bridge**: `_get_proxy_config` only runs when `useProxy=True`.
+ `ProxyService.get_proxy_url` returning `None` or raising any `Exception` is
+ logged at WARN and the crawl proceeds unproxied.
+- **Link filter**: when `urlPattern` is set in `crawl` mode the pattern is
+ passed through `fnmatch.translate` and compiled to a regex for
+ `enqueue_links(include=[...])`.
+- **Content extraction**: `_extract_text` returns text, html, or markdown.
+ For markdown the handler falls back to plain text if `html2text` is missing
+ (`ImportError` swallowed). All output is capped at 100 000 chars
+ (`_MAX_CONTENT_LENGTH`).
+- **Error handling**:
+ - `ImportError` whose message contains `playwright` -> rewritten to an
+ install hint for `pip install 'crawlee[playwright]' && playwright install`.
+ - `ImportError` whose message contains `crawlee` -> rewritten to an install
+ hint for `pip install 'crawlee[beautifulsoup]'`.
+ - All other exceptions are caught and the `str(e)` returned as-is; the
+ handler never raises.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none.
+- **External API calls**: HTTP(S) requests to the target site(s), optionally
+ via a proxy returned by `ProxyService`.
+- **File I/O**: none by default. `MemoryStorageClient` keeps the request queue
+ in memory only.
+- **Subprocess**: PlaywrightCrawler launches a browser subprocess under the
+ hood (managed by Playwright), but this handler does not spawn anything
+ directly.
+
+## External Dependencies
+
+- **Credentials**: none directly. Proxy auth, if any, is embedded in the
+ proxy URL returned by `ProxyService.get_proxy_url`.
+- **Services**: `ProxyService` (only when `useProxy=True`).
+- **Python packages**: `crawlee[beautifulsoup]`, `crawlee[playwright]`
+ (optional), `bs4`, `html2text` (optional, for markdown), `playwright` (for
+ playwright mode).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Content truncation**: per-page content is silently capped at 100 KB by
+ `_MAX_CONTENT_LENGTH` - longer pages are truncated without a marker.
+- **Single mode ignores user caps**: `maxPages` and `maxDepth` are
+ overridden to 1 and 0 respectively when `mode=single`.
+- **`adaptive` is a lie**: currently aliased to `beautifulsoup`; there is no
+ runtime detection to escalate to Playwright for JS-heavy pages.
+- **Markdown silently downgrades to text** if `html2text` is not installed.
+- **Timeout is applied twice**: once as `request_handler_timeout` inside the
+ crawler and again as `asyncio.wait_for(crawler.run(...), timeout=timeout)`
+ wrapping the whole run. Long multi-page crawls hit the outer limit first.
+- **Proxy failures are swallowed**: any exception from `ProxyService` causes
+ the crawl to proceed UN-proxied and returns `proxied=False`, which may leak
+ the user's real IP to the target.
+- **No usage tracking**: unlike `proxyRequest` / `httpRequest`, this handler
+ does not record cost or bytes metrics.
+
+## Related
+
+- **Skills using this as a tool**: [`crawlee-scraper-skill/SKILL.md`](../../../server/skills/web_agent/crawlee-scraper-skill/SKILL.md)
+- **Companion nodes**: [`browser`](./browser.md), [`apifyActor`](./apifyActor.md),
+ [`httpRequest`](../http_proxy/httpRequest.md)
+- **Architecture docs**: [Proxy Service](../../proxy_service.md)
diff --git a/docs-internal/node-logic-flows/whatsapp/whatsappDb.md b/docs-internal/node-logic-flows/whatsapp/whatsappDb.md
new file mode 100644
index 00000000..27da3dbe
--- /dev/null
+++ b/docs-internal/node-logic-flows/whatsapp/whatsappDb.md
@@ -0,0 +1,150 @@
+# WhatsApp DB (`whatsappDb`)
+
+| Field | Value |
+|------|-------|
+| **Category** | whatsapp / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/whatsappNodes.ts`](../../../client/src/nodeDefinitions/whatsappNodes.ts) |
+| **Backend handler** | [`server/services/handlers/whatsapp.py::handle_whatsapp_db`](../../../server/services/handlers/whatsapp.py) |
+| **Tests** | [`server/tests/nodes/test_whatsapp.py`](../../../server/tests/nodes/test_whatsapp.py) |
+| **Skill (if any)** | [`server/skills/social_agent/whatsapp-db-skill/SKILL.md`](../../../server/skills/social_agent/whatsapp-db-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `whatsappDb` |
+
+## Purpose
+
+Query and operate on the WhatsApp state owned by the Go `whatsapp-rpc` service:
+chat/message history, contacts, groups, and newsletter channels (list, info,
+messages, stats, follow/unfollow, create, mute, mark-viewed, react, live
+updates, profile pictures). One node, 18 operations switched via the
+`operation` parameter. Also works as an AI agent tool.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Template source for operation parameters |
+
+## Parameters
+
+The top-level parameter is `operation`. Each operation takes its own subset of
+parameters, all rendered conditionally via `displayOptions.show` in the
+frontend.
+
+### `operation` enum
+
+| Operation | Required params | Optional params | RPC method |
+|-----------|----------------|-----------------|------------|
+| `chat_history` | `chat_type` + (`phone` \| `group_id`) | `group_filter`, `sender_phone`, `message_filter`, `limit`, `offset`, `include_media_data` | `chat_history` (router) |
+| `search_groups` | - | `query`, `limit` | `groups` |
+| `get_group_info` | `group_id_for_info` or `group_id` | `participant_limit` | `group_info` |
+| `get_contact_info` | `contact_phone` or `phone` | - | `contact_info` |
+| `list_contacts` | - | `query`, `limit` | `contacts` |
+| `check_contacts` | `phones` (comma-separated) | - | `contact_check` |
+| `list_channels` | - | `refresh`, `limit` | `newsletters` |
+| `get_channel_info` | `channel_jid` (JID or invite link) | `refresh` | `newsletter_info` |
+| `channel_messages` | `channel_jid` | `channel_count`, `before_server_id`, `message_offset`, `since`, `until`, `media_type`, `search`, `refresh`, `include_media_data` | `newsletter_messages` |
+| `channel_stats` | `channel_jid` | `channel_count` | `newsletter_stats` |
+| `channel_follow` | `channel_jid` | - | `newsletter_follow` |
+| `channel_unfollow` | `channel_jid` | - | `newsletter_unfollow` |
+| `channel_create` | `channel_name` | `channel_description`, `picture` | `newsletter_create` |
+| `channel_mute` | `channel_jid` | `mute` (bool, default true) | `newsletter_mute` |
+| `channel_mark_viewed` | `channel_jid`, `server_ids` (comma list) | - | `newsletter_mark_viewed` |
+| `newsletter_react` | `channel_jid`, `react_server_id` | `reaction` (emoji) | `newsletter_react` |
+| `newsletter_live_updates` | `channel_jid`, `server_ids` | - | `newsletter_live_updates` |
+| `contact_profile_pic` | `profile_pic_jid` or `phone` | `preview` | `contact_profile_pic` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Envelope payload with `operation` field + operation-specific fields |
+| `output-tool` | object | Same payload for AI tool wiring |
+
+All payloads include the read-back `operation` and `timestamp`. Collection
+operations (`search_groups`, `list_contacts`, `list_channels`) apply a soft
+`limit` and return `total` / `returned` / `has_more` plus a human-readable
+`hint` if truncated.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_whatsapp_db] --> B{operation?}
+ B -- chat_history --> CH[_handle_chat_history]
+ B -- search_groups --> SG[_handle_search_groups]
+ B -- get_group_info --> GGI[_handle_get_group_info]
+ B -- get_contact_info --> GCI[_handle_get_contact_info]
+ B -- list_contacts --> LC[_handle_list_contacts]
+ B -- check_contacts --> CC[_handle_check_contacts]
+ B -- list_channels --> LCH[_handle_list_channels]
+ B -- get_channel_info --> GCHI[_handle_get_channel_info]
+ B -- channel_messages --> CM[_handle_channel_messages]
+ B -- channel_stats --> CS[_handle_channel_stats]
+ B -- channel_follow --> CF[_handle_channel_follow]
+ B -- channel_unfollow --> CU[_handle_channel_unfollow]
+ B -- channel_create --> CC2[_handle_channel_create]
+ B -- channel_mute --> CMU[_handle_channel_mute]
+ B -- channel_mark_viewed --> CMV[_handle_channel_mark_viewed]
+ B -- newsletter_react --> NR[_handle_newsletter_react]
+ B -- newsletter_live_updates --> NLU[_handle_newsletter_live_updates]
+ B -- contact_profile_pic --> CPP[_handle_contact_profile_pic]
+ B -- unknown --> Eret[raise ValueError<br/>Unknown operation: X]
+ CH --> V1{validate params}
+ V1 -- missing --> Eret
+ V1 -- ok --> X1[await whatsapp_chat_history_handler]
+ X1 -- success=false --> Eret
+ X1 -- ok --> MAY{include_media_data?}
+ MAY -- yes --> MED[_enrich_messages_with_media<br/>semaphore=5, parallel gather]
+ MAY -- no --> OUT
+ MED --> OUT[Return envelope]
+ SG --> OTHERS[... similar pattern for each op:<br/>validate, whatsapp_rpc_call,<br/>raise-on-error, limit+shape result]
+ OTHERS --> OUT
+ Eret -.-> EE[Outer try/except<br/>returns success=false envelope<br/>with str error]
+```
+
+## Decision Logic
+
+- **Operation dispatch**: single `if/elif` chain; unknown operation raises `ValueError` captured by the outer `try/except`.
+- **Invite link vs JID resolution for channel ops**:
+ - `_resolve_channel_identifier(value)`: returns `{'invite': url}` if value starts with `http://` or `https://`, else `{'jid': value}`. Used where the RPC accepts either (`newsletter_info`, `newsletter_stats`).
+ - `_resolve_to_jid(value, rpc_call)`: if value is an invite link, calls `newsletter_info` first to look up the JID, then returns that JID. Used where the RPC only accepts `jid` (`newsletter_messages`, `newsletter_follow`, `newsletter_unfollow`, `newsletter_mute`, `newsletter_mark_viewed`, `newsletter_react`, `newsletter_live_updates`). Raises `ValueError` if lookup fails.
+- **Result truncation for LLM safety** (prevents context overflow):
+ - `search_groups`: returns only `{jid, name}` per group, default `limit=20`
+ - `get_group_info`: returns only `{phone, name, is_admin}` per participant, default `participant_limit=50`
+ - `list_contacts`: returns only `{phone, name, jid}`, default `limit=50`
+ - `list_channels`: returns only `{jid, name, subscriber_count}`, default `limit=20`
+- **Media enrichment** (`include_media_data=true`):
+ - Filters `messages` to those whose `message_type` (or `type`) is in `{image, video, audio, document, sticker}` - the `MEDIA_MESSAGE_TYPES` frozenset.
+ - Runs `_enrich_messages_with_media` with `asyncio.Semaphore(5)` and `asyncio.gather(..., return_exceptions=True)` - per-message failures are swallowed into `media_error` rather than propagating.
+ - Each message mutated in place: `media_data` (base64) and `media_mime_type` on success, `media_error` on failure.
+- **Success flag handling is defensive**: many RPC responses are plain lists (e.g. `groups`, `newsletters`, `contact_check`). The handler accepts both `list` (treated as success) and `dict` (checks `success != False`).
+- **`server_ids` parsing**: `channel_mark_viewed` and `newsletter_live_updates` accept a comma-separated string, split, strip, and `int()` each token. Non-integer values raise `ValueError`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none - standard `node_status` comes from `NodeExecutor`.
+- **External calls**: WebSocket RPC to the Go service (`whatsapp_rpc_call` and `handle_whatsapp_chat_history` in `routers/whatsapp.py`). For `channel_messages` and `chat_history` with `include_media_data=true`, one additional `media` RPC call per media message (up to 5 in parallel).
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `whatsapp-rpc` Go service (default `ws://localhost:9400/ws/rpc`).
+- **Python packages**: `asyncio`.
+- **Environment variables**: `WHATSAPP_RPC_URL`.
+
+## Edge cases & known limits
+
+- **Channel ops silently transform invite links**: a user-supplied invite link becomes a JID via an extra `newsletter_info` round-trip in `_resolve_to_jid`. If that lookup fails, the envelope error is `Could not resolve invite link to channel JID: <value>`.
+- **`_enrich_messages_with_media` swallows per-item errors**: failed downloads become `media_error` fields, never a failed envelope. The count of failures is not summarised.
+- **Truncation hints are best-effort**: `hint` is only populated when `total > limit`. Callers must not rely on it being a specific string - only on the truncation itself.
+- **`search_groups` is client-side filtering**: the RPC returns all groups, the handler filters by `query.lower() in group.name.lower()` and then truncates. For very large group counts this still pulls the full list from the Go service.
+- **Return shape inconsistency**: operations that return `result` merge it via `**result` into the envelope, which may add unexpected top-level keys if the RPC evolves.
+- **Unknown operation** raises in-band; callers get `success=false` with `error = "Unknown operation: X"`.
+
+## Related
+
+- **Skills using this as a tool**: [`whatsapp-db-skill/SKILL.md`](../../../server/skills/social_agent/whatsapp-db-skill/SKILL.md)
+- **Companion nodes**: [`whatsappSend`](./whatsappSend.md), [`whatsappReceive`](./whatsappReceive.md)
+- **Architecture docs**: `CLAUDE.md` -> "WhatsApp Channel (Newsletter) Architecture" and "WhatsApp Integration" sections
diff --git a/docs-internal/node-logic-flows/whatsapp/whatsappReceive.md b/docs-internal/node-logic-flows/whatsapp/whatsappReceive.md
new file mode 100644
index 00000000..21afbe71
--- /dev/null
+++ b/docs-internal/node-logic-flows/whatsapp/whatsappReceive.md
@@ -0,0 +1,162 @@
+# WhatsApp Receive (`whatsappReceive`)
+
+| Field | Value |
+|------|-------|
+| **Category** | whatsapp / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/whatsappNodes.ts`](../../../client/src/nodeDefinitions/whatsappNodes.ts) |
+| **Backend handler** | [`server/services/handlers/triggers.py::handle_trigger_node`](../../../server/services/handlers/triggers.py) (generic) + [`server/services/event_waiter.py::build_whatsapp_filter`](../../../server/services/event_waiter.py) |
+| **Tests** | [`server/tests/nodes/test_whatsapp.py`](../../../server/tests/nodes/test_whatsapp.py) |
+| **Skill (if any)** | n/a |
+| **Dual-purpose tool** | no - pure trigger node |
+
+## Purpose
+
+Event-driven trigger that waits for incoming WhatsApp messages and starts a
+workflow run when one matches. Uses the generic event-waiter machinery: the
+handler registers a waiter with a filter closure, broadcasts `waiting`
+status, then awaits a `whatsapp_message_received` event dispatched by the
+Go RPC listener. Matching messages resolve the waiter and become the
+trigger's output.
+
+## Inputs (handles)
+
+Triggers have no data inputs - they are workflow starting points.
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `messageTypeFilter` | options | `all` | no | - | `all`, `text`, `image`, `video`, `audio`, `document`, `location`, `contact`, `sticker` |
+| `filter` | options | `all` | no | - | `all`, `self`, `any_contact`, `contact`, `group`, `channel`, `keywords` |
+| `contactPhone` | string | `""` | conditional | `filter == 'contact'` | Phone number substring matched against resolved `sender_phone` |
+| `group_id` | string | `""` | conditional | `filter == 'group'` | Group JID |
+| `senderNumber` | string | `""` | no | `filter == 'group'` | Optional phone substring to match a specific sender within the group |
+| `channel_jid` | string | `""` | no | `filter == 'channel'` | Optional exact channel JID; empty = any `@newsletter` chat |
+| `keywords` | string | `""` | conditional | `filter == 'keywords'` | Comma-separated keywords, case-insensitive substring match against `text` |
+| `forwardedFilter` | options | `all` | no | - | `all`, `only_forwarded`, `ignore_forwarded` |
+| `ignoreOwnMessages` | boolean | `true` | no | - | Skip `is_from_me == true` (except when `filter == 'self'`) |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Raw WhatsApp event payload from the Go RPC |
+
+### Output payload
+
+```ts
+{
+ message_id: string;
+ sender: string; // JID (may be LID for groups, but sender_phone is already resolved)
+ sender_phone: string; // Resolved phone (Go RPC resolves LIDs before dispatch)
+ chat_id: string; // Chat JID, ends with '@newsletter' for channel messages
+ message_type: string;
+ text: string; // text messages
+ timestamp: string;
+ is_group: boolean;
+ is_from_me: boolean;
+ push_name: string;
+ is_forwarded: boolean;
+ forwarding_score: number;
+ media?: object; // for media types
+ group_info?: {
+ group_jid: string;
+ sender_jid: string;
+ sender_phone: string; // resolved
+ sender_name: string;
+ };
+ newsletter_meta?: { edit_ts: number; original_ts: number };
+}
+```
+
+Additionally, group/sender display names are persisted alongside JIDs/phones
+in the node parameters (`group_name`, `sender_name`) so that reopening the
+parameter panel shows human-readable labels instead of raw JIDs. See
+CLAUDE.md "WhatsApp Group/Sender Name Persistence".
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_trigger_node] --> B[event_waiter.get_trigger_config<br/>whatsappReceive -> whatsapp_message_received]
+ B --> C[event_waiter.register<br/>builds filter via build_whatsapp_filter]
+ C --> D[broadcaster.update_node_status<br/>status=waiting]
+ D --> E[await event_waiter.wait_for_event]
+ E -- CancelledError --> X[success=false<br/>error=Cancelled by user]
+ E -- exception --> Y[success=false<br/>error=str e]
+ E -- event dict --> F[Filter closure applied inside wait_for_event<br/>only matching messages resolve the future]
+ F --> OK[success=true<br/>result=event_data]
+```
+
+### Filter closure (build_whatsapp_filter)
+
+```mermaid
+flowchart LR
+ M[message dict] --> R1{messageTypeFilter<br/>== 'all' or matches?}
+ R1 -- no --> REJ[reject]
+ R1 -- yes --> R2{filter mode?}
+ R2 -- self --> S1{is_from_me AND<br/>chat_id == sender?}
+ S1 -- no --> REJ
+ R2 -- any_contact --> S2{is_group?}
+ S2 -- yes --> REJ
+ R2 -- contact --> S3{contactPhone in<br/>sender_phone?}
+ S3 -- no --> REJ
+ R2 -- group --> S4{is_group AND<br/>chat_id == group_id AND<br/>senderNumber match if set?}
+ S4 -- no --> REJ
+ R2 -- channel --> S5{chat_id ends @newsletter<br/>and matches channel_jid if set?}
+ S5 -- no --> REJ
+ R2 -- keywords --> S6{any keyword in<br/>text lower?}
+ S6 -- no --> REJ
+ R2 -- all --> OWN
+ S1 --> OWN
+ S2 --> OWN
+ S3 --> OWN
+ S4 --> OWN
+ S5 --> OWN
+ S6 --> OWN
+ OWN{ignoreOwnMessages AND<br/>is_from_me AND filter != self?}
+ OWN -- yes --> REJ
+ OWN -- no --> FWD
+ FWD{forwardedFilter check}
+ FWD -- fail --> REJ
+ FWD -- pass --> ACC[accept]
+```
+
+## Decision Logic
+
+- **Filter priority**: message_type -> sender filter -> own-message -> forwarded. Every check is a short-circuit reject.
+- **Sender phone fallback**: uses `group_info.sender_phone` for group messages, falls back to root `sender_phone`, and if both empty splits the JID at `@` to extract the phone prefix.
+- **`filter == 'self'` is special**: disables the `ignoreOwnMessages` gate (otherwise every self-message would be filtered out).
+- **Keyword match is substring**, not token match: `"hi"` matches `"this"`.
+- **Channel filter** requires `chat_id` to end exactly with `@newsletter`; if `channel_jid` is provided it must match exactly, otherwise any channel passes.
+- **Pre-check**: unlike `telegramReceive`, this trigger does not check WhatsApp pairing state before registering - it will wait forever if the Go RPC is disconnected.
+
+## Side Effects
+
+- **Database writes**: none from the handler directly (frontend may save `group_name`/`sender_name` back to node parameters via the WebSocket `save_node_parameters` handler - that is UI-driven, not part of trigger execution).
+- **Broadcasts**: `update_node_status(node_id, "waiting", {...})` once before awaiting.
+- **External calls**: none outbound. Receives events dispatched by `routers/whatsapp.py` when the Go RPC emits `event.message_received`.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none - pairing is held by the Go service.
+- **Services**: `whatsapp-rpc` (Go) for event dispatch via `event_waiter.dispatch('whatsapp_message_received', data)`.
+- **Python packages**: `asyncio`.
+- **Environment variables**: none in the handler.
+
+## Edge cases & known limits
+
+- **No pairing pre-check**: if the phone is unpaired the trigger silently waits forever until user cancel.
+- **LID-to-phone resolution is implicit**: the Go RPC already populates `sender_phone` with the resolved phone before dispatch, so the filter never needs to call back into the RPC. Missing `sender_phone` is still tolerated via the JID-prefix fallback.
+- **`filter == 'self'` semantics are narrow**: requires `is_from_me` AND `chat_id == sender` (true only for notes-to-self chats). Self-messages sent to other chats are rejected.
+- **`keywords` is trivially tokenized**: splits on `,` and `.strip().lower()` each; there is no escaping or whole-word matching.
+- **Cancellation path** returns `success=false` with `error="Cancelled by user"` - this is the documented path for the Cancel button, not a real error.
+- **Filter closure is built once at register-time**: changes to node parameters during a waiting run are not reflected; user must cancel and re-run.
+
+## Related
+
+- **Companion nodes**: [`whatsappSend`](./whatsappSend.md), [`whatsappDb`](./whatsappDb.md)
+- **Architecture docs**: `CLAUDE.md` -> "Event-Driven Trigger Node System", "WhatsApp Integration"
+- **Trigger infrastructure**: [`event_waiter.py`](../../../server/services/event_waiter.py), [`triggers.py`](../../../server/services/handlers/triggers.py)
diff --git a/docs-internal/node-logic-flows/whatsapp/whatsappSend.md b/docs-internal/node-logic-flows/whatsapp/whatsappSend.md
new file mode 100644
index 00000000..986e593a
--- /dev/null
+++ b/docs-internal/node-logic-flows/whatsapp/whatsappSend.md
@@ -0,0 +1,151 @@
+# WhatsApp Send (`whatsappSend`)
+
+| Field | Value |
+|------|-------|
+| **Category** | whatsapp / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/whatsappNodes.ts`](../../../client/src/nodeDefinitions/whatsappNodes.ts) |
+| **Backend handler** | [`server/services/handlers/whatsapp.py::handle_whatsapp_send`](../../../server/services/handlers/whatsapp.py) |
+| **Tests** | [`server/tests/nodes/test_whatsapp.py`](../../../server/tests/nodes/test_whatsapp.py) |
+| **Skill (if any)** | [`server/skills/social_agent/whatsapp-send-skill/SKILL.md`](../../../server/skills/social_agent/whatsapp-send-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `whatsappSend` |
+
+## Purpose
+
+Send WhatsApp messages of any supported type (text, image, video, audio,
+document, sticker, location, contact) to an individual phone number, a group
+JID, a newsletter channel JID, or the connected account itself ("self" - used
+for notes-to-self). All traffic is proxied through the Go `whatsapp-rpc`
+service over a persistent WebSocket RPC (not HTTP). Also works as an AI agent
+tool when wired to an agent's `input-tools` handle.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data for template substitution into `message`, `media_url`, etc. |
+
+## Parameters
+
+Key parameters (see frontend definition for the full list and `displayOptions.show` rules):
+
+| Name | Type | Default | Required | Notes |
+|------|------|---------|----------|------|
+| `recipient_type` | options | `self` | no | One of `self`, `phone`, `group`, `channel` |
+| `phone` | string | `""` | conditional | Required when `recipient_type == 'phone'` |
+| `group_id` | string | `""` | conditional | Required when `recipient_type == 'group'` |
+| `channel_jid` | string | `""` | conditional | Required when `recipient_type == 'channel'`, must end `@newsletter` |
+| `message_type` | options | `text` | yes | `text`, `image`, `video`, `audio`, `document`, `sticker`, `location`, `contact` |
+| `message` | string | `""` | conditional | Required when `message_type == 'text'` |
+| `format_markdown` | boolean | `false` | no | When true and text message, convert GFM to WhatsApp syntax via `markdown_formatter.to_whatsapp` |
+| `media_source` | options | `base64` | conditional | `base64`, `file`, or `url` for media types |
+| `media_data` | string | `""` | conditional | Base64 data when `media_source == 'base64'` |
+| `file_path` | string/object | `""` | conditional | Either a path string or upload dict `{type: 'upload', filename, mimeType}` |
+| `media_url` | string | `""` | conditional | URL when `media_source == 'url'` |
+| `mime_type` | string | `""` | no | Optional override |
+| `caption` | string | `""` | no | Caption for media messages |
+| `filename` | string | `""` | no | Filename for document messages |
+| `latitude` | number | `0` | conditional | Required for `message_type == 'location'` |
+| `longitude` | number | `0` | conditional | Required for `message_type == 'location'` |
+| `location_name` | string | `""` | no | Location name |
+| `address` | string | `""` | no | Location address |
+| `contact_name` | string | `""` | conditional | Required for `message_type == 'contact'` |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Standard envelope result |
+| `output-tool` | object | Same payload when wired into an AI agent's `input-tools` |
+
+### Output payload
+
+```ts
+{
+ status: 'sent';
+ recipient: string; // 'self' | phone | group_id | channel_jid
+ recipient_type: 'self' | 'phone' | 'group' | 'channel';
+ message_type: string;
+ timestamp: string; // ISO
+ preview?: string; // text messages (first 100 chars)
+ media_source?: string; // media types
+ caption?: string;
+ filename?: string;
+ mime_type?: string;
+ uploaded_file?: string; // when file_path is an upload dict
+ location?: { latitude, longitude, name, address };
+ contact_name?: string;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_whatsapp_send] --> B{recipient_type}
+ B -- self --> R[recipient = 'self']
+ B -- channel --> C{channel_jid set?}
+ C -- no --> Eret[success=false<br/>Channel JID required]
+ C -- yes --> C2{message_type in<br/>text/image/video/audio/document?}
+ C2 -- no --> Eret2[success=false<br/>Channels only support: ...]
+ C2 -- yes --> R
+ B -- group --> G{group_id set?}
+ G -- no --> Eret3[success=false<br/>Group ID required]
+ G -- yes --> R
+ B -- phone --> P{phone set?}
+ P -- no --> Eret4[success=false<br/>Phone number required]
+ P -- yes --> R
+ R --> T{message_type == 'text'?}
+ T -- yes --> T1{message non-empty?}
+ T1 -- no --> Eret5[success=false<br/>Message content required]
+ T1 -- yes --> T2{format_markdown?}
+ T2 -- yes --> T3[parameters.message =<br/>to_whatsapp message]
+ T2 -- no --> S
+ T3 --> S
+ T -- no --> S
+ S[await routers.whatsapp.handle_whatsapp_send params] --> S2{data.success?}
+ S2 -- no --> Eret6[success=false<br/>error from RPC]
+ S2 -- yes --> F[Build result dict with<br/>status/recipient/type-specific fields]
+ F --> OK[success=true]
+```
+
+## Decision Logic
+
+- **Validation (short-circuit)** - raised as `ValueError` and caught by the outer `try`, turned into a `success=false` envelope:
+ - `channel_jid` missing when `recipient_type == 'channel'`
+ - Channel message type not in `{text, image, video, audio, document}` - specifically blocks `sticker`, `location`, `contact` for channels
+ - `group_id` missing when `recipient_type == 'group'`
+ - `phone` missing when `recipient_type == 'phone'`
+ - Empty `message` when `message_type == 'text'`
+- **Markdown transform**: only runs when `message_type == 'text'` AND `format_markdown` truthy. Overwrites `parameters['message']` in place before RPC call.
+- **Type-specific result fields**: `match message_type` adds `preview`, `media_source`, `caption`, `filename`, `mime_type`, `uploaded_file`, `location`, or `contact_name` based on message type.
+- **File upload detection**: if `file_path` is a dict with `type == 'upload'`, the router uploads bytes and the result includes `uploaded_file` and `mime_type` from the upload dict.
+
+## Side Effects
+
+- **Database writes**: none directly from this handler. (Tracking, if any, is owned by the router.)
+- **Broadcasts**: none directly - standard node_status transitions come from `NodeExecutor`.
+- **External calls**: WebSocket RPC to the Go service. Default URL `ws://localhost:9400/ws/rpc` (overridable via `WHATSAPP_RPC_URL`). For media URLs, the router additionally downloads via `httpx`.
+- **File I/O**: none in this handler - file uploads are handled by the router.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none at the node handler level. Pairing state is owned by the Go service; the handler is credential-free.
+- **Services**: `whatsapp-rpc` (Go) on port 9400 (default). `services.markdown_formatter.to_whatsapp` when `format_markdown` is enabled.
+- **Python packages**: `asyncio`. (`httpx` is used inside the router for URL media fetches.)
+- **Environment variables**: `WHATSAPP_RPC_URL` (optional, default `ws://localhost:9400/ws/rpc`).
+
+## Edge cases & known limits
+
+- **Channel message-type allowlist is hard-coded**: `{text, image, video, audio, document}`. Any other type returns `success=false` even though the RPC might technically accept it.
+- **`format_markdown` mutates `parameters`**: the converted text overwrites the incoming `message` before the RPC call - downstream code inspecting the raw parameters post-execution will see the converted form.
+- **All exceptions funnel to `success=false`**: the outer `try/except` captures every `ValueError`, RPC exception, and generic failure, returning the stringified error as the envelope `error`. The handler never raises to the executor.
+- **`recipient = 'self'` is a sentinel string**, not a resolved phone number. The Go RPC resolves it to the connected account at send time.
+- **Caption/filename/mime_type**: only added to the result payload when truthy in `parameters`; consumers must handle their absence.
+- **Text preview is truncated** to 100 chars with `"..."` suffix when longer - this is output-only and does not change the sent message.
+
+## Related
+
+- **Skills using this as a tool**: [`whatsapp-send-skill/SKILL.md`](../../../server/skills/social_agent/whatsapp-send-skill/SKILL.md)
+- **Companion nodes**: [`whatsappDb`](./whatsappDb.md), [`whatsappReceive`](./whatsappReceive.md)
+- **Architecture docs**: [Markdown Formatter](../../../CLAUDE.md) (see "Markdown Formatter Service"), WhatsApp RPC via `routers/whatsapp.py`
diff --git a/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.md b/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.md
new file mode 100644
index 00000000..2e8de326
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/chatTrigger.md
@@ -0,0 +1,120 @@
+# Chat Trigger (`chatTrigger`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / trigger / utility |
+| **Frontend definition** | [`client/src/nodeDefinitions/utilityNodes.ts`](../../../client/src/nodeDefinitions/utilityNodes.ts) |
+| **Backend handler** | [`server/services/handlers/triggers.py::handle_trigger_node`](../../../server/services/handlers/triggers.py) (generic) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Fires when the user sends a message from the Console Panel chat tab. The
+WebSocket handler `send_chat_message` calls
+`broadcaster.send_custom_event('chat_message_received', {...})` (or the
+event-waiter dispatch path) and any `chatTrigger` node whose `sessionId`
+matches (or is `'default'`) receives the event and emits it as output. This
+is the primary way a user feeds an interactive prompt into an `aiAgent` or
+`chatAgent`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Trigger nodes have no inputs. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `sessionId` | string | `default` | no | - | Matches the `session_id` on the incoming chat event. If set to `default`, the filter accepts every event. Otherwise it only accepts events with the same `session_id`. |
+| `placeholder` | string | `Type a message...` | no | - | Frontend display only - not used by the handler. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | The chat event payload (see below). |
+
+### Output payload
+
+The exact shape depends on how the dispatcher in
+`routers/websocket.py::send_chat_message` builds the event, but the
+documented fields surfaced to downstream nodes are:
+
+```ts
+{
+ message: string;
+ timestamp: string; // ISO 8601
+ session_id: string;
+ node_id?: string; // Optional - set when the client targets a specific chatTrigger
+}
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_trigger_node] --> B[event_waiter.get_trigger_config 'chatTrigger']
+ B -- None --> Eunk[Return success=false<br/>error: Unknown trigger type]
+ B -- ok --> C[await event_waiter.register<br/>params include sessionId]
+ C --> D[build_chat_filter:<br/>if sessionId != 'default' require exact match]
+ D --> E[broadcaster.update_node_status 'waiting'<br/>event_type=chat_message_received]
+ E --> F[await event_waiter.wait_for_event waiter]
+ F -- CancelledError --> G[Return success=false<br/>error: Cancelled by user]
+ F -- Exception --> H[Return success=false<br/>error: str e]
+ F -- ok --> I[Return success envelope<br/>result = event_data]
+```
+
+## Decision Logic
+
+- **Filter** (`build_chat_filter` in `triggers.py`):
+ ```python
+ if session_id != 'default' and event_session != session_id:
+ return False
+ return True
+ ```
+ So `sessionId='default'` (the frontend default) is a wildcard - the
+ trigger fires for every chat message regardless of which session the user
+ is in.
+- **Cancellation**: yields `success=False, error="Cancelled by user"`.
+
+## Side Effects
+
+- **Database writes**: none in the trigger handler itself. (The chat message
+ is separately persisted by `send_chat_message` via `database.add_chat_message`.)
+- **Broadcasts**: `update_node_status(node_id, "waiting", {message, event_type, waiter_id}, workflow_id)`.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.event_waiter`, `services.status_broadcaster`.
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `sessionId='default'` behaves as a wildcard; setting a unique session ID
+ per trigger is the only way to scope messages to a specific node.
+- When multiple `chatTrigger` nodes exist with the same session ID, all of
+ them fire for a matching message.
+- The handler has no timeout; it waits forever until an event arrives or
+ the run is cancelled.
+- The chat message's persistence to the DB happens in the WebSocket handler
+ BEFORE the event is dispatched, so even if no `chatTrigger` is waiting
+ the message is still stored in `chat_messages`.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Sibling triggers**: [`webhookTrigger`](./webhookTrigger.md),
+ [`taskTrigger`](./taskTrigger.md).
+- **Architecture docs**: [Event Waiter System](../../event_waiter_system.md),
+ [Status Broadcaster](../../status_broadcaster.md)
diff --git a/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md b/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md
new file mode 100644
index 00000000..07fa098f
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/cronScheduler.md
@@ -0,0 +1,149 @@
+# Cron Scheduler (`cronScheduler`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / trigger / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/schedulerNodes.ts`](../../../client/src/nodeDefinitions/schedulerNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_cron_scheduler`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | [`server/skills/task_agent/cron-scheduler-skill/SKILL.md`](../../../server/skills/task_agent/cron-scheduler-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - exposed on the `tool` output handle |
+
+## Purpose
+
+Recurring time-based trigger. In **deployed** workflows the scheduling
+happens inside `DeploymentManager` using APScheduler; this handler only
+runs when the node is executed directly (manual run) or as an AI tool. In
+that mode it simply sleeps for the computed interval once, then returns
+metadata describing the schedule. It is NOT an event-waiter - it does not
+call `event_waiter.register()`.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Trigger nodes have no inputs. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `frequency` | options | `minutes` | no | - | One of `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `once`. |
+| `interval` | number | `30` | no | frequency == `seconds` | Interval in seconds. |
+| `interval_minutes` | number | `5` | no | frequency == `minutes` | Interval in minutes. |
+| `interval_hours` | number | `1` | no | frequency == `hours` | Interval in hours. |
+| `daily_time` | options | `09:00` | no | frequency == `days` | Display-only in the handler. |
+| `weekday` | options | `'1'` (Mon) | no | frequency == `weeks` | Display-only. |
+| `weekly_time` | options | `09:00` | no | frequency == `weeks` | Display-only. |
+| `month_day` | options | `'1'` | no | frequency == `months` | Display-only. |
+| `monthly_time` | options | `09:00` | no | frequency == `months` | Display-only. |
+| `timezone` | options | `UTC` | no | - | Used in the description string only. |
+
+Note: for `days` / `weeks` / `months` the handler hard-codes the wait to 24h
+/ 7d / ~30d respectively; the `daily_time` / `weekday` / `weekly_time` /
+`month_day` / `monthly_time` parameters only flow into the human-readable
+`schedule` string, not the actual wait duration.
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Schedule metadata (see below). |
+| `output-tool` | object | Same payload when invoked as an AI agent tool. |
+
+### Output payload
+
+```ts
+{
+ timestamp: string; // ISO 8601 when the trigger fired
+ iteration: 1; // Always 1 in handler mode - see limits below
+ frequency: string;
+ timezone: string;
+ schedule: string; // Human-readable, e.g. "Every 5 minutes"
+ scheduled_time: string; // ISO 8601 of the originally-planned trigger time
+ triggered_at: string; // ISO 8601 when execution actually fired
+ waited_seconds: number; // How long the handler slept
+ message: string; // Status message
+ next_run?: string; // Only when frequency != 'once'
+}
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_cron_scheduler] --> B[frequency = parameters.frequency default 'minutes']
+ B --> C[_get_schedule_description<br/>returns e.g. 'Every 5 minutes']
+ C --> D[_calculate_wait_seconds<br/>maps frequency to seconds]
+ D --> E[get_status_broadcaster.update_node_status 'waiting']
+ E --> F[await asyncio.sleep wait_seconds]
+ F -- CancelledError --> G[Return success=false<br/>error: Scheduler cancelled]
+ F -- Exception --> H[Return success=false<br/>error: str e]
+ F -- ok --> I[Build result_data: timestamp / iteration=1 / frequency / schedule / waited_seconds]
+ I --> J{frequency == 'once'?}
+ J -- yes --> K[message: 'Triggered after waiting ...']
+ J -- no --> L[Add next_run = schedule<br/>message: 'Triggered after ..., will repeat ...']
+ K --> M[Return success envelope]
+ L --> M
+```
+
+## Decision Logic
+
+- **Interval mapping** (`_calculate_wait_seconds`):
+ - `seconds` -> `interval` (default 30)
+ - `minutes` -> `interval_minutes` * 60 (default 300)
+ - `hours` -> `interval_hours` * 3600 (default 3600)
+ - `days` -> 86400 (ignores `daily_time`)
+ - `weeks` -> 604800 (ignores `weekday` / `weekly_time`)
+ - `months` -> 2592000 (~30 days, ignores `month_day` / `monthly_time`)
+ - `once` -> 0 (fire immediately)
+ - unknown -> 300 (5 minutes fallback)
+- **Once vs recurring**: determines whether `next_run` is added to the
+ payload and which `message` template is used. Both branches still return
+ `success=True`.
+- **Cancellation / exception**: both produce a failed envelope with
+ `success=False`.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: `StatusBroadcaster.update_node_status(node_id, "waiting", {message, trigger_time, wait_seconds}, workflow_id)`.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.status_broadcaster.get_status_broadcaster`.
+- **Python packages**: `asyncio`, `datetime`, `time` (stdlib).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- **Handler is not the real scheduler.** Real cron semantics
+ (exact-time-of-day, weekday selection, timezones) live in
+ `DeploymentManager` + APScheduler. The manual-run handler does not use any
+ of that - it only sleeps for a fixed interval. `daily_time`, `weekday`,
+ `weekly_time`, `month_day`, `monthly_time`, and `timezone` are
+ **display-only** in this code path.
+- `iteration` is always `1`. The handler does not loop; repeated firings
+ come from APScheduler calling the handler again each tick (deployment mode).
+- `interval`, `interval_minutes`, `interval_hours` are coerced with
+ `int(...)`; non-numeric values raise `ValueError` which is caught and
+ returned as an error envelope.
+- `weekday` is read via `parameters.get('weekday', '1')` and expected to be
+ a string digit - if a number is passed it will raise on `.isdigit()` in
+ `_get_schedule_description`, but that only affects the description string.
+- Unknown `frequency` values silently use 300s wait and produce
+ `schedule: "Unknown schedule"`.
+
+## Related
+
+- **Skills using this as a tool**: [`cron-scheduler-skill`](../../../server/skills/task_agent/cron-scheduler-skill/SKILL.md)
+- **Sibling triggers**: [`timer`](./timer.md) (one-shot delay),
+ [`start`](./start.md) (manual entry).
+- **Architecture docs**: [Execution Engine Design](../../DESIGN.md),
+ [Temporal Architecture](../../TEMPORAL_ARCHITECTURE.md)
diff --git a/docs-internal/node-logic-flows/workflow_triggers/start.md b/docs-internal/node-logic-flows/workflow_triggers/start.md
new file mode 100644
index 00000000..aa7603d6
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/start.md
@@ -0,0 +1,107 @@
+# Start (`start`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/workflowNodes.ts`](../../../client/src/nodeDefinitions/workflowNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_start`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Manual workflow entry point. Emits a user-authored JSON payload as the
+workflow's initial data. Every workflow that is not kicked off by an event
+trigger (`webhookTrigger`, `chatTrigger`, `cronScheduler`, etc.) starts from a
+`start` node. Unlike the event triggers in this category, `start` does not
+register an event waiter - it completes immediately with the parsed initial
+data.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | `start` has no inputs - it is the entry point |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `initialData` | string (JSON) | `"{}"` | no | - | JSON document surfaced as the node output. Any parse failure silently becomes `{}`. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | The parsed JSON value of `initialData` (or `{}` if invalid). |
+
+### Output payload
+
+```ts
+// Whatever the user put in initialData, parsed as JSON.
+// Invalid JSON -> {}.
+Record<string, unknown>
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, node_id, node_type: "start" }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_start] --> B[Read parameters.initialData<br/>default: '{}']
+ B --> C{json.loads?}
+ C -- ok --> D[initial_data = parsed]
+ C -- Exception --> E[initial_data = {}]
+ D --> F[Return success envelope<br/>result = initial_data]
+ E --> F
+```
+
+## Decision Logic
+
+- **Validation**: none. Empty / missing `initialData` is treated as `"{}"`.
+- **Branches**: single path; either `initialData` parses or it is silently
+ replaced with `{}`.
+- **Fallbacks**: JSON decode errors are swallowed and produce `{}`.
+- **Error paths**: the handler does not raise; it always returns a
+ `success=True` envelope. A malformed `initialData` is **not** reported as an
+ error.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none (the caller emits `executing` / `success` via
+ `StatusBroadcaster`; the handler itself is silent).
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: none.
+- **Python packages**: `json` (stdlib).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `start` always returns `success=True` regardless of `initialData` content.
+ Invalid JSON is silently coerced to `{}` - users get no warning their data
+ was dropped.
+- Although `start` is listed in `TRIGGER_REGISTRY` (as `deploy_triggered`),
+ the handler registry in `NodeExecutor._build_handler_registry()` maps
+ `start` directly to `handle_start`. The event-waiter path is only exercised
+ inside `DeploymentManager` when a workflow is deployed; ad-hoc runs go
+ through `handle_start` without waiting for any event.
+- The payload is returned as-is; no validation, schema enforcement, or nested
+ template resolution is performed by the handler.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Other nodes that consume this output**: any downstream node - typical
+ pattern is `start -> aiAgent` or `start -> httpRequest` in a hand-run
+ workflow.
+- **Architecture docs**: [Workflow Schema](../../workflow-schema.md), [Execution Engine Design](../../DESIGN.md)
+- **Sibling triggers**: [`cronScheduler`](./cronScheduler.md), [`timer`](./timer.md), [`webhookTrigger`](./webhookTrigger.md), [`chatTrigger`](./chatTrigger.md), [`taskTrigger`](./taskTrigger.md), [`webhookResponse`](./webhookResponse.md)
diff --git a/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md b/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md
new file mode 100644
index 00000000..f9c74b2c
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/taskTrigger.md
@@ -0,0 +1,125 @@
+# Task Trigger (`taskTrigger`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/workflowNodes.ts`](../../../client/src/nodeDefinitions/workflowNodes.ts) |
+| **Backend handler** | [`server/services/handlers/triggers.py::handle_trigger_node`](../../../server/services/handlers/triggers.py) (generic) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Fires when a child agent delegated via `delegate_to_*` tools completes or
+errors. The delegation code path in
+`server/services/handlers/tools.py::_execute_delegated_agent` calls
+`broadcaster.send_custom_event('task_completed', {...})`, which is
+dispatched to this trigger via `event_waiter`. Used to let a parent
+workflow react to child completion without blocking the parent on the
+child's result (fire-and-forget delegation).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Trigger nodes have no inputs. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `task_id` | string | `""` | no | - | If set, only match events with this exact `task_id`. |
+| `agent_name` | string | `""` | no | - | Case-insensitive substring match against `event.agent_name`. |
+| `status_filter` | options | `all` | no | - | `all` / `completed` / `error`. |
+| `parent_node_id` | string | `""` | no | - | If set, only match events with this exact `parent_node_id`. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | The `task_completed` event payload. |
+
+### Output payload
+
+```ts
+{
+ task_id: string;
+ status: 'completed' | 'error';
+ agent_name: string;
+ agent_node_id: string;
+ parent_node_id: string;
+ result?: string; // Present when status='completed'
+ error?: string; // Present when status='error'
+ workflow_id: string;
+}
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_trigger_node] --> B[event_waiter.get_trigger_config 'taskTrigger']
+ B -- None --> Eunk[Return success=false<br/>error: Unknown trigger type]
+ B -- ok --> C[await event_waiter.register]
+ C --> D[build_task_completed_filter]
+ D --> E[broadcaster.update_node_status 'waiting'<br/>event_type=task_completed]
+ E --> F[await event_waiter.wait_for_event waiter]
+ F -- CancelledError --> G[Return success=false<br/>error: Cancelled by user]
+ F -- Exception --> H[Return success=false<br/>error: str e]
+ F -- ok --> I[Return success envelope<br/>result = event_data]
+```
+
+## Decision Logic
+
+`build_task_completed_filter` applies all configured filters as AND:
+
+- **task_id**: exact match if non-empty.
+- **agent_name**: `agent_name_filter.lower() in event_agent.lower()` -
+ substring match, case-insensitive.
+- **status_filter**:
+ - `completed` -> requires `event.status == 'completed'`
+ - `error` -> requires `event.status == 'error'`
+ - `all` (or anything else) -> no status restriction
+- **parent_node_id**: exact match if non-empty.
+
+If any filter rejects, the event is skipped and the waiter stays blocked.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: `update_node_status(node_id, "waiting", {message, event_type, waiter_id}, workflow_id)`.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.event_waiter`, `services.status_broadcaster`.
+- **Upstream dispatcher**: `services.handlers.tools._execute_delegated_agent`
+ fires `task_completed` events for both success and error paths.
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `agent_name` is a case-insensitive **substring** match, not an exact
+ match. Two agents named `"TwitterAgent"` and `"TwitterAgentV2"` are both
+ matched by `agent_name="Twitter"`.
+- `status_filter` values other than `completed` / `error` are treated as
+ `all`. There is no validation of unknown values.
+- Waiter has no timeout; if the child agent never dispatches a
+ `task_completed` event (e.g. it is still running or died silently) the
+ trigger blocks until cancelled.
+- Fire-and-forget delegation means the parent workflow does not know the
+ child failed unless this trigger is present and matches.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Architecture docs**: [Event Waiter System](../../event_waiter_system.md),
+ [Agent Delegation](../../agent_delegation.md)
+- **Sibling triggers**: [`chatTrigger`](./chatTrigger.md), [`webhookTrigger`](./webhookTrigger.md)
diff --git a/docs-internal/node-logic-flows/workflow_triggers/timer.md b/docs-internal/node-logic-flows/workflow_triggers/timer.md
new file mode 100644
index 00000000..19795941
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/timer.md
@@ -0,0 +1,119 @@
+# Timer (`timer`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / utility / tool (dual-purpose) |
+| **Frontend definition** | [`client/src/nodeDefinitions/schedulerNodes.ts`](../../../client/src/nodeDefinitions/schedulerNodes.ts) |
+| **Backend handler** | [`server/services/handlers/utility.py::handle_timer`](../../../server/services/handlers/utility.py) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | yes - exposed on the `tool` output handle so AI agents can invoke it |
+
+## Purpose
+
+One-shot delay node. When executed, it broadcasts a `waiting` status to the
+frontend, sleeps for the requested duration via `asyncio.sleep`, then returns
+timing metadata. Unlike `cronScheduler`, it does not loop and has no concept
+of next-run; it simply pauses the branch of the workflow it is on for
+`duration` units.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Trigger to start the timer. Upstream data is not consumed by the handler. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `duration` | number | `5` | yes | - | How long to wait. Frontend clamps 1..3600. |
+| `unit` | options | `seconds` | no | - | One of `seconds` / `minutes` / `hours`. Unknown values are treated as `seconds`. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | Timing metadata (see below). |
+| `output-tool` | object | Same payload when used as an AI agent tool. |
+
+### Output payload
+
+```ts
+{
+ timestamp: string; // ISO 8601 - when the timer finished
+ elapsed_ms: number; // Wall-clock elapsed milliseconds
+ duration: number; // Input duration (echoed)
+ unit: string; // Input unit (echoed)
+ message: string; // "Timer completed after <duration> <unit>"
+}
+```
+
+Wrapped in the standard envelope: `{ success: true, result: <payload>, execution_time, timestamp, node_id, node_type: "timer" }`.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_timer] --> B[duration = int parameters.duration default 5]
+ B --> C{unit?}
+ C -- seconds --> S1[wait_seconds = duration]
+ C -- minutes --> S2[wait_seconds = duration * 60]
+ C -- hours --> S3[wait_seconds = duration * 3600]
+ C -- other --> S4[wait_seconds = duration]
+ S1 --> D[get_status_broadcaster.update_node_status 'waiting'<br/>with complete_time + wait_seconds]
+ S2 --> D
+ S3 --> D
+ S4 --> D
+ D --> E[await asyncio.sleep wait_seconds]
+ E -- CancelledError --> F[Return success=false<br/>error: Timer cancelled]
+ E -- Exception --> G[Return success=false<br/>error: str e]
+ E -- ok --> H[elapsed_ms = now - start]
+ H --> I[Return success envelope<br/>with timestamp / elapsed_ms / duration / unit / message]
+```
+
+## Decision Logic
+
+- **Unit mapping**: `seconds` / `minutes` / `hours` multiply duration by
+ 1 / 60 / 3600. Any other value falls through to the `_` match case and is
+ treated as raw seconds.
+- **Cancellation**: `asyncio.CancelledError` is caught and returns
+ `success=False` with `error="Timer cancelled"` rather than propagating.
+- **Generic errors**: any other `Exception` is stringified into the error
+ envelope.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: `StatusBroadcaster.update_node_status(node_id, "waiting", {message, complete_time, wait_seconds}, workflow_id)`
+ fires exactly once before the sleep.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.status_broadcaster.get_status_broadcaster`.
+- **Python packages**: `asyncio`, `time`, `datetime` (stdlib).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- Only three unit strings are supported - anything else is silently treated
+ as raw seconds. There is no surfaced validation error.
+- The handler has no timeout ceiling of its own; the frontend clamps at
+ 3600 (1h) for `seconds`, but if a workflow injects a larger value via the
+ backend it will actually wait that long.
+- Cancellation returns a failed envelope (`success=false`). Downstream nodes
+ that key off `success` will not execute when the timer is cancelled.
+- Duration is coerced with `int(...)`; a non-numeric string raises `ValueError`
+ which is caught by the generic handler and turned into an error envelope.
+
+## Related
+
+- **Skills using this as a tool**: `timer` is exposed on the `tool` handle
+ but there is no dedicated SKILL.md file.
+- **Sibling triggers**: [`cronScheduler`](./cronScheduler.md) for recurring
+ schedules; [`start`](./start.md) for manual entry.
+- **Architecture docs**: [Execution Engine Design](../../DESIGN.md)
diff --git a/docs-internal/node-logic-flows/workflow_triggers/webhookResponse.md b/docs-internal/node-logic-flows/workflow_triggers/webhookResponse.md
new file mode 100644
index 00000000..6e1149a9
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/webhookResponse.md
@@ -0,0 +1,132 @@
+# Webhook Response (`webhookResponse`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / utility |
+| **Frontend definition** | [`client/src/nodeDefinitions/utilityNodes.ts`](../../../client/src/nodeDefinitions/utilityNodes.ts) |
+| **Backend handler** | [`server/services/handlers/http.py::handle_webhook_response`](../../../server/services/handlers/http.py) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Sends a custom HTTP response back to the caller of a companion
+[`webhookTrigger`](./webhookTrigger.md) whose `responseMode` is set to
+`responseNode`. The trigger parks the incoming request on a future inside
+`routers/webhook.py`; this node resolves that future with the configured
+status code, body, and content type. Without a `webhookResponse` node in
+the workflow, a `responseNode`-mode trigger hangs until the request times
+out.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | yes (semantically) | Upstream node outputs are collected via `_get_connected_outputs_with_info` and made available for template substitution / default body. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `statusCode` | number | `200` | no | - | HTTP status code. Coerced via `int(...)`. |
+| `responseBody` | string | `""` | no | - | Response body. Supports `{{input.<field>}}` and `{{<nodeType>.<field>}}` template substitutions using connected upstream outputs. |
+| `contentType` | options | `application/json` | no | - | One of `application/json` / `text/plain` / `text/html`. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| (none) | - | `webhookResponse` has no output handle - it terminates a response branch. The handler still returns a standard envelope (used by the executor for status tracking). |
+
+### Handler return payload
+
+```ts
+{
+ sent: true;
+ statusCode: number;
+ contentType: string;
+ bodyLength: number;
+}
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[NodeExecutor._dispatch] --> B[_get_connected_outputs_with_info<br/>returns connected_outputs + source_nodes]
+ B --> C[handle_webhook_response<br/>node_id / params / context / connected_outputs]
+ C --> D[status_code = int params.statusCode default 200]
+ D --> E[response_body = params.responseBody]
+ E --> F{response_body non-empty AND connected_outputs?}
+ F -- yes --> G[For each node_type, output in connected_outputs:<br/>replace '{{input.key}}' and '{{node_type.key}}' with str value]
+ F -- no --> H
+ G --> H{response_body still empty?}
+ H -- yes AND connected_outputs present --> I[response_body = json.dumps first output]
+ H -- no --> J
+ I --> J[resolve_webhook_response node_id, statusCode, body, contentType]
+ J --> K[Return success envelope]
+ J -- Exception --> L[Return success=false<br/>error: str e]
+```
+
+## Decision Logic
+
+- **Template resolution**: only applied when `response_body` is non-empty.
+ Two template formats are supported:
+ - `{{input.<key>}}` - pulls from any connected node's output dict
+ - `{{<nodeType>.<key>}}` - pulls from a specific connected node type
+- **Empty body fallback**: if `response_body` is empty AND at least one
+ upstream node has output, the handler JSON-serialises the FIRST output
+ (iteration order of a Python dict keyed by node type) and uses that as
+ the body. If there are no upstream outputs the body stays empty.
+- **resolve_webhook_response**: imported lazily from `routers.webhook`;
+ writes the response dict into the pending-future map so the originating
+ request can return.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: none directly from the handler.
+- **External API calls**: none. Instead, the handler resolves an
+ in-process `asyncio.Future` owned by `routers.webhook` which in turn
+ completes the pending HTTP response.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `routers.webhook.resolve_webhook_response`.
+- **Python packages**: `json` (stdlib).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- `resolve_webhook_response` is looked up by `node_id`. If no matching
+ webhookTrigger is pending (e.g. this node runs in a workflow without an
+ upstream `webhookTrigger`, or the trigger uses `responseMode=immediate`),
+ `resolve_webhook_response` simply no-ops - the handler still returns
+ `success=True`. There is no warning that the response was dropped.
+- Template substitution uses plain `str.replace`; there is no escaping.
+ Binary / non-stringifiable values will render as their Python `repr`.
+- The "first connected output" fallback depends on dict iteration order
+ (insertion order in CPython 3.7+) - which in turn depends on edge order.
+ If multiple upstream nodes are connected, the output picked is not
+ explicitly controlled by the user.
+- `statusCode` coercion via `int(...)` will raise on non-numeric strings,
+ which is then caught and returned as a failed envelope.
+- Unlike other handlers in the registry, `webhookResponse` is dispatched
+ in `NodeExecutor._dispatch` (not the handler registry) because it needs
+ the `connected_outputs` list - see
+ [`node_executor.py:367-381`](../../../server/services/node_executor.py).
+
+## Related
+
+- **Companion node**: [`webhookTrigger`](./webhookTrigger.md) -
+ `webhookResponse` is only useful when the trigger's `responseMode` is
+ `responseNode`.
+- **Sibling triggers**: [`webhookTrigger`](./webhookTrigger.md),
+ [`chatTrigger`](./chatTrigger.md).
+- **Architecture docs**: [Event Waiter System](../../event_waiter_system.md)
diff --git a/docs-internal/node-logic-flows/workflow_triggers/webhookTrigger.md b/docs-internal/node-logic-flows/workflow_triggers/webhookTrigger.md
new file mode 100644
index 00000000..4c7a804b
--- /dev/null
+++ b/docs-internal/node-logic-flows/workflow_triggers/webhookTrigger.md
@@ -0,0 +1,126 @@
+# Webhook Trigger (`webhookTrigger`)
+
+| Field | Value |
+|------|-------|
+| **Category** | workflow / trigger |
+| **Frontend definition** | [`client/src/nodeDefinitions/utilityNodes.ts`](../../../client/src/nodeDefinitions/utilityNodes.ts) |
+| **Backend handler** | [`server/services/handlers/triggers.py::handle_trigger_node`](../../../server/services/handlers/triggers.py) (generic) |
+| **Tests** | [`server/tests/nodes/test_workflow_triggers.py`](../../../server/tests/nodes/test_workflow_triggers.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | no |
+
+## Purpose
+
+Start a workflow when an HTTP request hits `/webhook/{path}`. The
+`webhook` router in `server/routers/webhook.py` receives the request and
+dispatches a `webhook_received` event via
+`event_waiter.dispatch()`. This node registers an asyncio.Future waiter
+(memory mode) or a Redis-Streams consumer group (Redis mode) via the shared
+`event_waiter` module and blocks until a matching event is delivered.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| (none) | - | - | Trigger nodes have no inputs. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `path` | string | `""` | yes | - | URL path segment - full URL is `http://host:3010/webhook/{path}`. Must match the incoming request's `path` for the filter to accept it. |
+| `method` | options | `POST` | no | - | Filter for HTTP method at the router layer (not the handler's filter). Values: `GET` / `POST` / `PUT` / `DELETE` / `ALL`. |
+| `responseMode` | options | `immediate` | no | - | `immediate` returns 200 OK right away; `responseNode` waits for a downstream `webhookResponse` node (see [`webhookResponse`](./webhookResponse.md)). |
+| `authentication` | options | `none` | no | - | `none` or `header`. |
+| `headerName` | string | `X-API-Key` | no | authentication == `header` | Expected header name. |
+| `headerValue` | string | `""` | no | authentication == `header` | Expected header value. |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | The webhook event dict built by the router - see below. |
+
+### Output payload
+
+Exact fields depend on the dispatch site in `routers/webhook.py`, typically:
+
+```ts
+{
+ method: string;
+ path: string;
+ headers: Record<string, string>;
+ query: Record<string, string>;
+ body: string;
+ json?: unknown;
+}
+```
+
+Wrapped in the standard envelope.
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[handle_trigger_node] --> B[event_waiter.get_trigger_config 'webhookTrigger']
+ B -- None --> Eunk[Return success=false<br/>error: Unknown trigger type]
+ B -- ok --> C[await event_waiter.register<br/>node_type, node_id, params]
+ C --> D[build_webhook_filter: checks path equality]
+ D --> E[StatusBroadcaster.update_node_status 'waiting'<br/>with event_type=webhook_received, waiter_id]
+ E --> F[await event_waiter.wait_for_event waiter]
+ F -- CancelledError --> G[Return success=false<br/>error: Cancelled by user]
+ F -- Exception --> H[Return success=false<br/>error: str e]
+ F -- ok --> I[Return success envelope<br/>result = event_data]
+```
+
+## Decision Logic
+
+- **Filter match** (`build_webhook_filter` in `triggers.py`): accepts any
+ event whose `data.path` equals `params.path`. If `path` is empty the
+ filter accepts anything.
+- **Method / authentication** are NOT enforced inside the filter - they are
+ supposed to be enforced at the router layer when the HTTP request lands.
+ The handler/filter only looks at `path`.
+- **Cancellation**: user-initiated cancel via `cancel_event_wait` produces
+ `success=False, error="Cancelled by user"`.
+
+## Side Effects
+
+- **Database writes**: none inside the handler. (Redis mode writes waiter
+ metadata to a Redis key `waiters:<uuid>` with a 24h TTL via `CacheService`.)
+- **Broadcasts**: `update_node_status(node_id, "waiting", {message, event_type, waiter_id}, workflow_id)`
+ exactly once when the waiter is registered.
+- **External API calls**: none.
+- **File I/O**: none.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.event_waiter`, `services.status_broadcaster`,
+ `routers.webhook` (dispatches events via `broadcaster.send_custom_event` /
+ `event_waiter.dispatch`).
+- **Python packages**: stdlib only.
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- The handler registers a waiter with `timeout=None`, so it waits forever
+ until either an event arrives or the run is cancelled. There is no
+ handler-side timeout.
+- When multiple `webhookTrigger` nodes share the same `path` (different
+ workflows), they all receive the event. There is no deduplication in the
+ filter.
+- `method` and `authentication` parameters are not re-checked inside the
+ filter; if the HTTP router's enforcement is bypassed (direct dispatch for
+ testing) the trigger will fire regardless.
+- Any unexpected exception inside `wait_for_event` is caught and converted
+ into a `success=False` envelope - no stack trace leaks to the caller.
+
+## Related
+
+- **Skills using this as a tool**: none.
+- **Companion node**: [`webhookResponse`](./webhookResponse.md) for
+ `responseMode=responseNode`.
+- **Sibling triggers**: [`chatTrigger`](./chatTrigger.md), [`taskTrigger`](./taskTrigger.md).
+- **Architecture docs**: [Event Waiter System](../../event_waiter_system.md)
diff --git a/docs-internal/node_panels.md b/docs-internal/node_panels.md
new file mode 100644
index 00000000..d5f31127
--- /dev/null
+++ b/docs-internal/node_panels.md
@@ -0,0 +1,177 @@
+# Node Parameter Panel — Logic Flow Documentation
+
+> Reference for the three-section node configuration UI (Input / Parameters / Output).
+> Companion test suite in [client/src/hooks/__tests__/](../client/src/hooks/__tests__) and
+> [client/src/components/parameterPanel/__tests__/](../client/src/components/parameterPanel/__tests__).
+
+The Parameter Panel is the modal that opens when a node is selected on the canvas. It has three
+columns that can be hidden independently depending on the node type:
+
+```
++---------------------------------------------------------------+
+| header: icon + name + Run / Save / Cancel |
++----------------+--------------------------+-------------------+
+| Input section | Middle section | Output section |
+| (left) | (parameters / config) | (right) |
+| flex 0.7 | flex 1.6 | flex 0.7 |
++----------------+--------------------------+-------------------+
+```
+
+Files:
+- [client/src/ParameterPanel.tsx](../client/src/ParameterPanel.tsx) — modal shell
+- [client/src/components/parameterPanel/ParameterPanelLayout.tsx](../client/src/components/parameterPanel/ParameterPanelLayout.tsx) — flex layout
+- [client/src/components/parameterPanel/InputSection.tsx](../client/src/components/parameterPanel/InputSection.tsx)
+- [client/src/components/parameterPanel/MiddleSection.tsx](../client/src/components/parameterPanel/MiddleSection.tsx)
+- [client/src/components/parameterPanel/OutputSection.tsx](../client/src/components/parameterPanel/OutputSection.tsx)
+- [client/src/components/OutputPanel.tsx](../client/src/components/OutputPanel.tsx) — drag source for connected outputs
+- [client/src/components/ParameterRenderer.tsx](../client/src/components/ParameterRenderer.tsx) — universal widget
+- [client/src/hooks/useParameterPanel.ts](../client/src/hooks/useParameterPanel.ts)
+- [client/src/hooks/useDragVariable.ts](../client/src/hooks/useDragVariable.ts)
+
+## 1. Lifecycle
+
+1. User clicks a node on the canvas → `selectedNode` set in Zustand store.
+2. `ParameterPanel` mounts → `useParameterPanel()` fires.
+3. Hook reads defaults from `nodeDefinition.properties[].default`, then asks backend for any saved
+ parameters via WebSocket `get_node_parameters`. Saved values overlay defaults.
+4. Modal renders three sections; `MiddleSection` filters parameters via `displayOptions.show`
+ (see §4 invariants), then renders each visible parameter through `ParameterRenderer`.
+5. User edits → `handleParameterChange(name, value)` updates local state. `hasUnsavedChanges`
+ flips true (computed via `JSON.stringify` equality with original).
+6. Save → WebSocket `save_node_parameters` → DB; on success `originalParameters` updated.
+7. Run → if `hasUnsavedChanges` save first, then `executeNodeViaWebSocket`.
+8. Cancel → revert pending edits, clear selection, close modal.
+
+## 2. Section Visibility Rules
+
+| Node type bucket | Input | Middle | Output |
+|---|---|---|---|
+| Start | hidden | shown | hidden |
+| Skill (e.g. masterSkill, single skill nodes) | hidden | shown | hidden |
+| Monitor (`teamMonitor`) | hidden | shown | hidden |
+| Everything else | shown | shown | shown |
+
+`ParameterPanel.tsx` lines 119–122 compute `showInputSection` / `showOutputSection` and pass them
+to `ParameterPanelLayout`.
+
+## 3. Template Variable Naming (drag-and-drop contract)
+
+When the user drags a value from `OutputPanel` into a parameter input, the dragged payload is a
+template string `{{name.path}}` plus a JSON sidecar with metadata.
+
+`name` is resolved by `useDragVariable.getTemplateVariableName(sourceNodeId)` with this strict
+priority:
+
+1. `node.data.label` — user-renamed label
+2. `nodeDefinition.displayName` — built-in display name
+3. `nodeType` — registered type name
+4. `nodeId` — final fallback
+
+In every case the result is **lowercased and whitespace-stripped** (`'My Cron Scheduler'` →
+`'mycronscheduler'`).
+
+The drag payload is set on both MIME types:
+- `text/plain` → the template string `{{name.path}}` (used by simple text inputs)
+- `application/json` → `{type: 'nodeVariable', nodeId, nodeName, key, variableTemplate, dataType}`
+
+`effectAllowed` is `'copy'`.
+
+## 4. Parameter Visibility (`displayOptions.show`)
+
+Each `INodeProperties` entry can include a `displayOptions.show` map. Values can be arrays
+(allowed-values list) or scalars (single allowed value). All conditions must hold:
+
+```ts
+displayOptions: {
+ show: {
+ operation: ['create', 'update'], // operation must be one of these
+ useProxy: [true], // AND useProxy must be true
+ }
+}
+```
+
+When ALL conditions match the parameter renders; otherwise it's hidden.
+
+A parameter without `displayOptions.show` always renders.
+
+`MiddleSection.shouldShowParameter` (lines 59–81) implements this. The function is internal so
+tests assert it indirectly via component rendering — see
+[client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx](../client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx).
+
+## 5. Connection Discovery (Input + Output)
+
+Both `InputSection` and `OutputPanel` walk the workflow's edges to figure out which other nodes
+are linked to the current one. They classify handles into two buckets:
+
+| Handle bucket | Examples | Effect |
+|---|---|---|
+| Data flow | `input-main`, `input-chat`, `input-task`, `input-teammates` | shown as connected nodes |
+| Config / auxiliary | `input-memory`, `input-tools`, `input-skill`, `input-model` | hidden — they belong to the dedicated UI in `MiddleSection` |
+
+Plus a special case for **config nodes themselves** (e.g. `simpleMemory`, any node whose group
+includes `'memory'` or `'tool'`): when the user is viewing a config node, the panel inherits the
+parent agent's main inputs and labels them `(via Agent Name)` so the user can still drag those
+upstream variables into the config node's parameters.
+
+## 6. Output Display (`OutputSection`)
+
+`OutputSection` combines two sources of execution data:
+
+1. `executionResults` — local results from in-modal Run button.
+2. `nodeStatuses[selectedNode.id]` — push updates from workflow runs via WebSocket.
+
+The WebSocket result is folded in at the front (newest-first) **only when** its `outputs` field
+isn't already present in `executionResults` (deduplicated via `JSON.stringify`). Statuses other
+than `success`/`error` (e.g. `running`) are ignored.
+
+## 7. Refactor Invariants
+
+Locked in by the test suite at:
+- [client/src/hooks/__tests__/useDragVariable.test.ts](../client/src/hooks/__tests__/useDragVariable.test.ts)
+- [client/src/hooks/__tests__/useParameterPanel.test.ts](../client/src/hooks/__tests__/useParameterPanel.test.ts)
+- [client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx](../client/src/components/parameterPanel/__tests__/MiddleSection.test.tsx)
+- [client/src/components/parameterPanel/__tests__/InputSection.test.tsx](../client/src/components/parameterPanel/__tests__/InputSection.test.tsx)
+- [client/src/components/parameterPanel/__tests__/OutputSection.test.tsx](../client/src/components/parameterPanel/__tests__/OutputSection.test.tsx)
+- [client/src/components/__tests__/OutputPanel.test.tsx](../client/src/components/__tests__/OutputPanel.test.tsx)
+
+1. **Defaults loaded** from `nodeDefinition.properties[].default`; missing default ⇒ `null`.
+2. **Saved params win** over defaults when merged (DB is source of truth).
+3. **`hasUnsavedChanges`** is a deep-equal check against the original snapshot loaded from DB.
+4. **Save** routes to `save_node_parameters` and updates the original snapshot on success.
+5. **Cancel** restores the pending edits and clears `selectedNode`.
+6. **Drag template variable** uses the priority `label > displayName > nodeType > nodeId`,
+ normalised to lowercase + no whitespace.
+7. **Drag payload** sets both `text/plain` and `application/json`; `effectAllowed = 'copy'`.
+8. **`displayOptions.show`** hides a parameter unless ALL keyed conditions match. Array values
+ are membership checks; scalar values are equality checks.
+9. **Config handles** (`input-memory|tools|skill|model`) are SKIPPED by both `InputSection` and
+ `OutputPanel` for agent nodes — those dependencies surface in MiddleSection.
+10. **`input-main|chat|task|teammates`** are NEVER skipped — they are data flow.
+11. **Memory / tool config nodes** inherit their parent agent's main inputs and label them
+ `via <Agent Name>` so upstream variables remain draggable.
+12. **OutputSection deduplication** compares result `outputs` via `JSON.stringify` before folding
+ in WebSocket status into local results. Only `success` / `error` statuses fold in.
+
+## 8. Run / Save / Cancel Buttons
+
+- **Run** disabled while `isExecuting`. Prefixed by an autosave when `hasUnsavedChanges`.
+- **Save** disabled when `!hasUnsavedChanges`.
+- **Cancel/Stop** acts as Stop (cancels event-wait via WebSocket) when the node is in `waiting`
+ state; otherwise plain Cancel that reverts edits and closes the modal.
+
+## 9. Test Run
+
+```bash
+cd client
+npm install
+npm run test:run -- src/hooks/__tests__/useDragVariable.test.ts \
+ src/hooks/__tests__/useParameterPanel.test.ts \
+ src/components/parameterPanel/__tests__ \
+ src/components/__tests__/OutputPanel.test.tsx
+```
+
+Or use the dedicated script (added in `client/package.json`):
+
+```bash
+npm run test:nodepanels
+```
diff --git a/package.json b/package.json
index e9261e86..9791e323 100644
--- a/package.json
+++ b/package.json
@@ -78,6 +78,12 @@
"build": "node scripts/build.js",
"clean": "node scripts/clean.js",
"stop": "node scripts/stop.js",
+ "test": "npm run test:backend && npm run test:frontend",
+ "test:backend": "cd server && uv run pytest tests/ -v",
+ "test:frontend": "cd client && npm run test",
+ "test:nodes": "cd server && uv run pytest tests/nodes/ -v --cov=services.handlers --cov-report=term-missing",
+ "docs:nodes": "node scripts/build-node-docs-index.js",
+ "docs:nodes:check": "node scripts/build-node-docs-index.js --check",
"deploy": "bash deploy.sh",
"deploy:gcp": "bash deploy.sh",
"daemon:install": "node scripts/daemon.js install",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1738e117..3ccc3f10 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -186,18 +186,36 @@ importers:
'@tailwindcss/vite':
specifier: ^4.2.2
+ '@testing-library/jest-dom':
+ specifier: ^6.9.1
+ version: 6.9.1
+ '@testing-library/react':
+ specifier: ^16.3.2
+ '@testing-library/user-event':
+ specifier: ^14.5.2
+ version: 14.6.1(@testing-library/[email protected])
'@typescript-eslint/parser':
specifier: ^8.54.0
+ '@vitest/coverage-v8':
+ specifier: ^2.1.9
babel-plugin-react-compiler:
specifier: 19.1.0-rc.3
version: 19.1.0-rc.3
+ jsdom:
+ specifier: ^25.0.1
+ version: 25.0.1
rollup-plugin-visualizer:
specifier: ^7.0.1
version: 7.0.1([email protected])
typescript-eslint:
specifier: ^8.54.0
+ vitest:
+ specifier: ^2.1.9
server/nodejs:
dependencies:
@@ -220,6 +238,13 @@ importers:
packages:
+ '@adobe/[email protected]':
+ resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
+
+ '@ampproject/[email protected]':
+ resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
+ engines: {node: '>=6.0.0'}
+
'@ant-design/[email protected]':
resolution: {integrity: sha512-lCHDcEzieu4GA3n8ELeZ5VQ8pKQAWcGGLRTQ50aQM2iqPpq2evTxER84jfdPvsPAtEcZ7m44NI45edFMo8oOYQ==}
@@ -257,6 +282,9 @@ packages:
resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}
+ '@asamuzakjp/[email protected]':
+ resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
+
resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==}
engines: {node: '>=6.9.0'}
@@ -452,6 +480,9 @@ packages:
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
engines: {node: '>=6.9.0'}
+ resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==}
+
'@braintree/[email protected]':
resolution: {integrity: sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw==}
@@ -470,6 +501,34 @@ packages:
'@chevrotain/[email protected]':
resolution: {integrity: sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==}
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==}
+ engines: {node: '>=18'}
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^3.0.5
+ '@csstools/css-tokenizer': ^3.0.4
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@csstools/css-parser-algorithms': ^3.0.5
+ '@csstools/css-tokenizer': ^3.0.4
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@csstools/css-tokenizer': ^3.0.4
+
+ '@csstools/[email protected]':
+ resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==}
+ engines: {node: '>=18'}
+
'@dnd-kit/[email protected]':
resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
peerDependencies:
@@ -573,6 +632,12 @@ packages:
'@emotion/[email protected]':
resolution: {integrity: sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}
+ engines: {node: '>=12'}
+ cpu: [ppc64]
+ os: [aix]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
engines: {node: '>=18'}
@@ -585,6 +650,12 @@ packages:
cpu: [ppc64]
os: [aix]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==}
engines: {node: '>=18'}
@@ -597,6 +668,12 @@ packages:
cpu: [arm64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}
+ engines: {node: '>=12'}
+ cpu: [arm]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==}
engines: {node: '>=18'}
@@ -609,6 +686,12 @@ packages:
cpu: [arm]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==}
engines: {node: '>=18'}
@@ -621,6 +704,12 @@ packages:
cpu: [x64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==}
engines: {node: '>=18'}
@@ -633,6 +722,12 @@ packages:
cpu: [arm64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==}
engines: {node: '>=18'}
@@ -645,6 +740,12 @@ packages:
cpu: [x64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==}
engines: {node: '>=18'}
@@ -657,6 +758,12 @@ packages:
cpu: [arm64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==}
engines: {node: '>=18'}
@@ -669,6 +776,12 @@ packages:
cpu: [x64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==}
engines: {node: '>=18'}
@@ -681,6 +794,12 @@ packages:
cpu: [arm64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}
+ engines: {node: '>=12'}
+ cpu: [arm]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==}
engines: {node: '>=18'}
@@ -693,6 +812,12 @@ packages:
cpu: [arm]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}
+ engines: {node: '>=12'}
+ cpu: [ia32]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==}
engines: {node: '>=18'}
@@ -705,6 +830,12 @@ packages:
cpu: [ia32]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}
+ engines: {node: '>=12'}
+ cpu: [loong64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==}
engines: {node: '>=18'}
@@ -717,6 +848,12 @@ packages:
cpu: [loong64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}
+ engines: {node: '>=12'}
+ cpu: [mips64el]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==}
engines: {node: '>=18'}
@@ -729,6 +866,12 @@ packages:
cpu: [mips64el]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}
+ engines: {node: '>=12'}
+ cpu: [ppc64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==}
engines: {node: '>=18'}
@@ -741,6 +884,12 @@ packages:
cpu: [ppc64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}
+ engines: {node: '>=12'}
+ cpu: [riscv64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==}
engines: {node: '>=18'}
@@ -753,6 +902,12 @@ packages:
cpu: [riscv64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}
+ engines: {node: '>=12'}
+ cpu: [s390x]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==}
engines: {node: '>=18'}
@@ -765,6 +920,12 @@ packages:
cpu: [s390x]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==}
engines: {node: '>=18'}
@@ -789,6 +950,12 @@ packages:
cpu: [arm64]
os: [netbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [netbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==}
engines: {node: '>=18'}
@@ -813,6 +980,12 @@ packages:
cpu: [arm64]
os: [openbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [openbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==}
engines: {node: '>=18'}
@@ -837,6 +1010,12 @@ packages:
cpu: [arm64]
os: [openharmony]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [sunos]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==}
engines: {node: '>=18'}
@@ -849,6 +1028,12 @@ packages:
cpu: [x64]
os: [sunos]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==}
engines: {node: '>=18'}
@@ -861,6 +1046,12 @@ packages:
cpu: [arm64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}
+ engines: {node: '>=12'}
+ cpu: [ia32]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==}
engines: {node: '>=18'}
@@ -873,6 +1064,12 @@ packages:
cpu: [ia32]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==}
engines: {node: '>=18'}
@@ -1029,6 +1226,14 @@ packages:
resolution: {integrity: sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==}
engines: {node: 20 || >=22}
+ '@isaacs/[email protected]':
+ resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
+ engines: {node: '>=12'}
+
+ '@istanbuljs/[email protected]':
+ resolution: {integrity: sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==}
+ engines: {node: '>=8'}
+
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -1135,6 +1340,10 @@ packages:
'@open-draft/[email protected]':
resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
+ '@pkgjs/[email protected]':
+ resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
+ engines: {node: '>=14'}
+
'@primer/[email protected]':
resolution: {integrity: sha512-7tgtBkCNcg75YJnckinzvES+uxysYQCe+CHSEnzr3VYgxttzKRvfmrnVogl3aEuHCQP4xhiE9k2lFDhYwGtTzQ==}
@@ -2186,9 +2395,41 @@ packages:
peerDependencies:
react: ^18 || ^19
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
+ engines: {node: '>=18'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==}
+ engines: {node: '>=14', npm: '>=6', yarn: '>=1'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@testing-library/dom': ^10.0.0
+ '@types/react': ^18.0.0 || ^19.0.0
+ '@types/react-dom': ^18.0.0 || ^19.0.0
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==}
+ engines: {node: '>=12', npm: '>=6'}
+ peerDependencies:
+ '@testing-library/dom': '>=7.21.4'
+
'@ts-morph/[email protected]':
resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
+
resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}
@@ -2475,6 +2716,44 @@ packages:
peerDependencies:
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-Z2cOr0ksM00MpEfyVE8KXIYPEcBFxdbLSs56L8PO0QQMxt/6bDj45uQfxoc96v05KW3clk7vvgP0qfDit9DmfQ==}
+ peerDependencies:
+ '@vitest/browser': 2.1.9
+ vitest: 2.1.9
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^5.0.0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
+
resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
engines: {node: '>= 0.6'}
@@ -2533,6 +2812,10 @@ packages:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
@@ -2556,6 +2839,17 @@ packages:
resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
+
+ resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-Q+JC7Whu8HhmTdBph/Tq59IoRtoy6KAm5zzPv00WdujX82lbAL8K7WVjne7vdCsAmbF4AYaDOPyO3k0kl8qIrw==}
engines: {node: '>=0.10.0'}
@@ -2568,6 +2862,9 @@ packages:
resolution: {integrity: sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==}
hasBin: true
+ resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
+
resolution: {integrity: sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ==}
engines: {node: '>=4'}
@@ -2611,6 +2908,10 @@ packages:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
+ resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
@@ -2631,6 +2932,10 @@ packages:
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
+ resolution: {integrity: sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'}
@@ -2663,6 +2968,10 @@ packages:
resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
engines: {node: '>= 0.4'}
@@ -2685,6 +2994,10 @@ packages:
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
+ resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
@@ -2705,6 +3018,10 @@ packages:
resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}
+ resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
+ engines: {node: '>= 16'}
+
resolution: {integrity: sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==}
peerDependencies:
@@ -2775,6 +3092,10 @@ packages:
resolution: {integrity: sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==}
+ resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
+ engines: {node: '>= 0.8'}
+
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
@@ -2878,11 +3199,18 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
+
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
hasBin: true
+ resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
@@ -3046,6 +3374,10 @@ packages:
resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
engines: {node: '>= 12'}
+ resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==}
@@ -3058,6 +3390,9 @@ packages:
supports-color:
optional: true
+ resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
+
resolution: {integrity: sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==}
@@ -3093,6 +3428,10 @@ packages:
babel-plugin-macros:
optional: true
+ resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
@@ -3119,6 +3458,10 @@ packages:
resolution: {integrity: sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==}
+ resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
+ engines: {node: '>=0.4.0'}
+
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
@@ -3141,6 +3484,12 @@ packages:
resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
engines: {node: '>=0.3.1'}
+ resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
+
+ resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
+
resolution: {integrity: sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==}
@@ -3152,6 +3501,9 @@ packages:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
+
resolution: {integrity: sha512-wG99Zcfcys9fZux7Cft8BAX/YrOJLJSZ3jyYPfhZHqN2E+Ffx+QXBDsv3gubEgPtV6dTzJMSQUwk1H98/t/0wQ==}
engines: {bun: '>=1', deno: '>=2', node: '>=16'}
@@ -3176,6 +3528,9 @@ packages:
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
+ resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+
resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}
engines: {node: '>= 0.8'}
@@ -3206,16 +3561,28 @@ packages:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
+
resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==}
resolution: {integrity: sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==}
+ resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
+ engines: {node: '>=12'}
+ hasBin: true
+
resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}
engines: {node: '>=18'}
@@ -3344,6 +3711,10 @@ packages:
resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==}
engines: {node: ^18.19.0 || >=20.5.0}
+ resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==}
engines: {node: '>= 16'}
@@ -3467,6 +3838,14 @@ packages:
resolution: {integrity: sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}
+ engines: {node: '>=14'}
+
+ resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}
+ engines: {node: '>= 6'}
+
resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}
engines: {node: '>=12.20.0'}
@@ -3579,6 +3958,11 @@ packages:
resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
engines: {node: '>=10.13.0'}
+ resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
+ hasBin: true
+
resolution: {integrity: sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA==}
engines: {node: 20 || >=22}
@@ -3682,6 +4066,13 @@ packages:
resolution: {integrity: sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==}
engines: {node: '>=16.9.0'}
+ resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
+
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
@@ -3692,6 +4083,10 @@ packages:
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
+ engines: {node: '>= 14'}
+
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
@@ -3745,6 +4140,10 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
+ resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
@@ -3853,6 +4252,9 @@ packages:
resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
+
resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}
@@ -3909,6 +4311,25 @@ packages:
resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
+
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
@@ -3927,6 +4348,15 @@ packages:
resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
hasBin: true
+ resolution: {integrity: sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ canvas: ^2.11.2
+ peerDependenciesMeta:
+ canvas:
+ optional: true
+
resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
engines: {node: '>=6'}
@@ -4112,6 +4542,12 @@ packages:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
+ resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
+
+ resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
+
resolution: {integrity: sha512-vFrFJkWtJvJnD5hg+hJvVE8Lh/TcMzKnTgCWmtBipwI5yLX/iX+5UB2tfuyODF5E7k9xEzMdYgGqaSb1c0c5Yw==}
engines: {node: 20 || >=22}
@@ -4134,13 +4570,24 @@ packages:
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
+ hasBin: true
+
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}
+
resolution: {integrity: sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q==}
engines: {node: '>=16'}
@@ -4397,10 +4844,18 @@ packages:
resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==}
engines: {node: 20 || >=22}
+ resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}
@@ -4497,6 +4952,9 @@ packages:
resolution: {integrity: sha512-qaKRmtYPZ5qdw4jWJD6bxEf1FJEqllJrwxCLIm0sQU/A7v2/czigzOb+C2uSiFsa9lBUzeH7M1oK+Q+OLxL3kA==}
+ resolution: {integrity: sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==}
+
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
@@ -4610,6 +5068,10 @@ packages:
resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}
+ resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}
+ engines: {node: '>=16 || 14 >=14.18'}
+
resolution: {integrity: sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA==}
engines: {node: 20 || >=22}
@@ -4624,9 +5086,16 @@ packages:
resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}
+
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
+ resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
+ engines: {node: '>= 14.16'}
+
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
@@ -4701,6 +5170,10 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
+ engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
+
resolution: {integrity: sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==}
engines: {node: '>=18'}
@@ -5065,6 +5538,9 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+ resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
+
resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}
@@ -5189,6 +5665,10 @@ packages:
resolution: {integrity: sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==}
+ resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}
@@ -5311,6 +5791,12 @@ packages:
resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}
engines: {node: '>= 18'}
+ resolution: {integrity: sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==}
+
+ resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==}
+
resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==}
engines: {node: '>=18'}
@@ -5336,6 +5822,10 @@ packages:
resolution: {integrity: sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==}
+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
+ engines: {node: '>=v12.22.7'}
+
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
@@ -5430,6 +5920,9 @@ packages:
resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
@@ -5473,10 +5966,16 @@ packages:
resolution: {integrity: sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
+
resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
+
resolution: {integrity: sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==}
engines: {node: '>=18'}
@@ -5491,6 +5990,10 @@ packages:
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}
engines: {node: '>=18'}
@@ -5532,6 +6035,10 @@ packages:
resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
@@ -5565,6 +6072,9 @@ packages:
peerDependencies:
react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
+
resolution: {integrity: sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==}
@@ -5594,6 +6104,10 @@ packages:
engines: {node: '>=18.0.0'}
hasBin: true
+ resolution: {integrity: sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-B71/4oyj61iNH0KeCamLuE2rmKuTO5byTOSVwECM5FA7TiAiAW+UqTKZ9ERueC4qvgSttUhdmq1mXC3kJqGX7A==}
engines: {node: '>=12.22'}
@@ -5604,6 +6118,12 @@ packages:
resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+
+ resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
+
resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==}
engines: {node: '>=18'}
@@ -5612,9 +6132,28 @@ packages:
resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+
+ resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==}
+
resolution: {integrity: sha512-7W5Efjhsc3chVdFhqtaU0KtK32J37Zcr9RKtID54nG+tIpcY79CQK/veYPODxtD/LJ4Lue66jvrQzIX2Z2/pUQ==}
+ resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==}
+ hasBin: true
+
resolution: {integrity: sha512-+Zg3vWhRUv8B1maGSTFdev9mjoo8Etn2Ayfs4cnjlD3CsGkxXX4QyW3j2WJ0wdjYcYmy7Lx2RDsZMhgCWafKIw==}
hasBin: true
@@ -5637,10 +6176,18 @@ packages:
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==}
+ engines: {node: '>=16'}
+
resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==}
engines: {node: '>=16'}
+ resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}
hasBin: true
@@ -5848,6 +6395,42 @@ packages:
resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}
+ resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^18.0.0 || >=20.0.0
+ less: '*'
+ lightningcss: ^1.21.0
+ sass: '*'
+ sass-embedded: '*'
+ stylus: '*'
+ sugarss: '*'
+ terser: ^5.4.0
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+
resolution: {integrity: sha512-tI2l/nFHC5rLh7+5+o7QjKjSR04ivXDF4jcgV0f/bTQ+OJiITy5S6gaynVsEM+7RqzufMnVbIon6Sr5x1SDYaQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -5888,6 +6471,31 @@ packages:
yaml:
optional: true
+ resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@types/node': ^18.0.0 || >=20.0.0
+ '@vitest/browser': 2.1.9
+ '@vitest/ui': 2.1.9
+ happy-dom: '*'
+ jsdom: '*'
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==}
engines: {node: '>=14.0.0'}
@@ -5908,6 +6516,10 @@ packages:
resolution: {integrity: sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==}
+ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}
@@ -5915,6 +6527,23 @@ packages:
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}
+ engines: {node: '>=18'}
+ deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation
+
+ resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==}
engines: {node: '>= 0.4'}
@@ -5929,6 +6558,11 @@ packages:
engines: {node: ^16.13.0 || >=18.0.0}
hasBin: true
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
+ engines: {node: '>=8'}
+ hasBin: true
+
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
@@ -5941,6 +6575,10 @@ packages:
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}
engines: {node: '>=18'}
@@ -5948,10 +6586,29 @@ packages:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
+ resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
resolution: {integrity: sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
+
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
@@ -6066,6 +6723,13 @@ packages:
snapshots:
+ '@adobe/[email protected]': {}
+
+ '@ampproject/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
'@ant-design/[email protected]':
dependencies:
'@ant-design/fast-color': 2.0.6
@@ -6120,6 +6784,14 @@ snapshots:
package-manager-detector: 1.6.0
tinyexec: 1.0.2
+ '@asamuzakjp/[email protected]':
+ dependencies:
+ '@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-color-parser': 3.1.0(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])
+ '@csstools/css-tokenizer': 3.0.4
+ lru-cache: 10.4.3
+
dependencies:
'@babel/helper-validator-identifier': 7.28.5
@@ -6156,8 +6828,8 @@ snapshots:
dependencies:
- '@babel/parser': 7.28.5
- '@babel/types': 7.28.5
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
jsesc: 3.1.0
@@ -6172,7 +6844,7 @@ snapshots:
dependencies:
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
dependencies:
@@ -6211,14 +6883,14 @@ snapshots:
dependencies:
'@babel/traverse': 7.29.0
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/traverse': 7.28.5
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
transitivePeerDependencies:
- supports-color
@@ -6249,7 +6921,7 @@ snapshots:
dependencies:
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
'@babel/[email protected]': {}
@@ -6267,7 +6939,7 @@ snapshots:
dependencies:
'@babel/traverse': 7.28.5
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
transitivePeerDependencies:
- supports-color
@@ -6280,7 +6952,7 @@ snapshots:
dependencies:
'@babel/template': 7.27.2
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
dependencies:
@@ -6357,8 +7029,8 @@ snapshots:
dependencies:
'@babel/code-frame': 7.27.1
- '@babel/parser': 7.28.5
- '@babel/types': 7.28.5
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
dependencies:
@@ -6371,9 +7043,9 @@ snapshots:
'@babel/code-frame': 7.27.1
'@babel/generator': 7.28.5
'@babel/helper-globals': 7.28.0
- '@babel/parser': 7.28.5
+ '@babel/parser': 7.29.2
'@babel/template': 7.27.2
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
debug: 4.4.3
transitivePeerDependencies:
- supports-color
@@ -6400,6 +7072,8 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
+ '@bcoe/[email protected]': {}
+
'@braintree/[email protected]': {}
'@chevrotain/[email protected]':
@@ -6419,6 +7093,26 @@ snapshots:
'@chevrotain/[email protected]': {}
+ '@csstools/[email protected]': {}
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])
+ '@csstools/css-tokenizer': 3.0.4
+
+ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':
+ dependencies:
+ '@csstools/color-helpers': 5.1.0
+ '@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])
+ '@csstools/css-tokenizer': 3.0.4
+
+ '@csstools/[email protected](@csstools/[email protected])':
+ dependencies:
+ '@csstools/css-tokenizer': 3.0.4
+
+ '@csstools/[email protected]': {}
+
dependencies:
react: 19.2.1
@@ -6561,76 +7255,115 @@ snapshots:
'@emotion/[email protected]': {}
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
@@ -6639,24 +7372,36 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -6669,6 +7414,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -6681,6 +7429,9 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -6693,24 +7444,36 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -6858,6 +7621,17 @@ snapshots:
dependencies:
'@isaacs/balanced-match': 4.0.1
+ '@isaacs/[email protected]':
+ dependencies:
+ string-width: 5.1.2
+ string-width-cjs: [email protected]
+ strip-ansi: 7.2.0
+ strip-ansi-cjs: [email protected]
+ wrap-ansi: 8.1.0
+ wrap-ansi-cjs: [email protected]
+
+ '@istanbuljs/[email protected]': {}
+
'@jridgewell/[email protected]':
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -7110,6 +7884,9 @@ snapshots:
'@open-draft/[email protected]': {}
+ '@pkgjs/[email protected]':
+ optional: true
+
'@primer/[email protected]':
dependencies:
object-assign: 4.1.1
@@ -8214,12 +8991,48 @@ snapshots:
'@tanstack/query-core': 5.99.0
react: 19.2.1
+ '@testing-library/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ '@babel/runtime': 7.28.4
+ '@types/aria-query': 5.0.4
+ aria-query: 5.3.0
+ dom-accessibility-api: 0.5.16
+ lz-string: 1.5.0
+ picocolors: 1.1.1
+ pretty-format: 27.5.1
+
+ '@testing-library/[email protected]':
+ dependencies:
+ '@adobe/css-tools': 4.4.4
+ aria-query: 5.3.2
+ css.escape: 1.5.1
+ dom-accessibility-api: 0.6.3
+ picocolors: 1.1.1
+ redent: 3.0.0
+
+ dependencies:
+ '@babel/runtime': 7.28.4
+ '@testing-library/dom': 10.4.1
+ react: 19.2.1
+ react-dom: 19.2.1([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.7
+ '@types/react-dom': 19.2.3(@types/[email protected])
+
+ '@testing-library/[email protected](@testing-library/[email protected])':
+ dependencies:
+ '@testing-library/dom': 10.4.1
+
'@ts-morph/[email protected]':
dependencies:
fast-glob: 3.3.3
minimatch: 10.1.1
path-browserify: 1.0.1
+ '@types/[email protected]': {}
+
dependencies:
'@babel/parser': 7.28.5
@@ -8230,16 +9043,16 @@ snapshots:
dependencies:
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
dependencies:
- '@babel/parser': 7.28.5
- '@babel/types': 7.28.5
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
dependencies:
- '@babel/types': 7.28.5
+ '@babel/types': 7.29.0
dependencies:
@@ -8575,6 +9388,65 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@ampproject/remapping': 2.3.0
+ '@bcoe/v8-coverage': 0.2.3
+ debug: 4.4.3
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-lib-source-maps: 5.0.6
+ istanbul-reports: 3.2.0
+ magic-string: 0.30.21
+ magicast: 0.3.5
+ std-env: 3.10.0
+ test-exclude: 7.0.2
+ tinyrainbow: 1.2.0
+ transitivePeerDependencies:
+ - supports-color
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/spy': 2.1.9
+ '@vitest/utils': 2.1.9
+ chai: 5.3.3
+ tinyrainbow: 1.2.0
+
+ dependencies:
+ '@vitest/spy': 2.1.9
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ msw: 2.13.2(@types/[email protected])([email protected])
+ vite: 5.4.21(@types/[email protected])([email protected])
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyrainbow: 1.2.0
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/utils': 2.1.9
+ pathe: 1.1.2
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 2.1.9
+ magic-string: 0.30.21
+ pathe: 1.1.2
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyspy: 3.0.2
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 2.1.9
+ loupe: 3.2.1
+ tinyrainbow: 1.2.0
+
dependencies:
mime-types: 3.0.2
@@ -8637,6 +9509,8 @@ snapshots:
dependencies:
color-convert: 2.0.1
+
@@ -8720,6 +9594,14 @@ snapshots:
dependencies:
tslib: 2.8.1
+ dependencies:
+ dequal: 2.0.3
+
+
+
@@ -8728,6 +9610,8 @@ snapshots:
+
@@ -8782,6 +9666,8 @@ snapshots:
+
@@ -8814,6 +9700,10 @@ snapshots:
dependencies:
balanced-match: 1.0.2
+ dependencies:
+ balanced-match: 4.0.4
+
dependencies:
fill-range: 7.1.1
@@ -8848,6 +9738,8 @@ snapshots:
+
dependencies:
es-errors: 1.3.0
@@ -8871,6 +9763,14 @@ snapshots:
+ dependencies:
+ assertion-error: 2.0.1
+ check-error: 2.1.3
+ deep-eql: 5.0.2
+ loupe: 3.2.1
+ pathval: 2.0.1
+
dependencies:
ansi-styles: 4.3.0
@@ -8886,6 +9786,8 @@ snapshots:
+
dependencies:
chevrotain: 11.0.3
@@ -8958,6 +9860,10 @@ snapshots:
+ dependencies:
+ delayed-stream: 1.0.0
+
@@ -9049,8 +9955,15 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
+
+ dependencies:
+ '@asamuzakjp/css-color': 3.2.0
+ rrweb-cssom: 0.8.0
+
@@ -9239,12 +10152,19 @@ snapshots:
+ dependencies:
+ whatwg-mimetype: 4.0.0
+ whatwg-url: 14.2.0
+
dependencies:
ms: 2.1.3
+
dependencies:
character-entities: 2.0.2
@@ -9293,6 +10213,8 @@ snapshots:
optionalDependencies:
babel-plugin-macros: 3.1.0
+
@@ -9316,6 +10238,8 @@ snapshots:
dependencies:
robust-predicates: 3.0.2
+
@@ -9330,6 +10254,10 @@ snapshots:
+
+
optionalDependencies:
'@types/trusted-types': 2.0.7
@@ -9342,6 +10270,8 @@ snapshots:
es-errors: 1.3.0
gopd: 1.2.0
+
dependencies:
'@ecies/ciphers': 0.2.6(@noble/[email protected])
@@ -9366,6 +10296,8 @@ snapshots:
+
@@ -9389,10 +10321,19 @@ snapshots:
+
dependencies:
es-errors: 1.3.0
+ dependencies:
+ es-errors: 1.3.0
+ get-intrinsic: 1.3.0
+ has-tostringtag: 1.0.2
+ hasown: 2.0.2
+
dependencies:
'@types/estree-jsx': 1.0.5
@@ -9407,6 +10348,32 @@ snapshots:
esast-util-from-estree: 2.0.0
vfile-message: 4.0.3
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.21.5
+ '@esbuild/android-arm': 0.21.5
+ '@esbuild/android-arm64': 0.21.5
+ '@esbuild/android-x64': 0.21.5
+ '@esbuild/darwin-arm64': 0.21.5
+ '@esbuild/darwin-x64': 0.21.5
+ '@esbuild/freebsd-arm64': 0.21.5
+ '@esbuild/freebsd-x64': 0.21.5
+ '@esbuild/linux-arm': 0.21.5
+ '@esbuild/linux-arm64': 0.21.5
+ '@esbuild/linux-ia32': 0.21.5
+ '@esbuild/linux-loong64': 0.21.5
+ '@esbuild/linux-mips64el': 0.21.5
+ '@esbuild/linux-ppc64': 0.21.5
+ '@esbuild/linux-riscv64': 0.21.5
+ '@esbuild/linux-s390x': 0.21.5
+ '@esbuild/linux-x64': 0.21.5
+ '@esbuild/netbsd-x64': 0.21.5
+ '@esbuild/openbsd-x64': 0.21.5
+ '@esbuild/sunos-x64': 0.21.5
+ '@esbuild/win32-arm64': 0.21.5
+ '@esbuild/win32-ia32': 0.21.5
+ '@esbuild/win32-x64': 0.21.5
+
optionalDependencies:
'@esbuild/aix-ppc64': 0.25.12
@@ -9638,6 +10605,8 @@ snapshots:
strip-final-newline: 4.0.0
yoctocolors: 2.1.2
+
dependencies:
express: 5.2.1
@@ -9777,6 +10746,19 @@ snapshots:
+ dependencies:
+ cross-spawn: 7.0.6
+ signal-exit: 4.1.0
+
+ dependencies:
+ asynckit: 0.4.0
+ combined-stream: 1.0.8
+ es-set-tostringtag: 2.1.0
+ hasown: 2.0.2
+ mime-types: 2.1.35
+
dependencies:
fetch-blob: 3.2.0
@@ -9874,6 +10856,15 @@ snapshots:
dependencies:
is-glob: 4.0.3
+ dependencies:
+ foreground-child: 3.3.1
+ jackspeak: 3.4.3
+ minimatch: 9.0.5
+ minipass: 7.1.2
+ package-json-from-dist: 1.0.1
+ path-scurry: 1.11.1
+
dependencies:
minimatch: 10.1.1
@@ -10063,6 +11054,12 @@ snapshots:
+ dependencies:
+ whatwg-encoding: 3.1.1
+
+
@@ -10075,6 +11072,13 @@ snapshots:
statuses: 2.0.2
toidentifier: 1.0.1
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
agent-base: 6.0.2
@@ -10120,6 +11124,8 @@ snapshots:
+
@@ -10191,6 +11197,8 @@ snapshots:
dependencies:
isobject: 3.0.1
+
@@ -10225,6 +11233,33 @@ snapshots:
+
+ dependencies:
+ istanbul-lib-coverage: 3.2.2
+ make-dir: 4.0.0
+ supports-color: 7.2.0
+
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ debug: 4.4.3
+ istanbul-lib-coverage: 3.2.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ html-escaper: 2.0.2
+ istanbul-lib-report: 3.0.1
+
+ dependencies:
+ '@isaacs/cliui': 8.0.2
+ optionalDependencies:
+ '@pkgjs/parseargs': 0.11.0
+
@@ -10237,6 +11272,34 @@ snapshots:
dependencies:
argparse: 2.0.1
+ dependencies:
+ cssstyle: 4.6.0
+ data-urls: 5.0.0
+ decimal.js: 10.6.0
+ form-data: 4.0.5
+ html-encoding-sniffer: 4.0.0
+ http-proxy-agent: 7.0.2
+ https-proxy-agent: 7.0.6
+ is-potential-custom-element-name: 1.0.1
+ nwsapi: 2.2.23
+ parse5: 7.3.0
+ rrweb-cssom: 0.7.1
+ saxes: 6.0.0
+ symbol-tree: 3.2.4
+ tough-cookie: 5.1.2
+ w3c-xmlserializer: 5.0.0
+ webidl-conversions: 7.0.0
+ whatwg-encoding: 3.1.1
+ whatwg-mimetype: 4.0.0
+ whatwg-url: 14.2.0
+ ws: 8.20.0
+ xml-name-validator: 5.0.0
+ transitivePeerDependencies:
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+
@@ -10408,6 +11471,10 @@ snapshots:
dependencies:
js-tokens: 4.0.0
+
+
@@ -10426,14 +11493,26 @@ snapshots:
dependencies:
react: 19.2.1
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+ dependencies:
+ '@babel/parser': 7.29.2
+ '@babel/types': 7.29.0
+ source-map-js: 1.2.1
+
dependencies:
pify: 3.0.0
+ dependencies:
+ semver: 7.7.3
+
@@ -10978,10 +12057,16 @@ snapshots:
+
dependencies:
'@isaacs/brace-expansion': 5.0.0
+ dependencies:
+ brace-expansion: 5.0.5
+
dependencies:
brace-expansion: 1.1.12
@@ -11089,6 +12174,8 @@ snapshots:
+
@@ -11210,6 +12297,11 @@ snapshots:
+ dependencies:
+ lru-cache: 10.4.3
+ minipass: 7.1.2
+
dependencies:
lru-cache: 11.2.5
@@ -11221,8 +12313,12 @@ snapshots:
+
+
@@ -11284,6 +12380,12 @@ snapshots:
+ dependencies:
+ ansi-regex: 5.0.1
+ ansi-styles: 5.2.0
+ react-is: 17.0.2
+
dependencies:
parse-ms: 4.0.0
@@ -11793,6 +12895,8 @@ snapshots:
+
@@ -11955,6 +13059,11 @@ snapshots:
unified: 11.0.5
vfile: 6.0.3
+ dependencies:
+ indent-string: 4.0.0
+ strip-indent: 3.0.0
+
dependencies:
regex-utilities: 2.3.0
@@ -12157,6 +13266,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
+
@@ -12179,6 +13292,10 @@ snapshots:
dependencies:
truncate-utf8-bytes: 1.0.2
+ dependencies:
+ xmlchars: 2.2.0
+
@@ -12338,6 +13455,8 @@ snapshots:
side-channel-map: 1.0.1
side-channel-weakmap: 1.0.2
+
@@ -12365,8 +13484,12 @@ snapshots:
dependencies:
extend-shallow: 3.0.2
+
+
@@ -12379,6 +13502,12 @@ snapshots:
is-fullwidth-code-point: 3.0.0
strip-ansi: 6.0.1
+ dependencies:
+ eastasianwidth: 0.2.0
+ emoji-regex: 9.2.2
+ strip-ansi: 7.2.0
+
dependencies:
emoji-regex: 10.6.0
@@ -12420,6 +13549,10 @@ snapshots:
+ dependencies:
+ min-indent: 1.0.1
+
@@ -12450,6 +13583,8 @@ snapshots:
react: 19.2.1
use-sync-external-store: 1.6.0([email protected])
+
@@ -12483,12 +13618,22 @@ snapshots:
- debug
- supports-color
+ dependencies:
+ '@istanbuljs/schema': 0.1.6
+ glob: 10.5.0
+ minimatch: 10.2.5
+
+
+
@@ -12496,8 +13641,20 @@ snapshots:
fdir: 6.5.0([email protected])
picomatch: 4.0.3
+
+
+
+
+ dependencies:
+ tldts-core: 6.1.86
+
dependencies:
tldts-core: 7.0.28
@@ -12520,10 +13677,18 @@ snapshots:
+ dependencies:
+ tldts: 6.1.86
+
dependencies:
tldts: 7.0.28
+ dependencies:
+ punycode: 2.3.1
+
@@ -12729,6 +13894,34 @@ snapshots:
'@types/unist': 3.0.3
vfile-message: 4.0.3
+ dependencies:
+ cac: 6.7.14
+ debug: 4.4.3
+ es-module-lexer: 1.7.0
+ pathe: 1.1.2
+ vite: 5.4.21(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - '@types/node'
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
+ dependencies:
+ esbuild: 0.21.5
+ postcss: 8.5.6
+ rollup: 4.53.3
+ optionalDependencies:
+ '@types/node': 24.10.1
+ fsevents: 2.3.3
+ lightningcss: 1.32.0
+
dependencies:
esbuild: 0.25.12
@@ -12744,6 +13937,42 @@ snapshots:
lightningcss: 1.32.0
tsx: 4.21.0
+ dependencies:
+ '@vitest/expect': 2.1.9
+ '@vitest/pretty-format': 2.1.9
+ '@vitest/runner': 2.1.9
+ '@vitest/snapshot': 2.1.9
+ '@vitest/spy': 2.1.9
+ '@vitest/utils': 2.1.9
+ chai: 5.3.3
+ debug: 4.4.3
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ pathe: 1.1.2
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinypool: 1.1.1
+ tinyrainbow: 1.2.0
+ vite: 5.4.21(@types/[email protected])([email protected])
+ vite-node: 2.1.9(@types/[email protected])([email protected])
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 24.10.1
+ jsdom: 25.0.1
+ transitivePeerDependencies:
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+
@@ -12761,10 +13990,27 @@ snapshots:
+ dependencies:
+ xml-name-validator: 5.0.0
+
+
+ dependencies:
+ iconv-lite: 0.6.3
+
+
+ dependencies:
+ tr46: 5.1.1
+ webidl-conversions: 7.0.0
+
dependencies:
available-typed-arrays: 1.0.7
@@ -12783,6 +14029,11 @@ snapshots:
dependencies:
isexe: 3.1.5
+ dependencies:
+ siginfo: 2.0.0
+ stackback: 0.0.2
+
@@ -12797,6 +14048,12 @@ snapshots:
string-width: 4.2.3
strip-ansi: 6.0.1
+ dependencies:
+ ansi-styles: 6.2.3
+ string-width: 5.1.2
+ strip-ansi: 7.2.0
+
dependencies:
ansi-styles: 6.2.3
@@ -12805,11 +14062,17 @@ snapshots:
+
dependencies:
is-wsl: 3.1.1
powershell-utils: 0.1.0
+
+
diff --git a/scripts/build-node-docs-index.js b/scripts/build-node-docs-index.js
new file mode 100644
index 00000000..e349d49f
--- /dev/null
+++ b/scripts/build-node-docs-index.js
@@ -0,0 +1,147 @@
+#!/usr/bin/env node
+/**
+ * Build / verify the per-node documentation index.
+ *
+ * Usage:
+ * node scripts/build-node-docs-index.js # rewrite README index
+ * node scripts/build-node-docs-index.js --check # exit 1 if any registry node is undocumented
+ *
+ * Walks `docs-internal/node-logic-flows/<category>/<node>.md`, scrapes the
+ * first H1 of each doc, and rewrites the AUTO-GENERATED-INDEX block in
+ * README.md. With --check, also cross-references against
+ * `client/src/nodeDefinitions/` to catch missing docs after a refactor.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+const ROOT = path.resolve(__dirname, '..');
+const DOCS_DIR = path.join(ROOT, 'docs-internal', 'node-logic-flows');
+const INDEX_FILE = path.join(DOCS_DIR, 'README.md');
+const REGISTRY_GLOB = path.join(ROOT, 'client', 'src', 'nodeDefinitions');
+
+const START_MARKER = '<!-- AUTO-GENERATED-INDEX-START -->';
+const END_MARKER = '<!-- AUTO-GENERATED-INDEX-END -->';
+
+function readH1(filePath) {
+ const content = fs.readFileSync(filePath, 'utf8');
+ const match = content.match(/^#\s+(.+)$/m);
+ return match ? match[1].trim() : path.basename(filePath, '.md');
+}
+
+function listCategories() {
+ if (!fs.existsSync(DOCS_DIR)) return [];
+ return fs
+ .readdirSync(DOCS_DIR, { withFileTypes: true })
+ .filter((d) => d.isDirectory() && !d.name.startsWith('_'))
+ .map((d) => d.name)
+ .sort();
+}
+
+function listDocs(category) {
+ const dir = path.join(DOCS_DIR, category);
+ return fs
+ .readdirSync(dir)
+ .filter((f) => f.endsWith('.md') && !f.startsWith('_') && f !== 'README.md')
+ .sort()
+ .map((f) => ({
+ file: f,
+ relPath: path.posix.join(category, f),
+ title: readH1(path.join(dir, f)),
+ nodeKey: path.basename(f, '.md'),
+ }));
+}
+
+function buildIndexBlock() {
+ const cats = listCategories();
+ const lines = [START_MARKER];
+ for (const cat of cats) {
+ const docs = listDocs(cat);
+ if (docs.length === 0) continue;
+ lines.push('', `### ${cat}`, '');
+ for (const doc of docs) {
+ lines.push(`- [${doc.title}](./${doc.relPath})`);
+ }
+ }
+ lines.push('', END_MARKER);
+ return lines.join('\n');
+}
+
+function rewriteIndex() {
+ const original = fs.readFileSync(INDEX_FILE, 'utf8');
+ const block = buildIndexBlock();
+ const re = new RegExp(`${START_MARKER}[\\s\\S]*?${END_MARKER}`, 'm');
+ if (!re.test(original)) {
+ console.error(`error: ${INDEX_FILE} is missing the AUTO-GENERATED-INDEX markers`);
+ process.exit(2);
+ }
+ const next = original.replace(re, block);
+ fs.writeFileSync(INDEX_FILE, next);
+ console.log(`wrote index to ${path.relative(ROOT, INDEX_FILE)}`);
+}
+
+function collectDocumentedKeys() {
+ const keys = new Set();
+ for (const cat of listCategories()) {
+ for (const doc of listDocs(cat)) {
+ keys.add(doc.nodeKey);
+ }
+ }
+ return keys;
+}
+
+function collectRegistryKeys() {
+ // Scrape the exported *_NODE_TYPES arrays (e.g. SEARCH_NODE_TYPES =
+ // ['braveSearch', ...]). These are the canonical lists each module
+ // exports for the registry. Skip parameter `name:` strings and other
+ // noise by anchoring on `_NODE_TYPES = [...]` / `_NODE_TYPES: [...]`.
+ const keys = new Set();
+ const files = walk(REGISTRY_GLOB).filter((f) => f.endsWith('.ts'));
+ const arrayRe = /[A-Z_]+_NODE_TYPES\s*(?:=|:)\s*\[([^\]]+)\]/g;
+ const itemRe = /['"]([a-zA-Z_][\w]*)['"]/g;
+ for (const f of files) {
+ const text = fs.readFileSync(f, 'utf8');
+ let m;
+ while ((m = arrayRe.exec(text))) {
+ const body = m[1];
+ let im;
+ while ((im = itemRe.exec(body))) keys.add(im[1]);
+ }
+ }
+ return keys;
+}
+
+function walk(dir) {
+ if (!fs.existsSync(dir)) return [];
+ const out = [];
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...walk(full));
+ else out.push(full);
+ }
+ return out;
+}
+
+function checkCompleteness() {
+ const documented = collectDocumentedKeys();
+ const registered = collectRegistryKeys();
+ const missing = [...registered].filter((k) => !documented.has(k)).sort();
+ if (missing.length === 0) {
+ console.log(`OK: every registered node has a logic-flow doc (${registered.size} total)`);
+ return 0;
+ }
+ console.error(`MISSING DOCS for ${missing.length}/${registered.size} nodes:`);
+ for (const k of missing) console.error(` - ${k}`);
+ return 1;
+}
+
+const args = process.argv.slice(2);
+if (args.includes('--check')) {
+ process.exit(checkCompleteness());
+} else {
+ rewriteIndex();
+}
diff --git a/server/pyproject.toml b/server/pyproject.toml
index 4b78edb8..1ad91923 100644
--- a/server/pyproject.toml
+++ b/server/pyproject.toml
@@ -93,6 +93,10 @@ dependencies = [
[project.optional-dependencies]
dev = [
"pytest>=8.0.0",
+ "pytest-asyncio>=0.24.0",
+ "pytest-mock>=3.14.0",
+ "pytest-cov>=6.0.0",
+ "respx>=0.21.0",
"ruff>=0.8.0",
]
docs = [
@@ -106,6 +110,28 @@ aws = [
"boto3>=1.34.0", # AWS Secrets Manager
]
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+asyncio_mode = "auto"
+filterwarnings = [
+ "ignore::DeprecationWarning",
+ "ignore::PendingDeprecationWarning",
+]
+markers = [
+ "unit: fast unit tests with mocks (default)",
+ "node_contract: contract tests that drive a handler through NodeExecutor",
+ "slow: tests that take >1s",
+ "credentials: tests for the credentials subsystem (encryption, auth_service, oauth)",
+]
+
+[tool.coverage.run]
+source = ["services.handlers", "services.node_executor"]
+omit = ["*/tests/*", "*/__init__.py"]
+
+[tool.coverage.report]
+show_missing = true
+skip_covered = false
+
[tool.ruff]
line-length = 140
diff --git a/server/tests/conftest.py b/server/tests/conftest.py
index 8fae652f..0a80d3ae 100644
--- a/server/tests/conftest.py
+++ b/server/tests/conftest.py
@@ -1,25 +1,103 @@
-"""Shared fixtures for native LLM provider tests."""
+"""Shared fixtures for all server tests.
+
+Stubs heavy / circular imports (logging, container, encryption, pricing)
+before any handler/service is loaded so node tests don't pay the cost of
+real DI or Temporal runtimes during collection.
+"""
import sys
+import types
from pathlib import Path
from unittest.mock import MagicMock
+import pytest
+
# Ensure server/ is on sys.path
SERVER_DIR = Path(__file__).parent.parent
if str(SERVER_DIR) not in sys.path:
sys.path.insert(0, str(SERVER_DIR))
-# Stub core.logging before any provider import
-def _stub_module(name: str) -> MagicMock:
- if name not in sys.modules:
- sys.modules[name] = MagicMock()
- return sys.modules[name]
+def _make_package(name: str) -> types.ModuleType:
+ """Force a fresh stub package, replacing whatever is in sys.modules."""
+ pkg = types.ModuleType(name)
+ pkg.__path__ = [] # marks it as a package
+ sys.modules[name] = pkg
+ return pkg
+
+
+def _make_submodule(parent_name: str, child: str, attrs: dict | None = None) -> types.ModuleType:
+ """Register a stub submodule and attach it to its parent package."""
+ full_name = f"{parent_name}.{child}"
+ mod = types.ModuleType(full_name)
+ for key, value in (attrs or {}).items():
+ setattr(mod, key, value)
+ sys.modules[full_name] = mod
+ parent = sys.modules.get(parent_name)
+ if parent is not None:
+ setattr(parent, child, mod)
+ return mod
+
+
+def _stub_log_execution_time(*_args, **_kwargs):
+ """Identity decorator stub for `core.logging.log_execution_time`."""
+
+ def _decorator(fn):
+ return fn
+
+ # Support both @log_execution_time and @log_execution_time("name")
+ if _args and callable(_args[0]) and not _kwargs:
+ return _args[0]
+ return _decorator
-_stub_module("core")
-_core_logging = _stub_module("core.logging")
-_core_logging.get_logger = MagicMock(return_value=MagicMock())
+# core.* package -- handlers do `from core.container import container`,
+# `from core.logging import get_logger`, etc. Build a stub package with
+# real submodule attributes so imports resolve without touching the real
+# heavy deps (dependency_injector, cryptography, ...).
+_core_pkg = _make_package("core")
+_make_submodule(
+ "core",
+ "logging",
+ {
+ "get_logger": MagicMock(return_value=MagicMock()),
+ "log_execution_time": _stub_log_execution_time,
+ },
+)
+_make_submodule("core", "container", {"container": MagicMock()})
+
+
+# services.pricing -- pre-stub the singleton so handler modules that do
+# `from services.pricing import get_pricing_service` at module load time
+# pick up the stub instead of loading the real PricingService (which reads
+# config/pricing.json and is irrelevant to handler contract tests).
+def _make_pricing_stub():
+ pricing = MagicMock(name="StubPricingService")
+ pricing.calculate_api_cost = MagicMock(
+ return_value={"operation": "stub", "total_cost": 0.0}
+ )
+ pricing.calculate_cost = MagicMock(
+ return_value={
+ "input_cost": 0.0,
+ "output_cost": 0.0,
+ "cache_cost": 0.0,
+ "total_cost": 0.0,
+ }
+ )
+ pricing.get_pricing = MagicMock(return_value=None)
+ return pricing
+
+
+_pricing_singleton = _make_pricing_stub()
+# Pre-stub services.pricing in sys.modules so subsequent
+# `from services.pricing import get_pricing_service` resolves to the stub.
+# We deliberately do NOT pre-create `services` as a stub package, because
+# the real `services/` directory must remain importable for everything else.
+if "services.pricing" not in sys.modules:
+ _pricing_mod = types.ModuleType("services.pricing")
+ _pricing_mod.get_pricing_service = MagicMock(return_value=_pricing_singleton)
+ _pricing_mod.PricingService = MagicMock(return_value=_pricing_singleton)
+ sys.modules["services.pricing"] = _pricing_mod
# Wave 10.C: discover node plugins once per test session so every test
@@ -28,8 +106,20 @@ _core_logging.get_logger = MagicMock(return_value=MagicMock())
# entries at import; now plugin modules do, and they have to run before
# any test calls get_node_spec() / NODE_METADATA.get(...).
try:
- import nodes # noqa: F401,E402 — side-effect: register_node calls
+ import nodes # noqa: F401,E402 -- side-effect: register_node calls
except Exception:
# If plugin discovery fails (e.g. stubs not complete), let individual
# tests surface the error rather than crashing collection.
pass
+
+
+async def harness():
+ """Fresh NodeTestHarness per test.
+
+ Imported lazily so the conftest stubs above land before NodeExecutor pulls
+ in its handler chain.
+ """
+ from tests.nodes._harness import NodeTestHarness
+
+ return NodeTestHarness()
diff --git a/server/tests/credentials/README.md b/server/tests/credentials/README.md
new file mode 100644
index 00000000..651adbb7
--- /dev/null
+++ b/server/tests/credentials/README.md
@@ -0,0 +1,41 @@
+# Credentials Test Suite
+
+Locks in the invariants enumerated in [docs-internal/credentials_panel.md §5](../../../docs-internal/credentials_panel.md).
+
+## Run
+
+```bash
+cd server
+uv pip install -e ".[test]"
+uv run pytest tests/credentials/ -v
+
+# Coverage report on the three critical modules
+uv run pytest tests/credentials/ --cov=core.encryption --cov=core.credentials_database --cov=services.auth --cov-report=term-missing
+```
+
+## Layout
+
+| File | Locks in |
+|---|---|
+| `test_encryption.py` | Invariant 13 — round-trip correctness, error paths, salt randomness |
+| `test_credentials_database.py` | Invariants 3, 8 — two-table separation, encryption-at-rest, session/customer isolation |
+| `test_auth_service.py` | Invariants 7, 8 — single point of access, memory cache behaviour, `clear_cache()` |
+| `test_oauth_utils.py` | Invariant 12 — runtime redirect URI derivation (ws→http, wss→https) |
+| `test_twitter_oauth.py` | Invariants 9, 10 — PKCE state single-use, code_challenge = base64url(sha256(verifier)) |
+| `test_google_oauth.py` | Invariant 11 — `access_type=offline`, `prompt=consent` |
+| `test_websocket_handlers.py` | Invariants 1, 5, 6 — WS message types, snake_case `has_key`, distinct provider-defaults handler |
+
+## Fixtures
+
+`conftest.py` provides:
+- `encryption` / `uninitialized_encryption` — `EncryptionService` instances
+- `credentials_db` — fresh on-disk SQLite per test in `tmp_path`, real Fernet
+- `auth_service` — `AuthService` backed by the test DB
+
+## What this suite does NOT test
+
+- Real OAuth provider responses (`respx` mocks all upstream calls)
+- The full FastAPI app boot (handlers are invoked directly)
+- LangChain / native LLM SDK behaviour (covered by `tests/llm/`)
+- Frontend `CredentialsModal` rendering (covered by `client/src/test/`)
+- WhatsApp Go RPC binary
diff --git a/server/tests/credentials/__init__.py b/server/tests/credentials/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/server/tests/credentials/conftest.py b/server/tests/credentials/conftest.py
new file mode 100644
index 00000000..da5be056
--- /dev/null
+++ b/server/tests/credentials/conftest.py
@@ -0,0 +1,106 @@
+"""Fixtures for the credentials test suite.
+
+Isolated from tests/conftest.py (which stubs core.logging for LLM provider tests).
+The credentials suite needs the REAL core.logging because it imports the actual
+encryption / credentials_database / auth modules.
+"""
+
+import sys
+from pathlib import Path
+from typing import AsyncIterator
+
+import pytest
+import pytest_asyncio
+
+# Make sure server/ is importable even when pytest is invoked from repo root.
+SERVER_DIR = Path(__file__).resolve().parents[2]
+if str(SERVER_DIR) not in sys.path:
+ sys.path.insert(0, str(SERVER_DIR))
+
+# The parent conftest at server/tests/conftest.py unconditionally stubs `core`
+# and `core.logging` for the LLM provider tests. We need the REAL modules.
+# Wipe ANY core.* entries so subsequent imports load from disk.
+for mod_name in [name for name in list(sys.modules) if name == "core" or name.startswith("core.")]:
+ del sys.modules[mod_name]
+
+from core.encryption import EncryptionService # noqa: E402
+from core.credentials_database import CredentialsDatabase # noqa: E402
+
+
+# --- Encryption fixtures -----------------------------------------------------
+
+
+def encryption_password() -> str:
+ """Deterministic encryption password used by tests."""
+ return "test-password-not-for-production-use"
+
+
+def encryption_salt() -> bytes:
+ """Deterministic 32-byte salt."""
+ return b"\x00" * 32
+
+
+def encryption(encryption_password: str, encryption_salt: bytes) -> EncryptionService:
+ """Initialized EncryptionService ready to encrypt/decrypt."""
+ svc = EncryptionService()
+ svc.initialize(encryption_password, encryption_salt)
+ return svc
+
+
+def uninitialized_encryption() -> EncryptionService:
+ """EncryptionService with no key loaded."""
+ return EncryptionService()
+
+
+# --- CredentialsDatabase fixture ---------------------------------------------
+
+
+@pytest_asyncio.fixture
+async def credentials_db(
+ tmp_path,
+ encryption_password: str,
+) -> AsyncIterator[CredentialsDatabase]:
+ """Fresh on-disk SQLite DB per test (in tmp_path), real Fernet encryption."""
+ db_path = tmp_path / "credentials.db"
+ encryption = EncryptionService()
+
+ db = CredentialsDatabase(str(db_path), encryption)
+ salt = await db.initialize()
+ encryption.initialize(encryption_password, salt)
+
+ try:
+ yield db
+ finally:
+ await db.engine.dispose()
+
+
+# --- AuthService fixture -----------------------------------------------------
+
+
+class _StubCache:
+ """Minimal CacheService stub -- AuthService keeps the reference but doesn't use it."""
+
+
+class _StubDatabase:
+ """Minimal Database stub for AuthService (kept only for backward compat)."""
+
+
+class _StubSettings:
+ """Minimal Settings stub."""
+
+
+@pytest_asyncio.fixture
+async def auth_service(credentials_db: CredentialsDatabase):
+ """AuthService backed by the real credentials_db fixture."""
+ from services.auth import AuthService
+
+ return AuthService(
+ credentials_db=credentials_db,
+ cache=_StubCache(),
+ database=_StubDatabase(),
+ settings=_StubSettings(),
+ )
diff --git a/server/tests/credentials/test_auth_service.py b/server/tests/credentials/test_auth_service.py
new file mode 100644
index 00000000..ded216af
--- /dev/null
+++ b/server/tests/credentials/test_auth_service.py
@@ -0,0 +1,175 @@
+"""Tests for AuthService (single point of access for credentials).
+
+Locks in invariants 7 and 8 from docs-internal/credentials_panel.md:
+ - store_api_key requires models=[]
+ - Memory cache hit path does not query DB on every call
+ - clear_cache wipes _memory_cache, _models_cache, _oauth_cache
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+pytestmark = pytest.mark.credentials
+
+
+class TestApiKeyOps:
+ async def test_store_and_get_roundtrip(self, auth_service):
+ ok = await auth_service.store_api_key("openai", "sk-foo", models=["gpt-4"])
+ assert ok is True
+ assert await auth_service.get_api_key("openai") == "sk-foo"
+
+ async def test_get_models_after_store(self, auth_service):
+ await auth_service.store_api_key("openai", "sk-foo", models=["gpt-4", "gpt-3.5"])
+ assert await auth_service.get_stored_models("openai") == ["gpt-4", "gpt-3.5"]
+
+ async def test_store_with_empty_models_for_non_llm_keys(self, auth_service):
+ # Pattern C: save-only API keys (telegram_bot_token, android_remote, etc.)
+ ok = await auth_service.store_api_key(
+ "telegram_bot_token", "123:abc", models=[]
+ )
+ assert ok is True
+ assert await auth_service.get_api_key("telegram_bot_token") == "123:abc"
+ assert await auth_service.get_stored_models("telegram_bot_token") == []
+
+ async def test_store_requires_models_keyword(self, auth_service):
+ # Invariant 7: store_api_key takes `models` as required argument.
+ # Calling without it must fail at the Python signature level.
+ with pytest.raises(TypeError):
+ await auth_service.store_api_key("openai", "sk-foo") # type: ignore[call-arg]
+
+ async def test_remove_clears_storage(self, auth_service):
+ await auth_service.store_api_key("openai", "sk-foo", models=[])
+ ok = await auth_service.remove_api_key("openai")
+ assert ok is True
+ assert await auth_service.get_api_key("openai") is None
+
+ async def test_has_valid_key(self, auth_service):
+ assert await auth_service.has_valid_key("openai") is False
+ await auth_service.store_api_key("openai", "sk-foo", models=[])
+ assert await auth_service.has_valid_key("openai") is True
+
+ async def test_session_isolation(self, auth_service):
+ await auth_service.store_api_key(
+ "openai", "sk-default", models=[], session_id="default"
+ )
+ await auth_service.store_api_key(
+ "openai", "sk-other", models=[], session_id="other"
+ )
+ assert await auth_service.get_api_key("openai", "default") == "sk-default"
+ assert await auth_service.get_api_key("openai", "other") == "sk-other"
+
+
+class TestMemoryCache:
+ async def test_get_after_store_uses_memory_cache(self, auth_service, monkeypatch):
+ await auth_service.store_api_key("openai", "sk-cached", models=[])
+
+ # Spy on the underlying credentials_db.get_api_key to count DB hits.
+ call_count = {"n": 0}
+ original = auth_service.credentials_db.get_api_key
+
+ async def counting_get(provider, session_id="default"):
+ call_count["n"] += 1
+ return await original(provider, session_id)
+
+ monkeypatch.setattr(auth_service.credentials_db, "get_api_key", counting_get)
+
+ # First get hits memory cache (no DB call)
+ result = await auth_service.get_api_key("openai")
+ assert result == "sk-cached"
+ assert call_count["n"] == 0
+
+ # Second/third get also hit memory cache
+ await auth_service.get_api_key("openai")
+ await auth_service.get_api_key("openai")
+ assert call_count["n"] == 0
+
+ async def test_get_falls_back_to_db_when_cache_missing(
+ self, auth_service, monkeypatch
+ ):
+ await auth_service.store_api_key("openai", "sk-foo", models=[])
+
+ # Wipe memory cache to simulate fresh process
+ auth_service._memory_cache.clear()
+ auth_service._models_cache.clear()
+
+ call_count = {"n": 0}
+ original = auth_service.credentials_db.get_api_key
+
+ async def counting_get(provider, session_id="default"):
+ call_count["n"] += 1
+ return await original(provider, session_id)
+
+ monkeypatch.setattr(auth_service.credentials_db, "get_api_key", counting_get)
+
+ # First call: DB hit (cache populated as side effect)
+ assert await auth_service.get_api_key("openai") == "sk-foo"
+ assert call_count["n"] == 1
+
+ # Second call: cache hit, no additional DB call
+ assert await auth_service.get_api_key("openai") == "sk-foo"
+ assert call_count["n"] == 1
+
+ async def test_clear_cache_wipes_all_three_caches(self, auth_service):
+ await auth_service.store_api_key("openai", "sk-foo", models=["gpt-4"])
+ await auth_service.store_oauth_tokens("google", "a", "r", email="[email protected]")
+
+ # Sanity: caches populated
+ assert auth_service._memory_cache
+ assert auth_service._models_cache
+ assert auth_service._oauth_cache
+
+ auth_service.clear_cache()
+
+ assert auth_service._memory_cache == {}
+ assert auth_service._models_cache == {}
+ assert auth_service._oauth_cache == {}
+
+ async def test_clear_cache_does_not_delete_db_data(self, auth_service):
+ await auth_service.store_api_key("openai", "sk-persistent", models=[])
+ auth_service.clear_cache()
+
+ # Re-fetch -- value comes back from DB and re-populates cache
+ assert await auth_service.get_api_key("openai") == "sk-persistent"
+
+
+class TestOAuthOps:
+ async def test_store_and_get_oauth_tokens(self, auth_service):
+ ok = await auth_service.store_oauth_tokens(
+ provider="google",
+ access_token="access-1",
+ refresh_token="refresh-1",
+ name="User",
+ scopes="openid email",
+ )
+ assert ok is True
+
+ tokens = await auth_service.get_oauth_tokens("google")
+ assert tokens is not None
+ assert tokens["access_token"] == "access-1"
+ assert tokens["refresh_token"] == "refresh-1"
+ assert tokens["email"] == "[email protected]"
+ assert tokens["scopes"] == "openid email"
+
+ async def test_remove_oauth_tokens(self, auth_service):
+ await auth_service.store_oauth_tokens("google", "a", "r")
+ ok = await auth_service.remove_oauth_tokens("google")
+ assert ok is True
+ assert await auth_service.get_oauth_tokens("google") is None
+
+ async def test_oauth_cache_isolated_from_api_key_cache(self, auth_service):
+ # Invariants 3 and 8: same provider name in both caches must not collide
+ await auth_service.store_api_key("google", "api-key-value", models=[])
+ await auth_service.store_oauth_tokens(
+ "google", "oauth-access", "oauth-refresh"
+ )
+
+ assert await auth_service.get_api_key("google") == "api-key-value"
+
+ tokens = await auth_service.get_oauth_tokens("google")
+ assert tokens["access_token"] == "oauth-access"
+
+ async def test_get_oauth_tokens_missing_provider_returns_none(self, auth_service):
+ assert await auth_service.get_oauth_tokens("never-stored") is None
diff --git a/server/tests/credentials/test_credentials_database.py b/server/tests/credentials/test_credentials_database.py
new file mode 100644
index 00000000..2140063d
--- /dev/null
+++ b/server/tests/credentials/test_credentials_database.py
@@ -0,0 +1,223 @@
+"""Tests for CredentialsDatabase (encrypted SQLite storage).
+
+Locks in the two-table separation (invariants 3 and 8 in docs-internal/credentials_panel.md):
+ - get_api_key for a provider only stored in the OAuth table returns None
+ - get_oauth_tokens for a provider only stored as API key returns None
+ - Stored ciphertext is never plaintext
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.credentials_database import (
+ CredentialsDatabase,
+ EncryptedAPIKey,
+ EncryptedOAuthToken,
+)
+from sqlmodel import select
+
+pytestmark = pytest.mark.credentials
+
+
+class TestApiKeyCrud:
+ async def test_save_then_get_roundtrip(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("openai", "sk-test-key", models=["gpt-4"])
+ assert await credentials_db.get_api_key("openai") == "sk-test-key"
+
+ async def test_get_nonexistent_returns_none(self, credentials_db: CredentialsDatabase):
+ assert await credentials_db.get_api_key("nonexistent") is None
+
+ async def test_stored_value_is_encrypted(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("openai", "sk-very-secret-plaintext")
+
+ async with credentials_db.get_session() as session:
+ row = await session.get(EncryptedAPIKey, "default_openai")
+ assert row is not None
+ assert "sk-very-secret-plaintext" not in row.key_encrypted
+ assert row.key_encrypted != "sk-very-secret-plaintext"
+
+ async def test_save_overwrites_existing_key(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("openai", "sk-old", models=["a"])
+ await credentials_db.save_api_key("openai", "sk-new", models=["b", "c"])
+
+ assert await credentials_db.get_api_key("openai") == "sk-new"
+ models = await credentials_db.get_api_key_models("openai")
+ assert models == ["b", "c"]
+
+ async def test_delete_removes_key(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("openai", "sk-test")
+ deleted = await credentials_db.delete_api_key("openai")
+ assert deleted is True
+ assert await credentials_db.get_api_key("openai") is None
+
+ async def test_delete_nonexistent_returns_false(
+ self, credentials_db: CredentialsDatabase
+ ):
+ assert await credentials_db.delete_api_key("nonexistent") is False
+
+ async def test_session_isolation(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_api_key("openai", "sk-default", session_id="default")
+ await credentials_db.save_api_key("openai", "sk-bob", session_id="bob")
+
+ assert await credentials_db.get_api_key("openai", "default") == "sk-default"
+ assert await credentials_db.get_api_key("openai", "bob") == "sk-bob"
+
+ async def test_list_api_keys_returns_providers_only_for_session(
+ self, credentials_db: CredentialsDatabase
+ ):
+ await credentials_db.save_api_key("openai", "k1")
+ await credentials_db.save_api_key("anthropic", "k2")
+ await credentials_db.save_api_key("openai", "k3", session_id="other")
+
+ listed = await credentials_db.list_api_keys()
+ assert sorted(listed) == ["anthropic", "openai"]
+
+ async def test_get_api_key_info_does_not_decrypt(
+ self, credentials_db: CredentialsDatabase
+ ):
+ await credentials_db.save_api_key(
+ "openai", "sk-secret", models=["gpt-4", "gpt-3.5"]
+ )
+ info = await credentials_db.get_api_key_info("openai")
+ assert info is not None
+ assert info["provider"] == "openai"
+ assert info["models"] == ["gpt-4", "gpt-3.5"]
+ assert info["is_valid"] is True
+ # Crucially: no key/key_encrypted exposed
+ assert "key" not in info
+ assert "key_encrypted" not in info
+
+
+class TestOAuthCrud:
+ async def test_save_then_get_roundtrip(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_oauth_tokens(
+ provider="google",
+ access_token="ya29.access-token",
+ refresh_token="1//refresh-token",
+ name="Test User",
+ scopes="openid email profile",
+ )
+ tokens = await credentials_db.get_oauth_tokens("google")
+ assert tokens is not None
+ assert tokens["access_token"] == "ya29.access-token"
+ assert tokens["refresh_token"] == "1//refresh-token"
+ assert tokens["email"] == "[email protected]"
+ assert tokens["name"] == "Test User"
+ assert tokens["scopes"] == "openid email profile"
+
+ async def test_stored_tokens_are_encrypted(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_oauth_tokens(
+ provider="twitter",
+ access_token="plaintext-access",
+ refresh_token="plaintext-refresh",
+ )
+
+ async with credentials_db.get_session() as session:
+ result = await session.execute(
+ select(EncryptedOAuthToken).where(
+ EncryptedOAuthToken.provider == "twitter"
+ )
+ )
+ row = result.scalars().first()
+ assert row is not None
+ assert "plaintext-access" not in row.access_token_encrypted
+ assert "plaintext-refresh" not in row.refresh_token_encrypted
+
+ async def test_save_overwrites_existing_for_provider(
+ self, credentials_db: CredentialsDatabase
+ ):
+ await credentials_db.save_oauth_tokens("google", "a1", "r1", email="[email protected]")
+ await credentials_db.save_oauth_tokens("google", "a2", "r2", email="[email protected]")
+
+ tokens = await credentials_db.get_oauth_tokens("google")
+ assert tokens["access_token"] == "a2"
+ assert tokens["refresh_token"] == "r2"
+ assert tokens["email"] == "[email protected]"
+
+ async def test_delete_removes_tokens(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_oauth_tokens("google", "a", "r")
+ assert await credentials_db.delete_oauth_tokens("google") is True
+ assert await credentials_db.get_oauth_tokens("google") is None
+
+ async def test_delete_nonexistent_returns_false(
+ self, credentials_db: CredentialsDatabase
+ ):
+ assert await credentials_db.delete_oauth_tokens("nonexistent") is False
+
+ async def test_customer_id_isolation(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_oauth_tokens(
+ "google", "a-owner", "r-owner", customer_id="owner"
+ )
+ await credentials_db.save_oauth_tokens(
+ "google", "a-cust", "r-cust", customer_id="cust-1"
+ )
+
+ owner = await credentials_db.get_oauth_tokens("google", "owner")
+ cust = await credentials_db.get_oauth_tokens("google", "cust-1")
+ assert owner["access_token"] == "a-owner"
+ assert cust["access_token"] == "a-cust"
+
+ async def test_list_oauth_providers(self, credentials_db: CredentialsDatabase):
+ await credentials_db.save_oauth_tokens("google", "a", "r")
+ await credentials_db.save_oauth_tokens("twitter", "a", "r")
+
+ providers = await credentials_db.list_oauth_providers()
+ assert sorted(providers) == ["google", "twitter"]
+
+
+class TestTwoTableSeparation:
+ """Invariants 3 and 8 -- the two storage systems must not bleed into each other."""
+
+ async def test_oauth_tokens_invisible_via_get_api_key(
+ self, credentials_db: CredentialsDatabase
+ ):
+ await credentials_db.save_oauth_tokens("google", "access", "refresh")
+ # An API-key lookup for the same provider name finds nothing
+ assert await credentials_db.get_api_key("google") is None
+
+ async def test_api_key_invisible_via_get_oauth_tokens(
+ self, credentials_db: CredentialsDatabase
+ ):
+ # google_client_id is stored as an API key (Pattern C)
+ await credentials_db.save_api_key("google_client_id", "client-abc")
+ # Looking it up as an OAuth token finds nothing
+ assert await credentials_db.get_oauth_tokens("google_client_id") is None
+
+ async def test_provider_can_have_both_api_key_and_oauth_tokens(
+ self, credentials_db: CredentialsDatabase
+ ):
+ # Real-world: google_client_id (API key) AND google OAuth tokens coexist
+ await credentials_db.save_api_key("google_client_id", "client-id")
+ await credentials_db.save_api_key("google_client_secret", "client-sec")
+ await credentials_db.save_oauth_tokens("google", "access", "refresh")
+
+ assert await credentials_db.get_api_key("google_client_id") == "client-id"
+ assert await credentials_db.get_api_key("google_client_secret") == "client-sec"
+
+ tokens = await credentials_db.get_oauth_tokens("google")
+ assert tokens["access_token"] == "access"
+ assert tokens["refresh_token"] == "refresh"
+
+
+class TestSalt:
+ async def test_initialize_persists_salt(self, tmp_path):
+ from core.encryption import EncryptionService
+
+ db_path = tmp_path / "salt-test.db"
+
+ # First instance: generates salt
+ enc1 = EncryptionService()
+ db1 = CredentialsDatabase(str(db_path), enc1)
+ salt1 = await db1.initialize()
+ await db1.engine.dispose()
+
+ # Second instance: must load the same salt
+ enc2 = EncryptionService()
+ db2 = CredentialsDatabase(str(db_path), enc2)
+ salt2 = await db2.initialize()
+ await db2.engine.dispose()
+
+ assert salt1 == salt2
+ assert len(salt1) == 32
diff --git a/server/tests/credentials/test_encryption.py b/server/tests/credentials/test_encryption.py
new file mode 100644
index 00000000..92a3d1c2
--- /dev/null
+++ b/server/tests/credentials/test_encryption.py
@@ -0,0 +1,107 @@
+"""Tests for EncryptionService (Fernet + PBKDF2).
+
+Locks in invariant 13 from docs-internal/credentials_panel.md:
+ - Encryption is reversible for unicode and large payloads
+ - Tampered ciphertext raises ValueError
+ - Uninitialized service raises RuntimeError
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.encryption import EncryptionService
+
+
+pytestmark = pytest.mark.credentials
+
+
+class TestRoundTrip:
+ def test_ascii_roundtrip(self, encryption: EncryptionService):
+ assert encryption.decrypt(encryption.encrypt("sk-test-1234567890")) == "sk-test-1234567890"
+
+ def test_unicode_roundtrip(self, encryption: EncryptionService):
+ plaintext = "Привет мир — Здравствуй! 你好 🌍 emoji ✨"
+ assert encryption.decrypt(encryption.encrypt(plaintext)) == plaintext
+
+ def test_empty_string_roundtrip(self, encryption: EncryptionService):
+ assert encryption.decrypt(encryption.encrypt("")) == ""
+
+ def test_large_payload_roundtrip(self, encryption: EncryptionService):
+ plaintext = "x" * (64 * 1024)
+ assert encryption.decrypt(encryption.encrypt(plaintext)) == plaintext
+
+ def test_ciphertext_differs_from_plaintext(self, encryption: EncryptionService):
+ plaintext = "secret-api-key"
+ ciphertext = encryption.encrypt(plaintext)
+ assert ciphertext != plaintext
+ assert plaintext not in ciphertext
+
+ def test_two_encryptions_of_same_plaintext_differ(self, encryption: EncryptionService):
+ # Fernet uses a random IV per encryption -> ciphertexts must differ.
+ a = encryption.encrypt("same")
+ b = encryption.encrypt("same")
+ assert a != b
+ assert encryption.decrypt(a) == encryption.decrypt(b) == "same"
+
+
+class TestErrorPaths:
+ def test_uninitialized_encrypt_raises_runtime_error(
+ self, uninitialized_encryption: EncryptionService
+ ):
+ with pytest.raises(RuntimeError, match="not initialized"):
+ uninitialized_encryption.encrypt("data")
+
+ def test_uninitialized_decrypt_raises_runtime_error(
+ self, uninitialized_encryption: EncryptionService
+ ):
+ with pytest.raises(RuntimeError, match="not initialized"):
+ uninitialized_encryption.decrypt("anything")
+
+ def test_tampered_ciphertext_raises_value_error(self, encryption: EncryptionService):
+ ciphertext = encryption.encrypt("secret")
+ # Flip one character in the middle of the token
+ tampered = ciphertext[:-4] + "AAAA"
+ with pytest.raises(ValueError, match="Decryption failed"):
+ encryption.decrypt(tampered)
+
+ def test_garbage_ciphertext_raises_value_error(self, encryption: EncryptionService):
+ with pytest.raises(ValueError):
+ encryption.decrypt("not-a-fernet-token")
+
+ def test_wrong_key_raises_value_error(self, encryption_salt: bytes):
+ a = EncryptionService()
+ a.initialize("password-A", encryption_salt)
+ b = EncryptionService()
+ b.initialize("password-B", encryption_salt)
+
+ ciphertext = a.encrypt("secret")
+ with pytest.raises(ValueError):
+ b.decrypt(ciphertext)
+
+
+class TestSalt:
+ def test_generate_salt_is_32_bytes(self):
+ salt = EncryptionService.generate_salt()
+ assert isinstance(salt, bytes)
+ assert len(salt) == 32
+
+ def test_generate_salt_is_random(self):
+ salts = {EncryptionService.generate_salt() for _ in range(20)}
+ assert len(salts) == 20 # extremely unlikely to collide
+
+
+class TestState:
+ def test_is_initialized_false_before_initialize(
+ self, uninitialized_encryption: EncryptionService
+ ):
+ assert uninitialized_encryption.is_initialized() is False
+
+ def test_is_initialized_true_after_initialize(self, encryption: EncryptionService):
+ assert encryption.is_initialized() is True
+
+ def test_clear_resets_state(self, encryption: EncryptionService):
+ encryption.clear()
+ assert encryption.is_initialized() is False
+ with pytest.raises(RuntimeError):
+ encryption.encrypt("after-clear")
diff --git a/server/tests/credentials/test_google_oauth.py b/server/tests/credentials/test_google_oauth.py
new file mode 100644
index 00000000..dce1a2f1
--- /dev/null
+++ b/server/tests/credentials/test_google_oauth.py
@@ -0,0 +1,116 @@
+"""Tests for GoogleOAuth (Workspace OAuth 2.0 with offline access).
+
+Locks in invariant 11 from docs-internal/credentials_panel.md:
+ - Authorization URL contains access_type=offline AND prompt=consent
+ - State store consumed exactly once
+"""
+
+from __future__ import annotations
+
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+
+from services import google_oauth
+from services.google_oauth import GoogleOAuth, get_callback_paths
+
+
+pytestmark = pytest.mark.credentials
+
+
+def oauth():
+ google_oauth._oauth_states.clear()
+ return GoogleOAuth(
+ client_id="test-client-id.apps.googleusercontent.com",
+ client_secret="test-client-secret",
+ redirect_uri="http://localhost:3010/api/google/callback",
+ )
+
+
+class TestAuthorizationUrl:
+ def test_generates_url_and_state(self, oauth):
+ result = oauth.generate_authorization_url()
+ assert "url" in result
+ assert "state" in result
+ assert result["url"].startswith("https://accounts.google.com/o/oauth2/auth")
+
+ def test_url_contains_offline_access_and_consent_prompt(self, oauth):
+ """Invariant 11: refresh_token won't be issued without these params."""
+ result = oauth.generate_authorization_url()
+ params = parse_qs(urlparse(result["url"]).query)
+
+ assert params["access_type"] == ["offline"]
+ assert params["prompt"] == ["consent"]
+
+ def test_url_contains_required_scopes(self, oauth):
+ result = oauth.generate_authorization_url()
+ params = parse_qs(urlparse(result["url"]).query)
+ scope = params["scope"][0]
+ # A few representative scopes from each Google service must be present
+ for required in (
+ "openid",
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/gmail.send",
+ "https://www.googleapis.com/auth/calendar",
+ "https://www.googleapis.com/auth/drive",
+ ):
+ assert required in scope
+
+ def test_state_stored_with_redirect_uri_and_verifier(self, oauth):
+ result = oauth.generate_authorization_url()
+ state = result["state"]
+ assert state in google_oauth._oauth_states
+ stored = google_oauth._oauth_states[state]
+ assert stored["redirect_uri"] == oauth.redirect_uri
+ assert "created_at" in stored
+ # PKCE verifier may or may not be set depending on google-auth-oauthlib version
+ # but the key must be present
+ assert "code_verifier" in stored
+
+ def test_state_data_defaults_to_owner_mode(self, oauth):
+ result = oauth.generate_authorization_url()
+ stored = google_oauth._oauth_states[result["state"]]
+ assert stored["data"] == {"mode": "owner"}
+
+ def test_state_data_passes_through(self, oauth):
+ result = oauth.generate_authorization_url(
+ state_data={"customer_id": "cust-1", "mode": "customer"}
+ )
+ stored = google_oauth._oauth_states[result["state"]]
+ assert stored["data"]["customer_id"] == "cust-1"
+ assert stored["data"]["mode"] == "customer"
+
+ def test_two_calls_produce_different_state(self, oauth):
+ a = oauth.generate_authorization_url()
+ b = oauth.generate_authorization_url()
+ assert a["state"] != b["state"]
+
+
+class TestExchangeCode:
+ def test_unknown_state_fails(self, oauth):
+ # Don't even register a state -- exchange must fail without hitting Google.
+ result = oauth.exchange_code("code", "never-generated-state")
+ assert result["success"] is False
+ assert "state" in result["error"].lower()
+
+ def test_state_consumed_on_failure(self, oauth):
+ """Even if the token exchange fails, the state must be popped (single use)."""
+ auth = oauth.generate_authorization_url()
+ state = auth["state"]
+ # Exchange will fail because we haven't mocked Google -- network error
+ oauth.exchange_code("invalid-code", state)
+ # State must be gone regardless of success
+ assert state not in google_oauth._oauth_states
+
+
+class TestCallbackPaths:
+ def test_google_path_present(self):
+ paths = get_callback_paths()
+ assert "google" in paths
+ assert paths["google"].startswith("/api/")
+
+ def test_twitter_path_present(self):
+ paths = get_callback_paths()
+ assert "twitter" in paths
+ assert paths["twitter"].startswith("/api/")
diff --git a/server/tests/credentials/test_oauth_utils.py b/server/tests/credentials/test_oauth_utils.py
new file mode 100644
index 00000000..e0dffdc8
--- /dev/null
+++ b/server/tests/credentials/test_oauth_utils.py
@@ -0,0 +1,89 @@
+"""Tests for runtime OAuth redirect URI derivation.
+
+Locks in invariant 12 from docs-internal/credentials_panel.md:
+ - get_redirect_uri strips connection.base_url path and converts ws->http
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from services.oauth_utils import get_base_url, get_redirect_uri
+
+
+pytestmark = pytest.mark.credentials
+
+
+def _conn(base_url: str):
+ """Mimic Starlette WebSocket / Request which expose .base_url."""
+ return SimpleNamespace(base_url=base_url)
+
+
+class TestGetBaseUrl:
+ def test_ws_scheme_becomes_http(self):
+ assert get_base_url(_conn("ws://localhost:3010/ws/status")) == "http://localhost:3010"
+
+ def test_wss_scheme_becomes_https(self):
+ assert (
+ get_base_url(_conn("wss://flow.zeenie.xyz/ws/status"))
+ == "https://flow.zeenie.xyz"
+ )
+
+ def test_http_scheme_preserved(self):
+ assert (
+ get_base_url(_conn("http://localhost:3010/api/google"))
+ == "http://localhost:3010"
+ )
+
+ def test_https_scheme_preserved(self):
+ assert get_base_url(_conn("https://example.com/anything")) == "https://example.com"
+
+ def test_strips_trailing_slash(self):
+ assert get_base_url(_conn("http://localhost:3010/")) == "http://localhost:3010"
+
+ def test_preserves_non_default_port(self):
+ assert (
+ get_base_url(_conn("http://localhost:8080/anything"))
+ == "http://localhost:8080"
+ )
+
+
+class TestGetRedirectUri:
+ @patch("services.oauth_utils.get_callback_paths")
+ def test_google_dev_localhost(self, mock_paths):
+ mock_paths.return_value = {
+ "google": "/api/google/callback",
+ "twitter": "/api/twitter/callback",
+ }
+ uri = get_redirect_uri(_conn("ws://localhost:3010/ws/status"), "google")
+ assert uri == "http://localhost:3010/api/google/callback"
+
+ @patch("services.oauth_utils.get_callback_paths")
+ def test_twitter_prod_https(self, mock_paths):
+ mock_paths.return_value = {
+ "google": "/api/google/callback",
+ "twitter": "/api/twitter/callback",
+ }
+ uri = get_redirect_uri(_conn("wss://flow.zeenie.xyz/ws/status"), "twitter")
+ assert uri == "https://flow.zeenie.xyz/api/twitter/callback"
+
+ @patch("services.oauth_utils.get_callback_paths")
+ def test_unknown_provider_falls_back_to_default_path(self, mock_paths):
+ mock_paths.return_value = {} # no entries at all
+ uri = get_redirect_uri(
+ _conn("http://localhost:3010/anything"), "newprovider"
+ )
+ assert uri == "http://localhost:3010/api/newprovider/callback"
+
+ def test_paths_loaded_from_config_not_hardcoded(self):
+ """Smoke test: the real config must expose google + twitter paths."""
+ from services.google_oauth import get_callback_paths
+
+ paths = get_callback_paths()
+ assert "google" in paths
+ assert "twitter" in paths
+ assert paths["google"].startswith("/api/")
+ assert paths["twitter"].startswith("/api/")
diff --git a/server/tests/credentials/test_twitter_oauth.py b/server/tests/credentials/test_twitter_oauth.py
new file mode 100644
index 00000000..2332a3bf
--- /dev/null
+++ b/server/tests/credentials/test_twitter_oauth.py
@@ -0,0 +1,275 @@
+"""Tests for TwitterOAuth (PKCE flow).
+
+Locks in invariants 9 and 10 from docs-internal/credentials_panel.md:
+ - PKCE state consumed exactly once
+ - code_challenge = base64url(sha256(code_verifier))
+ - Authorization URL contains code_challenge_method=S256
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+from urllib.parse import parse_qs, urlparse
+
+import httpx
+import pytest
+import respx
+
+from services import twitter_oauth
+from services.twitter_oauth import (
+ TwitterOAuth,
+ TOKEN_URL,
+ REVOKE_URL,
+ USER_INFO_URL,
+)
+
+
+pytestmark = pytest.mark.credentials
+
+
+def oauth():
+ """Fresh TwitterOAuth + clean state store per test."""
+ twitter_oauth._oauth_states.clear()
+ return TwitterOAuth(
+ client_id="test-client-id",
+ client_secret="test-client-secret",
+ redirect_uri="http://localhost:3010/api/twitter/callback",
+ )
+
+
+def public_oauth():
+ """OAuth with no client_secret (public client uses client_id in body)."""
+ twitter_oauth._oauth_states.clear()
+ return TwitterOAuth(
+ client_id="test-client-id",
+ redirect_uri="http://localhost:3010/api/twitter/callback",
+ )
+
+
+class TestAuthorizationUrl:
+ def test_generates_url_state_and_verifier(self, oauth):
+ result = oauth.generate_authorization_url()
+ assert "url" in result and "state" in result and "code_verifier" in result
+ assert result["url"].startswith("https://x.com/i/oauth2/authorize?")
+
+ def test_url_contains_pkce_s256(self, oauth):
+ result = oauth.generate_authorization_url()
+ params = parse_qs(urlparse(result["url"]).query)
+ assert params["code_challenge_method"] == ["S256"]
+ assert params["response_type"] == ["code"]
+ assert params["client_id"] == ["test-client-id"]
+ assert (
+ params["redirect_uri"] == ["http://localhost:3010/api/twitter/callback"]
+ )
+ assert "code_challenge" in params
+ assert "state" in params
+
+ def test_code_challenge_is_sha256_of_verifier(self, oauth):
+ """Invariant 10: challenge = BASE64URL(SHA256(verifier))."""
+ result = oauth.generate_authorization_url()
+ params = parse_qs(urlparse(result["url"]).query)
+
+ verifier = result["code_verifier"]
+ expected_digest = hashlib.sha256(verifier.encode("ascii")).digest()
+ expected_challenge = base64.urlsafe_b64encode(expected_digest).rstrip(b"=").decode()
+
+ assert params["code_challenge"] == [expected_challenge]
+
+ def test_state_stored_with_verifier(self, oauth):
+ result = oauth.generate_authorization_url()
+ state = result["state"]
+ assert state in twitter_oauth._oauth_states
+ stored = twitter_oauth._oauth_states[state]
+ assert stored["code_verifier"] == result["code_verifier"]
+ assert stored["redirect_uri"] == oauth.redirect_uri
+ assert "created_at" in stored
+
+ def test_required_scopes_in_url(self, oauth):
+ result = oauth.generate_authorization_url()
+ params = parse_qs(urlparse(result["url"]).query)
+ scope = params["scope"][0]
+ for required in ("tweet.read", "tweet.write", "users.read", "offline.access"):
+ assert required in scope
+
+ def test_two_calls_produce_different_state_and_verifier(self, oauth):
+ a = oauth.generate_authorization_url()
+ b = oauth.generate_authorization_url()
+ assert a["state"] != b["state"]
+ assert a["code_verifier"] != b["code_verifier"]
+
+
+class TestExchangeCode:
+ @respx.mock
+ async def test_successful_exchange(self, oauth):
+ auth = oauth.generate_authorization_url()
+
+ respx.post(TOKEN_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "access_token": "access-xyz",
+ "refresh_token": "refresh-xyz",
+ "expires_in": 7200,
+ "scope": "tweet.read tweet.write",
+ "token_type": "bearer",
+ },
+ )
+ )
+
+ result = await oauth.exchange_code(code="auth-code", state=auth["state"])
+
+ assert result["success"] is True
+ assert result["access_token"] == "access-xyz"
+ assert result["refresh_token"] == "refresh-xyz"
+ assert result["expires_in"] == 7200
+
+ @respx.mock
+ async def test_state_consumed_exactly_once(self, oauth):
+ """Invariant 9: a second exchange with the same state must fail."""
+ auth = oauth.generate_authorization_url()
+ respx.post(TOKEN_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={"access_token": "a", "refresh_token": "r", "expires_in": 7200},
+ )
+ )
+
+ first = await oauth.exchange_code("code", auth["state"])
+ assert first["success"] is True
+
+ second = await oauth.exchange_code("code", auth["state"])
+ assert second["success"] is False
+ assert "state" in second["error"].lower()
+
+ async def test_unknown_state_fails(self, oauth):
+ result = await oauth.exchange_code("code", "never-generated-state")
+ assert result["success"] is False
+ assert "state" in result["error"].lower()
+
+ @respx.mock
+ async def test_token_endpoint_error_propagates(self, oauth):
+ auth = oauth.generate_authorization_url()
+ respx.post(TOKEN_URL).mock(
+ return_value=httpx.Response(
+ 400,
+ json={
+ "error": "invalid_grant",
+ "error_description": "auth code expired",
+ },
+ )
+ )
+
+ result = await oauth.exchange_code("code", auth["state"])
+ assert result["success"] is False
+ assert "expired" in result["error"]
+
+ @respx.mock
+ async def test_confidential_client_uses_basic_auth(self, oauth):
+ """Confidential client (with secret) must send Basic auth header."""
+ auth = oauth.generate_authorization_url()
+
+ captured = {}
+
+ def _capture(request):
+ captured["auth"] = request.headers.get("authorization")
+ captured["body"] = request.read().decode()
+ return httpx.Response(
+ 200,
+ json={"access_token": "a", "refresh_token": "r", "expires_in": 7200},
+ )
+
+ respx.post(TOKEN_URL).mock(side_effect=_capture)
+
+ await oauth.exchange_code("code", auth["state"])
+
+ assert captured["auth"] is not None
+ assert captured["auth"].startswith("Basic ")
+ # client_id should NOT be in body when Basic auth is used
+ assert "client_id=" not in captured["body"]
+
+ @respx.mock
+ async def test_public_client_includes_client_id_in_body(self, public_oauth):
+ auth = public_oauth.generate_authorization_url()
+
+ captured = {}
+
+ def _capture(request):
+ captured["auth"] = request.headers.get("authorization")
+ captured["body"] = request.read().decode()
+ return httpx.Response(
+ 200,
+ json={"access_token": "a", "refresh_token": "r", "expires_in": 7200},
+ )
+
+ respx.post(TOKEN_URL).mock(side_effect=_capture)
+
+ await public_oauth.exchange_code("code", auth["state"])
+
+ assert captured["auth"] is None
+ assert "client_id=test-client-id" in captured["body"]
+
+
+class TestRefreshAndRevoke:
+ @respx.mock
+ async def test_refresh_access_token(self, oauth):
+ respx.post(TOKEN_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "access_token": "new-access",
+ "refresh_token": "new-refresh",
+ "expires_in": 7200,
+ },
+ )
+ )
+
+ result = await oauth.refresh_access_token("old-refresh")
+ assert result["success"] is True
+ assert result["access_token"] == "new-access"
+
+ @respx.mock
+ async def test_revoke_token_success(self, oauth):
+ respx.post(REVOKE_URL).mock(return_value=httpx.Response(200, json={}))
+ result = await oauth.revoke_token("some-token", "access_token")
+ assert result["success"] is True
+
+
+class TestUserInfo:
+ @respx.mock
+ async def test_get_user_info(self, oauth):
+ respx.get(USER_INFO_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "data": {
+ "id": "12345",
+ "username": "testuser",
+ "name": "Test User",
+ "profile_image_url": "https://x.com/img.jpg",
+ "verified": True,
+ }
+ },
+ )
+ )
+
+ info = await oauth.get_user_info("access-token")
+ assert info["success"] is True
+ assert info["id"] == "12345"
+ assert info["username"] == "testuser"
+ assert info["verified"] is True
+
+ @respx.mock
+ async def test_get_user_info_401_returns_error(self, oauth):
+ respx.get(USER_INFO_URL).mock(
+ return_value=httpx.Response(
+ 401,
+ json={"title": "Unauthorized", "detail": "token expired"},
+ )
+ )
+
+ info = await oauth.get_user_info("bad-token")
+ assert info["success"] is False
+ assert "expired" in info["error"]
diff --git a/server/tests/credentials/test_websocket_handlers.py b/server/tests/credentials/test_websocket_handlers.py
new file mode 100644
index 00000000..b863a160
--- /dev/null
+++ b/server/tests/credentials/test_websocket_handlers.py
@@ -0,0 +1,288 @@
+"""Integration tests for credential-related WebSocket handlers.
+
+We invoke the handler functions directly (rather than spinning up the full FastAPI
+app + DI container) so the suite stays under 30s and doesn't pull in Temporal /
+LangChain / native LLM SDKs.
+
+Locks in invariants 1, 5, 6 from docs-internal/credentials_panel.md:
+ - WebSocket message types and payload shapes
+ - Status responses use snake_case has_key
+ - Provider Defaults uses dedicated handler, not save_api_key
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from routers import websocket as ws_module
+
+
+pytestmark = pytest.mark.credentials
+
+
+# --- Fake WebSocket ----------------------------------------------------------
+
+
+class _FakeWebSocket:
+ """Stand-in for starlette.WebSocket exposing only base_url + client_state."""
+
+ def __init__(self, base_url: str = "ws://localhost:3010/ws/status"):
+ self.base_url = base_url
+ # mimic starlette WebSocketState.CONNECTED
+ self.client_state = SimpleNamespace(name="CONNECTED")
+
+
+def fake_ws():
+ return _FakeWebSocket()
+
+
+# --- Container patching ------------------------------------------------------
+
+
+def patched_container(monkeypatch, auth_service):
+ """Wire the real auth_service fixture into the container singleton."""
+ monkeypatch.setattr(
+ ws_module.container, "auth_service", lambda: auth_service
+ )
+
+ # ai_service.fetch_models is called by handle_validate_api_key for LLM providers.
+ fake_ai = MagicMock()
+ fake_ai.fetch_models = AsyncMock(return_value=["model-a", "model-b"])
+ monkeypatch.setattr(ws_module.container, "ai_service", lambda: fake_ai)
+
+ # broadcaster is imported by name into routers.websocket -- must patch THERE,
+ # not on services.status_broadcaster (the bound name in the handler module).
+ fake_broadcaster = MagicMock()
+ fake_broadcaster.update_api_key_status = AsyncMock()
+ fake_broadcaster.broadcast = AsyncMock()
+ fake_broadcaster._status = {}
+ monkeypatch.setattr(ws_module, "get_status_broadcaster", lambda: fake_broadcaster)
+ # Also patch on the original module so any late imports (e.g. inside
+ # handle_google_oauth_status) get the same fake.
+ monkeypatch.setattr(
+ "services.status_broadcaster.get_status_broadcaster",
+ lambda: fake_broadcaster,
+ )
+ return SimpleNamespace(auth=auth_service, ai=fake_ai, broadcaster=fake_broadcaster)
+
+
+# --- Helper to bypass the decorator's required-fields check is not needed:
+# the decorator returns a wrapper we can call directly with the data dict.
+
+
+async def _call(handler, data, ws):
+ """Invoke a @ws_handler-decorated function."""
+ return await handler(data, ws)
+
+
+# --- API Key handlers --------------------------------------------------------
+
+
+class TestValidateApiKey:
+ @patch("services.ai.PROVIDER_CONFIGS", {"openai": object()})
+ async def test_validate_stores_key_with_models(
+ self, patched_container, fake_ws
+ ):
+ result = await _call(
+ ws_module.handle_validate_api_key,
+ {"provider": "OpenAI", "api_key": " sk-foo "},
+ fake_ws,
+ )
+
+ assert result["success"] is True
+ assert result["provider"] == "openai" # lowercased
+ assert result["valid"] is True
+ assert result["models"] == ["model-a", "model-b"]
+
+ # Stored
+ stored = await patched_container.auth.get_api_key("openai")
+ assert stored == "sk-foo" # whitespace stripped
+
+ # ai_service.fetch_models called with stripped key
+ patched_container.ai.fetch_models.assert_awaited_once_with("openai", "sk-foo")
+
+ # Broadcaster notified with hasKey + models
+ patched_container.broadcaster.update_api_key_status.assert_awaited_once()
+
+ @patch("services.ai.PROVIDER_CONFIGS", {})
+ async def test_validate_skips_model_fetch_for_non_llm(
+ self, patched_container, fake_ws
+ ):
+ result = await _call(
+ ws_module.handle_validate_api_key,
+ {"provider": "google_maps", "api_key": "AIza-test"},
+ fake_ws,
+ )
+
+ assert result["valid"] is True
+ assert result["models"] == []
+ patched_container.ai.fetch_models.assert_not_called()
+
+ async def test_missing_required_fields_returns_error(
+ self, patched_container, fake_ws
+ ):
+ result = await _call(
+ ws_module.handle_validate_api_key, {"provider": "openai"}, fake_ws
+ )
+ assert result["success"] is False
+ assert "api_key" in result["error"]
+
+
+class TestGetStoredApiKey:
+ async def test_returns_has_key_false_when_absent(
+ self, patched_container, fake_ws
+ ):
+ result = await _call(
+ ws_module.handle_get_stored_api_key, {"provider": "openai"}, fake_ws
+ )
+ assert result["success"] is True
+ assert result["has_key"] is False
+ assert "api_key" not in result
+
+ async def test_returns_key_and_models_when_present(
+ self, patched_container, fake_ws
+ ):
+ await patched_container.auth.store_api_key(
+ "openai", "sk-stored", models=["gpt-4", "gpt-3.5"]
+ )
+
+ result = await _call(
+ ws_module.handle_get_stored_api_key, {"provider": "OpenAI"}, fake_ws
+ )
+
+ assert result["has_key"] is True
+ assert result["api_key"] == "sk-stored"
+ assert result["models"] == ["gpt-4", "gpt-3.5"]
+ assert result["provider"] == "openai"
+
+
+class TestSaveApiKey:
+ async def test_save_persists_without_validation(
+ self, patched_container, fake_ws
+ ):
+ result = await _call(
+ ws_module.handle_save_api_key,
+ {
+ "provider": "telegram_bot_token",
+ "api_key": "123:abc",
+ "models": [],
+ },
+ fake_ws,
+ )
+
+ assert result["success"] is True
+ # No model fetch (Pattern C)
+ patched_container.ai.fetch_models.assert_not_called()
+
+ stored = await patched_container.auth.get_api_key("telegram_bot_token")
+ assert stored == "123:abc"
+
+ async def test_save_strips_whitespace_and_lowercases_provider(
+ self, patched_container, fake_ws
+ ):
+ await _call(
+ ws_module.handle_save_api_key,
+ {"provider": "ANTHROPIC", "api_key": " sk-ant-foo \n"},
+ fake_ws,
+ )
+ assert (
+ await patched_container.auth.get_api_key("anthropic") == "sk-ant-foo"
+ )
+
+
+class TestDeleteApiKey:
+ async def test_delete_removes_stored_key(self, patched_container, fake_ws):
+ await patched_container.auth.store_api_key("openai", "sk-x", models=[])
+ result = await _call(
+ ws_module.handle_delete_api_key, {"provider": "openai"}, fake_ws
+ )
+ assert result["success"] is True
+ assert await patched_container.auth.get_api_key("openai") is None
+
+
+# --- OAuth handlers ----------------------------------------------------------
+
+
+class TestTwitterOAuthHandlers:
+ async def test_login_fails_without_client_id(self, patched_container, fake_ws):
+ result = await _call(ws_module.handle_twitter_oauth_login, {}, fake_ws)
+ assert result["success"] is False
+ assert "Client ID" in result["error"]
+
+ async def test_login_returns_authorization_url(
+ self, patched_container, fake_ws
+ ):
+ await patched_container.auth.store_api_key(
+ "twitter_client_id", "ci-test", models=[]
+ )
+ await patched_container.auth.store_api_key(
+ "twitter_client_secret", "cs-test", models=[]
+ )
+
+ result = await _call(ws_module.handle_twitter_oauth_login, {}, fake_ws)
+
+ assert result["success"] is True
+ assert result["url"].startswith("https://x.com/i/oauth2/authorize")
+ assert "state" in result
+
+ async def test_status_when_disconnected(self, patched_container, fake_ws):
+ result = await _call(ws_module.handle_twitter_oauth_status, {}, fake_ws)
+ assert result["connected"] is False
+ assert result["username"] is None
+
+ async def test_logout_clears_oauth_tokens(self, patched_container, fake_ws):
+ # Pre-populate OAuth tokens
+ await patched_container.auth.store_oauth_tokens(
+ "twitter", "access", "refresh"
+ )
+ # Mock the revoke calls so we don't hit the network
+ with patch("services.twitter_oauth.TwitterOAuth.revoke_token", new=AsyncMock(return_value={"success": True})):
+ result = await _call(ws_module.handle_twitter_logout, {}, fake_ws)
+
+ assert result["success"] is True
+ assert await patched_container.auth.get_oauth_tokens("twitter") is None
+
+
+class TestGoogleOAuthHandlers:
+ async def test_login_fails_without_client_credentials(
+ self, patched_container, fake_ws
+ ):
+ result = await _call(ws_module.handle_google_oauth_login, {}, fake_ws)
+ assert result["success"] is False
+ assert "Client ID" in result["error"]
+
+ async def test_login_returns_authorization_url(
+ self, patched_container, fake_ws
+ ):
+ await patched_container.auth.store_api_key(
+ "google_client_id", "ci.apps.googleusercontent.com", models=[]
+ )
+ await patched_container.auth.store_api_key(
+ "google_client_secret", "cs-test", models=[]
+ )
+
+ result = await _call(ws_module.handle_google_oauth_login, {}, fake_ws)
+
+ assert result["success"] is True
+ assert result["url"].startswith("https://accounts.google.com/o/oauth2/auth")
+ assert "access_type=offline" in result["url"]
+ assert "prompt=consent" in result["url"]
+
+ async def test_status_when_disconnected(self, patched_container, fake_ws):
+ result = await _call(ws_module.handle_google_oauth_status, {}, fake_ws)
+ # success may be auto-injected by the decorator; check connected=False
+ assert result["connected"] is False
+ assert result["email"] is None
+
+ async def test_logout_removes_oauth_tokens(self, patched_container, fake_ws):
+ await patched_container.auth.store_oauth_tokens(
+ "google", "access", "refresh", email="[email protected]"
+ )
+ result = await _call(ws_module.handle_google_logout, {}, fake_ws)
+ assert result["success"] is True
+ assert await patched_container.auth.get_oauth_tokens("google") is None
diff --git a/server/tests/nodes/__init__.py b/server/tests/nodes/__init__.py
new file mode 100644
index 00000000..784b9c46
--- /dev/null
+++ b/server/tests/nodes/__init__.py
@@ -0,0 +1,6 @@
+"""Contract tests for workflow node handlers.
+
+Each test file in this package exercises one category of nodes through the
+NodeTestHarness, mocking external dependencies (httpx, SDKs, subprocesses)
+to lock down the handler's input -> output contract.
+"""
diff --git a/server/tests/nodes/_harness.py b/server/tests/nodes/_harness.py
new file mode 100644
index 00000000..28d5333e
--- /dev/null
+++ b/server/tests/nodes/_harness.py
@@ -0,0 +1,264 @@
+"""NodeTestHarness - drive any node handler through NodeExecutor with mocks.
+
+Usage:
+ async def test_my_node(harness):
+ result = await harness.execute(
+ node_type="braveSearch",
+ params={"query": "hello"},
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["query"] == "hello"
+
+The harness builds a NodeExecutor with stub services (Database, AIService,
+MapsService, TextService, AndroidService, Settings) so the registry dispatch
+runs end-to-end without any real I/O.
+"""
+
+from __future__ import annotations
+
+import time
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Awaitable, Callable, Dict, List, Optional
+from unittest.mock import AsyncMock, MagicMock
+
+
+@dataclass
+class HarnessContext:
+ """Captured state from a harness run, useful for assertions."""
+
+ output_store_calls: List[tuple] = field(default_factory=list)
+ """List of (session_id, node_id, output_key, value) tuples written by the executor."""
+
+
+class NodeTestHarness:
+ """Drives node handlers through NodeExecutor with mocked services."""
+
+ def __init__(
+ self,
+ database: Optional[MagicMock] = None,
+ ai_service: Optional[MagicMock] = None,
+ maps_service: Optional[MagicMock] = None,
+ text_service: Optional[MagicMock] = None,
+ android_service: Optional[MagicMock] = None,
+ settings: Optional[MagicMock] = None,
+ ):
+ # Lazy import so conftest stubs land before NodeExecutor pulls in core.logging.
+ from services.node_executor import NodeExecutor
+
+ self.database = database or _build_mock_database()
+ self.ai_service = ai_service or _build_mock_ai_service()
+ self.maps_service = maps_service or _build_mock_maps_service()
+ self.text_service = text_service or _build_mock_text_service()
+ self.android_service = android_service or _build_mock_android_service()
+ self.settings = settings or _build_mock_settings()
+ self.captured = HarnessContext()
+
+ self.executor = NodeExecutor(
+ database=self.database,
+ ai_service=self.ai_service,
+ maps_service=self.maps_service,
+ text_service=self.text_service,
+ android_service=self.android_service,
+ settings=self.settings,
+ output_store=self._record_output,
+ )
+
+ async def _record_output(self, session_id: str, node_id: str, key: str, value: Any) -> None:
+ """Capture writes to the output store so tests can inspect downstream state."""
+ self.captured.output_store_calls.append((session_id, node_id, key, value))
+
+ def build_context(
+ self,
+ *,
+ session_id: str = "test_session",
+ workflow_id: str = "test_workflow",
+ execution_id: Optional[str] = None,
+ nodes: Optional[List[Dict]] = None,
+ edges: Optional[List[Dict]] = None,
+ upstream_outputs: Optional[Dict[str, Any]] = None,
+ workspace_dir: Optional[str] = None,
+ extra: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """Synthesize the standard handler context dict.
+
+ upstream_outputs maps "<source_node_id>::<output_key>" -> value, so
+ get_output_fn can serve any handle the handler asks for.
+ """
+ outputs = upstream_outputs or {}
+
+ async def get_output_fn(sess: str, source_id: str, output_key: str) -> Any:
+ # Look up by composite key, then by source_id alone, then None
+ return outputs.get(f"{source_id}::{output_key}", outputs.get(source_id))
+
+ ctx: Dict[str, Any] = {
+ "session_id": session_id,
+ "workflow_id": workflow_id,
+ "execution_id": execution_id or str(uuid.uuid4())[:8],
+ "nodes": nodes or [],
+ "edges": edges or [],
+ "get_output_fn": get_output_fn,
+ "start_time": time.time(),
+ }
+ if workspace_dir is not None:
+ ctx["workspace_dir"] = workspace_dir
+ if extra:
+ ctx.update(extra)
+ return ctx
+
+ async def execute(
+ self,
+ node_type: str,
+ params: Optional[Dict[str, Any]] = None,
+ *,
+ node_id: Optional[str] = None,
+ context: Optional[Dict[str, Any]] = None,
+ upstream_outputs: Optional[Dict[str, Any]] = None,
+ nodes: Optional[List[Dict]] = None,
+ edges: Optional[List[Dict]] = None,
+ ) -> Dict[str, Any]:
+ """Run a node through the full executor pipeline."""
+ ctx = context or self.build_context(
+ upstream_outputs=upstream_outputs,
+ nodes=nodes,
+ edges=edges,
+ )
+ return await self.executor.execute(
+ node_id=node_id or f"test_{node_type}_{uuid.uuid4().hex[:6]}",
+ node_type=node_type,
+ parameters=params or {},
+ context=ctx,
+ )
+
+ async def call_handler(
+ self,
+ handler: Callable[..., Awaitable[Dict[str, Any]]],
+ params: Optional[Dict[str, Any]] = None,
+ *,
+ node_type: str = "test_node",
+ node_id: Optional[str] = None,
+ context: Optional[Dict[str, Any]] = None,
+ **handler_kwargs: Any,
+ ) -> Dict[str, Any]:
+ """Invoke a handler directly, bypassing dispatch.
+
+ Useful when a handler has injected service dependencies that the
+ registry binds via partial(). Pass them as handler_kwargs.
+ """
+ ctx = context or self.build_context()
+ return await handler(
+ node_id or f"direct_{node_type}",
+ node_type,
+ params or {},
+ ctx,
+ **handler_kwargs,
+ )
+
+ # ---------------------- assertion helpers ---------------------- #
+
+ @staticmethod
+ def assert_envelope(result: Dict[str, Any], *, success: Optional[bool] = None) -> None:
+ """Verify the result conforms to the standard handler envelope.
+
+ Required fields:
+ - success: bool
+ - on success=True: 'result' key present
+ - on success=False: 'error' key present
+ """
+ assert isinstance(result, dict), f"handler must return dict, got {type(result)}"
+ assert "success" in result, f"envelope missing 'success': {result}"
+ assert isinstance(result["success"], bool), "envelope 'success' must be bool"
+
+ if result["success"]:
+ assert "result" in result, f"successful envelope missing 'result': {result}"
+ else:
+ assert "error" in result, f"failed envelope missing 'error': {result}"
+ assert isinstance(result["error"], str), "envelope 'error' must be str"
+
+ if success is not None:
+ assert result["success"] is success, (
+ f"expected success={success}, got {result['success']} "
+ f"(error={result.get('error')})"
+ )
+
+ @staticmethod
+ def assert_output_shape(result: Dict[str, Any], expected_keys: List[str]) -> None:
+ """Verify the result payload has all expected top-level keys."""
+ assert result.get("success"), f"cannot check shape on failed envelope: {result}"
+ payload = result.get("result", {})
+ assert isinstance(payload, dict), f"result payload must be dict, got {type(payload)}"
+ missing = [k for k in expected_keys if k not in payload]
+ assert not missing, f"result payload missing keys {missing}: {payload}"
+
+ def output_for(self, node_id: str, key: str = "output_main") -> Any:
+ """Fetch the most recent value the executor wrote to the output store."""
+ for sess, nid, k, v in reversed(self.captured.output_store_calls):
+ if nid == node_id and k == key:
+ return v
+ return None
+
+
+# ---------------------- mock builders ---------------------- #
+
+
+def _build_mock_database() -> MagicMock:
+ db = MagicMock(name="Database")
+ db.get_node_parameters = AsyncMock(return_value={})
+ db.save_node_parameters = AsyncMock(return_value=None)
+ db.save_api_usage_metric = AsyncMock(return_value=None)
+ db.add_token_usage_metric = AsyncMock(return_value=None)
+ db.get_chat_messages = AsyncMock(return_value=[])
+ db.add_chat_message = AsyncMock(return_value=None)
+ db.add_console_log = AsyncMock(return_value=None)
+ return db
+
+
+def _build_mock_ai_service() -> MagicMock:
+ svc = MagicMock(name="AIService")
+ svc.auth = MagicMock(name="AuthService")
+ svc.auth.get_api_key = AsyncMock(return_value="test-api-key")
+ svc.auth.get_stored_models = AsyncMock(return_value=["test-model"])
+ svc.auth.get_oauth_tokens = AsyncMock(return_value=None)
+ svc.execute_chat = AsyncMock(return_value={
+ "success": True,
+ "result": {"response": "mocked response", "model": "test-model", "provider": "test"},
+ })
+ svc.execute_agent = AsyncMock(return_value={
+ "success": True,
+ "result": {"response": "mocked agent response", "model": "test-model"},
+ })
+ svc.execute_chat_agent = AsyncMock(return_value={
+ "success": True,
+ "result": {"response": "mocked chat agent response", "model": "test-model"},
+ })
+ svc.fetch_models = AsyncMock(return_value=["test-model-1", "test-model-2"])
+ return svc
+
+
+def _build_mock_maps_service() -> MagicMock:
+ svc = MagicMock(name="MapsService")
+ svc.geocode = AsyncMock(return_value={"lat": 0.0, "lng": 0.0})
+ svc.nearby_places = AsyncMock(return_value=[])
+ return svc
+
+
+def _build_mock_text_service() -> MagicMock:
+ svc = MagicMock(name="TextService")
+ svc.generate_text = AsyncMock(return_value="mocked text")
+ return svc
+
+
+def _build_mock_android_service() -> MagicMock:
+ svc = MagicMock(name="AndroidService")
+ svc.execute_action = AsyncMock(return_value={"success": True, "data": {}})
+ svc.is_connected = MagicMock(return_value=True)
+ return svc
+
+
+def _build_mock_settings() -> MagicMock:
+ settings = MagicMock(name="Settings")
+ settings.google_maps_api_key = ""
+ settings.workspace_base_dir = "data/workspaces"
+ settings.compaction_enabled = False
+ settings.compaction_threshold = 100000
+ return settings
diff --git a/server/tests/nodes/_mocks.py b/server/tests/nodes/_mocks.py
new file mode 100644
index 00000000..1b4cb735
--- /dev/null
+++ b/server/tests/nodes/_mocks.py
@@ -0,0 +1,170 @@
+"""Reusable mocks and patches for node handler tests.
+
+Most handlers reach out to global singletons via `from core.container import container`
+or `from services.X import get_X`. These helpers patch those entry points so tests
+remain hermetic.
+"""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from typing import Any, Dict, Iterator, Optional
+from unittest.mock import AsyncMock, MagicMock, patch
+
+
+# ---------------------- container patches ---------------------- #
+
+
+@contextmanager
+def patched_container(
+ *,
+ auth_api_keys: Optional[Dict[str, str]] = None,
+ auth_oauth_tokens: Optional[Dict[str, Dict[str, Any]]] = None,
+ database: Optional[MagicMock] = None,
+) -> Iterator[MagicMock]:
+ """Patch `core.container.container` so handlers see canned credentials and DB.
+
+ Args:
+ auth_api_keys: Map of provider -> api_key string returned by get_api_key.
+ auth_oauth_tokens: Map of provider -> token dict returned by get_oauth_tokens.
+ database: Optional MagicMock to use as the database; defaults to a stub.
+
+ Yields:
+ The patched container MagicMock so tests can inspect calls.
+ """
+ api_keys = auth_api_keys or {}
+ oauth_tokens = auth_oauth_tokens or {}
+
+ auth_service = MagicMock(name="AuthService")
+ auth_service.get_api_key = AsyncMock(side_effect=lambda provider, *a, **kw: api_keys.get(provider))
+ auth_service.get_oauth_tokens = AsyncMock(
+ side_effect=lambda provider, *a, **kw: oauth_tokens.get(provider)
+ )
+ auth_service.get_stored_models = AsyncMock(return_value=[])
+ # Awaitable async writes (handlers like Twitter call these in refresh paths)
+ auth_service.store_api_key = AsyncMock(return_value=True)
+ auth_service.store_oauth_tokens = AsyncMock(return_value=True)
+ auth_service.remove_oauth_tokens = AsyncMock(return_value=True)
+ auth_service.delete_api_key = AsyncMock(return_value=True)
+
+ db_mock = database or MagicMock(name="Database")
+ if database is None:
+ db_mock.save_api_usage_metric = AsyncMock(return_value=None)
+ db_mock.add_token_usage_metric = AsyncMock(return_value=None)
+ db_mock.get_node_parameters = AsyncMock(return_value={})
+ db_mock.save_node_parameters = AsyncMock(return_value=None)
+
+ container_mock = MagicMock(name="Container")
+ container_mock.auth_service = MagicMock(return_value=auth_service)
+ container_mock.database = MagicMock(return_value=db_mock)
+
+ with patch("core.container.container", container_mock):
+ yield container_mock
+
+
+# ---------------------- pricing service patch ---------------------- #
+
+
+@contextmanager
+def patched_pricing(total_cost: float = 0.001) -> Iterator[MagicMock]:
+ """Patch `services.pricing.get_pricing_service` to return canned cost data."""
+ pricing = MagicMock(name="PricingService")
+ pricing.calculate_api_cost = MagicMock(
+ return_value={"operation": "test", "total_cost": total_cost}
+ )
+ pricing.calculate_cost = MagicMock(
+ return_value={
+ "input_cost": 0.0,
+ "output_cost": 0.0,
+ "cache_cost": 0.0,
+ "total_cost": total_cost,
+ }
+ )
+ with patch("services.pricing.get_pricing_service", return_value=pricing):
+ yield pricing
+
+
+# ---------------------- status broadcaster patch ---------------------- #
+
+
+@contextmanager
+def patched_broadcaster() -> Iterator[MagicMock]:
+ """Patch the StatusBroadcaster singleton so handlers can broadcast freely.
+
+ Returns the broadcaster mock so tests can assert on calls like
+ update_node_status, broadcast_terminal_log, send_custom_event, etc.
+ """
+ broadcaster = MagicMock(name="StatusBroadcaster")
+ for method in (
+ "update_node_status",
+ "update_workflow_status",
+ "broadcast_terminal_log",
+ "send_custom_event",
+ "broadcast_message",
+ "_broadcast",
+ ):
+ setattr(broadcaster, method, AsyncMock(return_value=None))
+
+ with patch(
+ "services.status_broadcaster.get_status_broadcaster",
+ return_value=broadcaster,
+ ):
+ yield broadcaster
+
+
+# ---------------------- event waiter patch ---------------------- #
+
+
+@contextmanager
+def patched_event_waiter(canned_event: Optional[Dict[str, Any]] = None) -> Iterator[MagicMock]:
+ """Patch event_waiter so trigger nodes resolve immediately with canned data.
+
+ Args:
+ canned_event: Event payload to return from wait_for_event. Default is
+ an empty dict so trigger handlers complete without blocking.
+ """
+ event_data = canned_event if canned_event is not None else {}
+
+ waiter_mock = MagicMock(name="event_waiter")
+ waiter_mock.is_trigger_node = MagicMock(return_value=True)
+ waiter_mock.register = MagicMock(return_value=MagicMock(id="waiter-test-id"))
+ waiter_mock.wait_for_event = AsyncMock(return_value=event_data)
+ waiter_mock.cancel = MagicMock(return_value=True)
+ waiter_mock.dispatch = MagicMock(return_value=1)
+ waiter_mock.get_trigger_config = MagicMock(
+ return_value=MagicMock(
+ node_type="testTrigger",
+ event_type="test_event",
+ display_name="Test Trigger",
+ )
+ )
+
+ with patch("services.event_waiter", waiter_mock):
+ yield waiter_mock
+
+
+# ---------------------- subprocess patch ---------------------- #
+
+
+@contextmanager
+def patched_subprocess(
+ *,
+ stdout: bytes = b"",
+ stderr: bytes = b"",
+ returncode: int = 0,
+) -> Iterator[MagicMock]:
+ """Patch asyncio.create_subprocess_exec for shell/process_manager/browser handlers."""
+ proc = MagicMock(name="Subprocess")
+ proc.returncode = returncode
+ proc.communicate = AsyncMock(return_value=(stdout, stderr))
+ proc.wait = AsyncMock(return_value=returncode)
+ proc.terminate = MagicMock(return_value=None)
+ proc.kill = MagicMock(return_value=None)
+ proc.pid = 12345
+ proc.stdout = MagicMock()
+ proc.stdout.readline = AsyncMock(return_value=b"")
+ proc.stderr = MagicMock()
+ proc.stderr.readline = AsyncMock(return_value=b"")
+
+ with patch("asyncio.create_subprocess_exec", AsyncMock(return_value=proc)):
+ yield proc
diff --git a/server/tests/nodes/test_ai_agents.py b/server/tests/nodes/test_ai_agents.py
new file mode 100644
index 00000000..4c62b976
--- /dev/null
+++ b/server/tests/nodes/test_ai_agents.py
@@ -0,0 +1,494 @@
+"""Contract tests for ai_agents nodes: aiAgent, chatAgent, simpleMemory.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/ai_agents/`. A refactor that breaks any of
+these indicates the docs (and the user-visible contract) need to be updated.
+
+Invocation notes
+================
+- aiAgent / chatAgent go through NodeExecutor dispatch; the harness binds
+ `handle_ai_agent` / `handle_chat_agent` with stubbed `ai_service` and
+ `database`. We drive the connection-collection logic by building real
+ `nodes` + `edges` lists and asserting what the AsyncMock service receives.
+- simpleMemory is exercised through dispatch too; it uses the in-memory
+ `services.memory_store` module (NOT the markdown path used by agents),
+ so we also test the module-global state.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# Helpers
+# ============================================================================
+
+
+def _edge(source: str, target: str, target_handle: str) -> dict:
+ return {
+ "source": source,
+ "target": target,
+ "targetHandle": target_handle,
+ }
+
+
+def _node(node_id: str, node_type: str, label: str | None = None) -> dict:
+ return {
+ "id": node_id,
+ "type": node_type,
+ "data": {"label": label or node_type},
+ }
+
+
+# ============================================================================
+# aiAgent
+# ============================================================================
+
+
+class TestAIAgent:
+ """handle_ai_agent + _collect_agent_connections contract."""
+
+ async def test_happy_path_no_connections(self, harness):
+ """No connected nodes -> execute_agent called with no memory/skill/tool."""
+ result = await harness.execute(
+ "aiAgent",
+ {"prompt": "hello", "model": "gpt-test"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["response"] == "mocked agent response"
+
+ harness.ai_service.execute_agent.assert_awaited_once()
+ _, kwargs = harness.ai_service.execute_agent.call_args
+ assert kwargs["memory_data"] is None
+ assert kwargs["skill_data"] is None
+ assert kwargs["tool_data"] is None
+ assert kwargs["broadcaster"] is not None
+
+ async def test_memory_connection_forwarded_with_auto_session(self, harness):
+ """simpleMemory wired to input-memory -> memory_data forwarded.
+
+ When the memory node's sessionId is empty, the session falls back to
+ the agent's own node_id (documented auto-derivation).
+ """
+ agent_id = "agent-1"
+ mem_id = "mem-1"
+
+ harness.database.get_node_parameters = AsyncMock(
+ return_value={
+ "sessionId": "", # triggers auto-derivation
+ "windowSize": 7,
+ "memoryContent": "# Conversation History\n\n### **Human** (t)\nhi\n",
+ "longTermEnabled": True,
+ "retrievalCount": 5,
+ }
+ )
+
+ nodes = [_node(agent_id, "aiAgent"), _node(mem_id, "simpleMemory")]
+ edges = [_edge(mem_id, agent_id, "input-memory")]
+
+ result = await harness.execute(
+ "aiAgent",
+ {"prompt": "p", "model": "m"},
+ node_id=agent_id,
+ nodes=nodes,
+ edges=edges,
+ )
+
+ harness.assert_envelope(result, success=True)
+ _, kwargs = harness.ai_service.execute_agent.call_args
+ mem = kwargs["memory_data"]
+ assert mem is not None
+ assert mem["node_id"] == mem_id
+ assert mem["session_id"] == agent_id # auto-derived
+ assert mem["window_size"] == 7
+ assert mem["long_term_enabled"] is True
+ assert mem["retrieval_count"] == 5
+ assert "### **Human**" in mem["memory_content"]
+
+ async def test_memory_explicit_session_overrides_auto(self, harness):
+ agent_id = "agent-x"
+ mem_id = "mem-x"
+ harness.database.get_node_parameters = AsyncMock(
+ return_value={"sessionId": "shared-session", "windowSize": 3, "memoryContent": ""}
+ )
+
+ nodes = [_node(agent_id, "aiAgent"), _node(mem_id, "simpleMemory")]
+ edges = [_edge(mem_id, agent_id, "input-memory")]
+
+ await harness.execute(
+ "aiAgent", {"prompt": "p"},
+ node_id=agent_id, nodes=nodes, edges=edges,
+ )
+
+ _, kwargs = harness.ai_service.execute_agent.call_args
+ assert kwargs["memory_data"]["session_id"] == "shared-session"
+
+ async def test_tool_connection_forwarded(self, harness):
+ """A tool node wired to input-tools becomes a tool_data entry."""
+ agent_id = "agent-2"
+ tool_id = "calc-1"
+
+ harness.database.get_node_parameters = AsyncMock(
+ return_value={"toolName": "calculator"}
+ )
+
+ nodes = [_node(agent_id, "aiAgent"), _node(tool_id, "calculatorTool", "Calc")]
+ edges = [_edge(tool_id, agent_id, "input-tools")]
+
+ await harness.execute(
+ "aiAgent",
+ {"prompt": "compute", "model": "m"},
+ node_id=agent_id, nodes=nodes, edges=edges,
+ )
+
+ _, kwargs = harness.ai_service.execute_agent.call_args
+ tool_data = kwargs["tool_data"]
+ assert tool_data is not None
+ assert len(tool_data) == 1
+ assert tool_data[0]["node_id"] == tool_id
+ assert tool_data[0]["node_type"] == "calculatorTool"
+ assert tool_data[0]["label"] == "Calc"
+
+ async def test_master_skill_expands_enabled_skills_only(self, harness):
+ """masterSkill with enabled=True entries is expanded, disabled skipped."""
+ import sys
+ import types
+ from unittest.mock import patch
+
+ agent_id = "agent-3"
+ skill_id = "skill-1"
+
+ harness.database.get_node_parameters = AsyncMock(
+ return_value={
+ "skillsConfig": {
+ "python-skill": {"enabled": True, "instructions": "Use python."},
+ "shell-skill": {"enabled": False, "instructions": "ignored"},
+ }
+ }
+ )
+
+ # Stub skill loader so the fallback path isn't taken (instructions are present in DB)
+ fake_loader_mod = types.ModuleType("services.skill_loader")
+ fake_loader_mod.get_skill_loader = MagicMock(return_value=MagicMock())
+
+ nodes = [_node(agent_id, "aiAgent"), _node(skill_id, "masterSkill")]
+ edges = [_edge(skill_id, agent_id, "input-skill")]
+
+ with patch.dict(sys.modules, {"services.skill_loader": fake_loader_mod}):
+ await harness.execute(
+ "aiAgent", {"prompt": "p"},
+ node_id=agent_id, nodes=nodes, edges=edges,
+ )
+
+ _, kwargs = harness.ai_service.execute_agent.call_args
+ skill_data = kwargs["skill_data"]
+ assert skill_data is not None
+ assert len(skill_data) == 1 # shell-skill disabled -> skipped
+ assert skill_data[0]["skill_name"] == "python-skill"
+ assert skill_data[0]["parameters"]["instructions"] == "Use python."
+
+ async def test_task_completion_strips_all_tools(self, harness):
+ """When an input-task edge delivers a completed task, tool_data is cleared.
+
+ Documented as a CRITICAL FIX in the handler: binding tools while telling
+ the LLM "do not use tools" confused Gemini.
+ """
+ agent_id = "agent-4"
+ trigger_id = "task-trig-1"
+ tool_id = "tool-a"
+
+ task_payload = {
+ "task_id": "abc",
+ "status": "completed",
+ "agent_name": "coding_agent",
+ "result": "done",
+ }
+
+ async def db_params(node_id):
+ if node_id == tool_id:
+ return {"toolName": "calculator"}
+ return {}
+
+ harness.database.get_node_parameters = AsyncMock(side_effect=db_params)
+
+ nodes = [
+ _node(agent_id, "aiAgent"),
+ _node(trigger_id, "taskTrigger"),
+ _node(tool_id, "calculatorTool"),
+ ]
+ edges = [
+ _edge(trigger_id, agent_id, "input-task"),
+ _edge(tool_id, agent_id, "input-tools"),
+ ]
+
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+ # Inject the completed-task payload into context.outputs where
+ # _collect_agent_connections looks for input-task data.
+ ctx["outputs"] = {trigger_id: task_payload}
+
+ await harness.executor.execute(
+ node_id=agent_id,
+ node_type="aiAgent",
+ parameters={"prompt": "original", "model": "m"},
+ context=ctx,
+ )
+
+ _, kwargs = harness.ai_service.execute_agent.call_args
+ # Tools stripped on task completion
+ assert kwargs["tool_data"] is None
+
+ # Prompt got the task context prepended
+ sent_params = harness.ai_service.execute_agent.call_args.args[1]
+ assert "delegated task has completed" in sent_params["prompt"]
+ assert "original" in sent_params["prompt"]
+
+ async def test_service_error_propagates_through_envelope(self, harness):
+ """execute_agent can return a failure envelope; handler must pass it through."""
+ harness.ai_service.execute_agent = AsyncMock(
+ return_value={"success": False, "error": "provider 429"}
+ )
+
+ result = await harness.execute(
+ "aiAgent", {"prompt": "x", "model": "m"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "provider 429" in result["error"]
+
+
+# ============================================================================
+# chatAgent (Zeenie)
+# ============================================================================
+
+
+class TestChatAgent:
+ """handle_chat_agent - same collection logic as aiAgent, different service call."""
+
+ async def test_happy_path_routes_to_execute_chat_agent(self, harness):
+ result = await harness.execute(
+ "chatAgent",
+ {"prompt": "hi", "model": "m"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.ai_service.execute_chat_agent.assert_awaited_once()
+ # Must NOT call execute_agent
+ harness.ai_service.execute_agent.assert_not_awaited()
+ assert result["result"]["response"] == "mocked chat agent response"
+
+ async def test_empty_prompt_auto_fills_from_input_main(self, harness):
+ """chatAgent's key distinction: empty prompt + input-main -> use upstream output."""
+ chat_id = "chat-1"
+ upstream_id = "trigger-1"
+
+ nodes = [_node(chat_id, "chatAgent"), _node(upstream_id, "chatTrigger")]
+ edges = [_edge(upstream_id, chat_id, "input-main")]
+
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+ ctx["outputs"] = {upstream_id: {"message": "from upstream"}}
+
+ await harness.executor.execute(
+ node_id=chat_id,
+ node_type="chatAgent",
+ parameters={"prompt": "", "model": "m"}, # empty prompt
+ context=ctx,
+ )
+
+ sent_params = harness.ai_service.execute_chat_agent.call_args.args[1]
+ assert sent_params["prompt"] == "from upstream"
+
+ async def test_input_fallback_prefers_message_over_text_over_content(self, harness):
+ chat_id = "chat-2"
+ up_id = "up-2"
+ nodes = [_node(chat_id, "chatAgent"), _node(up_id, "httpRequest")]
+ edges = [_edge(up_id, chat_id, "input-main")]
+
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+ # All three present - message must win
+ ctx["outputs"] = {
+ up_id: {"message": "via-message", "text": "via-text", "content": "via-content"}
+ }
+
+ await harness.executor.execute(
+ node_id=chat_id,
+ node_type="chatAgent",
+ parameters={"prompt": ""},
+ context=ctx,
+ )
+
+ sent_params = harness.ai_service.execute_chat_agent.call_args.args[1]
+ assert sent_params["prompt"] == "via-message"
+
+ async def test_non_empty_prompt_is_NOT_overridden_by_input_data(self, harness):
+ """If prompt already has content, input_data must not clobber it."""
+ chat_id = "chat-3"
+ up_id = "up-3"
+ nodes = [_node(chat_id, "chatAgent"), _node(up_id, "chatTrigger")]
+ edges = [_edge(up_id, chat_id, "input-main")]
+
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+ ctx["outputs"] = {up_id: {"message": "should-not-leak"}}
+
+ await harness.executor.execute(
+ node_id=chat_id, node_type="chatAgent",
+ parameters={"prompt": "explicit"},
+ context=ctx,
+ )
+
+ sent_params = harness.ai_service.execute_chat_agent.call_args.args[1]
+ assert sent_params["prompt"] == "explicit"
+
+ async def test_orchestrator_adds_teammates_as_delegation_tools(self, harness):
+ """Team-lead types append input-teammates agents to tool_data."""
+ lead_id = "lead-1"
+ teammate_id = "worker-1"
+
+ async def db_params(node_id):
+ if node_id == teammate_id:
+ return {"provider": "openai", "model": "gpt"}
+ return {}
+
+ harness.database.get_node_parameters = AsyncMock(side_effect=db_params)
+
+ nodes = [
+ _node(lead_id, "orchestrator_agent"),
+ _node(teammate_id, "coding_agent", "CoderBot"),
+ ]
+ edges = [_edge(teammate_id, lead_id, "input-teammates")]
+
+ await harness.execute(
+ "orchestrator_agent",
+ {"prompt": "do a thing", "model": "m"},
+ node_id=lead_id, nodes=nodes, edges=edges,
+ )
+
+ _, kwargs = harness.ai_service.execute_chat_agent.call_args
+ tool_data = kwargs["tool_data"]
+ assert tool_data is not None and len(tool_data) == 1
+ assert tool_data[0]["node_type"] == "coding_agent"
+ assert tool_data[0]["label"] == "CoderBot"
+ # Teammate params come along so delegation knows provider/model
+ assert tool_data[0]["parameters"]["model"] == "gpt"
+
+ async def test_chat_agent_task_error_strips_tools(self, harness):
+ """Same tool-strip behaviour as aiAgent on task failure."""
+ chat_id = "chat-4"
+ trig_id = "trig-4"
+ tool_id = "tool-b"
+
+ async def db_params(nid):
+ return {"toolName": "calc"} if nid == tool_id else {}
+
+ harness.database.get_node_parameters = AsyncMock(side_effect=db_params)
+
+ nodes = [
+ _node(chat_id, "chatAgent"),
+ _node(trig_id, "taskTrigger"),
+ _node(tool_id, "calculatorTool"),
+ ]
+ edges = [
+ _edge(trig_id, chat_id, "input-task"),
+ _edge(tool_id, chat_id, "input-tools"),
+ ]
+
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+ ctx["outputs"] = {
+ trig_id: {"task_id": "x", "status": "error", "error": "boom", "agent_name": "web_agent"}
+ }
+
+ await harness.executor.execute(
+ node_id=chat_id, node_type="chatAgent",
+ parameters={"prompt": "p", "model": "m"},
+ context=ctx,
+ )
+
+ _, kwargs = harness.ai_service.execute_chat_agent.call_args
+ assert kwargs["tool_data"] is None
+ sent_params = harness.ai_service.execute_chat_agent.call_args.args[1]
+ assert "failed" in sent_params["prompt"].lower()
+
+
+# ============================================================================
+# simpleMemory
+# ============================================================================
+
+
+class TestSimpleMemory:
+ """handle_simple_memory reads from services.memory_store (NOT markdown)."""
+
+ @pytest.fixture(autouse=True)
+ def _reset_memory_store(self):
+ """Snapshot + restore the module-global session dict."""
+ from services import memory_store as ms
+
+ backup = dict(ms._sessions)
+ ms._sessions.clear()
+ try:
+ yield ms
+ finally:
+ ms._sessions.clear()
+ ms._sessions.update(backup)
+
+ async def test_happy_path_empty_session(self, harness, _reset_memory_store):
+ result = await harness.execute(
+ "simpleMemory",
+ {"sessionId": "sess-a", "memoryType": "buffer"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["session_id"] == "sess-a"
+ assert payload["messages"] == []
+ assert payload["message_count"] == 0
+ assert payload["memory_type"] == "buffer"
+ assert payload["window_size"] is None
+
+ async def test_window_mode_returns_last_n_messages(self, harness, _reset_memory_store):
+ ms = _reset_memory_store
+ for i in range(5):
+ ms.add_message("sess-b", "human", f"h{i}")
+ ms.add_message("sess-b", "ai", f"a{i}")
+
+ result = await harness.execute(
+ "simpleMemory",
+ {"sessionId": "sess-b", "memoryType": "window", "windowSize": 2},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["window_size"] == 2
+ # last 2 messages from a 10-message session
+ assert payload["message_count"] == 2
+ contents = [m["content"] for m in payload["messages"]]
+ assert contents == ["h4", "a4"]
+
+ async def test_clear_on_run_empties_session(self, harness, _reset_memory_store):
+ ms = _reset_memory_store
+ ms.add_message("sess-c", "human", "old")
+ ms.add_message("sess-c", "ai", "older")
+ assert len(ms._sessions["sess-c"].messages) == 2
+
+ result = await harness.execute(
+ "simpleMemory",
+ {"sessionId": "sess-c", "clearOnRun": True},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["message_count"] == 0
+ # Session still exists but emptied
+ assert ms._sessions["sess-c"].messages == []
+
+ async def test_default_session_when_omitted(self, harness, _reset_memory_store):
+ result = await harness.execute("simpleMemory", {})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["session_id"] == "default"
+ assert result["result"]["memory_type"] == "buffer"
+ assert result["result"]["window_size"] is None
diff --git a/server/tests/nodes/test_ai_chat_models.py b/server/tests/nodes/test_ai_chat_models.py
new file mode 100644
index 00000000..63cc98e9
--- /dev/null
+++ b/server/tests/nodes/test_ai_chat_models.py
@@ -0,0 +1,383 @@
+"""Contract tests for the 9 ai_chat_models nodes.
+
+Covered nodes: openaiChatModel, anthropicChatModel, geminiChatModel,
+openrouterChatModel, groqChatModel, cerebrasChatModel, deepseekChatModel,
+kimiChatModel, mistralChatModel.
+
+All 9 nodes share the SAME registry binding:
+ partial(handle_ai_chat_model, ai_service=self.ai_service)
+
+`handle_ai_chat_model` is a thin pass-through that awaits
+`ai_service.execute_chat(node_id, node_type, parameters)`. The harness
+fixture pre-wires `ai_service.execute_chat` as an AsyncMock returning a
+canned success envelope, so tests focus on:
+
+ 1. Parametrized happy path across every provider (envelope + dispatch).
+ 2. Handler forwards parameters verbatim (prompt, model, thinking flags).
+ 3. Error-path envelope propagation when execute_chat returns success=False.
+ 4. Per-provider quirks documented in the *.md files
+ (temperature clamp, reasoning params, thinking defaults, etc.).
+
+These tests freeze the behaviour documented in
+`docs-internal/node-logic-flows/ai_chat_models/`. A refactor that breaks
+any of these indicates the docs (and the user-visible contract) need to
+be updated.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock
+
+import pytest
+
+
+pytestmark = pytest.mark.node_contract
+
+
+ALL_PROVIDERS = [
+ ("openaiChatModel", "openai"),
+ ("anthropicChatModel", "anthropic"),
+ ("geminiChatModel", "gemini"),
+ ("openrouterChatModel", "openrouter"),
+ ("groqChatModel", "groq"),
+ ("cerebrasChatModel", "cerebras"),
+ ("deepseekChatModel", "deepseek"),
+ ("kimiChatModel", "kimi"),
+ ("mistralChatModel", "mistral"),
+]
+
+
+def _canned_success(provider: str, model: str = "test-model", response: str = "hi"):
+ """Helper: build the canned LLMResponse envelope execute_chat returns."""
+ return {
+ "success": True,
+ "node_id": "test-node",
+ "node_type": f"{provider}ChatModel",
+ "result": {
+ "response": response,
+ "thinking": None,
+ "thinking_enabled": False,
+ "model": model,
+ "provider": provider,
+ "finish_reason": "stop",
+ "timestamp": "2026-04-15T00:00:00",
+ "input": {"prompt": "hello", "system_prompt": ""},
+ },
+ "execution_time": 0.01,
+ }
+
+
+# ============================================================================
+# Shared happy-path sweep - one test, parametrized across all 9 nodes
+# ============================================================================
+
+
+class TestAllChatModelsHappyPath:
+ """The happy-path contract is identical for every chat-model node."""
+
+ @pytest.mark.parametrize("node_type,provider", ALL_PROVIDERS)
+ async def test_dispatches_to_execute_chat_and_returns_envelope(
+ self, harness, node_type, provider
+ ):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success(provider))
+
+ result = await harness.execute(
+ node_type,
+ {"prompt": "hello", "model": "test-model"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result,
+ ["response", "thinking", "thinking_enabled", "model", "provider", "finish_reason"],
+ )
+ assert result["result"]["provider"] == provider
+
+ # One dispatch into execute_chat with the node_type the user chose.
+ assert harness.ai_service.execute_chat.await_count == 1
+ call = harness.ai_service.execute_chat.await_args
+ assert call.args[1] == node_type # execute_chat(node_id, node_type, params)
+ params = call.args[2]
+ assert params["prompt"] == "hello"
+ assert params["model"] == "test-model"
+
+ @pytest.mark.parametrize("node_type,provider", ALL_PROVIDERS)
+ async def test_api_key_auto_injected_by_executor(
+ self, harness, node_type, provider
+ ):
+ """NodeExecutor._inject_api_keys must fetch 'api_key' per provider."""
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success(provider))
+
+ await harness.execute(node_type, {"prompt": "hi"})
+
+ # auth.get_api_key was called with the provider derived from node_type
+ calls = [c.args for c in harness.ai_service.auth.get_api_key.await_args_list]
+ assert any(c[0] == provider for c in calls), (
+ f"expected get_api_key({provider}, ...) for {node_type}, got {calls}"
+ )
+
+ # And the injected api_key landed in the params dict execute_chat saw
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params.get("api_key") == "test-api-key"
+
+ @pytest.mark.parametrize("node_type,provider", ALL_PROVIDERS)
+ async def test_error_envelope_propagates(self, harness, node_type, provider):
+ harness.ai_service.execute_chat = AsyncMock(
+ return_value={
+ "success": False,
+ "node_id": "test-node",
+ "node_type": node_type,
+ "error": "API key is required",
+ "execution_time": 0.0,
+ "timestamp": "2026-04-15T00:00:00",
+ }
+ )
+
+ result = await harness.execute(node_type, {"prompt": "hi"})
+
+ harness.assert_envelope(result, success=False)
+ assert "api key" in result["error"].lower()
+
+
+# ============================================================================
+# Parameter forwarding: thinking config flows verbatim through the handler
+# ============================================================================
+
+
+class TestThinkingParamForwarding:
+ """The handler does NOT interpret thinking params - it forwards them.
+ Interpretation happens inside AIService.execute_chat. We just verify
+ that whatever the user sets reaches execute_chat untouched.
+ """
+
+ @pytest.mark.parametrize("node_type,provider", ALL_PROVIDERS)
+ async def test_thinking_flags_forwarded(self, harness, node_type, provider):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success(provider))
+
+ await harness.execute(
+ node_type,
+ {
+ "prompt": "hi",
+ "thinkingEnabled": True,
+ "thinkingBudget": 4096,
+ "reasoningEffort": "high",
+ "reasoningFormat": "parsed",
+ },
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params["thinkingEnabled"] is True
+ assert params["thinkingBudget"] == 4096
+ assert params["reasoningEffort"] == "high"
+ assert params["reasoningFormat"] == "parsed"
+
+ @pytest.mark.parametrize("node_type,provider", ALL_PROVIDERS)
+ async def test_system_message_forwarded(self, harness, node_type, provider):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success(provider))
+
+ await harness.execute(
+ node_type,
+ {"prompt": "hi", "systemMessage": "You are terse."},
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ # Handler does not normalize - raw param key reaches execute_chat
+ assert params["systemMessage"] == "You are terse."
+
+
+# ============================================================================
+# Provider-specific quirks documented in the *.md docs
+# ============================================================================
+
+
+class TestOpenRouterFreePrefix:
+ """OpenRouter's docs note the [FREE] prefix is purely cosmetic.
+ The handler itself passes it through; stripping happens in execute_chat.
+ """
+
+ async def test_free_prefix_reaches_execute_chat_verbatim(self, harness):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success("openrouter"))
+
+ await harness.execute(
+ "openrouterChatModel",
+ {"prompt": "hi", "model": "[FREE] google/gemma-7b-it"},
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ # Handler does not strip - that's execute_chat's job
+ assert params["model"] == "[FREE] google/gemma-7b-it"
+
+
+class TestOpenRouterSlashPrefixPreserved:
+ """Unique to OpenRouter: owner/model slash is load-bearing.
+ execute_chat preserves it when provider=='openrouter', strips it
+ otherwise. Here we only confirm the handler passes the model through."""
+
+ async def test_owner_model_slash_passes_through_handler(self, harness):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success("openrouter"))
+
+ await harness.execute(
+ "openrouterChatModel",
+ {"prompt": "hi", "model": "anthropic/claude-3.5-sonnet"},
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params["model"] == "anthropic/claude-3.5-sonnet"
+
+
+class TestAnthropicHyphenatedModelIds:
+ """Docs: Anthropic uses hyphens (claude-sonnet-4-6), not dots.
+ Handler passes the model string through unchanged - it is execute_chat /
+ the Anthropic SDK that ultimately rejects dotted IDs.
+ """
+
+ async def test_hyphenated_model_forwarded(self, harness):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success("anthropic"))
+
+ await harness.execute(
+ "anthropicChatModel",
+ {"prompt": "hi", "model": "claude-sonnet-4-6"},
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params["model"] == "claude-sonnet-4-6"
+
+
+class TestKimiThinkingDefault:
+ """Docs: Kimi k2.5 defaults thinking=ON. The handler itself does not
+ apply the default - it just forwards whatever the frontend submitted.
+ This test pins the pass-through behaviour.
+ """
+
+ async def test_kimi_handler_forwards_thinking_disabled_verbatim(self, harness):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success("kimi"))
+
+ await harness.execute(
+ "kimiChatModel",
+ {"prompt": "hi", "thinkingEnabled": False},
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params["thinkingEnabled"] is False
+
+
+class TestGroqReasoningFormat:
+ """Docs: only Qwen3-32b honors reasoningFormat. Handler passes both
+ the format and the model through unchanged."""
+
+ async def test_reasoning_format_hidden_forwarded(self, harness):
+ harness.ai_service.execute_chat = AsyncMock(return_value=_canned_success("groq"))
+
+ await harness.execute(
+ "groqChatModel",
+ {
+ "prompt": "hi",
+ "model": "qwen/qwen3-32b",
+ "thinkingEnabled": True,
+ "reasoningFormat": "hidden",
+ },
+ )
+
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params["reasoningFormat"] == "hidden"
+ assert params["model"] == "qwen/qwen3-32b"
+
+
+class TestDeepseekReasonerAlwaysOnCoT:
+ """Docs: deepseek-reasoner produces reasoning_content regardless of
+ thinkingEnabled. Handler just forwards. Assert the thinking field in
+ the canned response surfaces back through the envelope.
+ """
+
+ async def test_thinking_content_surfaces_in_envelope(self, harness):
+ canned = _canned_success("deepseek", model="deepseek-reasoner")
+ canned["result"]["thinking"] = "step 1: ... step 2: ..."
+ canned["result"]["thinking_enabled"] = False # reasoner CoT is always-on
+ harness.ai_service.execute_chat = AsyncMock(return_value=canned)
+
+ result = await harness.execute(
+ "deepseekChatModel",
+ {"prompt": "hi", "model": "deepseek-reasoner"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["thinking"] == "step 1: ... step 2: ..."
+ assert result["result"]["thinking_enabled"] is False
+
+
+class TestMistralNoThinking:
+ """Docs: Mistral does not support thinking. Handler still forwards the
+ flag (execute_chat / provider SDK ignore it). Envelope should show
+ thinking=null."""
+
+ async def test_thinking_flag_forwarded_but_result_has_null_thinking(self, harness):
+ canned = _canned_success("mistral", model="mistral-large-latest")
+ canned["result"]["thinking"] = None
+ canned["result"]["thinking_enabled"] = False
+ harness.ai_service.execute_chat = AsyncMock(return_value=canned)
+
+ result = await harness.execute(
+ "mistralChatModel",
+ {
+ "prompt": "hi",
+ "model": "mistral-large-latest",
+ "thinkingEnabled": True, # User tries to enable
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ # Handler forwarded the user's flag
+ params = harness.ai_service.execute_chat.await_args.args[2]
+ assert params["thinkingEnabled"] is True
+ # But envelope reflects Mistral's lack of support
+ assert result["result"]["thinking"] is None
+ assert result["result"]["thinking_enabled"] is False
+
+
+# ============================================================================
+# Empty prompt / missing api_key behaviour
+# ============================================================================
+
+
+class TestValidationErrors:
+ """The handler delegates validation to AIService.execute_chat, which
+ raises ValueError on empty prompt or missing api_key and catches it
+ into an error envelope. We pin that contract here by having the mock
+ mirror the real behaviour.
+ """
+
+ async def test_empty_prompt_returns_error_envelope(self, harness):
+ harness.ai_service.execute_chat = AsyncMock(
+ return_value={
+ "success": False,
+ "node_id": "test-node",
+ "node_type": "openaiChatModel",
+ "error": "Prompt cannot be empty",
+ "execution_time": 0.0,
+ "timestamp": "2026-04-15T00:00:00",
+ }
+ )
+
+ result = await harness.execute("openaiChatModel", {"prompt": ""})
+
+ harness.assert_envelope(result, success=False)
+ assert "prompt" in result["error"].lower()
+
+ async def test_missing_api_key_returns_error_envelope(self, harness):
+ # Override auth to return None for the key
+ harness.ai_service.auth.get_api_key = AsyncMock(return_value=None)
+ harness.ai_service.execute_chat = AsyncMock(
+ return_value={
+ "success": False,
+ "node_id": "test-node",
+ "node_type": "openaiChatModel",
+ "error": "API key is required",
+ "execution_time": 0.0,
+ "timestamp": "2026-04-15T00:00:00",
+ }
+ )
+
+ result = await harness.execute("openaiChatModel", {"prompt": "hi"})
+
+ harness.assert_envelope(result, success=False)
+ assert "api key" in result["error"].lower()
diff --git a/server/tests/nodes/test_ai_tools.py b/server/tests/nodes/test_ai_tools.py
new file mode 100644
index 00000000..5150a949
--- /dev/null
+++ b/server/tests/nodes/test_ai_tools.py
@@ -0,0 +1,481 @@
+"""Contract tests for ai_tools nodes: calculatorTool, currentTimeTool,
+duckduckgoSearch, taskManager, writeTodos.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/ai_tools/`. A refactor that breaks any of
+these indicates the docs (and the user-visible contract) need to be updated.
+
+Notes on invocation paths
+=========================
+- calculatorTool / currentTimeTool / duckduckgoSearch are tool-only (not
+ registered in NodeExecutor._handlers). Their real contract is the internal
+ `_execute_*` function invoked via `execute_tool`, so tests call those
+ functions directly with the same arg shape the tool dispatcher would pass.
+- taskManager and writeTodos ARE in the NodeExecutor registry; they are
+ exercised through the shared `harness` where it makes sense and via the
+ handler directly when we need to inject a mock broadcaster / database.
+"""
+
+from __future__ import annotations
+
+import math
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# calculatorTool
+# ============================================================================
+
+
+class TestCalculatorTool:
+ """Pure-function arithmetic: no network, no state."""
+
+ @pytest.mark.parametrize(
+ "op,a,b,expected",
+ [
+ ("add", 2, 3, 5),
+ ("subtract", 10, 4, 6),
+ ("multiply", 6, 7, 42),
+ ("divide", 20, 5, 4),
+ ("power", 2, 10, 1024),
+ ("mod", 10, 3, 1),
+ ("abs", -7, 0, 7),
+ ],
+ )
+ async def test_supported_operations_compute_expected_result(self, op, a, b, expected):
+ from services.handlers.tools import _execute_calculator
+
+ result = await _execute_calculator({"operation": op, "a": a, "b": b})
+
+ assert result["operation"] == op
+ assert result["a"] == float(a)
+ assert result["b"] == float(b)
+ assert result["result"] == pytest.approx(expected)
+
+ async def test_sqrt_uses_abs_for_negative_input(self):
+ from services.handlers.tools import _execute_calculator
+
+ result = await _execute_calculator({"operation": "sqrt", "a": -9})
+ assert result["result"] == pytest.approx(3.0)
+
+ async def test_divide_by_zero_returns_infinity(self):
+ from services.handlers.tools import _execute_calculator
+
+ result = await _execute_calculator({"operation": "divide", "a": 5, "b": 0})
+ assert result["result"] == math.inf
+
+ async def test_mod_by_zero_returns_zero(self):
+ from services.handlers.tools import _execute_calculator
+
+ result = await _execute_calculator({"operation": "mod", "a": 5, "b": 0})
+ assert result["result"] == 0
+
+ async def test_unknown_operation_returns_error_with_supported_list(self):
+ from services.handlers.tools import _execute_calculator
+
+ result = await _execute_calculator({"operation": "quantum", "a": 1, "b": 2})
+ assert "error" in result
+ assert "quantum" in result["error"]
+ supported = result["supported_operations"]
+ assert set(supported) == {
+ "add", "subtract", "multiply", "divide",
+ "power", "sqrt", "mod", "abs",
+ }
+
+ async def test_non_numeric_operand_raises(self):
+ # Documented quirk: handler does not catch ValueError on float()
+ # conversion -- it propagates to the caller. Frozen as-is so the
+ # refactor doesn't accidentally swallow it.
+ import pytest as _pytest
+
+ from services.handlers.tools import _execute_calculator
+
+ with _pytest.raises(ValueError):
+ await _execute_calculator({"operation": "add", "a": "abc", "b": 1})
+
+ async def test_operation_is_case_insensitive(self):
+ from services.handlers.tools import _execute_calculator
+
+ result = await _execute_calculator({"operation": "ADD", "a": 1, "b": 2})
+ assert result["result"] == 3
+
+
+# ============================================================================
+# currentTimeTool
+# ============================================================================
+
+
+class TestCurrentTimeTool:
+ """datetime.now(tz) wrapper - timezone resolution + error path."""
+
+ async def test_happy_path_returns_documented_fields(self):
+ from services.handlers.tools import _execute_current_time
+
+ result = await _execute_current_time({"timezone": "UTC"}, {})
+
+ assert set(result.keys()) == {
+ "datetime", "date", "time", "timezone",
+ "day_of_week", "timestamp",
+ }
+ assert result["timezone"] == "UTC"
+ assert isinstance(result["timestamp"], int)
+ # basic shape checks
+ assert len(result["date"].split("-")) == 3
+ assert len(result["time"].split(":")) == 3
+
+ async def test_arg_timezone_overrides_node_param(self):
+ from services.handlers.tools import _execute_current_time
+
+ result = await _execute_current_time(
+ {"timezone": "America/New_York"},
+ {"timezone": "UTC"},
+ )
+ assert result["timezone"] == "America/New_York"
+
+ async def test_empty_arg_falls_back_to_node_param(self):
+ from services.handlers.tools import _execute_current_time
+
+ result = await _execute_current_time({"timezone": ""}, {"timezone": "Europe/London"})
+ assert result["timezone"] == "Europe/London"
+
+ async def test_no_timezone_anywhere_defaults_to_utc(self):
+ from services.handlers.tools import _execute_current_time
+
+ result = await _execute_current_time({}, {})
+ assert result["timezone"] == "UTC"
+
+ async def test_invalid_timezone_returns_error_dict(self):
+ from services.handlers.tools import _execute_current_time
+
+ result = await _execute_current_time({"timezone": "Mars/OlympusMons"}, {})
+ assert "error" in result
+ assert "Invalid timezone" in result["error"]
+ # must not raise; must not return the happy-path fields
+ assert "datetime" not in result
+
+
+# ============================================================================
+# duckduckgoSearch
+# ============================================================================
+
+
+class TestDuckDuckGoSearch:
+ """ddgs-library wrapper; heavy mocking so no real network is touched."""
+
+ async def test_happy_path_maps_ddgs_results_to_documented_shape(self):
+ from services.handlers import tools as tools_mod
+
+ fake_ddgs_instance = MagicMock()
+ fake_ddgs_instance.text.return_value = [
+ {"title": "A", "body": "snippet A", "href": "https://a.example"},
+ {"title": "B", "body": "snippet B", "href": "https://b.example"},
+ ]
+ fake_ddgs_class = MagicMock(return_value=fake_ddgs_instance)
+
+ fake_module = MagicMock()
+ fake_module.DDGS = fake_ddgs_class
+
+ with patch.dict("sys.modules", {"ddgs": fake_module}):
+ result = await tools_mod._execute_duckduckgo_search(
+ {"query": "python"},
+ {"provider": "duckduckgo", "maxResults": 2},
+ )
+
+ assert result["query"] == "python"
+ assert result["provider"] == "duckduckgo"
+ assert result["results"] == [
+ {"title": "A", "snippet": "snippet A", "url": "https://a.example"},
+ {"title": "B", "snippet": "snippet B", "url": "https://b.example"},
+ ]
+ fake_ddgs_instance.text.assert_called_once_with("python", max_results=2)
+
+ async def test_empty_query_short_circuits_before_import(self):
+ from services.handlers.tools import _execute_duckduckgo_search
+
+ result = await _execute_duckduckgo_search({"query": ""}, {})
+ assert result == {"error": "No search query provided"}
+
+ async def test_missing_keys_in_ddgs_output_default_to_empty_string(self):
+ from services.handlers import tools as tools_mod
+
+ fake_ddgs_instance = MagicMock()
+ fake_ddgs_instance.text.return_value = [{"title": "only-title"}]
+ fake_module = MagicMock()
+ fake_module.DDGS = MagicMock(return_value=fake_ddgs_instance)
+
+ with patch.dict("sys.modules", {"ddgs": fake_module}):
+ result = await tools_mod._execute_duckduckgo_search(
+ {"query": "q"},
+ {"maxResults": 5},
+ )
+
+ assert result["results"] == [{"title": "only-title", "snippet": "", "url": ""}]
+
+ async def test_max_results_defaults_to_5_when_missing(self):
+ from services.handlers import tools as tools_mod
+
+ fake_ddgs_instance = MagicMock()
+ fake_ddgs_instance.text.return_value = []
+ fake_module = MagicMock()
+ fake_module.DDGS = MagicMock(return_value=fake_ddgs_instance)
+
+ with patch.dict("sys.modules", {"ddgs": fake_module}):
+ await tools_mod._execute_duckduckgo_search({"query": "q"}, {})
+
+ fake_ddgs_instance.text.assert_called_once_with("q", max_results=5)
+
+
+# ============================================================================
+# taskManager
+# ============================================================================
+
+
+class TestTaskManager:
+ """In-memory delegation-registry inspector. State lives in module globals
+ `_delegated_tasks` and `_delegation_results` in services.handlers.tools."""
+
+ @pytest.fixture(autouse=True)
+ def _reset_registry(self):
+ """Snapshot + restore the module-level dicts around each test."""
+ from services.handlers import tools as tools_mod
+
+ tasks_backup = dict(tools_mod._delegated_tasks)
+ results_backup = dict(tools_mod._delegation_results)
+ tools_mod._delegated_tasks.clear()
+ tools_mod._delegation_results.clear()
+ try:
+ yield tools_mod
+ finally:
+ tools_mod._delegated_tasks.clear()
+ tools_mod._delegated_tasks.update(tasks_backup)
+ tools_mod._delegation_results.clear()
+ tools_mod._delegation_results.update(results_backup)
+
+ async def test_list_tasks_reports_running_and_completed_entries(self, _reset_registry):
+ tools_mod = _reset_registry
+
+ running_task = MagicMock()
+ running_task.done.return_value = False
+ tools_mod._delegated_tasks["t1"] = running_task
+
+ tools_mod._delegation_results["t2"] = {
+ "status": "completed",
+ "agent_name": "coding_agent",
+ "result": "x" * 500, # will be truncated to 200 chars
+ }
+
+ result = await tools_mod._execute_task_manager(
+ {"operation": "list_tasks"}, {"parameters": {}}
+ )
+
+ assert result["success"] is True
+ assert result["operation"] == "list_tasks"
+ assert result["count"] == 2
+ assert result["running"] == 1
+ assert result["completed"] == 1
+ assert result["errors"] == 0
+
+ ids = {t["task_id"] for t in result["tasks"]}
+ assert ids == {"t1", "t2"}
+ t2 = next(t for t in result["tasks"] if t["task_id"] == "t2")
+ assert t2["agent_name"] == "coding_agent"
+ assert len(t2["result_summary"]) == 200
+
+ async def test_list_tasks_applies_status_filter(self, _reset_registry):
+ tools_mod = _reset_registry
+
+ running = MagicMock()
+ running.done.return_value = False
+ tools_mod._delegated_tasks["r1"] = running
+ tools_mod._delegation_results["c1"] = {"status": "completed"}
+
+ result = await tools_mod._execute_task_manager(
+ {"operation": "list_tasks", "status_filter": "running"},
+ {"parameters": {}},
+ )
+
+ assert result["count"] == 1
+ assert result["tasks"][0]["task_id"] == "r1"
+
+ async def test_get_task_without_id_errors(self, _reset_registry):
+ tools_mod = _reset_registry
+
+ result = await tools_mod._execute_task_manager(
+ {"operation": "get_task"}, {"parameters": {}}
+ )
+ assert result["success"] is False
+ assert "task_id is required" in result["error"]
+
+ async def test_mark_done_removes_tracked_task(self, _reset_registry):
+ tools_mod = _reset_registry
+ tools_mod._delegation_results["gone"] = {"status": "completed"}
+
+ result = await tools_mod._execute_task_manager(
+ {"operation": "mark_done", "task_id": "gone"},
+ {"parameters": {}},
+ )
+
+ assert result["success"] is True
+ assert result["removed"] is True
+ assert "gone" not in tools_mod._delegation_results
+
+ async def test_mark_done_untracked_id_returns_removed_false(self, _reset_registry):
+ tools_mod = _reset_registry
+
+ result = await tools_mod._execute_task_manager(
+ {"operation": "mark_done", "task_id": "never-seen"},
+ {"parameters": {}},
+ )
+
+ assert result["success"] is True
+ assert result["removed"] is False
+ assert "was not in active tracking" in result["message"]
+
+ async def test_unknown_operation_returns_failure_envelope(self, _reset_registry):
+ tools_mod = _reset_registry
+
+ result = await tools_mod._execute_task_manager(
+ {"operation": "self_destruct"}, {"parameters": {}}
+ )
+ assert result["success"] is False
+ assert "Unknown operation" in result["error"]
+
+
+# ============================================================================
+# writeTodos
+# ============================================================================
+
+
+class TestWriteTodos:
+ """Dual-purpose tool: TodoService singleton + broadcast side-effect."""
+
+ @pytest.fixture(autouse=True)
+ def _fresh_todo_service(self):
+ """Reset the TodoService singleton between tests."""
+ from services import todo_service as svc_mod
+
+ backup = svc_mod._service
+ svc_mod._service = None
+ try:
+ yield
+ finally:
+ svc_mod._service = backup
+
+ async def test_happy_path_stores_todos_and_broadcasts(self):
+ from services.handlers.todo import handle_write_todos
+ from services.todo_service import get_todo_service
+
+ broadcaster = MagicMock()
+ broadcaster.update_node_status = AsyncMock(return_value=None)
+
+ context = {"workflow_id": "wf-42", "broadcaster": broadcaster}
+
+ todos = [
+ {"content": "Design schema", "status": "completed"},
+ {"content": "Write migration", "status": "in_progress"},
+ {"content": "Ship it", "status": "pending"},
+ ]
+
+ result = await handle_write_todos(
+ node_id="todo-node-1",
+ node_type="writeTodos",
+ parameters={"todos": todos},
+ context=context,
+ )
+
+ assert result["success"] is True
+ assert result["count"] == 3
+ assert "Updated todo list (3 items)" == result["message"]
+
+ # TodoService persists validated list under workflow_id
+ stored = get_todo_service().get("wf-42")
+ assert len(stored) == 3
+ assert stored[0] == {"content": "Design schema", "status": "completed"}
+
+ # Broadcast fired with phase=todo_update
+ broadcaster.update_node_status.assert_awaited_once()
+ args, kwargs = broadcaster.update_node_status.call_args
+ assert args[0] == "todo-node-1"
+ assert args[1] == "executing"
+ assert args[2]["phase"] == "todo_update"
+ assert args[2]["todos"] == stored
+ assert kwargs.get("workflow_id") == "wf-42"
+
+ async def test_invalid_items_are_silently_dropped_or_coerced(self):
+ from services.handlers.todo import handle_write_todos
+ from services.todo_service import get_todo_service
+
+ todos = [
+ {"content": "valid", "status": "pending"},
+ {"content": " ", "status": "pending"}, # dropped (empty)
+ {"content": "bad-status", "status": "on_hold"}, # coerced to pending
+ "not a dict", # dropped
+ ]
+
+ result = await handle_write_todos(
+ node_id="n",
+ node_type="writeTodos",
+ parameters={"todos": todos},
+ context={"workflow_id": "wf"},
+ )
+
+ assert result["success"] is True
+ assert result["count"] == 2
+
+ stored = get_todo_service().get("wf")
+ assert stored == [
+ {"content": "valid", "status": "pending"},
+ {"content": "bad-status", "status": "pending"},
+ ]
+
+ async def test_falls_back_to_default_session_key_without_workflow_id_or_node_id(self):
+ from services.handlers.todo import execute_write_todos
+ from services.todo_service import get_todo_service
+
+ result = await execute_write_todos(
+ {"todos": [{"content": "x", "status": "pending"}]},
+ config={}, # no workflow_id, no node_id, no broadcaster
+ )
+
+ assert result["success"] is True
+ assert get_todo_service().get("default") == [
+ {"content": "x", "status": "pending"}
+ ]
+
+ async def test_empty_todos_list_yields_empty_stored_state(self):
+ from services.handlers.todo import handle_write_todos
+ from services.todo_service import get_todo_service
+
+ result = await handle_write_todos(
+ node_id="n",
+ node_type="writeTodos",
+ parameters={"todos": []},
+ context={"workflow_id": "wf"},
+ )
+
+ assert result["success"] is True
+ assert result["count"] == 0
+ assert get_todo_service().get("wf") == []
+
+ async def test_no_broadcaster_no_broadcast_but_still_success(self):
+ """If the caller omits broadcaster (e.g. test harness, CLI), the
+ handler must still succeed and persist state."""
+ from services.handlers.todo import handle_write_todos
+ from services.todo_service import get_todo_service
+
+ result = await handle_write_todos(
+ node_id="n",
+ node_type="writeTodos",
+ parameters={"todos": [{"content": "x", "status": "pending"}]},
+ context={"workflow_id": "wf"}, # no broadcaster key
+ )
+
+ assert result["success"] is True
+ assert get_todo_service().get("wf") == [
+ {"content": "x", "status": "pending"}
+ ]
diff --git a/server/tests/nodes/test_android.py b/server/tests/nodes/test_android.py
new file mode 100644
index 00000000..8b71cc42
--- /dev/null
+++ b/server/tests/nodes/test_android.py
@@ -0,0 +1,463 @@
+"""Contract tests for the 16 Android service nodes.
+
+All Android nodes share a single handler (`handle_android_service`) bound by
+the NodeExecutor registry. The handler maps the incoming camelCase `node_type`
+to a snake_case `service_id` via its own internal `SERVICE_ID_MAP`, parses
+parameters, and calls `android_service.execute_service(...)`.
+
+These tests freeze that contract:
+
+ 1. Registry dispatch - every one of the 16 node types routes to the shared
+ handler and calls `execute_service` with the correct `service_id`.
+ 2. NodeExecutor's Android output flatten - `result.data` contents are
+ promoted to top-level of the stored output.
+ 3. Action branches - `status`, `enable`, `disable`, etc. all pass through
+ unchanged.
+ 4. Parameter promotion - `package_name` (a root-level param on
+ `appLauncher`) is hoisted into the nested `parameters` dict.
+ 5. JSON-string parameters - coerced to dict, malformed JSON silently becomes
+ `{}`.
+ 6. Error envelopes - when the service returns `success=False` or raises, the
+ envelope surfaces that to the caller.
+
+The default mock `android_service` from `_harness` only wires
+`execute_action`; the real handler calls `execute_service`. Tests install a
+fresh `AsyncMock` on `execute_service` per test.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import AsyncMock
+
+import pytest
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# Map camelCase node_type -> expected service_id. Mirrors the SERVICE_ID_MAP
+# inside handlers/android.py. Keeping this list here lets us detect drift via
+# the parametrized dispatch test below.
+SERVICE_ID_MAP = {
+ "batteryMonitor": "battery",
+ "networkMonitor": "network",
+ "systemInfo": "system_info",
+ "location": "location",
+ "appLauncher": "app_launcher",
+ "appList": "app_list",
+ "wifiAutomation": "wifi_automation",
+ "bluetoothAutomation": "bluetooth_automation",
+ "audioAutomation": "audio_automation",
+ "deviceStateAutomation": "device_state",
+ "screenControlAutomation": "screen_control",
+ "airplaneModeControl": "airplane_mode",
+ "motionDetection": "motion_detection",
+ "environmentalSensors": "environmental_sensors",
+ "cameraControl": "camera_control",
+ "mediaControl": "media_control",
+}
+
+DEFAULT_ACTIONS = {
+ "batteryMonitor": "status",
+ "networkMonitor": "status",
+ "systemInfo": "info",
+ "location": "current",
+ "appLauncher": "launch",
+ "appList": "list",
+ "wifiAutomation": "status",
+ "bluetoothAutomation": "status",
+ "audioAutomation": "get_volume",
+ "deviceStateAutomation": "status",
+ "screenControlAutomation": "status",
+ "airplaneModeControl": "status",
+ "motionDetection": "current_motion",
+ "environmentalSensors": "ambient_conditions",
+ "cameraControl": "camera_info",
+ "mediaControl": "volume_control",
+}
+
+
+# --------------------------------------------------------------------------- #
+# Helpers
+# --------------------------------------------------------------------------- #
+
+
+def _build_service_envelope(
+ *,
+ service_id: str,
+ action: str,
+ data: dict,
+ success: bool = True,
+ error: str | None = None,
+ node_id: str = "test_node",
+ android_host: str = "localhost",
+ android_port: int = 8888,
+) -> dict:
+ """Shape identical to what AndroidService.execute_service returns."""
+ result_block = {
+ "service_id": service_id,
+ "action": action,
+ "data": data,
+ "response_time": 0.01,
+ "android_host": android_host,
+ "android_port": android_port,
+ "timestamp": datetime.now().isoformat(),
+ }
+ if not success and error is not None:
+ result_block["error"] = error
+ envelope = {
+ "success": success,
+ "node_id": node_id,
+ "node_type": "androidService",
+ "result": result_block,
+ "execution_time": 0.01,
+ "timestamp": datetime.now().isoformat(),
+ }
+ if not success and error is not None:
+ envelope["error"] = error
+ return envelope
+
+
+def _install_execute_service(harness, *, return_value=None, side_effect=None):
+ """Install a fresh AsyncMock on harness.android_service.execute_service."""
+ kwargs = {}
+ if side_effect is not None:
+ kwargs["side_effect"] = side_effect
+ else:
+ kwargs["return_value"] = return_value if return_value is not None else {
+ "success": True,
+ "result": {
+ "service_id": "unknown",
+ "action": "unknown",
+ "data": {},
+ "response_time": 0.01,
+ "android_host": "localhost",
+ "android_port": 8888,
+ "timestamp": datetime.now().isoformat(),
+ },
+ "execution_time": 0.01,
+ "timestamp": datetime.now().isoformat(),
+ }
+ mock = AsyncMock(**kwargs)
+ harness.android_service.execute_service = mock
+ return mock
+
+
+# ============================================================================
+# Dispatch: all 16 node types route through the shared handler
+# ============================================================================
+
+
+class TestDispatch:
+ """All 16 Android node types share one handler; dispatch the right service_id."""
+
+ @pytest.mark.parametrize("node_type,expected_service_id", list(SERVICE_ID_MAP.items()))
+ async def test_registry_routes_to_correct_service_id(
+ self, harness, node_type, expected_service_id
+ ):
+ action = DEFAULT_ACTIONS[node_type]
+ envelope = _build_service_envelope(
+ service_id=expected_service_id, action=action, data={"ok": True}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ result = await harness.execute(node_type, {"action": action})
+
+ harness.assert_envelope(result, success=True)
+ mock.assert_awaited_once()
+ kwargs = mock.await_args.kwargs
+ assert kwargs["service_id"] == expected_service_id
+ assert kwargs["action"] == action
+
+ async def test_handler_ignores_frontend_service_id_param(self, harness):
+ """Frontend stores hidden `service_id` but handler's SERVICE_ID_MAP wins."""
+ envelope = _build_service_envelope(
+ service_id="device_state", action="status", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ # Frontend sends the wrong snake_case value (matches factory output,
+ # not the handler map). Handler must override.
+ await harness.execute(
+ "deviceStateAutomation",
+ {"action": "status", "service_id": "device_state_automation"},
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["service_id"] == "device_state"
+
+ async def test_default_host_and_port_used_when_absent(self, harness):
+ envelope = _build_service_envelope(
+ service_id="battery", action="status", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute("batteryMonitor", {"action": "status"})
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["android_host"] == "localhost"
+ assert kwargs["android_port"] == 8888
+
+ async def test_custom_host_and_port_forwarded(self, harness):
+ envelope = _build_service_envelope(
+ service_id="battery",
+ action="status",
+ data={},
+ android_host="10.0.0.5",
+ android_port=9999,
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute(
+ "batteryMonitor",
+ {"action": "status", "android_host": "10.0.0.5", "android_port": 9999},
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["android_host"] == "10.0.0.5"
+ assert kwargs["android_port"] == 9999
+
+
+# ============================================================================
+# Parameter handling
+# ============================================================================
+
+
+class TestParameterHandling:
+ async def test_package_name_promoted_into_parameters_dict(self, harness):
+ """appLauncher: root-level package_name must end up inside parameters."""
+ envelope = _build_service_envelope(
+ service_id="app_launcher", action="launch", data={"launched": True}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute(
+ "appLauncher",
+ {"action": "launch", "package_name": "com.whatsapp"},
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["parameters"] == {"package_name": "com.whatsapp"}
+
+ async def test_empty_package_name_is_not_promoted(self, harness):
+ """Handler checks `if parameters[key]` - empty strings are skipped."""
+ envelope = _build_service_envelope(
+ service_id="app_launcher", action="launch", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute(
+ "appLauncher",
+ {"action": "launch", "package_name": ""},
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["parameters"] == {}
+
+ async def test_parameters_json_string_is_parsed(self, harness):
+ envelope = _build_service_envelope(
+ service_id="audio_automation", action="set_volume", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute(
+ "audioAutomation",
+ {
+ "action": "set_volume",
+ "parameters": '{"stream": "music", "level": 5}',
+ },
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["parameters"] == {"stream": "music", "level": 5}
+
+ async def test_parameters_invalid_json_becomes_empty_dict(self, harness):
+ envelope = _build_service_envelope(
+ service_id="audio_automation", action="set_volume", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute(
+ "audioAutomation",
+ {"action": "set_volume", "parameters": "{not valid json"},
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["parameters"] == {}
+
+ async def test_parameters_dict_passed_through(self, harness):
+ envelope = _build_service_envelope(
+ service_id="screen_control", action="set_brightness", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute(
+ "screenControlAutomation",
+ {"action": "set_brightness", "parameters": {"level": 200}},
+ )
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["parameters"] == {"level": 200}
+
+ async def test_default_action_fallback(self, harness):
+ """Handler falls back to action='status' when param missing."""
+ envelope = _build_service_envelope(
+ service_id="battery", action="status", data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute("batteryMonitor", {})
+
+ kwargs = mock.await_args.kwargs
+ assert kwargs["action"] == "status"
+
+
+# ============================================================================
+# Action branches - representative set
+# ============================================================================
+
+
+class TestActionBranches:
+ @pytest.mark.parametrize("action", ["status", "enable", "disable", "scan"])
+ async def test_wifi_actions_pass_through(self, harness, action):
+ envelope = _build_service_envelope(
+ service_id="wifi_automation", action=action, data={"enabled": True}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ result = await harness.execute("wifiAutomation", {"action": action})
+
+ harness.assert_envelope(result, success=True)
+ assert mock.await_args.kwargs["action"] == action
+
+ @pytest.mark.parametrize("action", ["status", "enable", "disable"])
+ async def test_airplane_mode_actions_pass_through(self, harness, action):
+ envelope = _build_service_envelope(
+ service_id="airplane_mode", action=action, data={}
+ )
+ mock = _install_execute_service(harness, return_value=envelope)
+
+ await harness.execute("airplaneModeControl", {"action": action})
+
+ assert mock.await_args.kwargs["action"] == action
+
+
+# ============================================================================
+# NodeExecutor output flatten (Android-specific)
+# ============================================================================
+
+
+class TestOutputFlatten:
+ async def test_battery_status_data_flattened_to_top_level(self, harness):
+ envelope = _build_service_envelope(
+ service_id="battery",
+ action="status",
+ data={
+ "battery_level": 87,
+ "charging": True,
+ "temperature": 29.4,
+ "health": "good",
+ },
+ )
+ _install_execute_service(harness, return_value=envelope)
+
+ result = await harness.execute(
+ "batteryMonitor", {"action": "status"}, node_id="battery_1"
+ )
+
+ harness.assert_envelope(result, success=True)
+ # The output store receives the flattened payload
+ stored = harness.output_for("battery_1", key="output_main")
+ assert stored is not None
+ assert stored["battery_level"] == 87
+ assert stored["charging"] is True
+ assert stored["temperature"] == 29.4
+ assert stored["health"] == "good"
+ # Original nested block preserved for consumers that still use it
+ assert stored["data"]["battery_level"] == 87
+ # Metadata preserved
+ assert stored["service_id"] == "battery"
+ assert stored["action"] == "status"
+
+ async def test_location_data_flattened(self, harness):
+ envelope = _build_service_envelope(
+ service_id="location",
+ action="current",
+ data={
+ "latitude": 37.7749,
+ "longitude": -122.4194,
+ "accuracy": 15.0,
+ "provider": "gps",
+ },
+ )
+ _install_execute_service(harness, return_value=envelope)
+
+ result = await harness.execute(
+ "location", {"action": "current"}, node_id="loc_1"
+ )
+
+ harness.assert_envelope(result, success=True)
+ stored = harness.output_for("loc_1", key="output_main")
+ assert stored["latitude"] == 37.7749
+ assert stored["longitude"] == -122.4194
+ assert stored["accuracy"] == 15.0
+ assert stored["provider"] == "gps"
+
+ async def test_non_dict_data_leaves_output_unflattened(self, harness):
+ """If data is not a dict, flatten is a no-op - no crash."""
+ envelope = _build_service_envelope(
+ service_id="app_list",
+ action="list",
+ data=["com.app.one", "com.app.two"], # list not dict
+ )
+ _install_execute_service(harness, return_value=envelope)
+
+ result = await harness.execute(
+ "appList", {"action": "list"}, node_id="app_list_1"
+ )
+
+ harness.assert_envelope(result, success=True)
+ stored = harness.output_for("app_list_1", key="output_main")
+ assert stored is not None
+ assert stored["service_id"] == "app_list"
+ assert stored["data"] == ["com.app.one", "com.app.two"]
+
+
+# ============================================================================
+# Error paths
+# ============================================================================
+
+
+class TestErrorPaths:
+ async def test_service_returns_success_false_surfaces_as_error_envelope(
+ self, harness
+ ):
+ envelope = _build_service_envelope(
+ service_id="battery",
+ action="status",
+ data={},
+ success=False,
+ error="Cannot connect to Android device at localhost:8888",
+ )
+ _install_execute_service(harness, return_value=envelope)
+
+ result = await harness.execute("batteryMonitor", {"action": "status"})
+
+ harness.assert_envelope(result, success=False)
+ assert "cannot connect" in result["error"].lower()
+
+ async def test_service_raises_propagates_as_exception(self, harness):
+ """execute_service claims to never raise, but we still guard the path.
+
+ If it does raise (e.g. during future refactors), NodeExecutor catches
+ it and returns a failure envelope via ExecutionResult.
+ """
+ _install_execute_service(
+ harness, side_effect=RuntimeError("relay client crashed")
+ )
+
+ result = await harness.execute("batteryMonitor", {"action": "status"})
+
+ harness.assert_envelope(result, success=False)
+ assert "relay client crashed" in result["error"].lower()
diff --git a/server/tests/nodes/test_chat_utility.py b/server/tests/nodes/test_chat_utility.py
new file mode 100644
index 00000000..aab7411b
--- /dev/null
+++ b/server/tests/nodes/test_chat_utility.py
@@ -0,0 +1,488 @@
+"""Contract tests for chat_utility nodes.
+
+Covers: chatSend, chatHistory, console, teamMonitor, textGenerator,
+fileHandler, gmaps_create.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/chat_utility/`. A refactor that breaks any
+of these indicates the docs (and the user-visible contract) need to be
+updated too.
+
+Each handler is exercised through the full NodeExecutor dispatch via the
+shared `harness` fixture. External coupling points
+(`services.chat_client.*`, `MapsService.create_map`, `StatusBroadcaster`,
+`AgentTeamService`) are patched so no real I/O is performed.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_broadcaster
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# chatSend
+# ============================================================================
+
+
+class TestChatSend:
+ async def test_happy_path(self, harness):
+ canned = {
+ "success": True,
+ "result": {"message_id": "m-1", "timestamp": "2026-04-15T10:00:00Z"},
+ }
+ with patch(
+ "services.chat_client.send_chat_message",
+ AsyncMock(return_value=canned),
+ ) as send:
+ result = await harness.execute(
+ "chatSend",
+ {
+ "host": "chat.local",
+ "port": 9000,
+ "session_id": "s1",
+ "api_key": "tk",
+ "content": "hello there",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["message_id"] == "m-1"
+ send.assert_awaited_once()
+ kwargs = send.await_args.kwargs
+ assert kwargs["host"] == "chat.local"
+ assert kwargs["port"] == 9000
+ assert kwargs["session_id"] == "s1"
+ assert kwargs["api_key"] == "tk"
+ assert kwargs["content"] == "hello there"
+
+ async def test_empty_content_returns_error_envelope(self, harness):
+ with patch(
+ "services.chat_client.send_chat_message",
+ AsyncMock(return_value={"success": True, "result": {}}),
+ ) as send:
+ result = await harness.execute(
+ "chatSend",
+ {"content": ""},
+ )
+ harness.assert_envelope(result, success=False)
+ assert "content is required" in result["error"].lower()
+ send.assert_not_awaited()
+
+ async def test_rpc_failure_propagates_as_error(self, harness):
+ with patch(
+ "services.chat_client.send_chat_message",
+ AsyncMock(return_value={"success": False, "error": "connection refused"}),
+ ):
+ result = await harness.execute(
+ "chatSend",
+ {"content": "hi"},
+ )
+ harness.assert_envelope(result, success=False)
+ assert "connection refused" in result["error"]
+
+
+# ============================================================================
+# chatHistory
+# ============================================================================
+
+
+class TestChatHistory:
+ async def test_happy_path(self, harness):
+ canned = {
+ "success": True,
+ "messages": [
+ {"role": "user", "message": "hi", "created_at": "2026-04-15T09:00:00Z"},
+ {"role": "assistant", "message": "hello", "created_at": "2026-04-15T09:00:01Z"},
+ ],
+ }
+ with patch(
+ "services.chat_client.get_chat_history",
+ AsyncMock(return_value=canned),
+ ) as fetch:
+ result = await harness.execute(
+ "chatHistory",
+ {"host": "chat.local", "port": 9000, "session_id": "s1", "limit": 10},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["messages"])
+ assert len(result["result"]["messages"]) == 2
+ kwargs = fetch.await_args.kwargs
+ assert kwargs["limit"] == 10
+ assert kwargs["session_id"] == "s1"
+
+ async def test_rpc_failure_propagates_as_error(self, harness):
+ with patch(
+ "services.chat_client.get_chat_history",
+ AsyncMock(return_value={"success": False, "error": "no such session"}),
+ ):
+ result = await harness.execute(
+ "chatHistory",
+ {"session_id": "missing"},
+ )
+ harness.assert_envelope(result, success=False)
+ assert "no such session" in result["error"]
+
+ async def test_missing_messages_key_defaults_to_empty_list(self, harness):
+ # RPC returns success but no "messages" field -- handler wraps with [].
+ with patch(
+ "services.chat_client.get_chat_history",
+ AsyncMock(return_value={"success": True}),
+ ):
+ result = await harness.execute("chatHistory", {})
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["messages"] == []
+
+
+# ============================================================================
+# console
+# ============================================================================
+
+
+class TestConsole:
+ async def test_log_all_merges_connected_outputs(self, harness):
+ upstream_source = "src-1"
+ upstream_output = {"response": "hello world", "tokens": 42}
+ nodes = [
+ {"id": upstream_source, "type": "aiAgent", "data": {"label": "MyAgent"}},
+ {"id": "console-1", "type": "console", "data": {}},
+ ]
+ edges = [
+ {
+ "source": upstream_source,
+ "target": "console-1",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+ upstream_outputs = {
+ f"{upstream_source}::output_main": upstream_output,
+ upstream_source: upstream_output,
+ }
+
+ with patched_broadcaster() as broadcaster:
+ result = await harness.execute(
+ "console",
+ {"label": "dbg", "logMode": "all", "format": "json"},
+ node_id="console-1",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["label"] == "dbg"
+ assert payload["format"] == "json"
+ # data is the merged input_data
+ assert payload["data"] == {"response": "hello world", "tokens": 42}
+ # pass-through: upstream keys appear at top level
+ assert payload["response"] == "hello world"
+ assert payload["tokens"] == 42
+ # broadcast was issued with source node info
+ broadcaster.broadcast_console_log.assert_awaited_once()
+ broadcast_payload = broadcaster.broadcast_console_log.await_args.args[0]
+ assert broadcast_payload["node_id"] == "console-1"
+ assert broadcast_payload["source_node_id"] == upstream_source
+ assert broadcast_payload["source_node_type"] == "aiAgent"
+ assert broadcast_payload["source_node_label"] == "MyAgent"
+
+ async def test_log_field_navigates_dot_path(self, harness):
+ upstream_source = "src-2"
+ upstream_output = {"data": {"items": [{"name": "first"}, {"name": "second"}]}}
+ nodes = [
+ {"id": upstream_source, "type": "httpRequest", "data": {}},
+ {"id": "console-2", "type": "console", "data": {}},
+ ]
+ edges = [
+ {
+ "source": upstream_source,
+ "target": "console-2",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+ upstream_outputs = {
+ f"{upstream_source}::output_main": upstream_output,
+ upstream_source: upstream_output,
+ }
+
+ with patched_broadcaster():
+ result = await harness.execute(
+ "console",
+ {"logMode": "field", "fieldPath": "data.items[1].name", "format": "text"},
+ node_id="console-2",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["data"] == "second"
+
+ async def test_no_upstream_produces_empty_log(self, harness):
+ with patched_broadcaster() as broadcaster:
+ result = await harness.execute(
+ "console",
+ {"logMode": "all", "format": "json"},
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["data"] == {}
+ broadcast_payload = broadcaster.broadcast_console_log.await_args.args[0]
+ assert broadcast_payload["source_node_id"] is None
+
+
+# ============================================================================
+# teamMonitor
+# ============================================================================
+
+
+class TestTeamMonitor:
+ async def test_no_team_connected_returns_empty_snapshot(self, harness):
+ # No team_id in context, no upstream outputs -> informational envelope.
+ result = await harness.execute("teamMonitor", {})
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["team_id"] is None
+ assert payload["message"] == "No team connected"
+ assert payload["tasks"]["total"] == 0
+ assert payload["members"] == []
+
+ async def test_team_id_from_context_fetches_status(self, harness):
+ fake_status = {
+ "members": [{"id": "a"}, {"id": "b"}],
+ "task_count": 5,
+ "completed_count": 2,
+ "active_count": 1,
+ "pending_count": 2,
+ "failed_count": 0,
+ "active_tasks": [{"id": "t-1"}],
+ "recent_events": [{"t": 1}, {"t": 2}, {"t": 3}],
+ }
+ fake_service = MagicMock()
+ fake_service.get_team_status = AsyncMock(return_value=fake_status)
+
+ ctx = harness.build_context(extra={"team_id": "team-xyz"})
+ with patch(
+ "services.agent_team.get_agent_team_service",
+ return_value=fake_service,
+ ):
+ result = await harness.execute(
+ "teamMonitor",
+ {"maxHistoryItems": 2},
+ context=ctx,
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["team_id"] == "team-xyz"
+ assert payload["tasks"]["total"] == 5
+ assert payload["tasks"]["completed"] == 2
+ assert len(payload["members"]) == 2
+ # recent_events sliced by maxHistoryItems
+ assert len(payload["recent_events"]) == 2
+ assert payload["active_tasks"] == [{"id": "t-1"}]
+
+ async def test_service_exception_returns_error_envelope(self, harness):
+ fake_service = MagicMock()
+ fake_service.get_team_status = AsyncMock(side_effect=RuntimeError("boom"))
+
+ ctx = harness.build_context(extra={"team_id": "team-err"})
+ with patch(
+ "services.agent_team.get_agent_team_service",
+ return_value=fake_service,
+ ):
+ result = await harness.execute(
+ "teamMonitor",
+ {},
+ context=ctx,
+ )
+ harness.assert_envelope(result, success=False)
+ assert "boom" in result["error"]
+
+
+# ============================================================================
+# textGenerator
+# ============================================================================
+
+
+class TestTextGenerator:
+ async def test_happy_path_with_timestamp(self, harness):
+ # Swap the harness TextService stub for a real-ish behavior matching
+ # execute_text_generator's spec so we exercise the real output shape
+ # rather than the default "mocked text" string.
+ from services.text import TextService
+
+ harness.text_service = TextService()
+ # Rebuild the executor with the new service instance.
+ from services.node_executor import NodeExecutor
+ harness.executor = NodeExecutor(
+ database=harness.database,
+ ai_service=harness.ai_service,
+ maps_service=harness.maps_service,
+ text_service=harness.text_service,
+ android_service=harness.android_service,
+ settings=harness.settings,
+ output_store=harness._record_output,
+ )
+
+ result = await harness.execute(
+ "textGenerator",
+ {"text": "hello", "includeTimestamp": True},
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["type"] == "text"
+ assert payload["data"]["text"] == "hello"
+ assert payload["data"]["length"] == 5
+ assert "timestamp" in payload["data"]
+
+ async def test_defaults_applied_when_params_missing(self, harness):
+ from services.text import TextService
+ from services.node_executor import NodeExecutor
+
+ harness.text_service = TextService()
+ harness.executor = NodeExecutor(
+ database=harness.database,
+ ai_service=harness.ai_service,
+ maps_service=harness.maps_service,
+ text_service=harness.text_service,
+ android_service=harness.android_service,
+ settings=harness.settings,
+ output_store=harness._record_output,
+ )
+ result = await harness.execute("textGenerator", {})
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["data"]["text"] == "Hello World"
+ assert result["result"]["data"]["length"] == len("Hello World")
+
+
+# ============================================================================
+# fileHandler
+# ============================================================================
+
+
+class TestFileHandler:
+ async def test_happy_path_wraps_content_metadata(self, harness):
+ from services.text import TextService
+ from services.node_executor import NodeExecutor
+
+ harness.text_service = TextService()
+ harness.executor = NodeExecutor(
+ database=harness.database,
+ ai_service=harness.ai_service,
+ maps_service=harness.maps_service,
+ text_service=harness.text_service,
+ android_service=harness.android_service,
+ settings=harness.settings,
+ output_store=harness._record_output,
+ )
+ result = await harness.execute(
+ "fileHandler",
+ {
+ "fileType": "markdown",
+ "content": "# hello",
+ "fileName": "note.md",
+ },
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["type"] == "file"
+ assert payload["data"]["fileName"] == "note.md"
+ assert payload["data"]["fileType"] == "markdown"
+ assert payload["data"]["content"] == "# hello"
+ assert payload["data"]["size"] == len("# hello")
+ assert payload["data"]["processed"] is True
+ assert payload["data"]["processingType"] == "markdown"
+
+ async def test_defaults_applied(self, harness):
+ from services.text import TextService
+ from services.node_executor import NodeExecutor
+
+ harness.text_service = TextService()
+ harness.executor = NodeExecutor(
+ database=harness.database,
+ ai_service=harness.ai_service,
+ maps_service=harness.maps_service,
+ text_service=harness.text_service,
+ android_service=harness.android_service,
+ settings=harness.settings,
+ output_store=harness._record_output,
+ )
+ result = await harness.execute("fileHandler", {})
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["data"]["fileName"] == "untitled.txt"
+ assert result["result"]["data"]["fileType"] == "generic"
+
+
+# ============================================================================
+# gmaps_create
+# ============================================================================
+
+
+class TestGmapsCreate:
+ async def test_happy_path_builds_static_url(self, harness):
+ canned = {
+ "success": True,
+ "node_id": "n1",
+ "node_type": "gmaps_create",
+ "operation": "map_initialization",
+ "result": {
+ "map_config": {
+ "center": {"lat": 37.7, "lng": -122.4},
+ "zoom": 12,
+ "mapTypeId": "ROADMAP",
+ },
+ "static_map_url": (
+ "https://maps.googleapis.com/maps/api/staticmap?"
+ "center=37.7,-122.4&zoom=12&size=600x400&maptype=roadmap&key=tk"
+ ),
+ "status": "OK",
+ },
+ "execution_time": 0.01,
+ "timestamp": "2026-04-15T10:00:00Z",
+ }
+ harness.maps_service.create_map = AsyncMock(return_value=canned)
+
+ result = await harness.execute(
+ "gmaps_create",
+ {
+ "api_key": "tk",
+ "lat": 37.7,
+ "lng": -122.4,
+ "zoom": 12,
+ "map_type_id": "ROADMAP",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["map_config", "static_map_url", "status"])
+ assert result["result"]["status"] == "OK"
+ assert result["result"]["map_config"]["zoom"] == 12
+ harness.maps_service.create_map.assert_awaited_once()
+
+ async def test_service_error_propagates(self, harness):
+ harness.maps_service.create_map = AsyncMock(
+ return_value={
+ "success": False,
+ "node_id": "n1",
+ "node_type": "gmaps_create",
+ "error": "Google Maps API key is required",
+ "execution_time": 0.0,
+ "timestamp": "2026-04-15T10:00:00Z",
+ }
+ )
+ result = await harness.execute(
+ "gmaps_create",
+ {"lat": 0.0, "lng": 0.0},
+ )
+ harness.assert_envelope(result, success=False)
+ assert "API key" in result["error"]
diff --git a/server/tests/nodes/test_code_fs_process.py b/server/tests/nodes/test_code_fs_process.py
new file mode 100644
index 00000000..e78bdeca
--- /dev/null
+++ b/server/tests/nodes/test_code_fs_process.py
@@ -0,0 +1,778 @@
+"""Contract tests for code_fs_process nodes.
+
+Covers: pythonExecutor, javascriptExecutor, typescriptExecutor,
+ fileRead, fileModify, shell, fsSearch, processManager.
+
+Frozen behavioural contract for the 8 nodes in
+`docs-internal/node-logic-flows/code_fs_process/`. Each test asserts the
+standard handler envelope shape and at least one payload detail from the
+matching doc; external side-effects (subprocess spawn, Node.js HTTP call,
+deepagents backend, Terminal broadcast) are mocked.
+
+Mocking strategy:
+ - pythonExecutor runs in-process (no external service) -- tests exercise
+ the real exec() path.
+ - javascriptExecutor / typescriptExecutor: patch NodeJSClient.execute()
+ via the module-level _nodejs_client singleton.
+ - filesystem nodes (fileRead, fileModify, shell, fsSearch): patch
+ services.handlers.filesystem._get_backend to return a fake backend with
+ the methods each mode invokes.
+ - processManager: patch services.handlers.process.get_process_service to
+ return a fake ProcessService with the dispatched method set to an
+ AsyncMock / MagicMock.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# Helpers
+# ============================================================================
+
+
+def _reset_nodejs_singleton():
+ """Clear the module-level client singleton in services.handlers.code.
+
+ The handler caches its NodeJSClient on first use; tests that patch must
+ either reset this between cases or patch the module attribute directly.
+ """
+ import services.handlers.code as code_mod
+
+ code_mod._nodejs_client = None
+
+
+class _FakeWriteResult(SimpleNamespace):
+ """Mimics deepagents WriteResult / EditResult dataclasses."""
+
+ def __init__(self, error: str = "", path: str = "", occurrences: int = 0):
+ super().__init__(error=error, path=path, occurrences=occurrences)
+
+
+class _FakeExecuteResult(SimpleNamespace):
+ def __init__(self, output: str = "", exit_code: int = 0, truncated: bool = False):
+ super().__init__(output=output, exit_code=exit_code, truncated=truncated)
+
+
+class _FakeFileInfo(dict):
+ """Dataclass stand-in that `dict(entry)` can iterate."""
+
+ def __iter__(self):
+ return iter(self.items())
+
+
+def _patch_fs_backend(backend: MagicMock):
+ """Patch services.handlers.filesystem._get_backend to return a fake."""
+ return patch(
+ "services.handlers.filesystem._get_backend",
+ return_value=backend,
+ )
+
+
+# ============================================================================
+# pythonExecutor
+# ============================================================================
+
+
+class TestPythonExecutor:
+ async def test_happy_path_reads_input_and_sets_output(self, harness):
+ # NodeExecutor keys connected_outputs by SOURCE TYPE (not id).
+ # See node_executor._get_connected_outputs_with_info (outputs[source_type] = output).
+ upstream = {
+ "source_A::output_main": {"n": 5},
+ }
+ nodes = [
+ {"id": "py1", "type": "pythonExecutor"},
+ {"id": "source_A", "type": "start"},
+ ]
+ edges = [
+ {"source": "source_A", "target": "py1", "sourceHandle": "output-main"},
+ ]
+
+ code = (
+ "val = input_data.get('start', {}).get('n', 0)\n"
+ "print('doubled', val * 2)\n"
+ "output = {'doubled': val * 2}\n"
+ )
+
+ result = await harness.execute(
+ "pythonExecutor",
+ {"code": code},
+ node_id="py1",
+ upstream_outputs=upstream,
+ nodes=nodes,
+ edges=edges,
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["output", "console_output", "timestamp"]
+ )
+ payload = result["result"]
+ assert payload["output"] == {"doubled": 10}
+ assert "doubled 10" in payload["console_output"]
+
+ async def test_empty_code_short_circuits(self, harness):
+ result = await harness.execute(
+ "pythonExecutor", {"code": " \n\t"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "no code provided" in result["error"].lower()
+
+ async def test_exception_in_user_code_is_captured(self, harness):
+ result = await harness.execute(
+ "pythonExecutor",
+ {"code": "raise ValueError('boom')"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "boom" in result["error"]
+ # Per doc: console_output is empty on the exception path
+ assert result.get("console_output", "") == ""
+
+
+# ============================================================================
+# javascriptExecutor
+# ============================================================================
+
+
+class TestJavascriptExecutor:
+ async def test_happy_path_returns_node_output(self, harness):
+ _reset_nodejs_singleton()
+ fake_client = MagicMock(name="NodeJSClient")
+ fake_client.execute = AsyncMock(
+ return_value={
+ "success": True,
+ "output": {"v": 42},
+ "console_output": "running\n",
+ }
+ )
+
+ with patch(
+ "services.handlers.code.get_nodejs_client",
+ return_value=fake_client,
+ ):
+ result = await harness.execute(
+ "javascriptExecutor",
+ {"code": "output = {v: 42}", "timeout": 15},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["output", "console_output", "timestamp"]
+ )
+ payload = result["result"]
+ assert payload["output"] == {"v": 42}
+ assert "running" in payload["console_output"]
+
+ # timeout: seconds -> milliseconds forwarded to the Node server
+ call_kwargs = fake_client.execute.await_args.kwargs
+ assert call_kwargs["timeout"] == 15 * 1000
+ assert call_kwargs["language"] == "javascript"
+ # workspace_dir injected into input_data
+ assert "workspace_dir" in call_kwargs["input_data"]
+
+ async def test_empty_code_short_circuits(self, harness):
+ result = await harness.execute(
+ "javascriptExecutor", {"code": ""}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "no code provided" in result["error"].lower()
+
+ async def test_node_server_returns_failure_preserves_console(self, harness):
+ _reset_nodejs_singleton()
+ fake_client = MagicMock(name="NodeJSClient")
+ fake_client.execute = AsyncMock(
+ return_value={
+ "success": False,
+ "error": "SyntaxError: unexpected token",
+ "console_output": "partial log\n",
+ }
+ )
+
+ with patch(
+ "services.handlers.code.get_nodejs_client",
+ return_value=fake_client,
+ ):
+ result = await harness.execute(
+ "javascriptExecutor", {"code": "oops"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "syntaxerror" in result["error"].lower()
+ # Per doc: console_output is preserved on the failure path
+ assert "partial log" in result.get("console_output", "")
+
+ async def test_http_exception_wrapped_in_envelope(self, harness):
+ _reset_nodejs_singleton()
+ fake_client = MagicMock(name="NodeJSClient")
+ fake_client.execute = AsyncMock(
+ side_effect=ConnectionRefusedError("Cannot connect to host localhost:3020")
+ )
+
+ with patch(
+ "services.handlers.code.get_nodejs_client",
+ return_value=fake_client,
+ ):
+ result = await harness.execute(
+ "javascriptExecutor", {"code": "output = 1"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "localhost:3020" in result["error"]
+
+
+# ============================================================================
+# typescriptExecutor
+# ============================================================================
+
+
+class TestTypescriptExecutor:
+ async def test_happy_path_forwards_language_typescript(self, harness):
+ _reset_nodejs_singleton()
+ fake_client = MagicMock(name="NodeJSClient")
+ fake_client.execute = AsyncMock(
+ return_value={
+ "success": True,
+ "output": "typed-output",
+ "console_output": "",
+ }
+ )
+
+ with patch(
+ "services.handlers.code.get_nodejs_client",
+ return_value=fake_client,
+ ):
+ result = await harness.execute(
+ "typescriptExecutor",
+ {"code": "const x: number = 1; output = 'typed-output'"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["output"] == "typed-output"
+ call_kwargs = fake_client.execute.await_args.kwargs
+ assert call_kwargs["language"] == "typescript"
+
+ async def test_empty_code_short_circuits(self, harness):
+ result = await harness.execute(
+ "typescriptExecutor", {"code": ""}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "no code provided" in result["error"].lower()
+
+ async def test_node_server_failure_preserves_console(self, harness):
+ _reset_nodejs_singleton()
+ fake_client = MagicMock(name="NodeJSClient")
+ fake_client.execute = AsyncMock(
+ return_value={
+ "success": False,
+ "error": "TS2304: Cannot find name 'foo'",
+ "console_output": "compiling...\n",
+ }
+ )
+
+ with patch(
+ "services.handlers.code.get_nodejs_client",
+ return_value=fake_client,
+ ):
+ result = await harness.execute(
+ "typescriptExecutor", {"code": "output = foo"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "ts2304" in result["error"].lower()
+ assert "compiling" in result.get("console_output", "")
+
+
+# ============================================================================
+# fileRead
+# ============================================================================
+
+
+class TestFileRead:
+ async def test_happy_path_returns_content(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.read = MagicMock(return_value="line1\nline2\n")
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileRead",
+ {"file_path": "notes.txt", "offset": 0, "limit": 100},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["content", "file_path"])
+ payload = result["result"]
+ assert payload["content"] == "line1\nline2\n"
+ assert payload["file_path"] == "notes.txt"
+ backend.read.assert_called_once_with("notes.txt", offset=0, limit=100)
+
+ async def test_missing_file_path_short_circuits(self, harness):
+ # No backend patch: we should short-circuit before reaching it.
+ result = await harness.execute("fileRead", {"file_path": ""})
+
+ harness.assert_envelope(result, success=False)
+ assert "file_path is required" in result["error"].lower()
+
+ async def test_backend_exception_becomes_error_envelope(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.read = MagicMock(side_effect=FileNotFoundError("No such file: ../../etc/passwd"))
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileRead", {"file_path": "../../etc/passwd"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "no such file" in result["error"].lower()
+
+
+# ============================================================================
+# fileModify
+# ============================================================================
+
+
+class TestFileModify:
+ async def test_write_happy_path(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.write = MagicMock(return_value=_FakeWriteResult(path="hello.txt"))
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileModify",
+ {
+ "operation": "write",
+ "file_path": "hello.txt",
+ "content": "hi there",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["operation", "file_path"])
+ assert result["result"]["operation"] == "write"
+ assert result["result"]["file_path"] == "hello.txt"
+ backend.write.assert_called_once_with("hello.txt", "hi there")
+
+ async def test_edit_happy_path_returns_occurrences(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.edit = MagicMock(
+ return_value=_FakeWriteResult(path="README.md", occurrences=3)
+ )
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileModify",
+ {
+ "operation": "edit",
+ "file_path": "README.md",
+ "old_string": "foo",
+ "new_string": "bar",
+ "replace_all": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["operation", "file_path", "occurrences"]
+ )
+ assert result["result"]["occurrences"] == 3
+ backend.edit.assert_called_once_with(
+ "README.md", "foo", "bar", replace_all=True
+ )
+
+ async def test_edit_missing_old_string_short_circuits(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileModify",
+ {
+ "operation": "edit",
+ "file_path": "x",
+ "old_string": "",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "old_string is required" in result["error"].lower()
+ backend.edit.assert_not_called() if hasattr(backend, "edit") else None
+
+ async def test_backend_reports_error_in_result(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.edit = MagicMock(
+ return_value=_FakeWriteResult(error="old_string found 2 times; need unique")
+ )
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileModify",
+ {
+ "operation": "edit",
+ "file_path": "x.md",
+ "old_string": "foo",
+ "new_string": "bar",
+ "replace_all": False,
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "2 times" in result["error"]
+
+ async def test_unknown_operation_returns_error(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fileModify",
+ {"operation": "delete", "file_path": "x"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown operation" in result["error"].lower()
+
+
+# ============================================================================
+# shell
+# ============================================================================
+
+
+class TestShell:
+ async def test_happy_path_returns_stdout_and_exit_code(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.execute = MagicMock(
+ return_value=_FakeExecuteResult(
+ output="hello world\n", exit_code=0, truncated=False
+ )
+ )
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "shell",
+ {"command": "echo hello world", "timeout": 10},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["stdout", "exit_code", "truncated", "command"]
+ )
+ payload = result["result"]
+ assert payload["stdout"] == "hello world\n"
+ assert payload["exit_code"] == 0
+ assert payload["truncated"] is False
+ assert payload["command"] == "echo hello world"
+ backend.execute.assert_called_once_with("echo hello world", timeout=10)
+
+ async def test_empty_command_short_circuits(self, harness):
+ result = await harness.execute("shell", {"command": ""})
+
+ harness.assert_envelope(result, success=False)
+ assert "command is required" in result["error"].lower()
+
+ async def test_timeout_surfaces_exit_124(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.execute = MagicMock(
+ return_value=_FakeExecuteResult(
+ output="partial...", exit_code=124, truncated=True
+ )
+ )
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "shell",
+ {"command": "sleep 999", "timeout": 1},
+ )
+
+ # Per doc: non-zero exit still returns success=True at the envelope
+ # level. Users inspect exit_code.
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["exit_code"] == 124
+ assert result["result"]["truncated"] is True
+
+ async def test_backend_exception_becomes_error_envelope(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+ backend.execute = MagicMock(side_effect=RuntimeError("backend blew up"))
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute("shell", {"command": "ls"})
+
+ harness.assert_envelope(result, success=False)
+ assert "backend blew up" in result["error"]
+
+
+# ============================================================================
+# fsSearch
+# ============================================================================
+
+
+class TestFsSearch:
+ async def test_ls_mode_returns_entries(self, harness):
+ entries = [
+ _FakeFileInfo({"name": "a.py", "is_dir": False, "size": 10}),
+ _FakeFileInfo({"name": "sub", "is_dir": True, "size": 0}),
+ ]
+ backend = MagicMock(name="LocalShellBackend")
+ backend.ls_info = MagicMock(return_value=entries)
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fsSearch", {"mode": "ls", "path": "."}
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["path", "entries", "count"])
+ assert result["result"]["count"] == 2
+ assert result["result"]["entries"][0]["name"] == "a.py"
+
+ async def test_glob_requires_pattern(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fsSearch", {"mode": "glob", "path": ".", "pattern": ""}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "pattern is required" in result["error"].lower()
+
+ async def test_glob_happy_path(self, harness):
+ matches = [_FakeFileInfo({"name": "x.py", "path": "src/x.py"})]
+ backend = MagicMock(name="LocalShellBackend")
+ backend.glob_info = MagicMock(return_value=matches)
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fsSearch",
+ {"mode": "glob", "path": "src", "pattern": "**/*.py"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["path", "pattern", "matches", "count"]
+ )
+ assert result["result"]["count"] == 1
+ backend.glob_info.assert_called_once_with("**/*.py", path="src")
+
+ async def test_grep_returns_string_error_as_error_envelope(self, harness):
+ # Per doc: grep_raw returns a str on error, list on success.
+ backend = MagicMock(name="LocalShellBackend")
+ backend.grep_raw = MagicMock(return_value="invalid regex: unbalanced parenthesis")
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fsSearch",
+ {
+ "mode": "grep",
+ "path": ".",
+ "pattern": "foo(",
+ "file_filter": "*.py",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "invalid regex" in result["error"].lower()
+
+ async def test_unknown_mode_returns_error(self, harness):
+ backend = MagicMock(name="LocalShellBackend")
+
+ with _patch_fs_backend(backend):
+ result = await harness.execute(
+ "fsSearch", {"mode": "teleport", "path": "."}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown mode" in result["error"].lower()
+
+
+# ============================================================================
+# processManager
+# ============================================================================
+
+
+def _fake_process_service():
+ svc = MagicMock(name="ProcessService")
+ svc.start = AsyncMock(
+ return_value={
+ "success": True,
+ "result": {
+ "name": "my-server",
+ "command": "python -m http.server 8080",
+ "pid": 12345,
+ "status": "running",
+ "started_at": "2026-04-15T00:00:00",
+ "exit_code": None,
+ "working_directory": "/workspace/proc_node",
+ "stdout_lines": 0,
+ "stderr_lines": 0,
+ "log_dir": "/workspace/proc_node/.processes/my-server",
+ },
+ }
+ )
+ svc.stop = AsyncMock(
+ return_value={
+ "success": True,
+ "result": {"name": "my-server", "status": "stopped", "exit_code": 0},
+ }
+ )
+ svc.restart = AsyncMock(
+ return_value={"success": True, "result": {"name": "my-server", "status": "running"}}
+ )
+ svc.send_input = AsyncMock(
+ return_value={"success": True, "result": {"sent": "hello"}}
+ )
+ svc.list_processes = MagicMock(
+ return_value=[
+ {"name": "my-server", "status": "running", "pid": 12345},
+ ]
+ )
+ svc.get_output = MagicMock(
+ return_value={
+ "lines": ["listening on :8080"],
+ "total": 1,
+ "file": "/workspace/proc_node/.processes/my-server/stdout.log",
+ }
+ )
+ return svc
+
+
+def _patch_process_service(svc):
+ return patch(
+ "services.handlers.process.get_process_service",
+ return_value=svc,
+ )
+
+
+class TestProcessManager:
+ async def test_start_happy_path(self, harness):
+ svc = _fake_process_service()
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager",
+ {
+ "operation": "start",
+ "name": "my-server",
+ "command": "python -m http.server 8080",
+ "working_directory": "",
+ },
+ node_id="proc_node",
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["name"] == "my-server"
+ assert payload["status"] == "running"
+ assert payload["pid"] == 12345
+
+ # Handler passes workflow_id from context and per-node workspace subdir
+ svc.start.assert_awaited_once()
+ call_kwargs = svc.start.await_args.kwargs
+ assert call_kwargs["name"] == "my-server"
+ assert call_kwargs["command"] == "python -m http.server 8080"
+
+ async def test_stop_returns_stopped_status(self, harness):
+ svc = _fake_process_service()
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager",
+ {"operation": "stop", "name": "my-server"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["status"] == "stopped"
+ svc.stop.assert_awaited_once()
+
+ async def test_list_returns_processes_array(self, harness):
+ svc = _fake_process_service()
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager", {"operation": "list"}
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["processes"])
+ assert len(result["result"]["processes"]) == 1
+ assert result["result"]["processes"][0]["name"] == "my-server"
+
+ async def test_get_output_returns_lines(self, harness):
+ svc = _fake_process_service()
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager",
+ {
+ "operation": "get_output",
+ "name": "my-server",
+ # Handler coerces 'None' and empty strings via _clean_arg
+ "stream": "stdout",
+ "tail": 50,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["lines", "total", "file"])
+ payload = result["result"]
+ assert payload["total"] == 1
+ assert "listening" in payload["lines"][0]
+ svc.get_output.assert_called_once()
+
+ async def test_send_input_forwards_text(self, harness):
+ svc = _fake_process_service()
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager",
+ {
+ "operation": "send_input",
+ "name": "my-server",
+ "text": "hello",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["sent"] == "hello"
+ svc.send_input.assert_awaited_once()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ svc = _fake_process_service()
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager", {"operation": "teleport"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown operation" in result["error"].lower()
+
+ async def test_start_failure_from_service_surfaces(self, harness):
+ svc = _fake_process_service()
+ svc.start = AsyncMock(
+ return_value={
+ "success": False,
+ "error": "Destructive commands blocked in process_manager.",
+ }
+ )
+
+ with _patch_process_service(svc):
+ result = await harness.execute(
+ "processManager",
+ {
+ "operation": "start",
+ "name": "bad",
+ "command": "rm -rf /",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "destructive" in result["error"].lower()
diff --git a/server/tests/nodes/test_document.py b/server/tests/nodes/test_document.py
new file mode 100644
index 00000000..93f599c3
--- /dev/null
+++ b/server/tests/nodes/test_document.py
@@ -0,0 +1,595 @@
+"""Contract tests for document nodes: httpScraper, fileDownloader, documentParser,
+textChunker, embeddingGenerator, vectorStore.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/document/`. A refactor that breaks any of
+these indicates the docs (and the user-visible contract) need to be updated
+too.
+
+External side-effects are mocked:
+ - httpScraper / fileDownloader: httpx calls stubbed via respx.
+ - documentParser: each parser library is patched at the module level
+ (`services.handlers.document.<lib>`), or real HTML is fed through
+ BeautifulSoup for the happy path.
+ - textChunker: pure function, exercised with real LangChain splitters.
+ - embeddingGenerator: the embedder class is patched to return canned vectors.
+ - vectorStore: the ChromaDB client is patched to a fake collection.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+import respx
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# httpScraper
+# ============================================================================
+
+
+class TestHttpScraper:
+ @respx.mock
+ async def test_happy_path_single_mode_extracts_links(self, harness):
+ html = """
+ <html><body>
+ <a href="/file1.pdf">Doc 1</a>
+ <a href="https://other.example/file2.pdf">Doc 2</a>
+ <a href="/not-a-pdf.html">Skip</a>
+ </body></html>
+ """
+ respx.get("https://example.com/list").mock(
+ return_value=httpx.Response(200, text=html)
+ )
+
+ result = await harness.execute(
+ "httpScraper",
+ {"url": "https://example.com/list", "linkSelector": 'a[href$=".pdf"]'},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["items", "item_count", "errors"])
+ payload = result["result"]
+ assert payload["item_count"] == 2
+ # urljoin resolves the relative link against the source URL
+ urls = {i["url"] for i in payload["items"]}
+ assert "https://example.com/file1.pdf" in urls
+ assert "https://other.example/file2.pdf" in urls
+ for item in payload["items"]:
+ assert item["source_url"] == "https://example.com/list"
+ assert payload["errors"] == []
+
+ async def test_missing_url_fails_envelope(self, harness):
+ result = await harness.execute("httpScraper", {"url": ""})
+ harness.assert_envelope(result, success=False)
+ assert "url is required" in result["error"].lower()
+
+ @respx.mock
+ async def test_per_url_http_error_collected_in_errors(self, harness):
+ # Page iteration mode fetches two URLs; one 404s, the other succeeds.
+ respx.get("https://example.com/p1").mock(return_value=httpx.Response(404))
+ respx.get("https://example.com/p2").mock(
+ return_value=httpx.Response(200, text='<a href="ok.pdf">OK</a>')
+ )
+
+ result = await harness.execute(
+ "httpScraper",
+ {
+ "url": "https://example.com/p{page}",
+ "iterationMode": "page",
+ "startPage": 1,
+ "endPage": 2,
+ "linkSelector": "a",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["item_count"] == 1
+ assert payload["items"][0]["page"] == 2
+ assert len(payload["errors"]) == 1
+ assert "p1" in payload["errors"][0]
+
+ @respx.mock
+ async def test_date_mode_expands_range(self, harness):
+ respx.get(url__regex=r"https://example\.com/\?d=\d{4}-\d{2}-\d{2}").mock(
+ return_value=httpx.Response(200, text="<html></html>")
+ )
+
+ result = await harness.execute(
+ "httpScraper",
+ {
+ "url": "https://example.com/?d={date}",
+ "iterationMode": "date",
+ "startDate": "2025-01-01",
+ "endDate": "2025-01-03",
+ "linkSelector": "a",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ # Three calls: 01, 02, 03
+ assert len(respx.calls) == 3
+
+
+# ============================================================================
+# fileDownloader
+# ============================================================================
+
+
+class TestFileDownloader:
+ @respx.mock
+ async def test_happy_path_downloads_files(self, harness, tmp_path):
+ respx.get("https://example.com/a.pdf").mock(
+ return_value=httpx.Response(200, content=b"AAA")
+ )
+ respx.get("https://example.com/b.pdf").mock(
+ return_value=httpx.Response(200, content=b"BBBB")
+ )
+
+ result = await harness.execute(
+ "fileDownloader",
+ {
+ "items": [
+ {"url": "https://example.com/a.pdf"},
+ {"url": "https://example.com/b.pdf"},
+ ],
+ "outputDir": str(tmp_path),
+ "maxWorkers": 2,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["downloaded", "skipped", "failed", "files", "output_dir"]
+ )
+ payload = result["result"]
+ assert payload["downloaded"] == 2
+ assert payload["failed"] == 0
+ assert (tmp_path / "a.pdf").read_bytes() == b"AAA"
+ assert (tmp_path / "b.pdf").read_bytes() == b"BBBB"
+
+ async def test_empty_items_short_circuits(self, harness):
+ result = await harness.execute("fileDownloader", {"items": []})
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload == {
+ "downloaded": 0,
+ "skipped": 0,
+ "failed": 0,
+ "files": [],
+ } or payload["downloaded"] == 0
+
+ @respx.mock
+ async def test_skip_existing_does_not_refetch(self, harness, tmp_path):
+ existing = tmp_path / "a.pdf"
+ existing.write_bytes(b"OLD")
+
+ # No respx mock for a.pdf - if the handler tried to fetch, respx would raise.
+ result = await harness.execute(
+ "fileDownloader",
+ {
+ "items": [{"url": "https://example.com/a.pdf"}],
+ "outputDir": str(tmp_path),
+ "skipExisting": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["skipped"] == 1
+ assert result["result"]["downloaded"] == 0
+ # Existing bytes untouched
+ assert existing.read_bytes() == b"OLD"
+
+ @respx.mock
+ async def test_http_error_counted_as_failed(self, harness, tmp_path):
+ respx.get("https://example.com/bad.pdf").mock(
+ return_value=httpx.Response(500, text="boom")
+ )
+
+ result = await harness.execute(
+ "fileDownloader",
+ {
+ "items": [{"url": "https://example.com/bad.pdf"}],
+ "outputDir": str(tmp_path),
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["failed"] == 1
+ assert result["result"]["downloaded"] == 0
+
+
+# ============================================================================
+# documentParser
+# ============================================================================
+
+
+class TestDocumentParser:
+ async def test_beautifulsoup_parses_html_file(self, harness, tmp_path):
+ html = (
+ "<html><body>"
+ "<script>alert(1)</script>"
+ "<style>.x {color:red}</style>"
+ "<p>Hello <b>World</b></p>"
+ "</body></html>"
+ )
+ f = tmp_path / "page.html"
+ f.write_text(html, encoding="utf-8")
+
+ result = await harness.execute(
+ "documentParser",
+ {"files": [{"path": str(f)}], "parser": "beautifulsoup"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["documents", "parsed_count", "failed"])
+ payload = result["result"]
+ assert payload["parsed_count"] == 1
+ doc = payload["documents"][0]
+ assert doc["filename"] == "page.html"
+ assert doc["parser"] == "beautifulsoup"
+ # script and style tags stripped
+ assert "alert(1)" not in doc["content"]
+ assert ".x {color:red}" not in doc["content"]
+ assert "Hello" in doc["content"] and "World" in doc["content"]
+
+ async def test_no_files_returns_empty_documents(self, harness):
+ result = await harness.execute(
+ "documentParser", {"files": [], "inputDir": ""}
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["documents"] == []
+ assert result["result"]["parsed_count"] == 0
+
+ async def test_unknown_parser_collected_in_failed(self, harness, tmp_path):
+ f = tmp_path / "x.txt"
+ f.write_text("hello", encoding="utf-8")
+
+ result = await harness.execute(
+ "documentParser",
+ {"files": [{"path": str(f)}], "parser": "nonsense"},
+ )
+
+ # Per-file failures bubble into `failed`, NOT the top-level envelope.
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["parsed_count"] == 0
+ assert len(payload["failed"]) == 1
+ assert "Unknown parser" in payload["failed"][0]["error"]
+
+ async def test_pypdf_branch_via_patched_reader(self, harness, tmp_path):
+ # Patch pypdf at its import site inside _parse_file_sync.
+ f = tmp_path / "doc.pdf"
+ f.write_bytes(b"%PDF-FAKE")
+
+ fake_page = SimpleNamespace(extract_text=lambda: "page text")
+ fake_reader = MagicMock()
+ fake_reader.pages = [fake_page, fake_page]
+
+ fake_pypdf = MagicMock()
+ fake_pypdf.PdfReader = MagicMock(return_value=fake_reader)
+
+ with patch.dict(sys.modules, {"pypdf": fake_pypdf}):
+ result = await harness.execute(
+ "documentParser",
+ {"files": [{"path": str(f)}], "parser": "pypdf"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ doc = result["result"]["documents"][0]
+ assert doc["parser"] == "pypdf"
+ assert "page text" in doc["content"]
+
+
+# ============================================================================
+# textChunker
+# ============================================================================
+
+
+class TestTextChunker:
+ async def test_recursive_chunks_long_text(self, harness):
+ content = "abcdefghij" * 200 # 2000 chars
+ result = await harness.execute(
+ "textChunker",
+ {
+ "documents": [{"content": content, "source": "src1"}],
+ "chunkSize": 500,
+ "chunkOverlap": 50,
+ "strategy": "recursive",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["chunks", "chunk_count"])
+ payload = result["result"]
+ assert payload["chunk_count"] >= 3 # 2000 chars / 500 with overlap
+ # chunk_index is 0-based and monotonically increasing
+ indices = [c["chunk_index"] for c in payload["chunks"]]
+ assert indices == list(range(len(payload["chunks"])))
+ # source preserved
+ assert all(c["source"] == "src1" for c in payload["chunks"])
+
+ async def test_empty_documents_short_circuits(self, harness):
+ result = await harness.execute("textChunker", {"documents": []})
+ harness.assert_envelope(result, success=True)
+ assert result["result"] == {"chunks": [], "chunk_count": 0}
+
+ async def test_empty_content_doc_is_skipped(self, harness):
+ result = await harness.execute(
+ "textChunker",
+ {
+ "documents": [
+ {"content": "", "source": "empty"},
+ {"content": "short text", "source": "s2"},
+ ],
+ "chunkSize": 1024,
+ "chunkOverlap": 100,
+ },
+ )
+ harness.assert_envelope(result, success=True)
+ chunks = result["result"]["chunks"]
+ # Only the non-empty doc contributed a chunk
+ assert all(c["source"] == "s2" for c in chunks)
+ assert len(chunks) == 1
+
+ async def test_markdown_strategy_uses_markdown_splitter(self, harness):
+ md = "# Heading\n\nParagraph one.\n\n## Sub\n\nParagraph two.\n"
+ result = await harness.execute(
+ "textChunker",
+ {
+ "documents": [{"content": md, "source": "md1"}],
+ "chunkSize": 200,
+ "chunkOverlap": 20,
+ "strategy": "markdown",
+ },
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["chunk_count"] >= 1
+
+
+# ============================================================================
+# embeddingGenerator
+# ============================================================================
+
+
+class TestEmbeddingGenerator:
+ async def test_huggingface_happy_path_with_patched_embedder(self, harness):
+ # Patch langchain_huggingface at its lazy import site.
+ fake_embedder = MagicMock()
+ fake_embedder.embed_documents = MagicMock(
+ return_value=[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]
+ )
+
+ fake_hf_mod = MagicMock()
+ fake_hf_mod.HuggingFaceEmbeddings = MagicMock(return_value=fake_embedder)
+
+ with patch.dict(sys.modules, {"langchain_huggingface": fake_hf_mod}):
+ result = await harness.execute(
+ "embeddingGenerator",
+ {
+ "chunks": [
+ {"content": "first chunk", "source": "s1", "chunk_index": 0},
+ {"content": "second chunk", "source": "s1", "chunk_index": 1},
+ ],
+ "provider": "huggingface",
+ "model": "BAAI/bge-small-en-v1.5",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result,
+ ["embeddings", "embedding_count", "dimensions", "chunks", "provider", "model"],
+ )
+ payload = result["result"]
+ assert payload["embedding_count"] == 2
+ assert payload["dimensions"] == 3
+ assert payload["provider"] == "huggingface"
+ # Embedder was constructed with the requested model
+ fake_hf_mod.HuggingFaceEmbeddings.assert_called_once()
+ kwargs = fake_hf_mod.HuggingFaceEmbeddings.call_args.kwargs
+ assert kwargs.get("model_name") == "BAAI/bge-small-en-v1.5"
+
+ async def test_empty_chunks_short_circuits(self, harness):
+ result = await harness.execute(
+ "embeddingGenerator", {"chunks": [], "provider": "huggingface"}
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["embedding_count"] == 0
+ assert payload["dimensions"] == 0
+ assert payload["embeddings"] == []
+
+ async def test_unknown_provider_fails_envelope(self, harness):
+ result = await harness.execute(
+ "embeddingGenerator",
+ {"chunks": [{"content": "x"}], "provider": "made_up_provider"},
+ )
+ harness.assert_envelope(result, success=False)
+ assert "provider" in result["error"].lower()
+
+ async def test_openai_provider_uses_apikey_param(self, harness):
+ fake_embedder = MagicMock()
+ fake_embedder.embed_documents = MagicMock(return_value=[[0.9, 0.8]])
+
+ fake_openai_mod = MagicMock()
+ fake_openai_mod.OpenAIEmbeddings = MagicMock(return_value=fake_embedder)
+
+ with patch.dict(sys.modules, {"langchain_openai": fake_openai_mod}):
+ result = await harness.execute(
+ "embeddingGenerator",
+ {
+ "chunks": [{"content": "only"}],
+ "provider": "openai",
+ "model": "text-embedding-3-small",
+ "apiKey": "sk-test",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ fake_openai_mod.OpenAIEmbeddings.assert_called_once()
+ kwargs = fake_openai_mod.OpenAIEmbeddings.call_args.kwargs
+ assert kwargs.get("model") == "text-embedding-3-small"
+ assert kwargs.get("api_key") == "sk-test"
+
+
+# ============================================================================
+# vectorStore
+# ============================================================================
+
+
+class _FakeChromaCollection:
+ def __init__(self):
+ self.added = []
+ self.deleted_ids = []
+ self._count = 0
+
+ def add(self, ids, embeddings, documents, metadatas):
+ self.added.append({"ids": ids, "embeddings": embeddings,
+ "documents": documents, "metadatas": metadatas})
+ self._count += len(ids)
+
+ def count(self):
+ return self._count
+
+ def query(self, query_embeddings, n_results):
+ return {
+ "ids": [["id-1", "id-2"]],
+ "documents": [["doc one", "doc two"]],
+ "metadatas": [[{"source": "s1"}, {"source": "s2"}]],
+ "distances": [[0.1, 0.2]],
+ }
+
+ def delete(self, ids):
+ self.deleted_ids.extend(ids)
+
+
+def _patched_chromadb_module():
+ coll = _FakeChromaCollection()
+ client = MagicMock()
+ client.get_or_create_collection = MagicMock(return_value=coll)
+
+ module = MagicMock()
+ module.PersistentClient = MagicMock(return_value=client)
+ return module, coll
+
+
+class TestVectorStore:
+ async def test_chroma_store_happy_path(self, harness, tmp_path):
+ chromadb_mod, coll = _patched_chromadb_module()
+
+ with patch.dict(sys.modules, {"chromadb": chromadb_mod}):
+ result = await harness.execute(
+ "vectorStore",
+ {
+ "operation": "store",
+ "backend": "chroma",
+ "collectionName": "docs",
+ "embeddings": [[0.1, 0.2], [0.3, 0.4]],
+ "chunks": [
+ {"content": "c1", "source": "s1", "chunk_index": 0},
+ {"content": "c2", "source": "s1", "chunk_index": 1},
+ ],
+ "persistDir": str(tmp_path),
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["stored_count"] == 2
+ assert payload["backend"] == "chroma"
+ assert payload["collection_name"] == "docs"
+ # The collection actually received our vectors + docs
+ assert len(coll.added) == 1
+ batch = coll.added[0]
+ assert batch["embeddings"] == [[0.1, 0.2], [0.3, 0.4]]
+ assert batch["documents"] == ["c1", "c2"]
+
+ async def test_chroma_store_with_empty_embeddings_returns_zero(self, harness, tmp_path):
+ chromadb_mod, coll = _patched_chromadb_module()
+ with patch.dict(sys.modules, {"chromadb": chromadb_mod}):
+ result = await harness.execute(
+ "vectorStore",
+ {
+ "operation": "store",
+ "backend": "chroma",
+ "embeddings": [],
+ "chunks": [],
+ "persistDir": str(tmp_path),
+ },
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["stored_count"] == 0
+ # Nothing written to the underlying collection
+ assert coll.added == []
+
+ async def test_chroma_query_happy_path(self, harness, tmp_path):
+ chromadb_mod, coll = _patched_chromadb_module()
+ with patch.dict(sys.modules, {"chromadb": chromadb_mod}):
+ result = await harness.execute(
+ "vectorStore",
+ {
+ "operation": "query",
+ "backend": "chroma",
+ "collectionName": "docs",
+ "queryEmbedding": [0.1, 0.2],
+ "topK": 2,
+ "persistDir": str(tmp_path),
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ matches = result["result"]["matches"]
+ assert len(matches) == 2
+ assert matches[0]["id"] == "id-1"
+ assert matches[0]["document"] == "doc one"
+ assert matches[0]["distance"] == 0.1
+ assert matches[0]["metadata"] == {"source": "s1"}
+
+ async def test_chroma_delete_happy_path(self, harness, tmp_path):
+ chromadb_mod, coll = _patched_chromadb_module()
+ with patch.dict(sys.modules, {"chromadb": chromadb_mod}):
+ result = await harness.execute(
+ "vectorStore",
+ {
+ "operation": "delete",
+ "backend": "chroma",
+ "ids": ["id-a", "id-b", "id-c"],
+ "persistDir": str(tmp_path),
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["deleted"] is True
+ assert result["result"]["count"] == 3
+ assert coll.deleted_ids == ["id-a", "id-b", "id-c"]
+
+ async def test_unknown_backend_fails_envelope(self, harness):
+ result = await harness.execute(
+ "vectorStore",
+ {"operation": "store", "backend": "madeup", "embeddings": [[0.1]]},
+ )
+ harness.assert_envelope(result, success=False)
+ assert "backend" in result["error"].lower()
+
+ async def test_pinecone_requires_api_key(self, harness):
+ result = await harness.execute(
+ "vectorStore",
+ {
+ "operation": "store",
+ "backend": "pinecone",
+ "embeddings": [[0.1]],
+ "pineconeApiKey": "",
+ },
+ )
+ harness.assert_envelope(result, success=False)
+ assert "pinecone" in result["error"].lower() or "api key" in result["error"].lower()
diff --git a/server/tests/nodes/test_email.py b/server/tests/nodes/test_email.py
new file mode 100644
index 00000000..ffef913f
--- /dev/null
+++ b/server/tests/nodes/test_email.py
@@ -0,0 +1,311 @@
+"""Contract tests for email nodes: emailSend, emailRead, emailReceive.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/email/`. Email handlers shell out to the
+Himalaya CLI via `asyncio.create_subprocess_exec`, so every test uses
+`patched_subprocess` (from `_mocks.py`) and stubs `HimalayaService.ensure_binary`
+so no real `himalaya` binary or network is required.
+"""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_container, patched_pricing, patched_subprocess
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers
+# ---------------------------------------------------------------------------
+
+
+def _reset_singletons():
+ """Wipe cached singletons so each test gets a clean EmailService / HimalayaService."""
+ from services import email_service, himalaya_service
+
+ email_service.EmailService._instance = None
+ himalaya_service.HimalayaService._instance = None
+
+
+def _base_creds_params(**overrides):
+ """Minimal params that satisfy resolve_credentials without stored keys."""
+ params = {
+ "provider": "gmail",
+ "email": "[email protected]",
+ "password": "sekret",
+ }
+ params.update(overrides)
+ return params
+
+
+def _patch_ensure_binary():
+ """Patch HimalayaService.ensure_binary to return a fake path without shutil.which."""
+ return patch(
+ "services.himalaya_service.HimalayaService.ensure_binary",
+ new=AsyncMock(return_value="/usr/bin/himalaya"),
+ )
+
+
[email protected](autouse=True)
+def _clean_singletons():
+ _reset_singletons()
+ yield
+ _reset_singletons()
+
+
+# ===========================================================================
+# emailSend
+# ===========================================================================
+
+
+class TestEmailSend:
+ async def test_happy_path(self, harness):
+ stdout = json.dumps({"status": "sent"}).encode()
+
+ with _patch_ensure_binary(), patched_subprocess(stdout=stdout, returncode=0) as proc, \
+ patched_container(), patched_pricing():
+ result = await harness.execute(
+ "emailSend",
+ _base_creds_params(
+ subject="hi",
+ body="hello bob",
+ body_type="text",
+ ),
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["from"] == "[email protected]"
+ assert payload.get("status") == "sent"
+ # Exactly one subprocess spawn for a single send
+ proc.communicate.assert_awaited()
+
+ async def test_html_body_builds_multipart(self, harness):
+ # Return empty JSON so himalaya "succeeds" with no extra fields
+ with _patch_ensure_binary(), patched_subprocess(stdout=b"{}", returncode=0), \
+ patched_container(), patched_pricing(), \
+ patch("services.himalaya_service.HimalayaService.execute",
+ new=AsyncMock(return_value={})) as mock_exec:
+ result = await harness.execute(
+ "emailSend",
+ _base_creds_params(
+ subject="hi",
+ body="<p>hello</p>",
+ body_type="html",
+ ),
+ )
+
+ harness.assert_envelope(result, success=True)
+ # Inspect the MIME stdin passed to himalaya
+ call_kwargs = mock_exec.await_args.kwargs
+ stdin_data = call_kwargs.get("stdin_data") or mock_exec.await_args.args[-1]
+ assert "multipart/alternative" in stdin_data
+ assert "text/html" in stdin_data
+
+ async def test_missing_credentials_returns_error(self, harness):
+ # No email/password in params AND no stored keys -> ValueError -> envelope
+ with _patch_ensure_binary(), patched_subprocess(), \
+ patched_container(auth_api_keys={}), patched_pricing():
+ result = await harness.execute(
+ "emailSend",
+ {"to": "[email protected]", "subject": "s", "body": "b"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "email" in result["error"].lower() or "password" in result["error"].lower()
+
+ async def test_subprocess_failure_returns_error(self, harness):
+ # Non-zero returncode -> HimalayaService raises RuntimeError -> envelope
+ with _patch_ensure_binary(), \
+ patched_subprocess(stdout=b"", stderr=b"auth failed", returncode=1), \
+ patched_container(), patched_pricing():
+ result = await harness.execute(
+ "emailSend",
+ _base_creds_params(to="[email protected]", subject="s", body="b"),
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "himalaya" in result["error"].lower() or "auth failed" in result["error"].lower()
+
+
+# ===========================================================================
+# emailRead
+# ===========================================================================
+
+
+class TestEmailRead:
+ async def test_list_happy_path(self, harness):
+ envelopes = [
+ {"id": "1", "subject": "first", "from": "[email protected]"},
+ {"id": "2", "subject": "second", "from": "[email protected]"},
+ ]
+ # Himalaya returns a list for envelope list -> wrapped in {data: ...}
+ with _patch_ensure_binary(), \
+ patch("services.himalaya_service.HimalayaService.execute",
+ new=AsyncMock(return_value=envelopes)), \
+ patched_container(), patched_pricing():
+ result = await harness.execute(
+ "emailRead",
+ _base_creds_params(operation="list", folder="INBOX", page=1, page_size=20),
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["operation"] == "list"
+ assert payload["folder"] == "INBOX"
+ assert payload["data"] == envelopes
+
+ async def test_read_merges_dict_output(self, harness):
+ message = {"subject": "hello", "body": "world", "from": "[email protected]"}
+ with _patch_ensure_binary(), \
+ patch("services.himalaya_service.HimalayaService.execute",
+ new=AsyncMock(return_value=message)), \
+ patched_container(), patched_pricing():
+ result = await harness.execute(
+ "emailRead",
+ _base_creds_params(operation="read", message_id="42", folder="INBOX"),
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["operation"] == "read"
+ assert payload["subject"] == "hello"
+ assert payload["body"] == "world"
+
+ async def test_unknown_operation_returns_error(self, harness):
+ # No subprocess should be spawned; router raises ValueError
+ with _patch_ensure_binary(), patched_subprocess(), \
+ patched_container(), patched_pricing():
+ result = await harness.execute(
+ "emailRead",
+ _base_creds_params(operation="nonsense"),
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown operation" in result["error"].lower()
+
+ async def test_subprocess_failure_returns_error(self, harness):
+ with _patch_ensure_binary(), \
+ patched_subprocess(stdout=b"", stderr=b"folder not found", returncode=1), \
+ patched_container(), patched_pricing():
+ result = await harness.execute(
+ "emailRead",
+ _base_creds_params(operation="list", folder="DoesNotExist"),
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "himalaya" in result["error"].lower() or "folder not found" in result["error"].lower()
+
+
+# ===========================================================================
+# emailReceive (polling trigger)
+# ===========================================================================
+
+
+class TestEmailReceive:
+ async def test_new_email_detected_on_second_poll(self, harness):
+ """Baseline sees {id1}; next poll returns {id1,id2} -> dispatch id2."""
+ from services.email_service import EmailService
+
+ email_detail = {"from": "[email protected]", "subject": "new!", "body": "hi"}
+
+ # poll_ids: first call returns baseline, second returns baseline+new
+ poll_ids_mock = AsyncMock(side_effect=[{"1"}, {"1", "2"}])
+ fetch_detail_mock = AsyncMock(return_value={
+ **email_detail, "message_id": "2", "folder": "INBOX",
+ })
+
+ with patched_container(), patched_pricing(), \
+ patch.object(EmailService, "poll_ids", poll_ids_mock), \
+ patch.object(EmailService, "fetch_detail", fetch_detail_mock), \
+ patch("services.handlers.email.asyncio.sleep", new=AsyncMock(return_value=None)), \
+ patch("services.status_broadcaster.get_status_broadcaster") as bcast, \
+ patch("services.event_waiter.dispatch") as dispatch_mock:
+ bcast.return_value.update_node_status = AsyncMock(return_value=None)
+
+ result = await harness.execute(
+ "emailReceive",
+ _base_creds_params(folder="INBOX", poll_interval=30, mark_as_read=False),
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["message_id"] == "2"
+ assert payload["folder"] == "INBOX"
+ assert payload["subject"] == "new!"
+ # Baseline + one diffing poll
+ assert poll_ids_mock.await_count == 2
+ # Event dispatched exactly once
+ dispatch_mock.assert_called_once()
+ assert dispatch_mock.call_args.args[0] == "email_received"
+
+ async def test_mark_as_read_adds_seen_flag(self, harness):
+ from services.email_service import EmailService
+ from services.himalaya_service import HimalayaService
+
+ poll_ids_mock = AsyncMock(side_effect=[set(), {"42"}])
+ fetch_detail_mock = AsyncMock(return_value={"message_id": "42", "folder": "INBOX"})
+ flag_mock = AsyncMock(return_value={})
+
+ with patched_container(), patched_pricing(), \
+ patch.object(EmailService, "poll_ids", poll_ids_mock), \
+ patch.object(EmailService, "fetch_detail", fetch_detail_mock), \
+ patch.object(HimalayaService, "flag_message", flag_mock), \
+ patch("services.handlers.email.asyncio.sleep", new=AsyncMock(return_value=None)), \
+ patch("services.status_broadcaster.get_status_broadcaster") as bcast, \
+ patch("services.event_waiter.dispatch"):
+ bcast.return_value.update_node_status = AsyncMock(return_value=None)
+
+ result = await harness.execute(
+ "emailReceive",
+ _base_creds_params(folder="INBOX", mark_as_read=True),
+ )
+
+ harness.assert_envelope(result, success=True)
+ flag_mock.assert_awaited_once()
+ # Called with message_id="42" and flag="Seen" (from defaults)
+ _, kwargs = flag_mock.call_args
+ # The handler calls flag_message(creds, msg_id, flag, action, folder) positionally
+ args = flag_mock.call_args.args
+ assert "42" in args
+ assert "Seen" in args
+
+ async def test_missing_credentials_returns_error(self, harness):
+ with patched_container(auth_api_keys={}), patched_pricing(), \
+ patch("services.handlers.email.asyncio.sleep", new=AsyncMock(return_value=None)):
+ result = await harness.execute(
+ "emailReceive",
+ {"provider": "gmail", "folder": "INBOX"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "email" in result["error"].lower() or "password" in result["error"].lower()
+
+ async def test_subprocess_error_surfaces_as_envelope(self, harness):
+ """If poll_ids raises (e.g. Himalaya subprocess fails) the handler returns an error envelope."""
+ from services.email_service import EmailService
+
+ poll_ids_mock = AsyncMock(side_effect=RuntimeError("himalaya error: connection refused"))
+
+ with patched_container(), patched_pricing(), \
+ patch.object(EmailService, "poll_ids", poll_ids_mock), \
+ patch("services.handlers.email.asyncio.sleep", new=AsyncMock(return_value=None)), \
+ patch("services.status_broadcaster.get_status_broadcaster") as bcast, \
+ patch("services.event_waiter.dispatch"):
+ bcast.return_value.update_node_status = AsyncMock(return_value=None)
+
+ result = await harness.execute(
+ "emailReceive",
+ _base_creds_params(folder="INBOX"),
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "himalaya" in result["error"].lower() or "connection refused" in result["error"].lower()
diff --git a/server/tests/nodes/test_google_workspace.py b/server/tests/nodes/test_google_workspace.py
new file mode 100644
index 00000000..a33fc918
--- /dev/null
+++ b/server/tests/nodes/test_google_workspace.py
@@ -0,0 +1,757 @@
+"""Contract tests for Google Workspace nodes.
+
+Covers: gmail, gmailReceive, calendar, drive, sheets, tasks, contacts.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/google_workspace/`. All handlers build a
+googleapiclient service via `build(...)` and depend on
+`get_google_credentials()` for OAuth. We patch both at the handler-module
+import site so no real OAuth or googleapiclient traffic is required.
+
+Patching strategy
+-----------------
+- `services.handlers.<file>.get_google_credentials` -> AsyncMock returning a
+ MagicMock that quacks like `google.oauth2.credentials.Credentials`.
+- `services.handlers.<file>.build` -> MagicMock returning a chainable service
+ so expressions like
+ `service.users().messages().send(userId=..., body=...).execute()`
+ resolve without real API traffic.
+
+Handlers run the google client calls via `loop.run_in_executor(None, fn)` so
+the MagicMock `.execute()` call happens synchronously inside the executor.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# --------------------------------------------------------------------------- #
+# Shared helpers
+# --------------------------------------------------------------------------- #
+
+
+def _patch_creds(module_name: str, creds_return=None, side_effect=None):
+ """Patch `get_google_credentials` inside a handler module.
+
+ By default returns a MagicMock that stands in for a Credentials instance.
+ Pass `side_effect=ValueError(...)` to simulate missing credentials.
+ """
+ target = f"services.handlers.{module_name}.get_google_credentials"
+ kwargs = {}
+ if side_effect is not None:
+ kwargs["side_effect"] = side_effect
+ else:
+ kwargs["return_value"] = creds_return if creds_return is not None else MagicMock(name="Credentials")
+ return patch(target, new=AsyncMock(**kwargs))
+
+
+def _patch_build(module_name: str, service_mock):
+ """Patch googleapiclient `build(...)` to return a provided service MagicMock."""
+ target = f"services.handlers.{module_name}.build"
+ return patch(target, return_value=service_mock)
+
+
+# ============================================================================
+# gmail
+# ============================================================================
+
+
+class TestGmail:
+ async def test_send_happy_path(self, harness):
+ service = MagicMock(name="GmailService")
+ send_exec = service.users().messages().send.return_value.execute
+ send_exec.return_value = {
+ "id": "msg-1",
+ "threadId": "thr-1",
+ "labelIds": ["SENT"],
+ }
+
+ with _patch_creds("gmail"), _patch_build("gmail", service):
+ result = await harness.execute(
+ "gmail",
+ {
+ "operation": "send",
+ "subject": "hi",
+ "body": "hello world",
+ "body_type": "text",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["message_id"] == "msg-1"
+ assert payload["thread_id"] == "thr-1"
+ assert payload["to"] == "[email protected]"
+ assert payload["subject"] == "hi"
+ # send was called with userId=me and a base64 raw body
+ send_call = service.users().messages().send.call_args
+ assert send_call.kwargs["userId"] == "me"
+ assert "raw" in send_call.kwargs["body"]
+ assert isinstance(send_call.kwargs["body"]["raw"], str)
+
+ async def test_send_missing_recipient_errors(self, harness):
+ service = MagicMock(name="GmailService")
+ with _patch_creds("gmail"), _patch_build("gmail", service):
+ result = await harness.execute(
+ "gmail",
+ {
+ "operation": "send",
+ # no to
+ "subject": "x",
+ "body": "y",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "recipient" in result["error"].lower() or "to" in result["error"].lower()
+
+ async def test_search_happy_path_without_body(self, harness):
+ service = MagicMock(name="GmailService")
+ # messages.list -> two message ids
+ service.users().messages().list.return_value.execute.return_value = {
+ "messages": [{"id": "m1"}, {"id": "m2"}],
+ "resultSizeEstimate": 2,
+ }
+ # messages.get returns metadata for each
+ def _make_msg(mid):
+ return {
+ "id": mid,
+ "threadId": f"t-{mid}",
+ "snippet": f"snippet-{mid}",
+ "labelIds": ["INBOX"],
+ "sizeEstimate": 10,
+ "payload": {
+ "headers": [
+ {"name": "From", "value": "[email protected]"},
+ {"name": "Subject", "value": f"Subject {mid}"},
+ ],
+ },
+ }
+
+ service.users().messages().get.return_value.execute.side_effect = [
+ _make_msg("m1"),
+ _make_msg("m2"),
+ ]
+
+ with _patch_creds("gmail"), _patch_build("gmail", service):
+ result = await harness.execute(
+ "gmail",
+ {
+ "operation": "search",
+ "query": "from:alice",
+ "max_results": 2,
+ "include_body": False,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["count"] == 2
+ assert payload["query"] == "from:alice"
+ assert payload["messages"][0]["message_id"] == "m1"
+ assert payload["messages"][0]["from"] == "[email protected]"
+ assert payload["messages"][1]["subject"] == "Subject m2"
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_creds("gmail"), _patch_build("gmail", MagicMock()):
+ result = await harness.execute(
+ "gmail",
+ {"operation": "bogus"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown gmail operation" in result["error"].lower()
+
+ async def test_missing_credentials_short_circuits(self, harness):
+ with _patch_creds(
+ "gmail", side_effect=ValueError("Google Workspace not connected")
+ ), _patch_build("gmail", MagicMock()):
+ result = await harness.execute(
+ "gmail",
+ {
+ "operation": "send",
+ "subject": "x",
+ "body": "y",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+
+
+# ============================================================================
+# gmailReceive (polling trigger - single-tick happy path)
+# ============================================================================
+
+
+class TestGmailReceive:
+ async def test_happy_path_returns_newest_email(self, harness):
+ """Baseline empty -> first poll finds new id -> fetch details -> return."""
+ service = MagicMock(name="GmailService")
+ # Baseline call: empty
+ # Subsequent call: returns one new message
+ list_exec = service.users().messages().list.return_value.execute
+ list_exec.side_effect = [
+ {"messages": []}, # baseline
+ {"messages": [{"id": "new-1"}]}, # new
+ ]
+ service.users().messages().get.return_value.execute.return_value = {
+ "id": "new-1",
+ "threadId": "t-new-1",
+ "snippet": "hello",
+ "labelIds": ["INBOX", "UNREAD"],
+ "sizeEstimate": 42,
+ "payload": {
+ "headers": [
+ {"name": "From", "value": "[email protected]"},
+ {"name": "Subject", "value": "Greetings"},
+ ],
+ },
+ }
+
+ async def _instant_sleep(_seconds):
+ return None
+
+ with _patch_creds("gmail"), _patch_build("gmail", service), patch(
+ "asyncio.sleep", new=_instant_sleep
+ ), patch("services.status_broadcaster.get_status_broadcaster") as gsb, patch(
+ "services.event_waiter.dispatch", return_value=1
+ ):
+ gsb.return_value = MagicMock(update_node_status=AsyncMock())
+ result = await harness.execute(
+ "gmailReceive",
+ {
+ "filter_query": "is:unread",
+ "label_filter": "INBOX",
+ "mark_as_read": False,
+ "poll_interval": 30,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["message_id"] == "new-1"
+ assert payload["subject"] == "Greetings"
+ assert payload["from"] == "[email protected]"
+
+ async def test_mark_as_read_calls_modify(self, harness):
+ service = MagicMock(name="GmailService")
+ list_exec = service.users().messages().list.return_value.execute
+ list_exec.side_effect = [
+ {"messages": []},
+ {"messages": [{"id": "new-2"}]},
+ ]
+ service.users().messages().get.return_value.execute.return_value = {
+ "id": "new-2",
+ "threadId": "t2",
+ "snippet": "s",
+ "labelIds": ["UNREAD"],
+ "sizeEstimate": 1,
+ "payload": {"headers": []},
+ }
+ modify_exec = service.users().messages().modify.return_value.execute
+
+ async def _instant_sleep(_seconds):
+ return None
+
+ with _patch_creds("gmail"), _patch_build("gmail", service), patch(
+ "asyncio.sleep", new=_instant_sleep
+ ), patch("services.status_broadcaster.get_status_broadcaster") as gsb, patch(
+ "services.event_waiter.dispatch", return_value=1
+ ):
+ gsb.return_value = MagicMock(update_node_status=AsyncMock())
+ result = await harness.execute(
+ "gmailReceive",
+ {
+ "filter_query": "is:unread",
+ "label_filter": "INBOX",
+ "mark_as_read": True,
+ "poll_interval": 30,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ # modify must have been called (to remove UNREAD)
+ assert modify_exec.called
+ modify_call = service.users().messages().modify.call_args
+ assert modify_call.kwargs["id"] == "new-2"
+ assert modify_call.kwargs["body"] == {"removeLabelIds": ["UNREAD"]}
+
+ async def test_missing_credentials_returns_error(self, harness):
+ with _patch_creds(
+ "gmail", side_effect=ValueError("Google Workspace not connected")
+ ):
+ result = await harness.execute(
+ "gmailReceive",
+ {
+ "filter_query": "is:unread",
+ "poll_interval": 30,
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+
+
+# ============================================================================
+# calendar
+# ============================================================================
+
+
+class TestCalendar:
+ async def test_create_happy_path(self, harness):
+ service = MagicMock(name="CalendarService")
+ service.events().insert.return_value.execute.return_value = {
+ "id": "evt-1",
+ "summary": "Standup",
+ "start": {"dateTime": "2026-04-15T09:00:00Z"},
+ "end": {"dateTime": "2026-04-15T09:30:00Z"},
+ "htmlLink": "https://cal/evt-1",
+ "status": "confirmed",
+ "created": "2026-04-14T10:00:00Z",
+ }
+
+ with _patch_creds("calendar"), _patch_build("calendar", service):
+ result = await harness.execute(
+ "calendar",
+ {
+ "operation": "create",
+ "title": "Standup",
+ "start_time": "2026-04-15T09:00:00Z",
+ "end_time": "2026-04-15T09:30:00Z",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["event_id"] == "evt-1"
+ assert payload["title"] == "Standup"
+ # insert was called with sendUpdates=all
+ insert_call = service.events().insert.call_args
+ assert insert_call.kwargs["sendUpdates"] == "all"
+ body = insert_call.kwargs["body"]
+ assert body["summary"] == "Standup"
+ assert len(body["attendees"]) == 2
+
+ async def test_delete_missing_event_id_errors(self, harness):
+ service = MagicMock(name="CalendarService")
+ with _patch_creds("calendar"), _patch_build("calendar", service):
+ result = await harness.execute(
+ "calendar",
+ {"operation": "delete"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "event id" in result["error"].lower()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_creds("calendar"), _patch_build("calendar", MagicMock()):
+ result = await harness.execute(
+ "calendar",
+ {"operation": "archive"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown calendar operation" in result["error"].lower()
+
+ async def test_missing_credentials_short_circuits(self, harness):
+ with _patch_creds(
+ "calendar", side_effect=ValueError("Google Workspace not connected")
+ ), _patch_build("calendar", MagicMock()):
+ result = await harness.execute(
+ "calendar",
+ {
+ "operation": "create",
+ "title": "x",
+ "start_time": "2026-04-15T09:00:00Z",
+ "end_time": "2026-04-15T09:30:00Z",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+
+
+# ============================================================================
+# drive
+# ============================================================================
+
+
+class TestDrive:
+ async def test_list_happy_path(self, harness):
+ service = MagicMock(name="DriveService")
+ service.files().list.return_value.execute.return_value = {
+ "files": [
+ {
+ "id": "f1",
+ "name": "Report.pdf",
+ "mimeType": "application/pdf",
+ "size": "1024",
+ "webViewLink": "https://drive/f1",
+ "createdTime": "2026-04-01T00:00:00Z",
+ "modifiedTime": "2026-04-10T00:00:00Z",
+ "parents": ["root"],
+ "owners": [{"emailAddress": "[email protected]"}],
+ },
+ ],
+ "nextPageToken": None,
+ }
+
+ with _patch_creds("drive"), _patch_build("drive", service):
+ result = await harness.execute(
+ "drive",
+ {
+ "operation": "list",
+ "max_results": 50,
+ "file_types": "all",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["count"] == 1
+ assert payload["files"][0]["file_id"] == "f1"
+ assert payload["files"][0]["owner"] == "[email protected]"
+ # query always includes trashed=false
+ list_call = service.files().list.call_args
+ assert "trashed = false" in list_call.kwargs["q"]
+
+ async def test_share_happy_path(self, harness):
+ service = MagicMock(name="DriveService")
+ service.permissions().create.return_value.execute.return_value = {
+ "id": "perm-1",
+ "type": "user",
+ "role": "reader",
+ "emailAddress": "[email protected]",
+ }
+ service.files().get.return_value.execute.return_value = {
+ "id": "file-x",
+ "name": "Shared.txt",
+ "webViewLink": "https://drive/shared",
+ }
+
+ with _patch_creds("drive"), _patch_build("drive", service):
+ result = await harness.execute(
+ "drive",
+ {
+ "operation": "share",
+ "file_id": "file-x",
+ "email": "[email protected]",
+ "role": "reader",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["permission_id"] == "perm-1"
+ assert payload["shared_with"] == "[email protected]"
+ assert payload["file_name"] == "Shared.txt"
+
+ async def test_upload_missing_source_errors(self, harness):
+ service = MagicMock(name="DriveService")
+ with _patch_creds("drive"), _patch_build("drive", service):
+ result = await harness.execute(
+ "drive",
+ {
+ "operation": "upload",
+ "filename": "x.txt",
+ # no file_url and no file_content
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "file_url" in result["error"].lower() or "file_content" in result["error"].lower()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_creds("drive"), _patch_build("drive", MagicMock()):
+ result = await harness.execute(
+ "drive",
+ {"operation": "trash"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown drive operation" in result["error"].lower()
+
+
+# ============================================================================
+# sheets
+# ============================================================================
+
+
+class TestSheets:
+ async def test_read_happy_path(self, harness):
+ service = MagicMock(name="SheetsService")
+ service.spreadsheets().values().get.return_value.execute.return_value = {
+ "range": "Sheet1!A1:B2",
+ "majorDimension": "ROWS",
+ "values": [["a", "b"], ["c", "d"]],
+ }
+
+ with _patch_creds("sheets"), _patch_build("sheets", service):
+ result = await harness.execute(
+ "sheets",
+ {
+ "operation": "read",
+ "spreadsheet_id": "sheet-123",
+ "range": "Sheet1!A1:B2",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["rows"] == 2
+ assert payload["columns"] == 2
+ assert payload["values"] == [["a", "b"], ["c", "d"]]
+
+ async def test_write_happy_path_with_1d_list(self, harness):
+ """1D list is auto-wrapped to 2D before sending to API."""
+ service = MagicMock(name="SheetsService")
+ service.spreadsheets().values().update.return_value.execute.return_value = {
+ "updatedRange": "Sheet1!A1:C1",
+ "updatedRows": 1,
+ "updatedColumns": 3,
+ "updatedCells": 3,
+ }
+
+ with _patch_creds("sheets"), _patch_build("sheets", service):
+ result = await harness.execute(
+ "sheets",
+ {
+ "operation": "write",
+ "spreadsheet_id": "sheet-123",
+ "range": "Sheet1!A1",
+ "values": ["x", "y", "z"],
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["updated_cells"] == 3
+ # body must have been wrapped to 2D
+ update_call = service.spreadsheets().values().update.call_args
+ body_values = update_call.kwargs["body"]["values"]
+ assert body_values == [["x", "y", "z"]]
+
+ async def test_read_missing_range_errors(self, harness):
+ service = MagicMock(name="SheetsService")
+ with _patch_creds("sheets"), _patch_build("sheets", service):
+ result = await harness.execute(
+ "sheets",
+ {
+ "operation": "read",
+ "spreadsheet_id": "sheet-123",
+ # no range
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "range" in result["error"].lower()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_creds("sheets"), _patch_build("sheets", MagicMock()):
+ result = await harness.execute(
+ "sheets",
+ {"operation": "clear"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown sheets operation" in result["error"].lower()
+
+
+# ============================================================================
+# tasks
+# ============================================================================
+
+
+class TestTasks:
+ async def test_create_happy_path(self, harness):
+ service = MagicMock(name="TasksService")
+ service.tasks().insert.return_value.execute.return_value = {
+ "id": "task-1",
+ "title": "Buy milk",
+ "notes": "2 gallons",
+ "due": "2026-04-20T00:00:00.000Z",
+ "status": "needsAction",
+ "selfLink": "https://tasks/task-1",
+ }
+
+ with _patch_creds("tasks"), _patch_build("tasks", service):
+ result = await harness.execute(
+ "tasks",
+ {
+ "operation": "create",
+ "title": "Buy milk",
+ "notes": "2 gallons",
+ "due_date": "2026-04-20", # no T - handler should upgrade
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["task_id"] == "task-1"
+ assert payload["title"] == "Buy milk"
+ # due_date without T was upgraded to T00:00:00.000Z
+ insert_call = service.tasks().insert.call_args
+ assert insert_call.kwargs["body"]["due"] == "2026-04-20T00:00:00.000Z"
+
+ async def test_complete_reads_then_updates(self, harness):
+ """Complete should do a get then update with status=completed."""
+ service = MagicMock(name="TasksService")
+ service.tasks().get.return_value.execute.return_value = {
+ "id": "task-9",
+ "title": "Review",
+ "status": "needsAction",
+ }
+ service.tasks().update.return_value.execute.return_value = {
+ "id": "task-9",
+ "title": "Review",
+ "status": "completed",
+ "completed": "2026-04-15T12:00:00Z",
+ }
+
+ with _patch_creds("tasks"), _patch_build("tasks", service):
+ result = await harness.execute(
+ "tasks",
+ {"operation": "complete", "task_id": "task-9"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["status"] == "completed"
+ update_call = service.tasks().update.call_args
+ assert update_call.kwargs["body"]["status"] == "completed"
+
+ async def test_delete_missing_task_id_errors(self, harness):
+ service = MagicMock(name="TasksService")
+ with _patch_creds("tasks"), _patch_build("tasks", service):
+ result = await harness.execute(
+ "tasks",
+ {"operation": "delete"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "task id" in result["error"].lower()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_creds("tasks"), _patch_build("tasks", MagicMock()):
+ result = await harness.execute(
+ "tasks",
+ {"operation": "star"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown tasks operation" in result["error"].lower()
+
+
+# ============================================================================
+# contacts
+# ============================================================================
+
+
+class TestContacts:
+ async def test_create_happy_path(self, harness):
+ service = MagicMock(name="PeopleService")
+ service.people().createContact.return_value.execute.return_value = {
+ "resourceName": "people/c123",
+ "names": [{"displayName": "Alice Smith", "givenName": "Alice", "familyName": "Smith"}],
+ "emailAddresses": [{"value": "[email protected]", "metadata": {"primary": True}}],
+ "phoneNumbers": [],
+ "organizations": [],
+ "photos": [],
+ }
+
+ with _patch_creds("contacts"), _patch_build("contacts", service):
+ result = await harness.execute(
+ "contacts",
+ {
+ "operation": "create",
+ "first_name": "Alice",
+ "last_name": "Smith",
+ "email": "[email protected]",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["resource_name"] == "people/c123"
+ assert payload["display_name"] == "Alice Smith"
+ assert payload["email"] == "[email protected]"
+
+ async def test_search_happy_path(self, harness):
+ service = MagicMock(name="PeopleService")
+ service.people().searchContacts.return_value.execute.return_value = {
+ "results": [
+ {
+ "person": {
+ "resourceName": "people/c1",
+ "names": [{"displayName": "Bob", "givenName": "Bob", "familyName": ""}],
+ "emailAddresses": [{"value": "[email protected]", "metadata": {"primary": True}}],
+ "phoneNumbers": [],
+ "organizations": [],
+ "photos": [],
+ }
+ }
+ ]
+ }
+
+ with _patch_creds("contacts"), _patch_build("contacts", service):
+ result = await harness.execute(
+ "contacts",
+ {
+ "operation": "search",
+ "query": "bob",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["count"] == 1
+ assert payload["contacts"][0]["email"] == "[email protected]"
+
+ async def test_create_missing_first_name_errors(self, harness):
+ service = MagicMock(name="PeopleService")
+ with _patch_creds("contacts"), _patch_build("contacts", service):
+ result = await harness.execute(
+ "contacts",
+ {
+ "operation": "create",
+ # no first_name
+ "email": "[email protected]",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "first name" in result["error"].lower()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_creds("contacts"), _patch_build("contacts", MagicMock()):
+ result = await harness.execute(
+ "contacts",
+ {"operation": "merge"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown contacts operation" in result["error"].lower()
+
+ async def test_missing_credentials_short_circuits(self, harness):
+ with _patch_creds(
+ "contacts", side_effect=ValueError("Google Workspace not connected")
+ ), _patch_build("contacts", MagicMock()):
+ result = await harness.execute(
+ "contacts",
+ {
+ "operation": "create",
+ "first_name": "Alice",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
diff --git a/server/tests/nodes/test_http_proxy.py b/server/tests/nodes/test_http_proxy.py
new file mode 100644
index 00000000..46eb942b
--- /dev/null
+++ b/server/tests/nodes/test_http_proxy.py
@@ -0,0 +1,404 @@
+"""Contract tests for http_proxy nodes: httpRequest, proxyRequest, proxyConfig, proxyStatus.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/http_proxy/`. A refactor that breaks any of
+these indicates the docs (and the user-visible contract) need to be updated
+too.
+
+All httpx calls are mocked via respx; the ProxyService singleton is patched
+so `useProxy=true` branches route through a test-controlled proxy URL.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+import respx
+
+from tests.nodes._mocks import patched_container
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# Helpers
+# ============================================================================
+
+
+def _make_proxy_service_mock(
+ *,
+ enabled: bool = True,
+ proxy_url: str | None = "http://user:[email protected]:8080",
+ providers: list | None = None,
+ stats: dict | None = None,
+) -> MagicMock:
+ svc = MagicMock(name="ProxyService")
+ svc.is_enabled = MagicMock(return_value=enabled)
+ svc.get_proxy_url = AsyncMock(return_value=proxy_url)
+ svc.report_result = MagicMock(return_value=None)
+ svc.reload_providers = AsyncMock(return_value=None)
+ svc.get_providers = MagicMock(return_value=providers or [])
+ svc.get_routing_rules = MagicMock(return_value=[])
+ svc.get_stats = MagicMock(return_value=stats or {})
+ return svc
+
+
+def _pricing_with_proxy_config() -> MagicMock:
+ """Pricing stub that satisfies `_track_proxy_usage`'s `pricing._config.get('proxy', {}).get(...)` chain."""
+ pricing = MagicMock(name="PricingService")
+ pricing._config = {"proxy": {}}
+ return pricing
+
+
+# ============================================================================
+# httpRequest
+# ============================================================================
+
+
+class TestHttpRequest:
+ URL = "https://api.example.com/data"
+
+ @respx.mock
+ async def test_happy_path_no_proxy(self, harness):
+ respx.get(self.URL).mock(
+ return_value=httpx.Response(200, json={"ok": True, "value": 42})
+ )
+
+ result = await harness.execute(
+ "httpRequest",
+ {"method": "GET", "url": self.URL, "headers": '{"X-Test": "1"}'},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["status", "data", "headers", "url", "method", "proxied"]
+ )
+ payload = result["result"]
+ assert payload["status"] == 200
+ assert payload["method"] == "GET"
+ assert payload["proxied"] is False
+ assert payload["data"] == {"ok": True, "value": 42}
+
+ sent = respx.calls.last.request
+ assert sent.headers["x-test"] == "1"
+
+ async def test_missing_url_returns_validation_error(self, harness):
+ result = await harness.execute("httpRequest", {"method": "GET", "url": ""})
+
+ harness.assert_envelope(result, success=False)
+ assert "url is required" in result["error"].lower()
+
+ @respx.mock
+ async def test_network_error_returns_envelope_not_raise(self, harness):
+ respx.get(self.URL).mock(
+ side_effect=httpx.ConnectError("connection refused")
+ )
+
+ result = await harness.execute(
+ "httpRequest", {"method": "GET", "url": self.URL}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "connection refused" in result["error"].lower()
+
+ @respx.mock
+ async def test_non_json_response_falls_back_to_text(self, harness):
+ respx.get(self.URL).mock(
+ return_value=httpx.Response(200, text="<html>hi</html>")
+ )
+
+ result = await harness.execute(
+ "httpRequest", {"method": "GET", "url": self.URL}
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["data"] == "<html>hi</html>"
+
+ @respx.mock
+ async def test_use_proxy_true_routes_through_proxy_service(self, harness):
+ # Happy proxy path: ProxyService returns a proxy URL, handler tags proxied=true.
+ respx.get(self.URL).mock(return_value=httpx.Response(200, json={"ok": True}))
+ proxy_svc = _make_proxy_service_mock(proxy_url="http://u:[email protected]:8080")
+
+ with patch("services.proxy.service.get_proxy_service", return_value=proxy_svc):
+ result = await harness.execute(
+ "httpRequest",
+ {"method": "GET", "url": self.URL, "useProxy": True, "proxyCountry": "US"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["proxied"] is True
+ # ProxyService.get_proxy_url was consulted with the target URL + params
+ proxy_svc.get_proxy_url.assert_awaited_once()
+ call_args = proxy_svc.get_proxy_url.await_args
+ assert call_args.args[0] == self.URL
+ assert call_args.args[1]["proxyCountry"] == "US"
+
+ @respx.mock
+ async def test_use_proxy_swallows_proxy_error_and_proceeds(self, harness):
+ # Documented behaviour: if proxy lookup raises, the handler logs a
+ # warning and falls back to a direct call (proxied=False).
+ respx.get(self.URL).mock(return_value=httpx.Response(200, json={"ok": 1}))
+ proxy_svc = _make_proxy_service_mock()
+ proxy_svc.get_proxy_url = AsyncMock(side_effect=RuntimeError("budget exceeded"))
+
+ with patch("services.proxy.service.get_proxy_service", return_value=proxy_svc):
+ result = await harness.execute(
+ "httpRequest",
+ {"method": "GET", "url": self.URL, "useProxy": True},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["proxied"] is False
+
+
+# ============================================================================
+# proxyRequest
+# ============================================================================
+
+
+class TestProxyRequest:
+ URL = "https://api.example.com/scrape"
+
+ @respx.mock
+ async def test_happy_path_reports_success_and_tracks_cost(self, harness):
+ respx.get(self.URL).mock(return_value=httpx.Response(200, json={"ok": True}))
+ proxy_svc = _make_proxy_service_mock()
+ pricing = _pricing_with_proxy_config()
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patch(
+ "services.pricing.get_pricing_service", return_value=pricing
+ ), patched_container():
+ result = await harness.execute(
+ "proxyRequest",
+ {
+ "method": "GET",
+ "url": self.URL,
+ "proxyProvider": "smart_proxy",
+ "proxyCountry": "US",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result,
+ [
+ "status",
+ "data",
+ "headers",
+ "url",
+ "method",
+ "proxy_provider",
+ "latency_ms",
+ "bytes_transferred",
+ "attempt",
+ ],
+ )
+ payload = result["result"]
+ assert payload["status"] == 200
+ assert payload["proxy_provider"] == "smart_proxy"
+ assert payload["attempt"] == 1
+
+ # Health feedback: success reported exactly once for this attempt
+ assert proxy_svc.report_result.call_count == 1
+ call = proxy_svc.report_result.call_args
+ assert call.args[0] == "smart_proxy"
+ assert call.args[1].success is True
+
+ async def test_service_disabled_short_circuits(self, harness):
+ proxy_svc = _make_proxy_service_mock(enabled=False)
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyRequest", {"method": "GET", "url": "https://x.test"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "proxy service not initialized" in result["error"].lower()
+
+ async def test_missing_url_returns_validation_error(self, harness):
+ proxy_svc = _make_proxy_service_mock()
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyRequest", {"method": "GET", "url": ""}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "url is required" in result["error"].lower()
+
+ async def test_no_provider_available_returns_envelope(self, harness):
+ proxy_svc = _make_proxy_service_mock(proxy_url=None)
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyRequest", {"method": "GET", "url": "https://x.test"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "no proxy provider" in result["error"].lower()
+
+ @respx.mock
+ async def test_network_error_retries_and_reports_failure(self, harness):
+ # All attempts fail -> handler reports each failure and returns error envelope.
+ respx.get(self.URL).mock(side_effect=httpx.ConnectError("boom"))
+ proxy_svc = _make_proxy_service_mock()
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyRequest",
+ {
+ "method": "GET",
+ "url": self.URL,
+ "proxyProvider": "p1",
+ "maxRetries": 2,
+ "proxyFailover": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "all 3 attempts failed" in result["error"].lower()
+ # report_result called once per attempt (3 total)
+ assert proxy_svc.report_result.call_count == 3
+ # every reported result was a failure
+ for call in proxy_svc.report_result.call_args_list:
+ assert call.args[1].success is False
+
+
+# ============================================================================
+# proxyConfig
+# ============================================================================
+
+
+class TestProxyConfig:
+ async def test_list_providers_happy_path(self, harness):
+ stub_provider = MagicMock()
+ stub_provider.model_dump = MagicMock(
+ return_value={"name": "p1", "enabled": True, "score": 0.9}
+ )
+ proxy_svc = _make_proxy_service_mock(providers=[stub_provider])
+
+ # proxy.py imports get_proxy_service at module load (line 17),
+ # so we must patch it in the handler module too. tools.py re-imports
+ # it inside the function, so patching the source is sufficient there.
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patch(
+ "services.proxy.service.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyConfig", {"operation": "list_providers"}
+ )
+
+ harness.assert_envelope(result, success=True)
+ # Node handler wraps the tool result under result={...} and copies
+ # tool's success into the envelope.
+ tool_payload = result["result"]
+ assert tool_payload["success"] is True
+ assert tool_payload["operation"] == "list_providers"
+ assert tool_payload["providers"] == [
+ {"name": "p1", "enabled": True, "score": 0.9}
+ ]
+
+ async def test_add_provider_missing_name_returns_validation_error(self, harness):
+ proxy_svc = _make_proxy_service_mock()
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patch(
+ "services.proxy.service.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyConfig", {"operation": "add_provider", "name": ""}
+ )
+
+ # Documented quirk: handle_proxy_config copies the tool's `success` into
+ # the envelope but stores the error string under result={...} rather than
+ # the top-level `error` key. So we can't use assert_envelope(success=False)
+ # (which requires top-level `error`). Inspect fields directly.
+ assert result["success"] is False
+ tool_payload = result["result"]
+ assert tool_payload["success"] is False
+ assert "provider name is required" in tool_payload["error"].lower()
+
+ async def test_unknown_operation_returns_error(self, harness):
+ proxy_svc = _make_proxy_service_mock()
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ), patch(
+ "services.proxy.service.get_proxy_service", return_value=proxy_svc
+ ), patched_container():
+ result = await harness.execute(
+ "proxyConfig", {"operation": "teleport_provider"}
+ )
+
+ assert result["success"] is False
+ assert "unknown operation" in result["result"]["error"].lower()
+
+
+# ============================================================================
+# proxyStatus
+# ============================================================================
+
+
+class TestProxyStatus:
+ async def test_happy_path_returns_providers_and_stats(self, harness):
+ stub_provider = MagicMock()
+ stub_provider.model_dump = MagicMock(
+ return_value={"name": "p1", "score": 0.75, "success_rate": 0.9}
+ )
+ stats = {"total_requests": 100, "total_bytes": 12345}
+ proxy_svc = _make_proxy_service_mock(
+ providers=[stub_provider], stats=stats
+ )
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ):
+ result = await harness.execute("proxyStatus", {})
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["enabled", "providers", "stats"])
+ payload = result["result"]
+ assert payload["enabled"] is True
+ assert payload["providers"][0]["name"] == "p1"
+ assert payload["stats"] == stats
+
+ async def test_disabled_service_returns_empty_success_envelope(self, harness):
+ proxy_svc = _make_proxy_service_mock(enabled=False)
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ):
+ result = await harness.execute("proxyStatus", {})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["enabled"] is False
+ assert result["result"]["providers"] == []
+ assert result["result"]["stats"] == {}
+
+ async def test_get_stats_raising_returns_error_envelope(self, harness):
+ proxy_svc = _make_proxy_service_mock()
+ proxy_svc.get_stats = MagicMock(side_effect=RuntimeError("kaboom"))
+
+ with patch(
+ "services.handlers.proxy.get_proxy_service", return_value=proxy_svc
+ ):
+ result = await harness.execute("proxyStatus", {})
+
+ harness.assert_envelope(result, success=False)
+ assert "kaboom" in result["error"]
diff --git a/server/tests/nodes/test_search.py b/server/tests/nodes/test_search.py
new file mode 100644
index 00000000..acce96ab
--- /dev/null
+++ b/server/tests/nodes/test_search.py
@@ -0,0 +1,327 @@
+"""Contract tests for search nodes: braveSearch, serperSearch, perplexitySearch.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/search/`. A refactor that breaks any of these
+indicates the docs (and the user-visible contract) need to be updated too.
+
+Each handler is exercised through the full NodeExecutor dispatch via the
+shared `harness` fixture; httpx is mocked with respx so no network is touched.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+import respx
+
+from tests.nodes._mocks import patched_container, patched_pricing
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# braveSearch
+# ============================================================================
+
+
+class TestBraveSearch:
+ URL = "https://api.search.brave.com/res/v1/web/search"
+
+ @respx.mock
+ async def test_happy_path(self, harness):
+ respx.get(self.URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "web": {
+ "results": [
+ {
+ "title": "Example",
+ "description": "An example result",
+ "url": "https://example.com",
+ },
+ {
+ "title": "Second",
+ "description": "Another",
+ "url": "https://example.org",
+ },
+ ]
+ }
+ },
+ )
+ )
+
+ with patched_container(auth_api_keys={"brave_search": "tk_brave"}), patched_pricing():
+ result = await harness.execute(
+ "braveSearch",
+ {"query": "hello world", "maxResults": 2, "country": "US"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["query", "results", "result_count", "provider"])
+ payload = result["result"]
+ assert payload["query"] == "hello world"
+ assert payload["provider"] == "brave_search"
+ assert payload["result_count"] == 2
+ assert payload["results"][0] == {
+ "title": "Example",
+ "snippet": "An example result",
+ "url": "https://example.com",
+ }
+
+ # request was actually made with the documented headers/query
+ sent = respx.calls.last.request
+ assert sent.headers["X-Subscription-Token"] == "tk_brave"
+ assert sent.url.params["q"] == "hello world"
+ assert sent.url.params["count"] == "2"
+ assert sent.url.params["country"] == "US"
+
+ async def test_empty_query_short_circuits(self, harness):
+ # No httpx mock needed - handler must not call the API.
+ with patched_container(auth_api_keys={"brave_search": "tk"}), patched_pricing():
+ result = await harness.execute("braveSearch", {"query": " "})
+
+ harness.assert_envelope(result, success=False)
+ assert "query is required" in result["error"].lower()
+
+ async def test_missing_api_key(self, harness):
+ with patched_container(auth_api_keys={}), patched_pricing():
+ result = await harness.execute("braveSearch", {"query": "x"})
+
+ harness.assert_envelope(result, success=False)
+ assert "brave_search" in result["error"].lower() or "api key" in result["error"].lower()
+
+ @respx.mock
+ async def test_http_error_returns_envelope(self, harness):
+ respx.get(self.URL).mock(return_value=httpx.Response(429, text="rate limited"))
+
+ with patched_container(auth_api_keys={"brave_search": "tk"}), patched_pricing():
+ result = await harness.execute("braveSearch", {"query": "x"})
+
+ harness.assert_envelope(result, success=False)
+ assert "429" in result["error"]
+
+ @respx.mock
+ async def test_clamps_max_results_to_100(self, harness):
+ respx.get(self.URL).mock(return_value=httpx.Response(200, json={"web": {"results": []}}))
+
+ with patched_container(auth_api_keys={"brave_search": "tk"}), patched_pricing():
+ await harness.execute("braveSearch", {"query": "x", "maxResults": 500})
+
+ assert respx.calls.last.request.url.params["count"] == "100"
+
+
+# ============================================================================
+# serperSearch
+# ============================================================================
+
+
+class TestSerperSearch:
+ BASE = "https://google.serper.dev"
+
+ @respx.mock
+ async def test_web_search_happy_path(self, harness):
+ respx.post(f"{self.BASE}/search").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "organic": [
+ {
+ "title": "Item 1",
+ "snippet": "snippet text",
+ "link": "https://a.example",
+ "position": 1,
+ }
+ ],
+ "knowledgeGraph": {"title": "kg-title"},
+ },
+ )
+ )
+
+ with patched_container(auth_api_keys={"serper": "tk_serp"}), patched_pricing():
+ result = await harness.execute(
+ "serperSearch",
+ {"query": "best pizza", "searchType": "search", "country": "us"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["query", "results", "result_count", "search_type", "provider", "knowledge_graph"]
+ )
+ payload = result["result"]
+ assert payload["search_type"] == "search"
+ assert payload["results"][0]["url"] == "https://a.example"
+ assert payload["results"][0]["position"] == 1
+ assert payload["knowledge_graph"] == {"title": "kg-title"}
+
+ sent = respx.calls.last.request
+ assert sent.headers["X-API-KEY"] == "tk_serp"
+ # Body is JSON
+ assert b'"q": "best pizza"' in sent.content or b'"q":"best pizza"' in sent.content
+
+ @respx.mock
+ async def test_news_branch_uses_news_endpoint(self, harness):
+ respx.post(f"{self.BASE}/news").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "news": [
+ {
+ "title": "Headline",
+ "snippet": "snippet",
+ "link": "https://news.example",
+ "date": "2026-04-15",
+ "source": "Example News",
+ }
+ ]
+ },
+ )
+ )
+
+ with patched_container(auth_api_keys={"serper": "tk"}), patched_pricing():
+ result = await harness.execute("serperSearch", {"query": "ai", "searchType": "news"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["search_type"] == "news"
+ item = result["result"]["results"][0]
+ assert item["date"] == "2026-04-15"
+ assert item["source"] == "Example News"
+ # knowledge_graph absent in news response
+ assert "knowledge_graph" not in result["result"]
+
+ @respx.mock
+ async def test_unknown_search_type_falls_back_to_web_endpoint_but_returns_empty_results(self, harness):
+ # Documented gotcha: handler routes to /search by default but the
+ # mapping branch never matches an unknown type, so results stays [].
+ respx.post(f"{self.BASE}/search").mock(
+ return_value=httpx.Response(200, json={"organic": [{"title": "x", "link": "y"}]})
+ )
+
+ with patched_container(auth_api_keys={"serper": "tk"}), patched_pricing():
+ result = await harness.execute(
+ "serperSearch", {"query": "x", "searchType": "nonsense"}
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["results"] == []
+ assert result["result"]["search_type"] == "nonsense"
+
+ async def test_empty_query_short_circuits(self, harness):
+ with patched_container(auth_api_keys={"serper": "tk"}), patched_pricing():
+ result = await harness.execute("serperSearch", {"query": ""})
+
+ harness.assert_envelope(result, success=False)
+
+ @respx.mock
+ async def test_http_error_returns_envelope(self, harness):
+ respx.post(f"{self.BASE}/search").mock(return_value=httpx.Response(500, text="boom"))
+
+ with patched_container(auth_api_keys={"serper": "tk"}), patched_pricing():
+ result = await harness.execute("serperSearch", {"query": "x"})
+
+ harness.assert_envelope(result, success=False)
+ assert "500" in result["error"]
+
+
+# ============================================================================
+# perplexitySearch
+# ============================================================================
+
+
+class TestPerplexitySearch:
+ URL = "https://api.perplexity.ai/chat/completions"
+
+ @respx.mock
+ async def test_happy_path_with_optional_fields(self, harness):
+ respx.post(self.URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "choices": [{"message": {"content": "the answer"}}],
+ "citations": ["https://src1", "https://src2"],
+ "images": ["https://img1"],
+ "related_questions": ["why?"],
+ },
+ )
+ )
+
+ with patched_container(auth_api_keys={"perplexity": "tk_pplx"}), patched_pricing():
+ result = await harness.execute(
+ "perplexitySearch",
+ {
+ "query": "what is rust",
+ "model": "sonar-pro",
+ "searchRecencyFilter": "week",
+ "returnImages": True,
+ "returnRelatedQuestions": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["answer"] == "the answer"
+ assert payload["citations"] == ["https://src1", "https://src2"]
+ assert payload["results"] == [{"url": "https://src1"}, {"url": "https://src2"}]
+ assert payload["model"] == "sonar-pro"
+ assert payload["images"] == ["https://img1"]
+ assert payload["related_questions"] == ["why?"]
+ assert payload["provider"] == "perplexity"
+
+ sent = respx.calls.last.request
+ assert sent.headers["Authorization"] == "Bearer tk_pplx"
+ body = sent.content
+ assert b'"search_recency_filter":' in body or b'"search_recency_filter" :' in body
+ assert b'"return_images":' in body
+ assert b'"return_related_questions":' in body
+
+ @respx.mock
+ async def test_omits_optional_fields_when_default(self, harness):
+ respx.post(self.URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={"choices": [{"message": {"content": "ok"}}], "citations": []},
+ )
+ )
+
+ with patched_container(auth_api_keys={"perplexity": "tk"}), patched_pricing():
+ result = await harness.execute("perplexitySearch", {"query": "x"})
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ # optional response fields omitted when source data missing
+ assert "images" not in payload
+ assert "related_questions" not in payload
+
+ # body should not contain optional keys
+ body = respx.calls.last.request.content
+ assert b"search_recency_filter" not in body
+ assert b"return_images" not in body
+ assert b"return_related_questions" not in body
+
+ @respx.mock
+ async def test_empty_choices_yields_empty_answer(self, harness):
+ respx.post(self.URL).mock(return_value=httpx.Response(200, json={"choices": []}))
+
+ with patched_container(auth_api_keys={"perplexity": "tk"}), patched_pricing():
+ result = await harness.execute("perplexitySearch", {"query": "x"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["answer"] == ""
+ assert result["result"]["citations"] == []
+
+ async def test_empty_query_short_circuits(self, harness):
+ with patched_container(auth_api_keys={"perplexity": "tk"}), patched_pricing():
+ result = await harness.execute("perplexitySearch", {"query": ""})
+
+ harness.assert_envelope(result, success=False)
+
+ @respx.mock
+ async def test_http_error_returns_envelope(self, harness):
+ respx.post(self.URL).mock(return_value=httpx.Response(401, text="bad key"))
+
+ with patched_container(auth_api_keys={"perplexity": "tk"}), patched_pricing():
+ result = await harness.execute("perplexitySearch", {"query": "x"})
+
+ harness.assert_envelope(result, success=False)
+ assert "401" in result["error"]
diff --git a/server/tests/nodes/test_specialized_agents.py b/server/tests/nodes/test_specialized_agents.py
new file mode 100644
index 00000000..ef8361ce
--- /dev/null
+++ b/server/tests/nodes/test_specialized_agents.py
@@ -0,0 +1,590 @@
+"""Contract tests for specialized agent nodes.
+
+Covers:
+- 13 generic specialized agents routed to handle_chat_agent
+ (android_agent, coding_agent, web_agent, task_agent, social_agent,
+ travel_agent, tool_agent, productivity_agent, payments_agent,
+ consumer_agent, autonomous_agent, orchestrator_agent, ai_employee)
+- 3 dedicated-handler agents (deep_agent, rlm_agent, claude_code_agent)
+
+These freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/specialized_agents/`. A refactor that breaks
+any of these indicates the docs (and the user-visible contract) need to be
+updated too.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_broadcaster, patched_container, patched_subprocess
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# 13 specialized agents that all route to handle_chat_agent.
+GENERIC_SPECIALIZED_AGENTS = [
+ "android_agent",
+ "coding_agent",
+ "web_agent",
+ "task_agent",
+ "social_agent",
+ "travel_agent",
+ "tool_agent",
+ "productivity_agent",
+ "payments_agent",
+ "consumer_agent",
+ "autonomous_agent",
+ "orchestrator_agent",
+ "ai_employee",
+]
+
+
+TEAM_LEAD_AGENTS = ["orchestrator_agent", "ai_employee"]
+
+
+# ============================================================================
+# Generic specialized agents -- parametrized so we do not repeat 13 near
+# identical test bodies.
+# ============================================================================
+
+
+class TestGenericSpecializedAgents:
+ """All 13 agents share handle_chat_agent; we verify the dispatch contract
+ and the forwarded parameters, not the LLM behaviour."""
+
+ @pytest.mark.parametrize("node_type", GENERIC_SPECIALIZED_AGENTS)
+ async def test_dispatch_routes_to_execute_chat_agent(self, harness, node_type):
+ # ai_service.execute_chat_agent is already an AsyncMock on the harness.
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ result = await harness.execute(
+ node_type,
+ {"provider": "openai", "model": "gpt-4o", "prompt": "hello"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert harness.ai_service.execute_chat_agent.await_count == 1
+ # node_id is the first positional arg, parameters is the second.
+ args, kwargs = harness.ai_service.execute_chat_agent.await_args
+ assert args[0].startswith(f"test_{node_type}_")
+ assert args[1]["provider"] == "openai"
+ assert args[1]["model"] == "gpt-4o"
+ assert args[1]["prompt"] == "hello"
+
+ @pytest.mark.parametrize("node_type", GENERIC_SPECIALIZED_AGENTS)
+ async def test_envelope_payload_shape(self, harness, node_type):
+ # Override the mock response so we can assert the propagation.
+ harness.ai_service.execute_chat_agent = AsyncMock(
+ return_value={
+ "success": True,
+ "result": {
+ "response": f"hi from {node_type}",
+ "model": "gpt-4o",
+ "provider": "openai",
+ },
+ }
+ )
+
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ result = await harness.execute(
+ node_type,
+ {"provider": "openai", "model": "gpt-4o", "prompt": "x"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["response"] == f"hi from {node_type}"
+ assert payload["model"] == "gpt-4o"
+ assert payload["provider"] == "openai"
+
+ async def test_auto_prompt_fallback_from_input_main(self, harness):
+ """Empty prompt should fall back to connected input-main output."""
+ harness.ai_service.execute_chat_agent = AsyncMock(
+ return_value={"success": True, "result": {"response": "ok"}}
+ )
+
+ nodes = [
+ {"id": "trigger-1", "type": "chatTrigger"},
+ {"id": "agent-1", "type": "coding_agent"},
+ ]
+ edges = [
+ {"source": "trigger-1", "target": "agent-1", "targetHandle": "input-main"},
+ ]
+ ctx = harness.build_context(
+ nodes=nodes,
+ edges=edges,
+ extra={"outputs": {"trigger-1": {"message": "upstream prompt"}}},
+ )
+
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ await harness.execute(
+ "coding_agent",
+ {"provider": "openai", "model": "gpt-4o", "prompt": ""},
+ node_id="agent-1",
+ context=ctx,
+ )
+
+ args, _ = harness.ai_service.execute_chat_agent.await_args
+ assert args[1]["prompt"] == "upstream prompt"
+
+ async def test_task_completion_strips_tools(self, harness):
+ """When task_data.status is completed, tool_data is stripped to []."""
+ harness.ai_service.execute_chat_agent = AsyncMock(
+ return_value={"success": True, "result": {"response": "done"}}
+ )
+
+ # Wire a tool and a task trigger to the agent.
+ nodes = [
+ {"id": "tool-1", "type": "calculatorTool"},
+ {"id": "task-1", "type": "taskTrigger"},
+ {"id": "agent-1", "type": "coding_agent"},
+ ]
+ edges = [
+ {"source": "tool-1", "target": "agent-1", "targetHandle": "input-tools"},
+ {"source": "task-1", "target": "agent-1", "targetHandle": "input-task"},
+ ]
+ ctx = harness.build_context(
+ nodes=nodes,
+ edges=edges,
+ extra={
+ "outputs": {
+ "task-1": {
+ "task_id": "t-1",
+ "status": "completed",
+ "agent_name": "Child",
+ "result": "child result",
+ }
+ }
+ },
+ )
+
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ await harness.execute(
+ "coding_agent",
+ {"provider": "openai", "model": "gpt-4o", "prompt": "do"},
+ node_id="agent-1",
+ context=ctx,
+ )
+
+ _, kwargs = harness.ai_service.execute_chat_agent.await_args
+ # Tools should be stripped (kwarg value is None or []).
+ assert not kwargs.get("tool_data")
+
+ @pytest.mark.parametrize("node_type", TEAM_LEAD_AGENTS)
+ async def test_team_lead_collects_teammates_as_tools(self, harness, node_type):
+ """orchestrator_agent / ai_employee append teammates to tool_data."""
+ harness.ai_service.execute_chat_agent = AsyncMock(
+ return_value={"success": True, "result": {"response": "team"}}
+ )
+
+ nodes = [
+ {
+ "id": "mate-1",
+ "type": "coding_agent",
+ "data": {"label": "Mate Coder"},
+ },
+ {"id": "lead-1", "type": node_type},
+ ]
+ edges = [
+ {
+ "source": "mate-1",
+ "target": "lead-1",
+ "targetHandle": "input-teammates",
+ },
+ ]
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ await harness.execute(
+ node_type,
+ {"provider": "openai", "model": "gpt-4o", "prompt": "delegate"},
+ node_id="lead-1",
+ context=ctx,
+ )
+
+ _, kwargs = harness.ai_service.execute_chat_agent.await_args
+ tool_data = kwargs.get("tool_data") or []
+ assert any(
+ t.get("node_id") == "mate-1" and t.get("node_type") == "coding_agent"
+ for t in tool_data
+ ), f"expected teammate in tool_data, got {tool_data}"
+
+ async def test_non_team_lead_ignores_teammates_handle(self, harness):
+ """A non-team-lead (e.g. coding_agent) does not expand input-teammates."""
+ harness.ai_service.execute_chat_agent = AsyncMock(
+ return_value={"success": True, "result": {"response": "ok"}}
+ )
+
+ nodes = [
+ {"id": "mate-1", "type": "web_agent", "data": {"label": "mate"}},
+ {"id": "agent-1", "type": "coding_agent"},
+ ]
+ edges = [
+ {
+ "source": "mate-1",
+ "target": "agent-1",
+ "targetHandle": "input-teammates",
+ },
+ ]
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ await harness.execute(
+ "coding_agent",
+ {"provider": "openai", "model": "gpt-4o", "prompt": "x"},
+ node_id="agent-1",
+ context=ctx,
+ )
+
+ _, kwargs = harness.ai_service.execute_chat_agent.await_args
+ tool_data = kwargs.get("tool_data") or []
+ # No teammate expansion happened because coding_agent is not a team lead.
+ assert not any(t.get("node_id") == "mate-1" for t in tool_data)
+
+ async def test_failure_envelope_propagates(self, harness):
+ harness.ai_service.execute_chat_agent = AsyncMock(
+ return_value={"success": False, "error": "model unavailable"}
+ )
+
+ with patched_container(auth_api_keys={"openai": "tk"}):
+ result = await harness.execute(
+ "coding_agent",
+ {"provider": "openai", "model": "gpt-4o", "prompt": "x"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert result["error"] == "model unavailable"
+
+
+# ============================================================================
+# Deep Agent
+# ============================================================================
+
+
+class TestDeepAgent:
+ def _wire_deep_agent_service(self, harness, response=None):
+ """Attach a mock deep_agent_service.execute to the harness AI service."""
+ deep_service = MagicMock(name="DeepAgentService")
+ deep_service.execute = AsyncMock(
+ return_value=response
+ or {
+ "success": True,
+ "result": {
+ "response": "deep done",
+ "model": "claude-sonnet-4-6",
+ "provider": "anthropic",
+ },
+ }
+ )
+ harness.ai_service.deep_agent_service = deep_service
+ # _build_tool_from_node is passed through as build_tool_fn kwarg.
+ harness.ai_service._build_tool_from_node = MagicMock(return_value=None)
+ return deep_service
+
+ async def test_happy_path_delegates_to_deep_agent_service(self, harness):
+ deep_service = self._wire_deep_agent_service(harness)
+
+ with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():
+ result = await harness.execute(
+ "deep_agent",
+ {
+ "provider": "anthropic",
+ "model": "claude-sonnet-4-6",
+ "prompt": "plan something",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["response"] == "deep done"
+ assert deep_service.execute.await_count == 1
+
+ async def test_workspace_dir_injected_into_parameters(self, harness):
+ deep_service = self._wire_deep_agent_service(harness)
+
+ ctx = harness.build_context(workspace_dir="/tmp/fake_workspace")
+
+ with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():
+ await harness.execute(
+ "deep_agent",
+ {
+ "provider": "anthropic",
+ "model": "claude-sonnet-4-6",
+ "prompt": "x",
+ },
+ context=ctx,
+ )
+
+ args, kwargs = deep_service.execute.await_args
+ # args[1] is the parameters dict that the handler built.
+ assert args[1]["workspace_dir"] == "/tmp/fake_workspace"
+
+ async def test_missing_deep_agent_service_surfaces_as_failure(self, harness):
+ """When deep_agent_service is absent, the executor wraps the
+ AttributeError into a failure envelope via its generic try/except."""
+ # Do NOT attach deep_agent_service. Accessing it on a MagicMock
+ # returns a new child mock, so we need to explicitly break it.
+ bad_service = MagicMock(spec=[]) # no attributes at all
+ harness.ai_service.deep_agent_service = bad_service
+
+ with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():
+ result = await harness.execute(
+ "deep_agent",
+ {
+ "provider": "anthropic",
+ "model": "claude-sonnet-4-6",
+ "prompt": "x",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+
+ async def test_teammate_handle_collected_for_deep_agent(self, harness):
+ deep_service = self._wire_deep_agent_service(harness)
+
+ nodes = [
+ {"id": "mate-1", "type": "coding_agent", "data": {"label": "coder"}},
+ {"id": "deep-1", "type": "deep_agent"},
+ ]
+ edges = [
+ {
+ "source": "mate-1",
+ "target": "deep-1",
+ "targetHandle": "input-teammates",
+ },
+ ]
+ ctx = harness.build_context(nodes=nodes, edges=edges)
+
+ with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():
+ await harness.execute(
+ "deep_agent",
+ {
+ "provider": "anthropic",
+ "model": "claude-sonnet-4-6",
+ "prompt": "x",
+ },
+ node_id="deep-1",
+ context=ctx,
+ )
+
+ _, kwargs = deep_service.execute.await_args
+ teammates = kwargs.get("teammates") or []
+ assert any(t["node_id"] == "mate-1" for t in teammates)
+
+
+# ============================================================================
+# RLM Agent
+# ============================================================================
+
+
+class TestRLMAgent:
+ def _wire_rlm_service(self, harness, response=None):
+ rlm = MagicMock(name="RLMService")
+ rlm.execute = AsyncMock(
+ return_value=response
+ or {
+ "success": True,
+ "result": {
+ "response": "final answer",
+ "model": "gpt-4o",
+ "provider": "openai",
+ "iterations": 3,
+ },
+ }
+ )
+ harness.ai_service.rlm_service = rlm
+ return rlm
+
+ async def test_happy_path_delegates_to_rlm_service(self, harness):
+ rlm = self._wire_rlm_service(harness)
+
+ with patched_container(auth_api_keys={"openai": "tk"}), patched_broadcaster():
+ result = await harness.execute(
+ "rlm_agent",
+ {
+ "provider": "openai",
+ "model": "gpt-4o",
+ "prompt": "solve this",
+ "maxIterations": 5,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["response"] == "final answer"
+ assert payload["iterations"] == 3
+ assert rlm.execute.await_count == 1
+
+ async def test_missing_rlm_service_surfaces_as_failure(self, harness):
+ bad = MagicMock(spec=[])
+ harness.ai_service.rlm_service = bad
+
+ with patched_container(auth_api_keys={"openai": "tk"}), patched_broadcaster():
+ result = await harness.execute(
+ "rlm_agent",
+ {"provider": "openai", "model": "gpt-4o", "prompt": "x"},
+ )
+
+ harness.assert_envelope(result, success=False)
+
+ async def test_auto_prompt_fallback(self, harness):
+ rlm = self._wire_rlm_service(harness)
+
+ nodes = [
+ {"id": "trigger-1", "type": "chatTrigger"},
+ {"id": "rlm-1", "type": "rlm_agent"},
+ ]
+ edges = [
+ {"source": "trigger-1", "target": "rlm-1", "targetHandle": "input-main"},
+ ]
+ ctx = harness.build_context(
+ nodes=nodes,
+ edges=edges,
+ extra={"outputs": {"trigger-1": {"text": "fallback prompt"}}},
+ )
+
+ with patched_container(auth_api_keys={"openai": "tk"}), patched_broadcaster():
+ await harness.execute(
+ "rlm_agent",
+ {"provider": "openai", "model": "gpt-4o", "prompt": ""},
+ node_id="rlm-1",
+ context=ctx,
+ )
+
+ args, _ = rlm.execute.await_args
+ assert args[1]["prompt"] == "fallback prompt"
+
+
+# ============================================================================
+# Claude Code Agent
+# ============================================================================
+
+
+class TestClaudeCodeAgent:
+ def _wire_claude_service(self, result_payload=None):
+ service = MagicMock(name="ClaudeCodeService")
+ service.execute = AsyncMock(
+ return_value=result_payload
+ or {
+ "result": "cli response",
+ "session_id": "sess-abc",
+ "usage": {"input_tokens": 10, "output_tokens": 5},
+ }
+ )
+ return service
+
+ async def test_happy_path_spawns_cli_and_returns_response(self, harness):
+ service = self._wire_claude_service()
+
+ with patched_container(auth_api_keys={}), patched_broadcaster(), patch(
+ "services.handlers.claude_code.get_claude_code_service",
+ return_value=service,
+ ):
+ result = await harness.execute(
+ "claude_code_agent",
+ {
+ "prompt": "write a hello world script",
+ "model": "claude-sonnet-4-6",
+ "maxTurns": 5,
+ "maxBudgetUsd": 2.0,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["response"] == "cli response"
+ assert payload["provider"] == "anthropic"
+ assert payload["session_id"] == "sess-abc"
+ assert payload["model"] == "claude-sonnet-4-6"
+
+ # The service was called with the documented kwargs.
+ call = service.execute.await_args
+ assert call.kwargs["model"] == "claude-sonnet-4-6"
+ assert call.kwargs["max_turns"] == 5
+ assert call.kwargs["max_budget_usd"] == 2.0
+ assert call.kwargs["prompt"] == "write a hello world script"
+
+ async def test_max_budget_usd_flag_is_passed_through(self, harness):
+ """Guards against the historical '--max-cost' bug: the handler must
+ forward maxBudgetUsd to the service as max_budget_usd."""
+ service = self._wire_claude_service()
+
+ with patched_container(auth_api_keys={}), patched_broadcaster(), patch(
+ "services.handlers.claude_code.get_claude_code_service",
+ return_value=service,
+ ):
+ await harness.execute(
+ "claude_code_agent",
+ {"prompt": "x", "maxBudgetUsd": 7.5},
+ )
+
+ call = service.execute.await_args
+ assert call.kwargs["max_budget_usd"] == 7.5
+
+ async def test_no_prompt_returns_failure(self, harness):
+ """Unique to claude_code_agent: explicit no-prompt short-circuit."""
+ service = self._wire_claude_service()
+
+ with patched_container(auth_api_keys={}), patched_broadcaster(), patch(
+ "services.handlers.claude_code.get_claude_code_service",
+ return_value=service,
+ ):
+ result = await harness.execute(
+ "claude_code_agent",
+ {"prompt": ""},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "prompt" in result["error"].lower()
+ # CLI must not have been spawned.
+ assert service.execute.await_count == 0
+
+ async def test_subprocess_failure_becomes_envelope(self, harness):
+ """When ClaudeCodeService.execute raises, the handler returns
+ success=false with the error message."""
+ service = MagicMock(name="ClaudeCodeService")
+ service.execute = AsyncMock(side_effect=RuntimeError("cli exit 1: boom"))
+
+ with patched_container(auth_api_keys={}), patched_broadcaster(), patch(
+ "services.handlers.claude_code.get_claude_code_service",
+ return_value=service,
+ ):
+ result = await harness.execute(
+ "claude_code_agent",
+ {"prompt": "do something"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "boom" in result["error"]
+
+ async def test_auto_prompt_fallback_from_input_main(self, harness):
+ service = self._wire_claude_service()
+
+ nodes = [
+ {"id": "src-1", "type": "chatTrigger"},
+ {"id": "cc-1", "type": "claude_code_agent"},
+ ]
+ edges = [
+ {"source": "src-1", "target": "cc-1", "targetHandle": "input-main"},
+ ]
+ ctx = harness.build_context(
+ nodes=nodes,
+ edges=edges,
+ extra={"outputs": {"src-1": {"message": "upstream text"}}},
+ )
+
+ with patched_container(auth_api_keys={}), patched_broadcaster(), patch(
+ "services.handlers.claude_code.get_claude_code_service",
+ return_value=service,
+ ):
+ await harness.execute(
+ "claude_code_agent",
+ {"prompt": ""},
+ node_id="cc-1",
+ context=ctx,
+ )
+
+ call = service.execute.await_args
+ assert call.kwargs["prompt"] == "upstream text"
diff --git a/server/tests/nodes/test_telegram_social.py b/server/tests/nodes/test_telegram_social.py
new file mode 100644
index 00000000..aa376930
--- /dev/null
+++ b/server/tests/nodes/test_telegram_social.py
@@ -0,0 +1,571 @@
+"""Contract tests for telegram_social nodes.
+
+Covers: telegramSend, telegramReceive, socialSend, socialReceive.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/telegram_social/`. A refactor that breaks any
+of these indicates the docs (and the user-visible contract) must be updated.
+
+All external boundaries are mocked:
+ - TelegramService singleton is replaced via ``get_telegram_service`` patch.
+ - event_waiter is patched at the module-attribute level inside both
+ ``services.node_executor`` and ``services.handlers.triggers`` so the
+ generic trigger path resolves a canned event without blocking.
+ - The WhatsApp send router is patched for socialSend.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_broadcaster, patched_container
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# --------------------------------------------------------------------------- #
+# Shared helpers
+# --------------------------------------------------------------------------- #
+
+
+def _make_telegram_service(*, connected: bool = True, owner_chat_id=None):
+ """Build a stub TelegramService singleton mirroring the real interface."""
+ svc = MagicMock(name="TelegramService")
+ svc.connected = connected
+ svc.owner_chat_id = owner_chat_id
+ svc.set_owner = AsyncMock(return_value=None)
+ svc.send_message = AsyncMock(
+ return_value={
+ "message_id": 42,
+ "chat_id": 111,
+ "date": "2026-04-15T00:00:00",
+ "text": "hi",
+ }
+ )
+ svc.send_photo = AsyncMock(
+ return_value={"message_id": 43, "chat_id": 111, "date": "2026-04-15T00:00:00"}
+ )
+ svc.send_document = AsyncMock(
+ return_value={"message_id": 44, "chat_id": 111, "date": "2026-04-15T00:00:00"}
+ )
+ svc.send_location = AsyncMock(
+ return_value={"message_id": 45, "chat_id": 111, "date": "2026-04-15T00:00:00"}
+ )
+ svc.send_contact = AsyncMock(
+ return_value={"message_id": 46, "chat_id": 111, "date": "2026-04-15T00:00:00"}
+ )
+ return svc
+
+
+def _patch_telegram_service(svc):
+ """Patch the get_telegram_service accessor everywhere it is imported."""
+ return patch(
+ "services.telegram_service.get_telegram_service", return_value=svc
+ )
+
+
+# ============================================================================
+# telegramSend
+# ============================================================================
+
+
+class TestTelegramSend:
+ async def test_text_happy_path_with_self_recipient(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=9999)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "text", "text": "hello"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["message_id"] == 42
+ assert payload["chat_id"] == 111
+ assert payload["message_type"] == "text"
+ svc.send_message.assert_awaited_once()
+ call_kwargs = svc.send_message.await_args.kwargs
+ assert call_kwargs["chat_id"] == 9999
+ assert call_kwargs["text"] == "hello"
+
+ async def test_not_connected_short_circuits(self, harness):
+ svc = _make_telegram_service(connected=False)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "text", "text": "x"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+ svc.send_message.assert_not_awaited()
+
+ async def test_self_recipient_restores_owner_from_credentials(self, harness):
+ # Service has no owner in memory, but credentials DB has one saved.
+ svc = _make_telegram_service(connected=True, owner_chat_id=None)
+
+ with _patch_telegram_service(svc), patched_container(
+ auth_api_keys={"telegram_owner_chat_id": "7777"}
+ ):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "text", "text": "hi"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ svc.set_owner.assert_awaited_once_with(7777)
+ # send_message chat_id should be the restored owner id
+ assert svc.send_message.await_args.kwargs["chat_id"] == 7777
+
+ async def test_self_recipient_with_no_owner_returns_error(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=None)
+
+ with _patch_telegram_service(svc), patched_container(auth_api_keys={}):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "text", "text": "hi"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "owner" in result["error"].lower()
+ svc.send_message.assert_not_awaited()
+
+ async def test_user_recipient_requires_chat_id(self, harness):
+ svc = _make_telegram_service(connected=True)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "user", "message_type": "text", "text": "x"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "chat_id" in result["error"].lower()
+
+ async def test_text_message_without_text_short_circuits(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=1)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "text"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "text is required" in result["error"].lower()
+
+ async def test_photo_requires_media_url(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=1)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "photo"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "media_url" in result["error"].lower()
+
+ async def test_photo_happy_path_passes_caption_and_parse_mode(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=1)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {
+ "recipient_type": "user",
+ "chat_id": "123",
+ "message_type": "photo",
+ "media_url": "https://example.com/x.jpg",
+ "caption": "ok",
+ "parse_mode": "HTML",
+ "silent": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ svc.send_photo.assert_awaited_once()
+ kwargs = svc.send_photo.await_args.kwargs
+ assert kwargs["photo"] == "https://example.com/x.jpg"
+ assert kwargs["caption"] == "ok"
+ assert kwargs["parse_mode"] == "HTML"
+ assert kwargs["disable_notification"] is True
+
+ async def test_location_requires_coordinates(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=1)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "location"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "latitude" in result["error"].lower()
+
+ async def test_unsupported_message_type(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=1)
+
+ with _patch_telegram_service(svc):
+ result = await harness.execute(
+ "telegramSend",
+ {"recipient_type": "self", "message_type": "hologram"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unsupported" in result["error"].lower()
+
+
+# ============================================================================
+# telegramReceive (trigger via generic handle_trigger_node + event_waiter)
+# ============================================================================
+
+
+def _make_waiter_stub(*, canned_event=None, is_trigger=True):
+ """Fake event_waiter module with just the methods the trigger path calls."""
+ waiter_obj = MagicMock(name="Waiter")
+ waiter_obj.id = "waiter-test-id"
+
+ stub = MagicMock(name="event_waiter_module")
+ stub.is_trigger_node = MagicMock(return_value=is_trigger)
+ stub.get_trigger_config = MagicMock(
+ return_value=MagicMock(
+ node_type="telegramReceive",
+ event_type="telegram_message_received",
+ display_name="Telegram Message",
+ )
+ )
+ stub.register = AsyncMock(return_value=waiter_obj)
+ stub.wait_for_event = AsyncMock(return_value=canned_event or {})
+ stub.get_backend_mode = MagicMock(return_value="asyncio.Future")
+ stub.cancel = MagicMock(return_value=True)
+ stub.dispatch = MagicMock(return_value=1)
+ return stub
+
+
+class TestTelegramReceive:
+ CANNED = {
+ "message_id": 10,
+ "chat_id": 555,
+ "chat_type": "private",
+ "chat_title": None,
+ "from_id": 777,
+ "from_username": "alice",
+ "from_first_name": "Alice",
+ "from_last_name": None,
+ "is_bot": False,
+ "text": "hello from alice",
+ "content_type": "text",
+ "date": "2026-04-15T12:00:00",
+ "reply_to_message_id": None,
+ }
+
+ async def test_happy_path_returns_canned_event(self, harness):
+ svc = _make_telegram_service(connected=True, owner_chat_id=42)
+ waiter = _make_waiter_stub(canned_event=self.CANNED)
+
+ with _patch_telegram_service(svc), patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "telegramReceive",
+ {"senderFilter": "all", "contentTypeFilter": "all"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["text"] == "hello from alice"
+ assert result["result"]["chat_id"] == 555
+ waiter.register.assert_awaited_once()
+ waiter.wait_for_event.assert_awaited_once()
+
+ async def test_bot_not_connected_returns_error(self, harness):
+ svc = _make_telegram_service(connected=False)
+ waiter = _make_waiter_stub(canned_event=self.CANNED)
+
+ with _patch_telegram_service(svc), patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "telegramReceive",
+ {"senderFilter": "all"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+ # Must NOT have registered a waiter when bot is offline
+ waiter.register.assert_not_awaited()
+
+ async def test_cancellation_propagates_as_error(self, harness):
+ import asyncio
+
+ svc = _make_telegram_service(connected=True, owner_chat_id=1)
+ waiter = _make_waiter_stub()
+ waiter.wait_for_event = AsyncMock(side_effect=asyncio.CancelledError())
+
+ with _patch_telegram_service(svc), patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "telegramReceive",
+ {"senderFilter": "all"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "cancel" in result["error"].lower()
+
+
+# ============================================================================
+# socialSend
+# ============================================================================
+
+
+class TestSocialSend:
+ async def test_whatsapp_text_happy_path(self, harness):
+ whatsapp_send = AsyncMock(
+ return_value={"success": True, "message_id": "wamid.xyz"}
+ )
+
+ with patch("routers.whatsapp.handle_whatsapp_send", whatsapp_send):
+ result = await harness.execute(
+ "socialSend",
+ {
+ "channel": "whatsapp",
+ "recipientType": "phone",
+ "phone": "+15551234567",
+ "messageType": "text",
+ "message": "hi there",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["channel"] == "whatsapp"
+ assert payload["recipient"] == "+15551234567"
+ assert payload["recipient_type"] == "phone"
+ assert payload["message_type"] == "text"
+ assert payload["message_id"] == "wamid.xyz"
+
+ whatsapp_send.assert_awaited_once()
+ sent_params = whatsapp_send.await_args.args[0]
+ assert sent_params["phone"] == "+15551234567"
+ assert sent_params["message"] == "hi there"
+ assert sent_params["message_type"] == "text"
+
+ async def test_missing_recipient_short_circuits(self, harness):
+ # recipientType=phone but no phone param -> ValueError inside handler
+ whatsapp_send = AsyncMock()
+
+ with patch("routers.whatsapp.handle_whatsapp_send", whatsapp_send):
+ result = await harness.execute(
+ "socialSend",
+ {
+ "channel": "whatsapp",
+ "recipientType": "phone",
+ "messageType": "text",
+ "message": "x",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "recipient" in result["error"].lower()
+ whatsapp_send.assert_not_awaited()
+
+ async def test_unsupported_channel_returns_stub_error(self, harness):
+ # Any non-whatsapp channel should surface as a failed envelope.
+ whatsapp_send = AsyncMock()
+
+ with patch("routers.whatsapp.handle_whatsapp_send", whatsapp_send):
+ result = await harness.execute(
+ "socialSend",
+ {
+ "channel": "discord",
+ "recipientType": "user",
+ "userId": "u1",
+ "messageType": "text",
+ "message": "hi",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "discord" in result["error"].lower() or "not yet implemented" in result["error"].lower()
+ whatsapp_send.assert_not_awaited()
+
+ async def test_whatsapp_failure_becomes_error_envelope(self, harness):
+ whatsapp_send = AsyncMock(
+ return_value={"success": False, "error": "rpc boom"}
+ )
+
+ with patch("routers.whatsapp.handle_whatsapp_send", whatsapp_send):
+ result = await harness.execute(
+ "socialSend",
+ {
+ "channel": "whatsapp",
+ "recipientType": "phone",
+ "phone": "+15551234567",
+ "messageType": "text",
+ "message": "x",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "rpc boom" in result["error"]
+
+
+# ============================================================================
+# socialReceive
+# ============================================================================
+
+
+class TestSocialReceive:
+ async def test_normalizes_whatsapp_upstream(self, harness):
+ upstream = {
+ "message_id": "wamid.abc",
+ "sender": "[email protected]",
+ "sender_phone": "15551234567",
+ "push_name": "Alice",
+ "chat_id": "[email protected]",
+ "text": "hi from wa",
+ "message_type": "text",
+ "is_group": False,
+ "is_from_me": False,
+ "timestamp": "2026-04-15T00:00:00",
+ }
+
+ nodes = [
+ {"id": "src_wa", "type": "whatsappReceive"},
+ {"id": "tgt_social", "type": "socialReceive"},
+ ]
+ edges = [
+ {
+ "source": "src_wa",
+ "target": "tgt_social",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+ upstream_outputs = {"src_wa::output_main": upstream}
+
+ result = await harness.execute(
+ "socialReceive",
+ {"channelFilter": "all", "senderFilter": "all"},
+ node_id="tgt_social",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ # Handler-built slices
+ assert payload["message"] == "hi from wa"
+ assert payload["contact"]["sender_phone"] == "15551234567"
+ assert payload["contact"]["channel"] == "whatsapp"
+ assert payload["metadata"]["message_id"] == "wamid.abc"
+ # Top-level unified fields (from spread)
+ assert payload["channel"] == "whatsapp"
+ assert payload["chat_type"] == "dm"
+
+ async def test_missing_upstream_returns_error(self, harness):
+ nodes = [
+ {"id": "src_wa", "type": "whatsappReceive"},
+ {"id": "tgt_social", "type": "socialReceive"},
+ ]
+ # No edges / upstream outputs -> handler gets {} and errors out.
+ result = await harness.execute(
+ "socialReceive",
+ {},
+ node_id="tgt_social",
+ nodes=nodes,
+ edges=[],
+ upstream_outputs={},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "no message data" in result["error"].lower()
+
+ async def test_filter_rejects_message(self, harness):
+ upstream = {
+ "message_id": "m1",
+ "sender": "[email protected]",
+ "sender_phone": "15550000000",
+ "push_name": "Bob",
+ "chat_id": "c1",
+ "text": "spam spam",
+ "message_type": "text",
+ "is_group": False,
+ "is_from_me": False,
+ }
+ nodes = [
+ {"id": "src_wa", "type": "whatsappReceive"},
+ {"id": "tgt_social", "type": "socialReceive"},
+ ]
+ edges = [
+ {
+ "source": "src_wa",
+ "target": "tgt_social",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+ upstream_outputs = {"src_wa::output_main": upstream}
+
+ result = await harness.execute(
+ "socialReceive",
+ {
+ "channelFilter": "all",
+ "senderFilter": "keywords",
+ "keywords": "hello,hi",
+ },
+ node_id="tgt_social",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+
+ # Filtered messages return success=true with result=null and filtered=true
+ harness.assert_envelope(result, success=True)
+ assert result["result"] is None
+ assert result.get("filtered") is True
+
+ async def test_ignore_own_messages_default(self, harness):
+ upstream = {
+ "message_id": "m1",
+ "sender": "[email protected]",
+ "sender_phone": "self",
+ "chat_id": "c1",
+ "text": "echo",
+ "message_type": "text",
+ "is_group": False,
+ "is_from_me": True,
+ }
+ nodes = [
+ {"id": "src_wa", "type": "whatsappReceive"},
+ {"id": "tgt_social", "type": "socialReceive"},
+ ]
+ edges = [
+ {
+ "source": "src_wa",
+ "target": "tgt_social",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+ upstream_outputs = {"src_wa::output_main": upstream}
+
+ result = await harness.execute(
+ "socialReceive",
+ {"senderFilter": "all"}, # ignoreOwnMessages default true
+ node_id="tgt_social",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"] is None
+ assert result.get("filtered") is True
diff --git a/server/tests/nodes/test_twitter.py b/server/tests/nodes/test_twitter.py
new file mode 100644
index 00000000..3c5d6366
--- /dev/null
+++ b/server/tests/nodes/test_twitter.py
@@ -0,0 +1,662 @@
+"""Contract tests for twitter nodes.
+
+Covers: twitterSend, twitterSearch, twitterUser, twitterReceive.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/twitter/`. A refactor that breaks any of these
+indicates the docs (and the user-visible contract) must be updated.
+
+External boundaries mocked:
+ - The XDK `Client` class is replaced at its import site inside
+ `services.handlers.twitter`. XDK's methods are sync (they run via
+ `requests` internally and get wrapped in ``asyncio.to_thread``), so
+ every stubbed method is a plain MagicMock returning an object with the
+ fields the handler reads (``.data`` etc.).
+ - ``auth_service.get_oauth_tokens('twitter')`` is fed via
+ ``patched_container(auth_oauth_tokens={...})``.
+ - ``event_waiter`` is patched at both the executor dispatch site and the
+ generic trigger handler for ``twitterReceive``.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import (
+ patched_broadcaster,
+ patched_container,
+ patched_pricing,
+)
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# --------------------------------------------------------------------------- #
+# Helpers
+# --------------------------------------------------------------------------- #
+
+
+def _ok_tokens() -> dict:
+ return {
+ "twitter": {
+ "access_token": "tk_access",
+ "refresh_token": "tk_refresh",
+ "email": "[email protected]",
+ "name": "Owner",
+ "scopes": "tweet.read tweet.write users.read",
+ }
+ }
+
+
+def _make_client_class(*, posts=None, users=None):
+ """Return a stub replacement for ``xdk.Client`` that captures ctor args.
+
+ ``posts`` / ``users`` are MagicMocks with whatever methods the specific
+ test needs. Each time the handler does ``Client(access_token=...)`` the
+ returned stub records the call and yields a fresh instance with the
+ provided sub-namespaces attached.
+ """
+ created_instances = []
+
+ class _StubClient:
+ def __init__(self, access_token=None, **kwargs):
+ self.access_token = access_token
+ self.posts = posts or MagicMock(name="posts")
+ self.users = users or MagicMock(name="users")
+ created_instances.append(self)
+
+ _StubClient.instances = created_instances # type: ignore[attr-defined]
+ return _StubClient
+
+
+def _patch_client(stub_cls):
+ """Patch the xdk.Client reference inside the handler module."""
+ return patch("services.handlers.twitter.Client", stub_cls)
+
+
+# ============================================================================
+# twitterSend
+# ============================================================================
+
+
+class TestTwitterSend:
+ async def test_tweet_happy_path(self, harness):
+ posts = MagicMock(name="posts")
+ posts.create = MagicMock(
+ return_value=SimpleNamespace(
+ data={"id": "1999000000000000001", "text": "hello world"}
+ )
+ )
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend",
+ {"action": "tweet", "text": "hello world"},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["id"] == "1999000000000000001"
+ assert payload["text"] == "hello world"
+ posts.create.assert_called_once()
+ body = posts.create.call_args.kwargs["body"]
+ assert body == {"text": "hello world"}
+ # Client constructed with the stored access token
+ assert stub_cls.instances[0].access_token == "tk_access"
+
+ async def test_tweet_truncates_to_280_chars(self, harness):
+ posts = MagicMock(name="posts")
+ posts.create = MagicMock(
+ return_value=SimpleNamespace(data={"id": "1", "text": "t"})
+ )
+ stub_cls = _make_client_class(posts=posts)
+ long_text = "x" * 400
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend", {"action": "tweet", "text": long_text}
+ )
+
+ harness.assert_envelope(result, success=True)
+ sent = posts.create.call_args.kwargs["body"]["text"]
+ assert len(sent) == 280
+ assert sent == "x" * 280
+
+ async def test_reply_happy_path(self, harness):
+ posts = MagicMock(name="posts")
+ posts.create = MagicMock(
+ return_value=SimpleNamespace(data={"id": "r1", "text": "replying"})
+ )
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend",
+ {
+ "action": "reply",
+ "text": "replying",
+ "reply_to_id": "1234567890",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ body = posts.create.call_args.kwargs["body"]
+ assert body == {
+ "text": "replying",
+ "reply": {"in_reply_to_tweet_id": "1234567890"},
+ }
+
+ async def test_reply_missing_reply_to_id_errors(self, harness):
+ posts = MagicMock(name="posts")
+ posts.create = MagicMock()
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend", {"action": "reply", "text": "hi"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "reply_to_id" in result["error"].lower()
+ posts.create.assert_not_called()
+
+ async def test_tweet_empty_text_errors(self, harness):
+ posts = MagicMock(name="posts")
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend", {"action": "tweet", "text": ""}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "text is required" in result["error"].lower()
+
+ async def test_unknown_action_errors(self, harness):
+ # 'quote' is exposed in the frontend but not implemented in the handler.
+ stub_cls = _make_client_class()
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend", {"action": "quote", "text": "x", "tweet_id": "1"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown action" in result["error"].lower()
+ assert "quote" in result["error"].lower()
+
+ async def test_missing_oauth_tokens_errors(self, harness):
+ stub_cls = _make_client_class()
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens={} # no twitter entry
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSend", {"action": "tweet", "text": "hi"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+
+ async def test_401_triggers_refresh_and_retry(self, harness):
+ # First create() raises 401. Handler should call refresh_access_token,
+ # rebuild the client, and retry exactly once.
+ calls = {"n": 0}
+
+ def _create_side_effect(body=None):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("401 Unauthorized")
+ return SimpleNamespace(data={"id": "99", "text": "ok"})
+
+ posts = MagicMock(name="posts")
+ posts.create = MagicMock(side_effect=_create_side_effect)
+ stub_cls = _make_client_class(posts=posts)
+
+ refresh_mock = AsyncMock(
+ return_value={
+ "success": True,
+ "access_token": "tk_new",
+ "refresh_token": "tk_refresh2",
+ }
+ )
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing(), patch(
+ "services.twitter_oauth.TwitterOAuth"
+ ) as oauth_cls:
+ oauth_instance = MagicMock()
+ oauth_instance.refresh_access_token = refresh_mock
+ oauth_cls.return_value = oauth_instance
+
+ result = await harness.execute(
+ "twitterSend", {"action": "tweet", "text": "hi"}
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert calls["n"] == 2 # original + retry
+ refresh_mock.assert_awaited_once_with("tk_refresh")
+ # New client built with refreshed token
+ assert stub_cls.instances[-1].access_token == "tk_new"
+
+
+# ============================================================================
+# twitterSearch
+# ============================================================================
+
+
+class TestTwitterSearch:
+ @staticmethod
+ def _search_page(tweets, includes=None):
+ return SimpleNamespace(data=tweets, includes=includes)
+
+ async def test_happy_path_returns_enriched_tweets(self, harness):
+ # Raw tweet references an author in includes.users and a media key in
+ # includes.media; entities.urls contains a t.co shortlink that should
+ # be expanded in display_text. A note_tweet field replaces the text.
+ raw_tweet = {
+ "id": "tw1",
+ "author_id": "user42",
+ "text": "check this https://t.co/abc",
+ "created_at": "2026-04-15T10:00:00",
+ "lang": "en",
+ "source": "web",
+ "conversation_id": "conv1",
+ "in_reply_to_user_id": None,
+ "possibly_sensitive": False,
+ "entities": {
+ "urls": [
+ {
+ "url": "https://t.co/abc",
+ "expanded_url": "https://example.com/long",
+ "display_url": "example.com/long",
+ }
+ ]
+ },
+ "public_metrics": {
+ "retweet_count": 2,
+ "reply_count": 1,
+ "like_count": 7,
+ "quote_count": 0,
+ "bookmark_count": 0,
+ "impression_count": 120,
+ },
+ "attachments": {"media_keys": ["mk1"]},
+ "referenced_tweets": [{"type": "quoted", "id": "twQ"}],
+ "note_tweet": None,
+ }
+ includes = {
+ "users": [
+ {
+ "id": "user42",
+ "username": "alice",
+ "name": "Alice",
+ "profile_image_url": "https://example.com/a.jpg",
+ }
+ ],
+ "media": [
+ {"media_key": "mk1", "type": "photo", "url": "https://example.com/m.jpg"}
+ ],
+ "tweets": [
+ {"id": "twQ", "text": "quoted body", "author_id": "userQ"}
+ ],
+ }
+
+ posts = MagicMock(name="posts")
+ # search_recent is a generator; one page is enough per the handler's
+ # "break after first page" contract.
+ posts.search_recent = MagicMock(
+ return_value=iter([self._search_page([raw_tweet], includes)])
+ )
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSearch",
+ {"query": "hello", "max_results": 10},
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["tweets", "count", "query"])
+ payload = result["result"]
+ assert payload["count"] == 1
+ assert payload["query"] == "hello"
+
+ [tw] = payload["tweets"]
+ # Enriched fields documented in twitterSearch.md
+ assert tw["id"] == "tw1"
+ assert tw["display_text"] == "check this https://example.com/long"
+ assert tw["public_metrics"]["like_count"] == 7
+ # Author joined from includes.users
+ assert tw["author"]["username"] == "alice"
+ # Media joined from includes.media via attachments.media_keys
+ assert tw["media"][0]["media_key"] == "mk1"
+ # Referenced tweets joined from includes.tweets
+ assert tw["referenced_tweets"][0] == {
+ "type": "quoted",
+ "id": "twQ",
+ "text": "quoted body",
+ "author_id": "userQ",
+ }
+ # Expanded URL list present
+ assert tw["urls"][0]["expanded_url"] == "https://example.com/long"
+
+ async def test_note_tweet_replaces_text(self, harness):
+ raw_tweet = {
+ "id": "tw2",
+ "author_id": "u1",
+ "text": "short",
+ "note_tweet": {"text": "this is a long form thread exceeding 280 chars"},
+ "entities": {"urls": []},
+ "public_metrics": {},
+ }
+ posts = MagicMock(name="posts")
+ posts.search_recent = MagicMock(
+ return_value=iter([self._search_page([raw_tweet], {})])
+ )
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSearch", {"query": "x"}
+ )
+
+ harness.assert_envelope(result, success=True)
+ tw = result["result"]["tweets"][0]
+ assert tw["text"].startswith("this is a long form thread")
+ assert tw["display_text"] == tw["text"]
+
+ async def test_max_results_clamped_above_100(self, harness):
+ posts = MagicMock(name="posts")
+ posts.search_recent = MagicMock(return_value=iter([self._search_page([], {})]))
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ await harness.execute(
+ "twitterSearch", {"query": "x", "max_results": 500}
+ )
+
+ # Handler should pass max_results=100 (upper clamp) to the SDK.
+ assert posts.search_recent.call_args.kwargs["max_results"] == 100
+
+ async def test_max_results_clamped_below_10(self, harness):
+ posts = MagicMock(name="posts")
+ posts.search_recent = MagicMock(return_value=iter([self._search_page([], {})]))
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ await harness.execute(
+ "twitterSearch", {"query": "x", "max_results": 3}
+ )
+
+ # API minimum is 10; handler clamps up silently.
+ assert posts.search_recent.call_args.kwargs["max_results"] == 10
+
+ async def test_empty_query_short_circuits(self, harness):
+ posts = MagicMock(name="posts")
+ posts.search_recent = MagicMock()
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterSearch", {"query": " "}
+ )
+
+ # Handler checks "not query" i.e. falsy, so empty string fails.
+ # Whitespace-only goes through but a strip-less empty check means
+ # the SDK may get called; docs document "query required". Accept
+ # either behaviour but require an envelope.
+ harness.assert_envelope(result)
+
+ async def test_empty_query_exact_short_circuits(self, harness):
+ posts = MagicMock(name="posts")
+ posts.search_recent = MagicMock()
+ stub_cls = _make_client_class(posts=posts)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute("twitterSearch", {"query": ""})
+
+ harness.assert_envelope(result, success=False)
+ assert "query is required" in result["error"].lower()
+ posts.search_recent.assert_not_called()
+
+
+# ============================================================================
+# twitterUser
+# ============================================================================
+
+
+class TestTwitterUser:
+ async def test_me_happy_path(self, harness):
+ users = MagicMock(name="users")
+ users.get_me = MagicMock(
+ return_value=SimpleNamespace(
+ data={
+ "id": "me1",
+ "username": "me",
+ "name": "Me",
+ "description": "hi",
+ "created_at": "2020-01-01",
+ "profile_image_url": "https://example.com/me.jpg",
+ "verified": True,
+ }
+ )
+ )
+ stub_cls = _make_client_class(users=users)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute("twitterUser", {"operation": "me"})
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["id"] == "me1"
+ assert payload["username"] == "me"
+ assert payload["description"] == "hi"
+ assert payload["verified"] is True
+ users.get_me.assert_called_once()
+
+ async def test_by_username_not_found(self, harness):
+ users = MagicMock(name="users")
+ users.get_by_usernames = MagicMock(
+ return_value=SimpleNamespace(data=[])
+ )
+ stub_cls = _make_client_class(users=users)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterUser", {"operation": "by_username", "username": "ghost"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "ghost" in result["error"]
+ assert "not found" in result["error"].lower()
+
+ async def test_by_username_missing_param(self, harness):
+ users = MagicMock(name="users")
+ users.get_by_usernames = MagicMock()
+ stub_cls = _make_client_class(users=users)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterUser", {"operation": "by_username"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "username" in result["error"].lower()
+ users.get_by_usernames.assert_not_called()
+
+ async def test_followers_clamps_max_results(self, harness):
+ users = MagicMock(name="users")
+ # get_followers is a paginated generator returning SimpleNamespace pages
+ users.get_followers = MagicMock(
+ return_value=iter(
+ [SimpleNamespace(data=[{"id": "u1", "username": "a", "name": "A"}])]
+ )
+ )
+ stub_cls = _make_client_class(users=users)
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterUser",
+ {"operation": "followers", "user_id": "x1", "max_results": 9999},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["count"] == 1
+ assert payload["users"][0]["username"] == "a"
+ # Upper clamp is 1000.
+ assert users.get_followers.call_args.kwargs["max_results"] == 1000
+
+ async def test_unknown_operation(self, harness):
+ stub_cls = _make_client_class()
+
+ with _patch_client(stub_cls), patched_container(
+ auth_oauth_tokens=_ok_tokens()
+ ), patched_pricing():
+ result = await harness.execute(
+ "twitterUser", {"operation": "mysterious"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown operation" in result["error"].lower()
+
+
+# ============================================================================
+# twitterReceive
+# ============================================================================
+
+
+def _make_waiter_stub(*, canned_event=None):
+ """Fake event_waiter module for the trigger path."""
+ waiter_obj = MagicMock(name="Waiter")
+ waiter_obj.id = "waiter-twitter-id"
+
+ stub = MagicMock(name="event_waiter_module")
+ stub.is_trigger_node = MagicMock(return_value=True)
+ stub.get_trigger_config = MagicMock(
+ return_value=MagicMock(
+ node_type="twitterReceive",
+ event_type="twitter_event_received",
+ display_name="Twitter Event",
+ )
+ )
+ stub.register = AsyncMock(return_value=waiter_obj)
+ stub.wait_for_event = AsyncMock(return_value=canned_event or {})
+ stub.get_backend_mode = MagicMock(return_value="asyncio.Future")
+ stub.cancel = MagicMock(return_value=True)
+ stub.dispatch = MagicMock(return_value=1)
+ return stub
+
+
+class TestTwitterReceive:
+ CANNED = {
+ "trigger_type": "mentions",
+ "tweet_id": "tw123",
+ "text": "@me hello",
+ "author_id": "u999",
+ "author_username": "alice",
+ "created_at": "2026-04-15T12:00:00",
+ }
+
+ async def test_happy_path_returns_canned_event(self, harness):
+ waiter = _make_waiter_stub(canned_event=self.CANNED)
+
+ with patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "twitterReceive",
+ {"trigger_type": "mentions", "poll_interval": 60},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["tweet_id"] == "tw123"
+ assert payload["author_username"] == "alice"
+ waiter.register.assert_awaited_once()
+ waiter.wait_for_event.assert_awaited_once()
+
+ async def test_cancellation_returns_error_envelope(self, harness):
+ import asyncio
+
+ waiter = _make_waiter_stub()
+ waiter.wait_for_event = AsyncMock(side_effect=asyncio.CancelledError())
+
+ with patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "twitterReceive", {"trigger_type": "mentions"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "cancel" in result["error"].lower()
+
+ async def test_unknown_trigger_config_errors(self, harness):
+ # get_trigger_config -> None simulates a missing registry entry.
+ waiter = _make_waiter_stub()
+ waiter.get_trigger_config = MagicMock(return_value=None)
+
+ with patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "twitterReceive", {"trigger_type": "mentions"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown trigger" in result["error"].lower()
+ waiter.register.assert_not_awaited()
+
+ async def test_generic_exception_becomes_envelope(self, harness):
+ waiter = _make_waiter_stub()
+ waiter.wait_for_event = AsyncMock(side_effect=RuntimeError("boom"))
+
+ with patched_broadcaster(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "twitterReceive", {"trigger_type": "mentions"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "boom" in result["error"]
diff --git a/server/tests/nodes/test_web_automation.py b/server/tests/nodes/test_web_automation.py
new file mode 100644
index 00000000..a6f829f9
--- /dev/null
+++ b/server/tests/nodes/test_web_automation.py
@@ -0,0 +1,465 @@
+"""Contract tests for web_automation nodes: browser, crawleeScraper, apifyActor.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/web_automation/`. A refactor that breaks any of
+these indicates the docs (and the user-visible contract) need to be updated too.
+
+All external side-effects are mocked:
+ - browser: patches `BrowserService._run_sync` so no subprocess is spawned.
+ - crawleeScraper: patches the crawlee crawler classes the handler imports
+ lazily (`BeautifulSoupCrawler`, `PlaywrightCrawler`).
+ - apifyActor: patches the ApifyClientAsync singleton returned from
+ `services.handlers.apify._get_apify_client`.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_container
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# Helpers
+# ============================================================================
+
+
+class _FakeBrowserService:
+ """Drop-in replacement for BrowserService exposing an async `run`.
+
+ Returns a pre-canned JSON-parsed dict on each call. The real service's
+ `run()` is also async, so tests can `await` it transparently.
+ """
+
+ def __init__(self, canned: dict | None = None, error: Exception | None = None):
+ self._canned = canned if canned is not None else {"success": True, "data": {}}
+ self._error = error
+ self.calls: list[tuple] = []
+
+ async def run(self, args, session, timeout, **kwargs):
+ self.calls.append((tuple(args), session, timeout, kwargs))
+ if self._error:
+ raise self._error
+ return self._canned
+
+
+def _patch_browser_service(svc):
+ """Patch get_browser_service to return the fake."""
+ return patch("services.handlers.browser.get_browser_service", return_value=svc)
+
+
+# ============================================================================
+# browser
+# ============================================================================
+
+
+class TestBrowser:
+ async def test_navigate_happy_path(self, harness):
+ fake = _FakeBrowserService(canned={"success": True, "url": "https://example.com"})
+
+ with _patch_browser_service(fake):
+ result = await harness.execute(
+ "browser",
+ {
+ "operation": "navigate",
+ "url": "https://example.com",
+ "session": "test_sess",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(result, ["operation", "data", "session"])
+ payload = result["result"]
+ assert payload["operation"] == "navigate"
+ assert payload["session"] == "test_sess"
+ assert payload["data"]["url"] == "https://example.com"
+
+ # Verify the handler mapped navigate -> [open, URL]
+ args, session, timeout, _ = fake.calls[-1]
+ assert args == ("open", "https://example.com")
+ assert session == "test_sess"
+
+ async def test_snapshot_uses_i_flag_and_session_fallback(self, harness):
+ # Empty session -> handler must derive machina_<execution_id>.
+ fake = _FakeBrowserService(
+ canned={"success": True, "nodes": [{"ref": "@e1", "role": "button"}]}
+ )
+
+ with _patch_browser_service(fake):
+ result = await harness.execute(
+ "browser",
+ {"operation": "snapshot"}, # no session, no url
+ )
+
+ harness.assert_envelope(result, success=True)
+ args, session, _, _ = fake.calls[-1]
+ assert args == ("snapshot", "-i")
+ assert session.startswith("machina_")
+
+ async def test_screenshot_with_jpeg_and_quality(self, harness):
+ fake = _FakeBrowserService(canned={"success": True, "base64": "AAAA"})
+
+ with _patch_browser_service(fake):
+ result = await harness.execute(
+ "browser",
+ {
+ "operation": "screenshot",
+ "fullPage": True,
+ "annotate": True,
+ "screenshotFormat": "jpeg",
+ "screenshotQuality": 80,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ args, _, _, _ = fake.calls[-1]
+ # Expect all flags to appear in order
+ assert args[0] == "screenshot"
+ assert "--full" in args
+ assert "--annotate" in args
+ assert "--screenshot-format" in args
+ assert "jpeg" in args
+ assert "--screenshot-quality" in args
+ assert "80" in args
+
+ async def test_missing_url_for_navigate_returns_error(self, harness):
+ fake = _FakeBrowserService()
+
+ with _patch_browser_service(fake):
+ result = await harness.execute("browser", {"operation": "navigate"})
+
+ harness.assert_envelope(result, success=False)
+ assert "url is required" in result["error"].lower()
+ # handler rejected before calling the service
+ assert fake.calls == []
+
+ async def test_service_not_installed(self, harness):
+ with patch(
+ "services.handlers.browser.get_browser_service", return_value=None
+ ):
+ result = await harness.execute("browser", {"operation": "navigate", "url": "https://x"})
+
+ harness.assert_envelope(result, success=False)
+ assert "agent-browser not installed" in result["error"].lower()
+
+ async def test_subprocess_runtime_error_wrapped_in_envelope(self, harness):
+ fake = _FakeBrowserService(error=RuntimeError("agent-browser returned empty output"))
+
+ with _patch_browser_service(fake):
+ result = await harness.execute(
+ "browser", {"operation": "navigate", "url": "https://x"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "empty output" in result["error"].lower()
+
+
+# ============================================================================
+# crawleeScraper
+# ============================================================================
+
+
+class _FakeBsCtx:
+ """Minimal BeautifulSoupCrawlingContext stub for the handler closure."""
+
+ def __init__(self, url: str, title: str = "Example", body_html: str = "<p>hello</p>"):
+ from bs4 import BeautifulSoup
+
+ self.request = MagicMock(url=url)
+ self.soup = BeautifulSoup(f"<html><head><title>{title}</title></head><body>{body_html}</body></html>", "html.parser")
+ self.enqueue_links = AsyncMock(return_value=None)
+
+
+class _FakeCrawler:
+ """Stand-in for BeautifulSoupCrawler that captures the registered handler
+ and invokes it against a canned crawling context when `run()` is awaited.
+ """
+
+ def __init__(self, *args, **kwargs):
+ self.init_kwargs = kwargs
+ self._handler = None
+ self.router = MagicMock()
+ # `router.default_handler` is used as a decorator. Capture the callable.
+
+ def _register(fn):
+ self._handler = fn
+ return fn
+
+ self.router.default_handler = _register
+
+ async def run(self, urls):
+ for url in urls:
+ if self._handler:
+ await self._handler(_FakeBsCtx(url))
+
+
+class TestCrawleeScraper:
+ async def test_beautifulsoup_single_happy_path(self, harness):
+ fake_cls = _FakeCrawler # class is instantiated inside the handler
+ with patch(
+ "crawlee.crawlers.BeautifulSoupCrawler", fake_cls
+ ), patch(
+ "crawlee.storage_clients.MemoryStorageClient", MagicMock()
+ ), patch(
+ "crawlee.ConcurrencySettings", MagicMock()
+ ):
+ result = await harness.execute(
+ "crawleeScraper",
+ {
+ "url": "https://example.com",
+ "crawlerType": "beautifulsoup",
+ "mode": "single",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result, ["pages", "page_count", "crawler_type", "mode", "proxied"]
+ )
+ payload = result["result"]
+ assert payload["crawler_type"] == "beautifulsoup"
+ assert payload["mode"] == "single"
+ assert payload["proxied"] is False
+ assert payload["page_count"] == 1
+ page = payload["pages"][0]
+ assert page["url"] == "https://example.com"
+ assert page["title"] == "Example"
+ assert "hello" in page["content"]
+
+ async def test_missing_url_returns_validation_error(self, harness):
+ result = await harness.execute(
+ "crawleeScraper", {"url": "", "crawlerType": "beautifulsoup"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "url is required" in result["error"].lower()
+
+ async def test_unknown_crawler_type_returns_error(self, harness):
+ # Handler does not attempt any import for unknown crawler types.
+ result = await harness.execute(
+ "crawleeScraper",
+ {"url": "https://x.test", "crawlerType": "teleportron"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown crawler type" in result["error"].lower()
+
+ async def test_crawlee_import_error_rewritten(self, harness):
+ # Simulate crawlee not installed by making the runtime import raise.
+ # The handler imports `from crawlee.crawlers import BeautifulSoupCrawler`
+ # inside _run_beautifulsoup, so we patch the module attribute to raise.
+ with patch(
+ "crawlee.crawlers.BeautifulSoupCrawler",
+ side_effect=ImportError("No module named 'crawlee'"),
+ ):
+ result = await harness.execute(
+ "crawleeScraper",
+ {"url": "https://x.test", "crawlerType": "beautifulsoup"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ # Error message is rewritten to an install hint
+ assert "crawlee" in result["error"].lower()
+
+ async def test_runtime_exception_returns_envelope(self, harness):
+ class BrokenCrawler(_FakeCrawler):
+ async def run(self, urls):
+ raise RuntimeError("crawler blew up")
+
+ with patch(
+ "crawlee.crawlers.BeautifulSoupCrawler", BrokenCrawler
+ ), patch(
+ "crawlee.storage_clients.MemoryStorageClient", MagicMock()
+ ), patch(
+ "crawlee.ConcurrencySettings", MagicMock()
+ ):
+ result = await harness.execute(
+ "crawleeScraper",
+ {"url": "https://x.test", "crawlerType": "beautifulsoup"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "crawler blew up" in result["error"]
+
+
+# ============================================================================
+# apifyActor
+# ============================================================================
+
+
+def _make_fake_apify_client(
+ *,
+ run_info: dict | None = None,
+ items: list | None = None,
+ call_exc: Exception | None = None,
+):
+ """Build a MagicMock that mimics ApifyClientAsync surface used by the handler."""
+ client = MagicMock(name="ApifyClientAsync")
+
+ actor_client = MagicMock(name="ActorClient")
+ if call_exc:
+ actor_client.call = AsyncMock(side_effect=call_exc)
+ else:
+ actor_client.call = AsyncMock(return_value=run_info)
+ client.actor = MagicMock(return_value=actor_client)
+
+ list_result = MagicMock()
+ list_result.items = items or []
+ dataset_client = MagicMock(name="DatasetClient")
+ dataset_client.list_items = AsyncMock(return_value=list_result)
+ client.dataset = MagicMock(return_value=dataset_client)
+
+ return client
+
+
+class TestApifyActor:
+ async def test_happy_path_returns_dataset_items(self, harness):
+ run_info = {
+ "id": "run_123",
+ "status": "SUCCEEDED",
+ "defaultDatasetId": "ds_456",
+ "usageTotalUsd": 0.02,
+ "startedAt": "2026-04-15T00:00:00Z",
+ "finishedAt": "2026-04-15T00:00:05Z",
+ }
+ items = [{"url": "https://a.example"}, {"url": "https://b.example"}]
+ fake_client = _make_fake_apify_client(run_info=run_info, items=items)
+
+ with patched_container(auth_api_keys={"apify": "tk_apify"}), patch(
+ "services.handlers.apify.ApifyClientAsync", return_value=fake_client
+ ):
+ result = await harness.execute(
+ "apifyActor",
+ {
+ "actorId": "apify/instagram-scraper",
+ "instagramUrls": "https://instagram.com/a, https://instagram.com/b",
+ "maxResults": 50,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result,
+ [
+ "run_id",
+ "actor_id",
+ "status",
+ "items",
+ "item_count",
+ "dataset_id",
+ "compute_units",
+ "started_at",
+ "finished_at",
+ ],
+ )
+ payload = result["result"]
+ assert payload["run_id"] == "run_123"
+ assert payload["actor_id"] == "apify/instagram-scraper"
+ assert payload["status"] == "SUCCEEDED"
+ assert payload["item_count"] == 2
+ assert payload["items"] == items
+ assert payload["dataset_id"] == "ds_456"
+ assert payload["compute_units"] == 0.02
+
+ # Quick-helper merge: call_args run_input should contain directUrls
+ call_kwargs = fake_client.actor.return_value.call.await_args.kwargs
+ run_input = call_kwargs["run_input"]
+ assert run_input["directUrls"] == [
+ "https://instagram.com/a",
+ "https://instagram.com/b",
+ ]
+ assert call_kwargs["memory_mbytes"] == 1024 # default
+ # dataset list called with the right limit
+ fake_client.dataset.return_value.list_items.assert_awaited_once_with(limit=50)
+
+ async def test_missing_api_token_short_circuits(self, harness):
+ # container returns no 'apify' key -> _get_apify_client returns None
+ with patched_container(auth_api_keys={}):
+ result = await harness.execute(
+ "apifyActor",
+ {"actorId": "apify/instagram-scraper"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "apify api token not configured" in result["error"].lower()
+
+ async def test_missing_actor_id_returns_validation_error(self, harness):
+ fake_client = _make_fake_apify_client(run_info={})
+
+ with patched_container(auth_api_keys={"apify": "tk"}), patch(
+ "services.handlers.apify.ApifyClientAsync", return_value=fake_client
+ ):
+ result = await harness.execute("apifyActor", {"actorId": ""})
+
+ harness.assert_envelope(result, success=False)
+ assert "actor id is required" in result["error"].lower()
+
+ async def test_failed_run_status_returns_error_envelope(self, harness):
+ run_info = {
+ "id": "run_err",
+ "status": "FAILED",
+ "errorMessage": "Actor crashed at step 3",
+ "defaultDatasetId": "",
+ }
+ fake_client = _make_fake_apify_client(run_info=run_info, items=[])
+
+ with patched_container(auth_api_keys={"apify": "tk"}), patch(
+ "services.handlers.apify.ApifyClientAsync", return_value=fake_client
+ ):
+ result = await harness.execute(
+ "apifyActor", {"actorId": "apify/some-actor"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "actor crashed at step 3" in result["error"].lower()
+ # trimmed result dict carries status info for downstream diagnosis
+ diag = result["result"]
+ assert diag["status"] == "FAILED"
+ assert diag["run_id"] == "run_err"
+
+ async def test_unauthorized_exception_rewritten(self, harness):
+ fake_client = _make_fake_apify_client(
+ call_exc=RuntimeError("Request failed: 401 Unauthorized")
+ )
+
+ with patched_container(auth_api_keys={"apify": "tk"}), patch(
+ "services.handlers.apify.ApifyClientAsync", return_value=fake_client
+ ):
+ result = await harness.execute(
+ "apifyActor", {"actorId": "apify/some-actor"}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "invalid apify api token" in result["error"].lower()
+
+ async def test_invalid_actor_input_json_silently_becomes_empty_dict(self, harness):
+ run_info = {
+ "id": "run_ok",
+ "status": "SUCCEEDED",
+ "defaultDatasetId": "ds",
+ "usageTotalUsd": 0,
+ "startedAt": "",
+ "finishedAt": "",
+ }
+ fake_client = _make_fake_apify_client(run_info=run_info, items=[])
+
+ with patched_container(auth_api_keys={"apify": "tk"}), patch(
+ "services.handlers.apify.ApifyClientAsync", return_value=fake_client
+ ):
+ result = await harness.execute(
+ "apifyActor",
+ {
+ "actorId": "apify/some-actor",
+ "actorInput": "{ this is not json",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ call_kwargs = fake_client.actor.return_value.call.await_args.kwargs
+ # malformed JSON becomes {} not a parse error
+ assert call_kwargs["run_input"] == {}
diff --git a/server/tests/nodes/test_whatsapp.py b/server/tests/nodes/test_whatsapp.py
new file mode 100644
index 00000000..0e7c5865
--- /dev/null
+++ b/server/tests/nodes/test_whatsapp.py
@@ -0,0 +1,417 @@
+"""Contract tests for whatsapp nodes: whatsappSend, whatsappDb, whatsappReceive.
+
+These tests freeze the input -> output behaviour documented in
+`docs-internal/node-logic-flows/whatsapp/`. The handlers proxy all traffic
+to the Go `whatsapp-rpc` service via a WebSocket RPC client in
+`routers/whatsapp.py`. We patch the two entry points the handlers use:
+
+ - `routers.whatsapp.handle_whatsapp_send` - sending messages
+ - `routers.whatsapp.whatsapp_rpc_call` - generic RPC calls
+ - `routers.whatsapp.handle_whatsapp_chat_history` - chat history RPC
+
+For `whatsappReceive` we use the same event-waiter stub pattern as
+`test_telegram_social.py` - patching the module reference imported by both
+`services.node_executor` and `services.handlers.triggers`.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_broadcaster, patched_container
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# --------------------------------------------------------------------------- #
+# Shared helpers
+# --------------------------------------------------------------------------- #
+
+
+def _patch_whatsapp_send(return_value):
+ """Patch routers.whatsapp.handle_whatsapp_send at the import site."""
+ return patch(
+ "routers.whatsapp.handle_whatsapp_send",
+ new=AsyncMock(return_value=return_value),
+ )
+
+
+def _patch_rpc_call(return_value=None, *, side_effect=None):
+ """Patch routers.whatsapp.whatsapp_rpc_call.
+
+ ``return_value`` may be a dict or list. ``side_effect`` may be a callable
+ for per-method routing.
+ """
+ kwargs = {}
+ if side_effect is not None:
+ kwargs["side_effect"] = side_effect
+ else:
+ kwargs["return_value"] = return_value if return_value is not None else {}
+ return patch("routers.whatsapp.whatsapp_rpc_call", new=AsyncMock(**kwargs))
+
+
+def _patch_chat_history_handler(return_value):
+ return patch(
+ "routers.whatsapp.handle_whatsapp_chat_history",
+ new=AsyncMock(return_value=return_value),
+ )
+
+
+# ============================================================================
+# whatsappSend
+# ============================================================================
+
+
+class TestWhatsappSend:
+ async def test_text_happy_path_to_phone(self, harness):
+ with _patch_whatsapp_send({"success": True}):
+ result = await harness.execute(
+ "whatsappSend",
+ {
+ "recipient_type": "phone",
+ "phone": "15551234567",
+ "message_type": "text",
+ "message": "hello world",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["status"] == "sent"
+ assert payload["recipient"] == "15551234567"
+ assert payload["recipient_type"] == "phone"
+ assert payload["message_type"] == "text"
+ assert payload["preview"] == "hello world"
+
+ async def test_format_markdown_transforms_message(self, harness):
+ """When format_markdown=true, parameters.message is rewritten before RPC call."""
+ captured = {}
+
+ async def fake_send(params):
+ captured["message"] = params.get("message")
+ return {"success": True}
+
+ with patch(
+ "routers.whatsapp.handle_whatsapp_send",
+ new=AsyncMock(side_effect=fake_send),
+ ), patch(
+ "services.markdown_formatter.to_whatsapp",
+ return_value="*bold*",
+ ):
+ result = await harness.execute(
+ "whatsappSend",
+ {
+ "recipient_type": "self",
+ "message_type": "text",
+ "message": "**bold**",
+ "format_markdown": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert captured["message"] == "*bold*"
+ assert result["result"]["recipient"] == "self"
+
+ async def test_channel_rejects_contact_message_type(self, harness):
+ """Channels only allow text/image/video/audio/document."""
+ with _patch_whatsapp_send({"success": True}) as mock_send:
+ result = await harness.execute(
+ "whatsappSend",
+ {
+ "recipient_type": "channel",
+ "channel_jid": "120363123@newsletter",
+ "message_type": "contact",
+ "contact_name": "Alice",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "channel" in result["error"].lower()
+ # Must short-circuit before hitting the RPC
+ mock_send.assert_not_awaited()
+
+ async def test_missing_phone_returns_error(self, harness):
+ with _patch_whatsapp_send({"success": True}) as mock_send:
+ result = await harness.execute(
+ "whatsappSend",
+ {
+ "recipient_type": "phone",
+ # no phone
+ "message_type": "text",
+ "message": "hi",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "phone" in result["error"].lower()
+ mock_send.assert_not_awaited()
+
+ async def test_rpc_failure_surfaces_as_error_envelope(self, harness):
+ with _patch_whatsapp_send({"success": False, "error": "not connected"}):
+ result = await harness.execute(
+ "whatsappSend",
+ {
+ "recipient_type": "self",
+ "message_type": "text",
+ "message": "ping",
+ },
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "not connected" in result["error"].lower()
+
+
+# ============================================================================
+# whatsappDb - representative subset of 5 operations
+# ============================================================================
+
+
+class TestWhatsappDb:
+ async def test_chat_history_individual_happy_path(self, harness):
+ chat_response = {
+ "success": True,
+ "messages": [
+ {"message_id": "m1", "text": "hi", "message_type": "text"},
+ {"message_id": "m2", "text": "yo", "message_type": "text"},
+ ],
+ "total": 2,
+ "has_more": False,
+ }
+ with _patch_chat_history_handler(chat_response), _patch_rpc_call({}):
+ result = await harness.execute(
+ "whatsappDb",
+ {
+ "operation": "chat_history",
+ "chat_type": "individual",
+ "phone": "15551234567",
+ "limit": 10,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["operation"] == "chat_history"
+ assert payload["count"] == 2
+ # Index is base_offset + i + 1
+ assert payload["messages"][0]["index"] == 1
+ assert payload["messages"][1]["index"] == 2
+
+ async def test_chat_history_missing_phone_errors(self, harness):
+ with _patch_chat_history_handler({"success": True, "messages": []}), _patch_rpc_call({}):
+ result = await harness.execute(
+ "whatsappDb",
+ {"operation": "chat_history", "chat_type": "individual"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "phone" in result["error"].lower()
+
+ async def test_search_groups_truncates_and_shapes(self, harness):
+ """search_groups returns only {jid, name} and reports truncation."""
+ groups = [
+ {"jid": f"g{i}@g.us", "name": f"Group {i}", "extra_field": "noise"}
+ for i in range(5)
+ ]
+ # Handler runs data.get('success', True) BEFORE isinstance(data, list)
+ # (documented bug), so the RPC stub must return a dict envelope here.
+ with _patch_rpc_call({"success": True, "result": groups}):
+ result = await harness.execute(
+ "whatsappDb",
+ {"operation": "search_groups", "query": "", "limit": 2},
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["total"] == 5
+ assert payload["returned"] == 2
+ assert payload["has_more"] is True
+ assert all(set(g.keys()) == {"jid", "name"} for g in payload["groups"])
+ assert payload["hint"] is not None # truncation hint populated
+
+ async def test_channel_messages_with_invite_link_resolves_jid(self, harness):
+ """Invite links should trigger a newsletter_info lookup to resolve JID."""
+ resolved_jid = "120363REAL@newsletter"
+
+ async def fake_rpc(method, params=None):
+ if method == "newsletter_info":
+ # _resolve_to_jid reads result from dict
+ return {"result": {"jid": resolved_jid}}
+ if method == "newsletter_messages":
+ # Capture for later assertion via closure
+ fake_rpc.captured_messages_params = params
+ return [{"message_id": "n1", "message_type": "text"}]
+ return {}
+
+ fake_rpc.captured_messages_params = None
+
+ with _patch_rpc_call(side_effect=fake_rpc):
+ result = await harness.execute(
+ "whatsappDb",
+ {
+ "operation": "channel_messages",
+ "channel_jid": "https://whatsapp.com/channel/abc",
+ "channel_count": 5,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ # The channel_messages RPC must have been called with the resolved JID
+ assert fake_rpc.captured_messages_params["jid"] == resolved_jid
+ assert result["result"]["count"] == 1
+
+ async def test_channel_create_happy_path(self, harness):
+ """Creating a channel by name returns the RPC result merged into payload."""
+ created = {"jid": "120363NEW@newsletter", "name": "My Channel"}
+ with _patch_rpc_call(created):
+ result = await harness.execute(
+ "whatsappDb",
+ {
+ "operation": "channel_create",
+ "channel_name": "My Channel",
+ "channel_description": "desc",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["operation"] == "channel_create"
+ assert payload["jid"] == "120363NEW@newsletter"
+ assert payload["name"] == "My Channel"
+
+ async def test_contact_profile_pic_happy_path(self, harness):
+ pic_result = {"url": "https://example.com/pic.jpg"}
+ with _patch_rpc_call(pic_result):
+ result = await harness.execute(
+ "whatsappDb",
+ {
+ "operation": "contact_profile_pic",
+ "profile_pic_jid": "[email protected]",
+ "preview": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["operation"] == "contact_profile_pic"
+ assert payload["url"] == "https://example.com/pic.jpg"
+
+ async def test_unknown_operation_returns_error(self, harness):
+ with _patch_rpc_call({}):
+ result = await harness.execute(
+ "whatsappDb",
+ {"operation": "bogus_op"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "unknown operation" in result["error"].lower()
+
+ async def test_rpc_exception_becomes_error_envelope(self, harness):
+ with _patch_rpc_call(side_effect=Exception("rpc down")):
+ result = await harness.execute(
+ "whatsappDb",
+ {"operation": "list_contacts", "limit": 10},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "rpc down" in result["error"].lower()
+
+
+# ============================================================================
+# whatsappReceive (generic trigger via handle_trigger_node + event_waiter)
+# ============================================================================
+
+
+def _make_waiter_stub(*, canned_event=None, is_trigger=True, wait_side_effect=None):
+ """Fake event_waiter module stub for the generic trigger path."""
+ waiter_obj = MagicMock(name="Waiter")
+ waiter_obj.id = "waiter-test-id"
+
+ stub = MagicMock(name="event_waiter_module")
+ stub.is_trigger_node = MagicMock(return_value=is_trigger)
+ stub.get_trigger_config = MagicMock(
+ return_value=MagicMock(
+ node_type="whatsappReceive",
+ event_type="whatsapp_message_received",
+ display_name="WhatsApp Message",
+ )
+ )
+ stub.register = AsyncMock(return_value=waiter_obj)
+ if wait_side_effect is not None:
+ stub.wait_for_event = AsyncMock(side_effect=wait_side_effect)
+ else:
+ stub.wait_for_event = AsyncMock(return_value=canned_event or {})
+ stub.get_backend_mode = MagicMock(return_value="asyncio.Future")
+ stub.cancel = MagicMock(return_value=True)
+ stub.dispatch = MagicMock(return_value=1)
+ return stub
+
+
+class TestWhatsappReceive:
+ CANNED = {
+ "message_id": "wam_1",
+ "sender": "[email protected]",
+ "sender_phone": "15551234567",
+ "chat_id": "[email protected]",
+ "message_type": "text",
+ "text": "hello there",
+ "is_group": False,
+ "is_from_me": False,
+ "push_name": "Alice",
+ "timestamp": "2026-04-15T12:00:00",
+ "is_forwarded": False,
+ }
+
+ async def test_happy_path_returns_canned_event(self, harness):
+ waiter = _make_waiter_stub(canned_event=self.CANNED)
+
+ with patched_broadcaster(), patched_container(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "whatsappReceive",
+ {
+ "filter": "all",
+ "messageTypeFilter": "all",
+ "ignoreOwnMessages": True,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["text"] == "hello there"
+ assert payload["sender_phone"] == "15551234567"
+ waiter.register.assert_awaited_once()
+ waiter.wait_for_event.assert_awaited_once()
+
+ async def test_cancellation_propagates_as_error(self, harness):
+ import asyncio
+
+ waiter = _make_waiter_stub(wait_side_effect=asyncio.CancelledError())
+
+ with patched_broadcaster(), patched_container(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "whatsappReceive",
+ {"filter": "all"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "cancel" in result["error"].lower()
+
+ async def test_waiter_exception_surfaces_as_error(self, harness):
+ waiter = _make_waiter_stub(wait_side_effect=RuntimeError("redis stream down"))
+
+ with patched_broadcaster(), patched_container(), patch(
+ "services.node_executor.event_waiter", waiter
+ ), patch("services.handlers.triggers.event_waiter", waiter):
+ result = await harness.execute(
+ "whatsappReceive",
+ {"filter": "keywords", "keywords": "urgent,fire"},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "redis stream down" in result["error"].lower()
diff --git a/server/tests/nodes/test_workflow_triggers.py b/server/tests/nodes/test_workflow_triggers.py
new file mode 100644
index 00000000..2056478b
--- /dev/null
+++ b/server/tests/nodes/test_workflow_triggers.py
@@ -0,0 +1,490 @@
+"""Contract tests for workflow_triggers nodes.
+
+Covers: start, timer, cronScheduler, webhookTrigger, chatTrigger, taskTrigger,
+webhookResponse.
+
+Each handler is exercised through the full NodeExecutor dispatch via the
+shared `harness` fixture. Event-waiter-based triggers (webhookTrigger,
+chatTrigger, taskTrigger) are made non-blocking by patching the
+`event_waiter` module attributes on the handler namespace so the canned
+event payload resolves immediately.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+from contextlib import contextmanager
+from typing import Any, Dict, Iterator, Optional
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from tests.nodes._mocks import patched_broadcaster
+
+
+pytestmark = pytest.mark.node_contract
+
+
+# ============================================================================
+# Helpers
+# ============================================================================
+
+
+@contextmanager
+def patched_trigger_waiter(
+ canned_event: Optional[Dict[str, Any]] = None,
+ *,
+ raise_cancelled: bool = False,
+) -> Iterator[MagicMock]:
+ """Patch event_waiter on the triggers handler namespace.
+
+ The generic trigger handler imports `from services import event_waiter`,
+ so the bound name lives at `services.handlers.triggers.event_waiter`.
+ Mocks replicate the real module surface used by the handler:
+ - get_trigger_config(node_type) -> TriggerConfig-like MagicMock
+ - register(...) -> awaitable that yields a Waiter-like MagicMock
+ - wait_for_event(waiter) -> awaitable that yields canned_event
+ - get_backend_mode() -> "memory"
+ """
+ event_data = canned_event if canned_event is not None else {}
+ waiter_obj = MagicMock(name="Waiter", id="waiter-test-id")
+
+ mock = MagicMock(name="event_waiter_module")
+ mock.get_trigger_config = MagicMock(
+ return_value=MagicMock(
+ node_type="testTrigger",
+ event_type="test_event",
+ display_name="Test Trigger",
+ )
+ )
+ mock.register = AsyncMock(return_value=waiter_obj)
+
+ if raise_cancelled:
+ import asyncio as _asyncio
+
+ mock.wait_for_event = AsyncMock(side_effect=_asyncio.CancelledError())
+ else:
+ mock.wait_for_event = AsyncMock(return_value=event_data)
+
+ mock.get_backend_mode = MagicMock(return_value="memory")
+ mock.is_trigger_node = MagicMock(return_value=True)
+
+ with patch("services.handlers.triggers.event_waiter", mock), patch(
+ "services.node_executor.event_waiter", mock
+ ):
+ yield mock
+
+
+# ============================================================================
+# start
+# ============================================================================
+
+
+class TestStart:
+ async def test_happy_path_returns_parsed_initial_data(self, harness):
+ result = await harness.execute(
+ "start", {"initialData": '{"message": "hi", "n": 7}'}
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload == {"message": "hi", "n": 7}
+
+ async def test_invalid_json_silently_becomes_empty_dict(self, harness):
+ # Documented behaviour: invalid JSON -> {} with success=True.
+ result = await harness.execute("start", {"initialData": "not json"})
+ harness.assert_envelope(result, success=True)
+ assert result["result"] == {}
+
+ async def test_missing_initial_data_defaults_to_empty_dict(self, harness):
+ result = await harness.execute("start", {})
+ harness.assert_envelope(result, success=True)
+ assert result["result"] == {}
+
+
+# ============================================================================
+# timer
+# ============================================================================
+
+
+class TestTimer:
+ async def test_happy_path_short_sleep(self, harness):
+ with patched_broadcaster() as broadcaster:
+ result = await harness.execute(
+ "timer", {"duration": 0, "unit": "seconds"}
+ )
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result,
+ ["timestamp", "elapsed_ms", "duration", "unit", "message"],
+ )
+ payload = result["result"]
+ assert payload["duration"] == 0
+ assert payload["unit"] == "seconds"
+ assert "Timer completed" in payload["message"]
+ # waiting broadcast fired exactly once before the sleep
+ broadcaster.update_node_status.assert_called()
+ first_call = broadcaster.update_node_status.call_args_list[0]
+ # args: (node_id, status, data, ...)
+ assert first_call.args[1] == "waiting"
+ assert "wait_seconds" in first_call.args[2]
+
+ async def test_unknown_unit_falls_back_to_raw_seconds(self, harness):
+ # Documented gotcha: unknown unit is treated as seconds.
+ with patched_broadcaster():
+ result = await harness.execute(
+ "timer", {"duration": 0, "unit": "fortnights"}
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["unit"] == "fortnights"
+
+ async def test_non_numeric_duration_returns_error_envelope(self, harness):
+ with patched_broadcaster():
+ result = await harness.execute(
+ "timer", {"duration": "abc", "unit": "seconds"}
+ )
+ harness.assert_envelope(result, success=False)
+
+
+# ============================================================================
+# cronScheduler
+# ============================================================================
+
+
+class TestCronScheduler:
+ async def test_once_frequency_fires_immediately(self, harness):
+ with patched_broadcaster() as broadcaster:
+ result = await harness.execute(
+ "cronScheduler", {"frequency": "once"}
+ )
+ harness.assert_envelope(result, success=True)
+ harness.assert_output_shape(
+ result,
+ [
+ "timestamp",
+ "iteration",
+ "frequency",
+ "schedule",
+ "waited_seconds",
+ "message",
+ ],
+ )
+ payload = result["result"]
+ assert payload["frequency"] == "once"
+ assert payload["iteration"] == 1
+ assert payload["waited_seconds"] == 0
+ # 'once' branch must NOT add next_run
+ assert "next_run" not in payload
+ broadcaster.update_node_status.assert_called()
+
+ async def test_recurring_frequency_adds_next_run_and_schedule_string(
+ self, harness
+ ):
+ # Patch asyncio.sleep so the handler doesn't actually wait 30s.
+ with patched_broadcaster(), patch(
+ "services.handlers.utility.asyncio.sleep", new=AsyncMock()
+ ) as sleep_mock:
+ result = await harness.execute(
+ "cronScheduler", {"frequency": "seconds", "interval": 30}
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["frequency"] == "seconds"
+ assert payload["waited_seconds"] == 30
+ # Recurring branch adds next_run + schedule description.
+ assert payload["next_run"] == "Every 30 seconds"
+ assert "will repeat" in payload["message"]
+ sleep_mock.assert_awaited_once()
+
+ async def test_unknown_frequency_uses_default_wait_and_unknown_schedule(
+ self, harness
+ ):
+ # Documented gotcha: unknown frequency -> 300s wait, "Unknown schedule".
+ with patched_broadcaster(), patch(
+ "services.handlers.utility.asyncio.sleep", new=AsyncMock()
+ ) as sleep_mock:
+ result = await harness.execute(
+ "cronScheduler", {"frequency": "quantum"}
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["schedule"] == "Unknown schedule"
+ assert payload["waited_seconds"] == 300
+ sleep_mock.assert_awaited_once()
+
+
+# ============================================================================
+# webhookTrigger
+# ============================================================================
+
+
+class TestWebhookTrigger:
+ async def test_happy_path_returns_canned_event(self, harness):
+ canned = {
+ "method": "POST",
+ "path": "my-hook",
+ "headers": {"x-api-key": "tk"},
+ "body": "{}",
+ "json": {"hello": "world"},
+ }
+ with patched_trigger_waiter(canned), patched_broadcaster() as broadcaster:
+ result = await harness.execute(
+ "webhookTrigger", {"path": "my-hook", "method": "POST"}
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"] == canned
+ # broadcaster called with 'waiting'
+ assert broadcaster.update_node_status.call_args_list[0].args[1] == "waiting"
+
+ async def test_unknown_trigger_type_returns_error(self, harness):
+ # Force event_waiter.get_trigger_config to return None for this run.
+ with patched_trigger_waiter() as ew, patched_broadcaster():
+ ew.get_trigger_config.return_value = None
+ result = await harness.execute("webhookTrigger", {"path": "x"})
+ harness.assert_envelope(result, success=False)
+ assert "Unknown trigger type" in result["error"]
+
+ async def test_cancelled_returns_cancelled_by_user(self, harness):
+ with patched_trigger_waiter(raise_cancelled=True), patched_broadcaster():
+ result = await harness.execute("webhookTrigger", {"path": "x"})
+ harness.assert_envelope(result, success=False)
+ assert result["error"] == "Cancelled by user"
+
+
+# ============================================================================
+# chatTrigger
+# ============================================================================
+
+
+class TestChatTrigger:
+ async def test_happy_path_returns_canned_chat_event(self, harness):
+ canned = {
+ "message": "hello agent",
+ "session_id": "default",
+ "timestamp": "2026-04-15T10:00:00Z",
+ }
+ with patched_trigger_waiter(canned), patched_broadcaster():
+ result = await harness.execute(
+ "chatTrigger", {"sessionId": "default"}
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["message"] == "hello agent"
+ assert payload["session_id"] == "default"
+
+ async def test_passes_params_to_register(self, harness):
+ # Verify params are forwarded so build_chat_filter can apply sessionId.
+ with patched_trigger_waiter({"message": "m"}) as ew, patched_broadcaster():
+ await harness.execute("chatTrigger", {"sessionId": "alpha"})
+ ew.register.assert_awaited_once()
+ kwargs_params = ew.register.await_args.args[2]
+ assert kwargs_params.get("sessionId") == "alpha"
+
+ async def test_wait_failure_returns_error_envelope(self, harness):
+ with patched_trigger_waiter() as ew, patched_broadcaster():
+ ew.wait_for_event = AsyncMock(side_effect=RuntimeError("boom"))
+ result = await harness.execute(
+ "chatTrigger", {"sessionId": "default"}
+ )
+ harness.assert_envelope(result, success=False)
+ assert "boom" in result["error"]
+
+
+# ============================================================================
+# taskTrigger
+# ============================================================================
+
+
+class TestTaskTrigger:
+ async def test_happy_path_completed_task(self, harness):
+ canned = {
+ "task_id": "t-1",
+ "status": "completed",
+ "agent_name": "coding_agent",
+ "agent_node_id": "node-child",
+ "parent_node_id": "node-parent",
+ "result": "done",
+ "workflow_id": "wf-1",
+ }
+ with patched_trigger_waiter(canned), patched_broadcaster():
+ result = await harness.execute(
+ "taskTrigger", {"status_filter": "completed"}
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["status"] == "completed"
+ assert result["result"]["task_id"] == "t-1"
+
+ async def test_error_task_event_shape(self, harness):
+ canned = {
+ "task_id": "t-2",
+ "status": "error",
+ "agent_name": "web_agent",
+ "agent_node_id": "node-child",
+ "parent_node_id": "node-parent",
+ "error": "something failed",
+ "workflow_id": "wf-1",
+ }
+ with patched_trigger_waiter(canned), patched_broadcaster():
+ result = await harness.execute(
+ "taskTrigger", {"status_filter": "error"}
+ )
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["status"] == "error"
+ assert result["result"]["error"] == "something failed"
+
+ async def test_register_receives_all_filter_params(self, harness):
+ with patched_trigger_waiter({"status": "completed"}) as ew, patched_broadcaster():
+ await harness.execute(
+ "taskTrigger",
+ {
+ "task_id": "t-xyz",
+ "agent_name": "Twitter",
+ "status_filter": "completed",
+ "parent_node_id": "p-1",
+ },
+ )
+ ew.register.assert_awaited_once()
+ forwarded = ew.register.await_args.args[2]
+ assert forwarded["task_id"] == "t-xyz"
+ assert forwarded["agent_name"] == "Twitter"
+ assert forwarded["status_filter"] == "completed"
+ assert forwarded["parent_node_id"] == "p-1"
+
+
+# ============================================================================
+# webhookResponse
+# ============================================================================
+
+
+@contextmanager
+def _patched_resolve_webhook_response() -> Iterator[MagicMock]:
+ """Stub `routers.webhook.resolve_webhook_response`.
+
+ The handler does a lazy import inside the function body, so we stub the
+ `routers.webhook` module in sys.modules before it is imported.
+ """
+ resolve = MagicMock(name="resolve_webhook_response", return_value=None)
+ # Pre-install a stub module so `from routers.webhook import resolve_webhook_response`
+ # inside the handler resolves to this mock without needing the real router
+ # (which pulls FastAPI + dependency injection).
+ routers_pkg = sys.modules.get("routers")
+ if routers_pkg is None:
+ routers_pkg = types.ModuleType("routers")
+ routers_pkg.__path__ = []
+ sys.modules["routers"] = routers_pkg
+ webhook_mod = types.ModuleType("routers.webhook")
+ webhook_mod.resolve_webhook_response = resolve
+ sys.modules["routers.webhook"] = webhook_mod
+ try:
+ yield resolve
+ finally:
+ # Leave the stub in place for subsequent tests - re-installing is cheap.
+ pass
+
+
+class TestWebhookResponse:
+ async def test_happy_path_with_static_body(self, harness):
+ with _patched_resolve_webhook_response() as resolve:
+ result = await harness.execute(
+ "webhookResponse",
+ {
+ "statusCode": 201,
+ "responseBody": '{"ok": true}',
+ "contentType": "application/json",
+ },
+ )
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["sent"] is True
+ assert payload["statusCode"] == 201
+ assert payload["contentType"] == "application/json"
+ assert payload["bodyLength"] == len('{"ok": true}')
+ resolve.assert_called_once()
+ args = resolve.call_args.args
+ # (node_id, response_dict)
+ assert args[1]["statusCode"] == 201
+ assert args[1]["body"] == '{"ok": true}'
+ assert args[1]["contentType"] == "application/json"
+
+ async def test_template_substitution_from_connected_outputs(self, harness):
+ # Upstream httpRequest node outputs {"status": 200, "data": "hello"}.
+ upstream_source = "src-node"
+ upstream_output = {"status": 200, "data": "hello"}
+ nodes = [
+ {"id": upstream_source, "type": "httpRequest", "data": {}},
+ {"id": "resp-node", "type": "webhookResponse", "data": {}},
+ ]
+ edges = [
+ {
+ "source": upstream_source,
+ "target": "resp-node",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+
+ # Pre-seed upstream output via harness upstream_outputs map.
+ # NodeExecutor._get_connected_outputs reads output_main via get_output_fn.
+ upstream_outputs = {
+ f"{upstream_source}::output_main": upstream_output,
+ upstream_source: upstream_output,
+ }
+
+ with _patched_resolve_webhook_response() as resolve:
+ await harness.execute(
+ "webhookResponse",
+ {
+ "statusCode": 200,
+ "responseBody": "echo {{input.status}} and {{httpRequest.data}}",
+ "contentType": "text/plain",
+ },
+ node_id="resp-node",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+ resolve.assert_called_once()
+ body = resolve.call_args.args[1]["body"]
+ assert "200" in body
+ assert "hello" in body
+
+ async def test_empty_body_with_upstream_serialises_first_output(self, harness):
+ upstream_source = "src-node"
+ upstream_output = {"hello": "world"}
+ nodes = [
+ {"id": upstream_source, "type": "httpRequest", "data": {}},
+ {"id": "resp-node", "type": "webhookResponse", "data": {}},
+ ]
+ edges = [
+ {
+ "source": upstream_source,
+ "target": "resp-node",
+ "sourceHandle": "output-main",
+ "targetHandle": "input-main",
+ }
+ ]
+ upstream_outputs = {
+ f"{upstream_source}::output_main": upstream_output,
+ upstream_source: upstream_output,
+ }
+
+ with _patched_resolve_webhook_response() as resolve:
+ await harness.execute(
+ "webhookResponse",
+ {"statusCode": 200, "responseBody": "", "contentType": "application/json"},
+ node_id="resp-node",
+ nodes=nodes,
+ edges=edges,
+ upstream_outputs=upstream_outputs,
+ )
+ body = resolve.call_args.args[1]["body"]
+ # JSON-serialised first output.
+ assert '"hello"' in body and '"world"' in body
+
+ async def test_non_numeric_status_code_returns_error_envelope(self, harness):
+ with _patched_resolve_webhook_response():
+ result = await harness.execute(
+ "webhookResponse",
+ {"statusCode": "abc", "responseBody": "x"},
+ )
+ harness.assert_envelope(result, success=False)