Skip to content

Self-improving AI Employees for everyone

feat: harden managed processes and triggered agent tools

trohitg3fb28eb2d05f
diff --git a/CLAUDE.md b/CLAUDE.md
index f00765cf..98406476 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2749,6 +2749,7 @@ This function:
- **`get_node_output` race**: in-memory `_outputs` cache re-population after a DB-fallback `await` previously overwrote a fresh in-memory write with a stale DB value. Fix uses nested `dict.setdefault` (atomic at the CPython GIL level -- no lock needed). `store_node_output` and `clear_all_outputs` had no real race because asyncio coroutines do not preempt at synchronous statements. Reference for the Python concurrency model: https://docs.python.org/3/library/asyncio-task.html#asyncio-await
- **`NodeUserError` (services.plugin)**: typed exception for user/LLM-correctable failures (string not found, command not found, bad cwd, missing required field, operator-only Twitter query, Python sandbox `import`, Node.js sidecar down). `BaseNode.execute()` catches it specifically: single WARN line in the operator log (no traceback) + structured `{success: False, error_type: "NodeUserError", error: ...}` envelope. Genuine bugs still flow through the generic `except Exception` branch and keep their full stacktrace via `logger.exception`. Adopted across `fileRead` / `fileModify` / `fsSearch` / `process_manager` / `pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`. Reach for it whenever the LLM (or user) can fix the input and retry — never for actual server bugs.
- **Process manager Windows shim resolution**: `process_service.start()` resolves `argv[0]` via `shutil.which()` before `asyncio.create_subprocess_exec`. On Windows, `shutil.which` honours `PATHEXT` and returns the absolute `.cmd` path (e.g. `C:\...\npm.cmd`); `CreateProcessW` then launches it directly. No `cmd /c` wrap — same canonical idiom used by `browser_service`, `claude_code_service`, `claude_oauth`, `himalaya_service`. Without this, bare `argv[0]="npm"` raises `WinError 2` because `CreateProcessW` does NOT apply `PATHEXT` to bare names. Missing binary → early `Command not found: '<bin>'. Check spelling or ensure the binary is on PATH.` envelope (no traceback).
+- **Process manager port admission + middle panel**: server commands declare listener `ports` (with compatibility inference for `--port`, `-p`, `PORT`, and `*_PORT`). `ProcessService.start()` serializes admission, checks managed reservations plus OS TCP listeners, and returns structured `PORT_IN_USE` without killing the owner or allowing framework auto-port fallback. Explicit ports/environment survive restart. The `isProcessManagerPanel` UI hint gives only `processManager` a full-height workflow-scoped process table with PID/ports/timestamps/elapsed/output and stop/restart controls. See [docs-internal/process_manager.md](./docs-internal/process_manager.md).
- **Telegram message auto-split**: Telegram Bot API caps `sendMessage.text` at 4096 chars (per https://core.telegram.org/bots/api). `TelegramService.send_message` splits longer text at paragraph → line → sentence → space → hard-cut boundaries via `_split_text` helper, sends each chunk threaded under the previous (`reply_to_message_id` cascade), returns first message's metadata + `parts` + `message_ids[]`. Captions on `send_photo` / `send_document` still take the legacy path and will fail on >1024 chars — separate fix once needed (constants `_TG_TEXT_LIMIT=3500`, `_TG_CAPTION_LIMIT=900` in `_service.py` already account for ~20% HTML expansion from markdown→HTML conversion in `_resolve_body`).
- **Google OAuth scope expansion**: Google's authorisation server legitimately returns a wider scope set than requested when the OAuth Client's "Data Access" page lists extra scopes (commonly `cloud-platform`) or when `include_granted_scopes` replays a previously-granted scope. `oauthlib` does strict set-equality and aborts with `Warning: Scope has changed`. As of 2026 (`google-auth-oauthlib` 1.2.4, `oauthlib` upstream issue #562 still open), no constructor flag, context manager, or `expected_scopes` argument exists — the documented relief is the env var. `services/google_oauth.py` sets `OAUTHLIB_RELAX_TOKEN_SCOPE=1` via `os.environ.setdefault` BEFORE the `google_auth_oauthlib.flow` import (oauthlib reads it once at parameters-module import; request-time setting races under uvicorn workers), paired with `warnings.filterwarnings(message=r"Scope has changed.*")` to keep the operator log clean. Long-term root cause: audit the Cloud Console Data Access page and remove `cloud-platform` if no handler uses it.
- **Code-executor error mapping** (`pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`): wrap user-code execution and sidecar calls in `try/except`. Python: detect `ImportError("__import__ not found")` (the LLM tried `import X` against the sandboxed builtins) and surface the pre-injected names list (`math, json, datetime, timedelta, re, random, Counter, defaultdict`) plus the suggestion to use `process_manager` for unsupported modules; other exceptions get formatted as `<ErrorName> at line N: <message>` (line N walked from `<string>` frame in the traceback) plus any captured stdout. JS/TS: detect `aiohttp.ClientConnectorError` and surface "JavaScript executor not running on localhost:3020. Start the dev runner or fall back to python_executor." All raise `NodeUserError` so the framework logs one WARN line — no aiohttp/CreateProcessW noise in the operator log.
diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsx
index 1520322a..fad3eb3b 100644
--- a/client/src/components/parameterPanel/MiddleSection.tsx
+++ b/client/src/components/parameterPanel/MiddleSection.tsx
@@ -31,6 +31,7 @@ import MasterSkillEditor from './MasterSkillEditor';
import TodoEditor from './TodoEditor';
import TaskManagerPanel from './TaskManagerPanel';
import TeamMonitorPanel from './TeamMonitorPanel';
+import ProcessManagerPanel from './ProcessManagerPanel';
import { useAppStore } from '../../store/useAppStore';
import { useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';
import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';
@@ -187,6 +188,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const isTodoEditorNode = hints.isTodoEditor === true;
const isTaskManagerNode = hints.isTaskManagerPanel === true;
const isMonitorNode = hints.isMonitorPanel === true;
+ const isProcessManagerNode = hints.isProcessManagerPanel === true;
const isAgentWithSkills = hints.hasSkills === true;
const { data: userSettings } = useUserSettingsQuery();
@@ -522,7 +524,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
<div className="relative flex h-full flex-1 flex-col overflow-hidden">
{/* Description - hide for code editor nodes (Python, Skill), masterSkill,
and the todo editor (each renders its own full-panel header). */}
- {!needsCodeEditorLayout && !isMasterSkillNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && (
+ {!needsCodeEditorLayout && !isMasterSkillNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && !isProcessManagerNode && (
<div className="shrink-0 border-b border-border-default bg-bg-panel px-6 pt-4 pb-2">
<p className="m-0 text-base leading-[1.5] text-fg-muted">
{nodeDefinition.description}
@@ -559,6 +561,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
nodes={currentWorkflow?.nodes || []}
edges={currentWorkflow?.edges || []}
/>
+ ) : isProcessManagerNode ? (
+ <ProcessManagerPanel workflowId={currentWorkflow?.id} />
) : (
<>
{/* Parameters */}
diff --git a/client/src/components/parameterPanel/ProcessManagerPanel.tsx b/client/src/components/parameterPanel/ProcessManagerPanel.tsx
new file mode 100644
index 00000000..191e97e3
--- /dev/null
+++ b/client/src/components/parameterPanel/ProcessManagerPanel.tsx
@@ -0,0 +1,139 @@
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { Eye, RefreshCw, RotateCw, Search, Square } from 'lucide-react';
+import { toast } from 'sonner';
+
+import { useWebSocket } from '@/contexts/WebSocketContext';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+
+interface Props { workflowId?: string }
+
+interface ManagedProcess {
+ name: string;
+ command: string;
+ pid: number;
+ status: 'running' | 'stopped' | 'error' | string;
+ started_at?: string;
+ stopped_at?: string;
+ exit_code?: number | null;
+ working_directory?: string;
+ stdout_lines?: number;
+ stderr_lines?: number;
+ ports?: number[];
+}
+
+const duration = (startedAt?: string, end = Date.now()) => {
+ if (!startedAt) return '—';
+ const ms = Math.max(0, end - new Date(startedAt).getTime());
+ if (!Number.isFinite(ms)) return '—';
+ const seconds = Math.floor(ms / 1000);
+ const hours = Math.floor(seconds / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ return hours ? `${hours}h ${minutes}m` : minutes ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
+};
+
+const timestamp = (value?: string) => value
+ ? new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'medium' }).format(new Date(value))
+ : '—';
+
+const ProcessManagerPanel: React.FC<Props> = ({ workflowId }) => {
+ const { sendRequest } = useWebSocket();
+ const [processes, setProcesses] = useState<ManagedProcess[]>([]);
+ const [maxProcesses, setMaxProcesses] = useState(10);
+ const [loading, setLoading] = useState(false);
+ const [search, setSearch] = useState('');
+ const [selected, setSelected] = useState<ManagedProcess | null>(null);
+ const [output, setOutput] = useState('');
+ const [busy, setBusy] = useState<string | null>(null);
+ const [now, setNow] = useState(Date.now());
+
+ const refresh = useCallback(async (quiet = false) => {
+ if (!workflowId) return;
+ if (!quiet) setLoading(true);
+ try {
+ const response = await sendRequest<{ success: boolean; processes?: ManagedProcess[]; max_processes?: number }>(
+ 'process_list', { workflow_id: workflowId },
+ );
+ setProcesses(response.processes ?? []);
+ setMaxProcesses(response.max_processes ?? 10);
+ setSelected((current) => current
+ ? (response.processes ?? []).find((process) => process.name === current.name) ?? current
+ : null);
+ } catch (error) {
+ if (!quiet) toast.error(error instanceof Error ? error.message : 'Unable to load managed processes');
+ } finally {
+ if (!quiet) setLoading(false);
+ }
+ }, [sendRequest, workflowId]);
+
+ const loadOutput = useCallback(async (process: ManagedProcess) => {
+ if (!workflowId) return;
+ setSelected(process);
+ const response = await sendRequest<{ lines?: string[] }>('process_get_output', {
+ workflow_id: workflowId, name: process.name, stream: 'stdout', tail: 300,
+ });
+ setOutput((response.lines ?? []).join('\n'));
+ }, [sendRequest, workflowId]);
+
+ const mutate = useCallback(async (operation: 'process_stop' | 'process_restart', process: ManagedProcess) => {
+ if (!workflowId) return;
+ setBusy(process.name);
+ try {
+ const response = await sendRequest<{ success: boolean; error?: string }>(operation, {
+ workflow_id: workflowId, name: process.name,
+ });
+ if (!response.success) throw new Error(response.error || 'Process operation failed');
+ toast.success(operation === 'process_stop' ? `Stopped ${process.name}` : `Restarted ${process.name}`);
+ await refresh(true);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : 'Process operation failed');
+ } finally {
+ setBusy(null);
+ }
+ }, [refresh, sendRequest, workflowId]);
+
+ useEffect(() => { void refresh(); }, [refresh]);
+ useEffect(() => {
+ const poll = window.setInterval(() => void refresh(true), 2500);
+ const clock = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => { window.clearInterval(poll); window.clearInterval(clock); };
+ }, [refresh]);
+
+ const visible = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ return term ? processes.filter((process) =>
+ [process.name, process.command, process.working_directory, ...(process.ports ?? []).map(String)]
+ .some((value) => value?.toLowerCase().includes(term)),
+ ) : processes;
+ }, [processes, search]);
+ const running = processes.filter((process) => process.status === 'running').length;
+ const failed = processes.filter((process) => process.status === 'error').length;
+
+ return <div className="flex min-h-0 flex-1 flex-col overflow-hidden p-4">
+ <header className="mb-4 flex shrink-0 items-start justify-between gap-3">
+ <div><h2 className="text-lg font-semibold text-fg-default">Managed Processes</h2><p className="text-sm text-fg-muted">Live workflow processes, listener ports, output, and lifecycle controls.</p></div>
+ <Button variant="outline" size="sm" disabled={loading} onClick={() => void refresh()}><RefreshCw className={loading ? 'h-4 w-4 animate-spin' : 'h-4 w-4'} /> Refresh</Button>
+ </header>
+ <section className="mb-4 grid shrink-0 grid-cols-3 gap-3">
+ <div className="rounded border border-border-default bg-bg-elevated p-3"><div className="text-xs text-fg-muted">Running</div><div className="text-xl font-semibold text-success">{running} / {maxProcesses}</div></div>
+ <div className="rounded border border-border-default bg-bg-elevated p-3"><div className="text-xs text-fg-muted">Stopped</div><div className="text-xl font-semibold">{processes.length - running - failed}</div></div>
+ <div className="rounded border border-border-default bg-bg-elevated p-3"><div className="text-xs text-fg-muted">Errors</div><div className="text-xl font-semibold text-destructive">{failed}</div></div>
+ </section>
+ <div className="relative mb-3 shrink-0"><Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-fg-muted" /><Input className="pl-9" value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Search name, command, directory, or port" /></div>
+ <div className="min-h-0 flex-1 overflow-auto rounded border border-border-default bg-bg-elevated">
+ <table className="w-full min-w-[1000px] border-collapse text-sm"><thead className="sticky top-0 z-10 bg-bg-panel text-left text-xs text-fg-muted"><tr>{['Name','Status','PID','Ports','Started','Elapsed','Output','Command',''].map((label) => <th key={label} className="border-b border-border-default px-3 py-2 font-medium">{label}</th>)}</tr></thead>
+ <tbody>{visible.map((process) => <tr key={process.name} className="border-b border-border-default/70 hover:bg-bg-panel">
+ <td className="px-3 py-3 font-medium">{process.name}</td><td className="px-3 py-3"><Badge variant="outline" className={process.status === 'running' ? 'text-success' : process.status === 'error' ? 'text-destructive' : 'text-fg-muted'}>{process.status}</Badge></td>
+ <td className="px-3 py-3 tabular-nums">{process.pid}</td><td className="px-3 py-3 tabular-nums">{process.ports?.join(', ') || '—'}</td><td className="whitespace-nowrap px-3 py-3 text-xs">{timestamp(process.started_at)}</td><td className="px-3 py-3 tabular-nums">{duration(process.started_at, process.status === 'running' ? now : process.stopped_at ? new Date(process.stopped_at).getTime() : now)}</td>
+ <td className="px-3 py-3 text-xs tabular-nums">{process.stdout_lines ?? 0} out · {process.stderr_lines ?? 0} err</td><td className="max-w-[320px] truncate px-3 py-3 font-mono text-xs" title={process.command}>{process.command}</td>
+ <td className="whitespace-nowrap px-3 py-3"><Button variant="ghost" size="sm" aria-label={`Inspect ${process.name}`} onClick={() => void loadOutput(process)}><Eye className="h-4 w-4" /></Button>{process.status === 'running' && <Button variant="ghost" size="sm" disabled={busy === process.name} aria-label={`Stop ${process.name}`} onClick={() => void mutate('process_stop', process)}><Square className="h-4 w-4" /></Button>}<Button variant="ghost" size="sm" disabled={busy === process.name} aria-label={`Restart ${process.name}`} onClick={() => void mutate('process_restart', process)}><RotateCw className="h-4 w-4" /></Button></td>
+ </tr>)}{!loading && visible.length === 0 && <tr><td colSpan={9} className="p-12 text-center text-fg-muted">No managed processes in this workflow.</td></tr>}</tbody>
+ </table>
+ </div>
+ <Dialog open={!!selected} onOpenChange={(open) => { if (!open) setSelected(null); }}><DialogContent className="max-w-4xl"><DialogHeader><DialogTitle>{selected?.name}</DialogTitle></DialogHeader>{selected && <div className="space-y-3 text-sm"><div className="grid gap-2 sm:grid-cols-3"><span>PID<br/><strong>{selected.pid}</strong></span><span>Ports<br/><strong>{selected.ports?.join(', ') || '—'}</strong></span><span>Started<br/><strong>{timestamp(selected.started_at)}</strong></span></div><div><div className="mb-1 text-xs text-fg-muted">Command</div><code className="block rounded bg-bg-panel p-2 text-xs">{selected.command}</code></div><div><div className="mb-1 text-xs text-fg-muted">Recent stdout</div><pre className="max-h-[45vh] overflow-auto whitespace-pre-wrap rounded bg-bg-panel p-3 text-xs">{output || 'No stdout captured.'}</pre></div></div>}</DialogContent></Dialog>
+ </div>;
+};
+
+export default ProcessManagerPanel;
diff --git a/client/src/components/parameterPanel/TaskManagerPanel.tsx b/client/src/components/parameterPanel/TaskManagerPanel.tsx
index fa098877..2a4aaae8 100644
--- a/client/src/components/parameterPanel/TaskManagerPanel.tsx
+++ b/client/src/components/parameterPanel/TaskManagerPanel.tsx
@@ -288,9 +288,9 @@ const TaskManagerPanel: React.FC<Props> = ({ nodeId, workflowId, nodes, edges })
<div className="flex min-h-0 flex-1 flex-col p-4">
<div className="mb-3 flex gap-2"><div className="relative flex-1"><Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-fg-muted" /><Input className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search tasks, missions, or assignees" /></div><Select value={filter} onValueChange={setFilter}><SelectTrigger className="w-40"><Filter className="h-4 w-4" /><SelectValue /></SelectTrigger><SelectContent><SelectItem value="all">All statuses</SelectItem>{STATUSES.map((name) => <SelectItem key={name} value={name} className="capitalize">{name}</SelectItem>)}</SelectContent></Select></div>
<div className="min-h-0 flex-1 overflow-auto rounded-md border border-border-default bg-bg-elevated">
- <table className="w-full min-w-[1200px] border-collapse text-sm"><thead className="sticky top-0 z-10 bg-bg-panel text-left text-xs text-fg-muted"><tr>{['Task','Assignee','Status','Created','Started','Completed','Elapsed','Attempt','Tokens',''].map((h) => <th key={h} className="border-b border-border-default px-3 py-2 font-medium">{h}</th>)}</tr></thead><tbody>
- {visible.map((task) => { const usage = taskUsage(task); return <tr key={task.id} className="border-b border-border-default/70 hover:bg-bg-panel"><td className="max-w-[320px] px-3 py-3"><button className="block w-full text-left" onClick={() => setSelected(task)}><span className="block truncate font-medium text-fg-default">{task.title}</span><span className="block truncate text-xs text-fg-muted">{task.mission || task.description || 'No mission provided'}</span></button></td><td className="px-3 py-3"><span className="block">{task.assignee_label || task.assigned_to || 'Unassigned'}</span><span className="text-xs text-fg-muted">{task.assignee_type || ''}</span></td><td className="px-3 py-3"><Badge variant="outline" className={cn('capitalize', STATUS_STYLES[task.status])}>{task.status}</Badge></td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.created_at)}</td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.started_at)}</td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.completed_at)}</td><td className="px-3 py-3 tabular-nums">{elapsed(task, nowMs)}</td><td className="px-3 py-3 tabular-nums">{task.current_attempt ?? 0}{task.retry_count ? ` (+${task.retry_count})` : ''}</td><td className="px-3 py-3 tabular-nums"><span className="block font-medium">{usage.total.toLocaleString()}</span><span className="whitespace-nowrap text-[11px] text-fg-muted">{usage.input.toLocaleString()} in · {usage.output.toLocaleString()} out</span></td><td className="px-3 py-3"><Button variant="ghost" size="sm" onClick={() => setSelected(task)} aria-label={`Inspect ${task.title}`}><Eye className="h-4 w-4" /></Button></td></tr>; })}
- {!loading && visible.length === 0 && <tr><td colSpan={10} className="p-12 text-center text-fg-muted">No tasks match this view.</td></tr>}
+ <table className="w-full min-w-[1100px] border-collapse text-sm"><thead className="sticky top-0 z-10 bg-bg-panel text-left text-xs text-fg-muted"><tr>{['Task','Assignee','Status','Started','Completed','Elapsed','Attempt','Tokens',''].map((h) => <th key={h} className="border-b border-border-default px-3 py-2 font-medium">{h}</th>)}</tr></thead><tbody>
+ {visible.map((task) => { const usage = taskUsage(task); return <tr key={task.id} className="border-b border-border-default/70 hover:bg-bg-panel"><td className="max-w-[320px] px-3 py-3"><button className="block w-full text-left" onClick={() => setSelected(task)}><span className="block truncate font-medium text-fg-default">{task.title}</span><span className="block truncate text-xs text-fg-muted">{task.mission || task.description || 'No mission provided'}</span></button></td><td className="px-3 py-3"><span className="block">{task.assignee_label || task.assigned_to || 'Unassigned'}</span><span className="text-xs text-fg-muted">{task.assignee_type || ''}</span></td><td className="px-3 py-3"><Badge variant="outline" className={cn('capitalize', STATUS_STYLES[task.status])}>{task.status}</Badge></td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.started_at)}</td><td className="whitespace-nowrap px-3 py-3 text-xs">{formatTimestamp(task.completed_at)}</td><td className="px-3 py-3 tabular-nums">{elapsed(task, nowMs)}</td><td className="px-3 py-3 tabular-nums">{task.current_attempt ?? 0}{task.retry_count ? ` (+${task.retry_count})` : ''}</td><td className="px-3 py-3 tabular-nums"><span className="block font-medium">{usage.total.toLocaleString()}</span><span className="whitespace-nowrap text-[11px] text-fg-muted">{usage.input.toLocaleString()} in · {usage.output.toLocaleString()} out</span></td><td className="px-3 py-3"><Button variant="ghost" size="sm" onClick={() => setSelected(task)} aria-label={`Inspect ${task.title}`}><Eye className="h-4 w-4" /></Button></td></tr>; })}
+ {!loading && visible.length === 0 && <tr><td colSpan={9} className="p-12 text-center text-fg-muted">No tasks match this view.</td></tr>}
</tbody></table>
</div>
{pages > 1 && <div className="mt-3 flex items-center justify-end gap-2 text-sm text-fg-muted"><Button variant="outline" size="sm" disabled={page === 0} onClick={() => setPage(page - 1)}>Previous</Button><span>{page + 1} / {pages}</span><Button variant="outline" size="sm" disabled={page + 1 >= pages} onClick={() => setPage(page + 1)}>Next</Button></div>}
diff --git a/client/src/components/parameterPanel/__tests__/ProcessManagerPanel.test.tsx b/client/src/components/parameterPanel/__tests__/ProcessManagerPanel.test.tsx
new file mode 100644
index 00000000..a1e49247
--- /dev/null
+++ b/client/src/components/parameterPanel/__tests__/ProcessManagerPanel.test.tsx
@@ -0,0 +1,47 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders as render } from '../../../test/providers';
+
+const { wsMock } = vi.hoisted(() => ({ wsMock: { sendRequest: vi.fn() } }));
+vi.mock('../../../contexts/WebSocketContext', () => ({ useWebSocket: () => wsMock }));
+
+import ProcessManagerPanel from '../ProcessManagerPanel';
+
+const process = {
+ name: 'frontend', command: 'npm run dev -- --port 5173', pid: 4321,
+ status: 'running', ports: [5173], started_at: new Date(Date.now() - 65_000).toISOString(),
+ stdout_lines: 8, stderr_lines: 1, working_directory: 'D:/workspace',
+};
+
+describe('ProcessManagerPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ wsMock.sendRequest.mockImplementation((type: string) => {
+ if (type === 'process_list') return Promise.resolve({ success: true, processes: [process], max_processes: 10 });
+ if (type === 'process_get_output') return Promise.resolve({ success: true, lines: ['ready on 5173'] });
+ return Promise.resolve({ success: true });
+ });
+ });
+
+ it('renders live process identity, port, timing, and output details', async () => {
+ render(<ProcessManagerPanel workflowId="workflow-1" />);
+ expect(await screen.findByText('frontend')).toBeInTheDocument();
+ expect(screen.getAllByText('5173').length).toBeGreaterThan(0);
+ expect(screen.getByText(/1m [5-9]s/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Inspect frontend' }));
+ expect(await screen.findByText('ready on 5173')).toBeInTheDocument();
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('process_get_output', {
+ workflow_id: 'workflow-1', name: 'frontend', stream: 'stdout', tail: 300,
+ });
+ });
+
+ it('scopes lifecycle controls to the current workflow', async () => {
+ render(<ProcessManagerPanel workflowId="workflow-1" />);
+ await screen.findByText('frontend');
+ fireEvent.click(screen.getByRole('button', { name: 'Stop frontend' }));
+ await waitFor(() => expect(wsMock.sendRequest).toHaveBeenCalledWith('process_stop', {
+ workflow_id: 'workflow-1', name: 'frontend',
+ }));
+ });
+});
diff --git a/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx b/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx
index 44cb59a9..0d132af9 100644
--- a/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx
+++ b/client/src/components/parameterPanel/__tests__/TaskManagerPanel.test.tsx
@@ -50,7 +50,6 @@ describe('TaskManagerPanel', () => {
expect(await screen.findByText('Implement feature')).toBeInTheDocument();
expect(screen.getByText('2 / 3')).toBeInTheDocument();
expect(screen.getByText('Coder')).toBeInTheDocument();
- expect(screen.getByText('Created')).toBeInTheDocument();
expect(screen.getByText('Started')).toBeInTheDocument();
expect(screen.getByText('Completed')).toBeInTheDocument();
expect(screen.getByText('1m 5s')).toBeInTheDocument();
diff --git a/client/src/types/INodeProperties.ts b/client/src/types/INodeProperties.ts
index 8a40d83c..568deb63 100644
--- a/client/src/types/INodeProperties.ts
+++ b/client/src/types/INodeProperties.ts
@@ -206,6 +206,8 @@ export interface INodeUIHints {
isMonitorPanel?: boolean;
/** MiddleSection: render the execution-scoped team task control panel. */
isTaskManagerPanel?: boolean;
+ /** MiddleSection: render live managed-process inspection and controls. */
+ isProcessManagerPanel?: boolean;
/** Special-case panel for gmaps_create with map preview. */
showLocationPanel?: boolean;
/** ConsolePanel: this node is a chat-message target. */
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index c1802a10..2248d099 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -403,6 +403,8 @@ AgentWorkflow.run(context):
Each LLM step is one activity and each ordinary tool call is one per-type activity. Team-lead Task Manager assignments are different: persistence happens first, then the lead starts a deterministic detached `DelegatedTaskWorkflow` with `ParentClosePolicy.ABANDON` and receives `queued` immediately. The runner owns the root-wide permit, claim, child `AgentWorkflow`, terminal result/usage persistence, `taskTrigger`, and permit release, so the assigning lead can return without polling. Direct non-team delegation retains the child-workflow path. Non-agent tools and excluded types (`rlm_agent`, `claude_code_agent`) still go through `execute_activity`. Failures surface as durable task failures and trigger review rather than being lost when the lead invocation closes.
+Durable event listeners retain their deployment graph as a fallback, but each firing resolves the latest persisted workflow graph through `load_persisted_workflow_graph_activity` before filtering downstream nodes. This makes tools added after deployment available to `taskTrigger` and other triggered agent runs. Edge traversal accepts both canonical `targetHandle` and legacy `target_handle`; tool choice remains entirely with the agent and no trigger-specific tool-use prompt is injected.
+
**Delegation input contract (input-vs-config separation).** The LLM's `{task, context}` args are per-invocation *input*, not node configuration, and travel as the child workflow input's `invocation` field. `prepare_agent_payload` applies it AFTER its config resolution (`{**node_data, **db_params}` — DB wins for config liveness): `task` → system_message, `context`-or-`task` → prompt — the same semantics as the legacy `handlers.tools._execute_delegated_agent`. Stored node parameters (including the empty default `prompt` the frontend persists on drop) therefore never override the delegated task. A call with both fields empty is rejected at the parent's call boundary (tool-error message to the LLM, no child spawn). Bypass agents dispatched as plain activities (`rlm_agent` / `claude_code_agent`) instead receive the remap directly in `node_data` — their per-type activity consumes `node_data` verbatim with no DB re-merge.
**Canvas-aware tools** opt into receiving the parent workflow's `nodes`/`edges` by declaring `needs_canvas: ClassVar[bool] = True` on their `BaseNode` subclass. The F4.B tool dispatch reads this via `services.node_registry.get_node_class(node_type).needs_canvas` and forwards `context.get("nodes")` / `context.get("edges")` into `tool_payload`; default plugins keep the empty-canvas optimisation. Today only `agentBuilder` opts in (it walks edges to resolve its calling agent and mutates the canvas). Operations inside agentBuilder reload via `database.get_workflow(workflow_id)` so in-run duplicate detection sees mutations from earlier calls in the same workflow run — see [agent_builder section in CLAUDE.md](../CLAUDE.md).
diff --git a/docs-internal/process_manager.md b/docs-internal/process_manager.md
new file mode 100644
index 00000000..d1ec2953
--- /dev/null
+++ b/docs-internal/process_manager.md
@@ -0,0 +1,33 @@
+# Process Manager
+
+`processManager` owns long-running workflow subprocesses such as development
+servers and watchers. Processes are isolated by workflow ID and name and are
+visible in the node's dedicated full-height middle panel.
+
+## Port-safe startup
+
+Server processes should declare every listener in the `ports` parameter. The
+service also recognizes `--port N`, `--port=N`, `-p N`, `PORT`, and `*_PORT`
+for compatibility. Positional numbers are deliberately not guessed.
+
+Startup is serialized through one admission lock. Before spawning, the service
+checks both ports reserved by managed processes and operating-system TCP
+listeners. A collision returns `PORT_IN_USE` with the occupied ports and known
+owner PIDs. It never kills an unrelated listener or silently changes the port.
+Explicit ports and environment settings survive restart.
+
+The unavoidable boundary is a process that neither declares a port nor uses a
+recognized command/environment form. Connectors and agents should always fill
+`ports` for server commands.
+
+## Middle panel
+
+The panel is scoped to the current workflow and polls the in-memory process
+registry for live state. It shows running capacity, status, PID, declared
+ports, start time, elapsed time, output counts, command, and recent stdout.
+Operators can stop or restart a process. Stopped elapsed time freezes at
+`stopped_at`; running elapsed time updates once per second.
+
+Process output is stored under `<workspace>/.processes/<name>/` while the
+process remains inspectable. Completed entries and logs retain the existing
+60-second cleanup policy.
diff --git a/server/nodes/utility/process_manager/__init__.py b/server/nodes/utility/process_manager/__init__.py
index d2659e0c..55749334 100644
--- a/server/nodes/utility/process_manager/__init__.py
+++ b/server/nodes/utility/process_manager/__init__.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any, Dict, Literal, Optional
+from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
@@ -20,6 +20,10 @@ class ProcessManagerParams(BaseModel):
command: str = Field(default="", json_schema_extra=_START)
cwd: str = Field(default="", json_schema_extra=_START)
env: Dict[str, str] = Field(default_factory=dict, json_schema_extra=_START)
+ ports: List[int] = Field(
+ default_factory=list,
+ json_schema_extra={**_START, "description": "Listener ports to reserve before spawning"},
+ )
input_text: str = Field(default="", json_schema_extra=_SEND_INPUT)
stream: Literal["stdout", "stderr"] = Field(default="stdout", json_schema_extra=_GET_OUTPUT)
tail: int = Field(default=100, ge=1, le=10000, json_schema_extra=_GET_OUTPUT)
@@ -45,7 +49,7 @@ class ProcessManagerNode(ActionNode):
description = "Start, stop, restart, and manage long-running processes"
component_kind = "square"
tool_name = "process_manager"
- tool_description = "Start, stop, and manage long-running processes (dev servers, watchers, build tools). Operations: start (spawn a process), stop (kill process tree), restart, list (show all running), send_input (write to stdin), get_output (read recent output lines). Output streams to Terminal tab. Use get_output to check what a process printed."
+ tool_description = "Start, stop, and manage long-running processes (dev servers, watchers, build tools). For servers, always declare listener ports in ports; startup fails safely with PORT_IN_USE instead of launching on an occupied port. Operations: start, stop, restart, list, send_input, get_output. Output streams to Terminal tab."
handles = (
{"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
{"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
@@ -53,6 +57,11 @@ class ProcessManagerNode(ActionNode):
annotations = {"destructive": True, "readonly": False, "open_world": True}
task_queue = TaskQueue.DEFAULT
usable_as_tool = True
+ ui_hints = {
+ "isProcessManagerPanel": True,
+ "hideInputSection": True,
+ "hideOutputSection": True,
+ }
Params = ProcessManagerParams
Output = ProcessManagerOutput
@@ -93,6 +102,8 @@ class ProcessManagerNode(ActionNode):
command=_clean(params.command),
workflow_id=workflow_id,
working_directory=_clean(params.cwd) or agent_dir,
+ ports=params.ports,
+ extra_env=params.env,
)
)
if op == "stop":
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 7255dfbc..467c7083 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1235,6 +1235,22 @@ async def handle_process_send_input(data: Dict[str, Any], websocket: WebSocket)
return await get_process_service().send_input(name, workflow_id, text)
+@ws_handler("name")
+async def handle_process_stop(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Stop one workflow-scoped managed process."""
+ from services.process_service import get_process_service
+
+ return await get_process_service().stop(data["name"], data.get("workflow_id", "default"))
+
+
+@ws_handler("name")
+async def handle_process_restart(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Restart one workflow-scoped managed process after port preflight."""
+ from services.process_service import get_process_service
+
+ return await get_process_service().restart(data["name"], data.get("workflow_id", "default"))
+
+
# ============================================================================
# User Skills Handlers — extracted to services/skills/handlers.py (Wave 13.1)
# ============================================================================
@@ -1436,6 +1452,8 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"process_list": handle_process_list,
"process_get_output": handle_process_get_output,
"process_send_input": handle_process_send_input,
+ "process_stop": handle_process_stop,
+ "process_restart": handle_process_restart,
# User Skills + Built-in Skill Content + Memory/Reset — extracted to
# services/skills/handlers.py (Wave 13.1); register via the shared
# ws_handler_registry on package import. No entries below.
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 3b872507..8b4065ff 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -1111,7 +1111,7 @@ class DeploymentManager:
for edge in edges:
target = edge.get("target")
source = edge.get("source")
- handle = edge.get("targetHandle", "")
+ handle = edge.get("targetHandle") or edge.get("target_handle") or ""
is_config = handle and handle.startswith("input-") and handle != "input-main"
if is_config and target in downstream_ids and source not in downstream_ids:
@@ -1145,7 +1145,7 @@ class DeploymentManager:
for edge in edges:
target = edge.get("target")
source = edge.get("source")
- target_handle = edge.get("targetHandle", "")
+ target_handle = edge.get("targetHandle") or edge.get("target_handle") or ""
# Include tool nodes connected to agent's input-tools handle
if target in agent_node_ids and target_handle == "input-tools" and source not in downstream_ids:
downstream_ids.add(source)
diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.py
index 529e1d09..0eb444fc 100644
--- a/server/services/plugin/edge_walker.py
+++ b/server/services/plugin/edge_walker.py
@@ -183,14 +183,14 @@ async def collect_agent_connections(
for e in incoming_edges:
logger.debug(f"{log_prefix} Edge: source={e.get('source')}, " f"targetHandle={e.get('targetHandle')}")
- tool_incoming = [e for e in incoming_edges if e.get("targetHandle") == "input-tools"]
+ tool_incoming = [e for e in incoming_edges if edge_target_handle(e) == "input-tools"]
logger.info(f"{log_prefix} Tool edges (input-tools handle): {len(tool_incoming)}")
for edge in edges:
if edge.get("target") != node_id:
continue
- target_handle = edge.get("targetHandle")
+ target_handle = edge_target_handle(edge)
source_node_id = edge.get("source")
source_node = next((n for n in nodes if n.get("id") == source_node_id), None)
if not source_node:
@@ -384,7 +384,7 @@ async def _append_tool_entry(
if tool_type in AI_AGENT_TYPES:
child_tools: List[Dict[str, Any]] = []
child_incoming_edges = [e for e in edges if e.get("target") == source_node_id]
- child_tool_edges = [e for e in child_incoming_edges if e.get("targetHandle") == "input-tools"]
+ child_tool_edges = [e for e in child_incoming_edges if edge_target_handle(e) == "input-tools"]
logger.debug(
f"{log_prefix} Child agent {source_node_id}: "
f"{len(child_incoming_edges)} incoming edges, "
@@ -396,7 +396,7 @@ async def _append_tool_entry(
for child_edge in edges:
if child_edge.get("target") != source_node_id:
continue
- if child_edge.get("targetHandle") != "input-tools":
+ if edge_target_handle(child_edge) != "input-tools":
continue
child_tool_id = child_edge.get("source")
child_tool_node = next((n for n in nodes if n.get("id") == child_tool_id), None)
diff --git a/server/services/process_service.py b/server/services/process_service.py
index 4fa0021b..eb6a9d86 100644
--- a/server/services/process_service.py
+++ b/server/services/process_service.py
@@ -13,6 +13,7 @@ import asyncio
import os
import shlex
import shutil
+import socket
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
@@ -48,6 +49,9 @@ class ManagedProcess:
exit_code: Optional[int] = None
stdout_lines: int = 0
stderr_lines: int = 0
+ ports: tuple[int, ...] = ()
+ extra_env: Optional[Dict[str, str]] = None
+ stopped_at: Optional[str] = None
# Optional per-line callback: framework-level subscribers (e.g. the
# generalised event source `DaemonEventSource`) install this to ingest
# the daemon's stdout/stderr without re-tailing the log files we already
@@ -68,6 +72,9 @@ class ProcessService:
self._processes: Dict[tuple, ManagedProcess] = {}
self._broadcaster = None
self.max_processes: int = MAX_PROCESSES
+ # Port preflight and subprocess creation must be one critical section.
+ # Without this, two concurrent tool calls can both observe a free port.
+ self._start_lock = asyncio.Lock()
def set_broadcaster(self, broadcaster) -> None:
self._broadcaster = broadcaster
@@ -83,6 +90,8 @@ class ProcessService:
working_directory: str = "",
*,
line_handler: Optional[LineHandler] = None,
+ ports: Optional[List[int]] = None,
+ extra_env: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""Start a long-running process.
@@ -121,15 +130,6 @@ class ProcessService:
name = name or f"proc_{id(command) % 100000}"
key = self._key(workflow_id, name)
- # Check process limit (exclude stopped/error -- only count running)
- running = sum(1 for m in self._processes.values() if m.status == "running")
- if key not in self._processes and running >= self.max_processes:
- return {"success": False, "error": f"Process limit reached ({self.max_processes}). Stop a process first."}
-
- # Stop existing process with same name
- if key in self._processes and self._processes[key].status == "running":
- await self.stop(name, workflow_id)
-
argv = shlex.split(command)
# Resolve argv[0] to an absolute path. Canonical idiom in this
# codebase (browser_service, claude_code_service, claude_oauth,
@@ -146,7 +146,8 @@ class ProcessService:
"error": (f"Command not found: '{argv[0] if argv else ''}'. " "Check spelling or ensure the binary is on PATH."),
}
argv[0] = resolved
- env = {**os.environ, "PYTHONUNBUFFERED": "1"}
+ env = {**os.environ, **(extra_env or {}), "PYTHONUNBUFFERED": "1"}
+ requested_ports = self._requested_ports(argv, ports or [], extra_env or {})
from core.config import Settings
from core.paths import daemons_dir
@@ -180,54 +181,141 @@ class ProcessService:
# lands at ``{daemons_dir}/.processes/{name}/``. Either way it
# holds stdout.log + stderr.log.
log_dir = Path(cwd) / ".processes" / name
- log_dir.mkdir(parents=True, exist_ok=True)
- # Clear old logs if restarting
- for f in ("stdout.log", "stderr.log"):
- (log_dir / f).write_text("")
-
- logger.info("[Process] Starting: %s (name=%s, cwd=%s, logs=%s)", command[:200], name, cwd, log_dir)
- try:
- proc = await asyncio.create_subprocess_exec(
- *argv,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- cwd=cwd,
- env=env,
+ async with self._start_lock:
+ running = sum(1 for m in self._processes.values() if m.status == "running")
+ if key not in self._processes and running >= self.max_processes:
+ return {"success": False, "error": f"Process limit reached ({self.max_processes}). Stop a process first."}
+
+ # Same-name replacement is allowed, but it must fully stop before
+ # the port preflight. Differently named/external owners are never killed.
+ if key in self._processes and self._processes[key].status == "running":
+ await self.stop(name, workflow_id)
+
+ collisions: Dict[int, List[int]] = {}
+ for managed_process in self._processes.values():
+ if managed_process.status != "running":
+ continue
+ for port in set(requested_ports).intersection(managed_process.ports):
+ collisions.setdefault(port, []).append(managed_process.pid)
+ for port, pids in self._occupied_ports(requested_ports).items():
+ collisions.setdefault(port, []).extend(pid for pid in pids if pid not in collisions.get(port, []))
+ if collisions:
+ detail = ", ".join(
+ f"{port} (PID{'s' if len(pids) != 1 else ''} {', '.join(map(str, pids)) or 'unknown'})"
+ for port, pids in collisions.items()
+ )
+ return {
+ "success": False,
+ "code": "PORT_IN_USE",
+ "error": f"Cannot start '{name}': requested port(s) already in use: {detail}.",
+ "ports": list(collisions),
+ "owners": collisions,
+ }
+
+ # Do not create or truncate logs until all admission checks pass.
+ log_dir.mkdir(parents=True, exist_ok=True)
+ for f in ("stdout.log", "stderr.log"):
+ (log_dir / f).write_text("")
+
+ logger.info("[Process] Starting: %s (name=%s, cwd=%s, ports=%s, logs=%s)", command[:200], name, cwd, requested_ports, log_dir)
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ cwd=cwd,
+ env=env,
+ )
+ except Exception as e:
+ logger.error("[Process] Failed to start: %s -> %s", command[:100], e)
+ return {"success": False, "error": str(e)}
+
+ # Publish ownership before releasing the admission lock. A second
+ # concurrent start must see this process even if it has not bound
+ # its listener socket yet.
+ managed = ManagedProcess(
+ name=name,
+ command=command,
+ argv=argv,
+ pid=proc.pid,
+ status="running",
+ started_at=datetime.now().isoformat(),
+ workflow_id=workflow_id,
+ working_directory=cwd,
+ process=proc,
+ log_dir=log_dir,
+ line_handler=line_handler,
+ ports=tuple(requested_ports),
+ extra_env=dict(extra_env or {}),
)
- except Exception as e:
- logger.error("[Process] Failed to start: %s -> %s", command[:100], e)
- return {"success": False, "error": str(e)}
-
- managed = ManagedProcess(
- name=name,
- command=command,
- argv=argv,
- pid=proc.pid,
- status="running",
- started_at=datetime.now().isoformat(),
- workflow_id=workflow_id,
- working_directory=cwd,
- process=proc,
- log_dir=log_dir,
- line_handler=line_handler,
- )
-
- managed.stdout_task = asyncio.create_task(
- self._read_stream(managed, proc.stdout, "stdout"),
- name=f"proc-stdout-{name}",
- )
- managed.stderr_task = asyncio.create_task(
- self._read_stream(managed, proc.stderr, "stderr"),
- name=f"proc-stderr-{name}",
- )
-
- self._processes[key] = managed
+ managed.stdout_task = asyncio.create_task(
+ self._read_stream(managed, proc.stdout, "stdout"), name=f"proc-stdout-{name}",
+ )
+ managed.stderr_task = asyncio.create_task(
+ self._read_stream(managed, proc.stderr, "stderr"), name=f"proc-stderr-{name}",
+ )
+ self._processes[key] = managed
logger.info("[Process] Started: %s (pid=%d)", name, proc.pid)
return {"success": True, "result": self._info(managed)}
+ @staticmethod
+ def _requested_ports(argv: List[str], declared: List[int], env: Dict[str, str]) -> List[int]:
+ """Return explicit and conventionally-declared listener ports.
+
+ Explicit ``ports`` are authoritative. Common ``--port``/``-p`` CLI
+ forms and PORT-like environment variables are included for existing
+ workflows. Positional ports remain opt-in because guessing arbitrary
+ numeric arguments would create false positives.
+ """
+ found = {int(port) for port in declared if 1 <= int(port) <= 65535}
+ for index, token in enumerate(argv):
+ value: Optional[str] = None
+ if token in {"--port", "-p"} and index + 1 < len(argv):
+ value = argv[index + 1]
+ elif token.startswith("--port="):
+ value = token.split("=", 1)[1]
+ if value and value.isdigit() and 1 <= int(value) <= 65535:
+ found.add(int(value))
+ for key, value in env.items():
+ if (key.upper() == "PORT" or key.upper().endswith("_PORT")) and str(value).isdigit():
+ port = int(value)
+ if 1 <= port <= 65535:
+ found.add(port)
+ return sorted(found)
+
+ @staticmethod
+ def _occupied_ports(ports: List[int]) -> Dict[int, List[int]]:
+ """Resolve listening owners without mutating unrelated processes."""
+ if not ports:
+ return {}
+ wanted = set(ports)
+ owners: Dict[int, set[int]] = {port: set() for port in ports}
+ try:
+ import psutil
+
+ for conn in psutil.net_connections(kind="inet"):
+ if conn.laddr and conn.laddr.port in wanted and conn.status == psutil.CONN_LISTEN:
+ if conn.pid:
+ owners[conn.laddr.port].add(conn.pid)
+ else:
+ owners[conn.laddr.port].add(0)
+ except Exception as exc:
+ # A bind probe still reliably detects occupancy when process-owner
+ # enumeration is restricted by the OS.
+ logger.debug("[Process] Port owner enumeration unavailable: %s", exc)
+ for port in ports:
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ probe.bind(("0.0.0.0", port))
+ except OSError:
+ owners[port].add(0)
+ finally:
+ probe.close()
+ return {port: sorted(pid for pid in pids if pid) for port, pids in owners.items() if pids}
+
async def stop(self, name: str, workflow_id: str = "default") -> Dict[str, Any]:
"""Stop a running process by killing its process tree."""
key = self._key(workflow_id, name)
@@ -241,6 +329,7 @@ class ProcessService:
logger.info("[Process] Stopping: %s (pid=%d)", name, managed.pid)
kill_tree(managed.pid)
managed.status = "stopped"
+ managed.stopped_at = datetime.now().isoformat()
for task in (managed.stdout_task, managed.stderr_task):
if task and not task.done():
@@ -268,8 +357,10 @@ class ProcessService:
command = managed.command
cwd = managed.working_directory
+ ports = list(managed.ports)
+ extra_env = dict(managed.extra_env or {})
await self.stop(name, workflow_id)
- return await self.start(name, command, workflow_id, cwd)
+ return await self.start(name, command, workflow_id, cwd, ports=ports, extra_env=extra_env)
async def send_input(self, name: str, workflow_id: str, text: str) -> Dict[str, Any]:
"""Write text to a process's stdin."""
@@ -455,6 +546,7 @@ class ProcessService:
except (asyncio.TimeoutError, Exception):
managed.exit_code = managed.process.returncode
managed.status = "stopped" if managed.exit_code == 0 else "error"
+ managed.stopped_at = datetime.now().isoformat()
logger.info("[Process] Exited: %s (exit=%s)", managed.name, managed.exit_code)
# Schedule auto-cleanup of log files and process entry after delay
@@ -468,10 +560,12 @@ class ProcessService:
"pid": m.pid,
"status": m.status,
"started_at": m.started_at,
+ "stopped_at": m.stopped_at,
"exit_code": m.exit_code,
"working_directory": m.working_directory,
"stdout_lines": m.stdout_lines,
"stderr_lines": m.stderr_lines,
+ "ports": list(m.ports),
"log_dir": str(m.log_dir),
}
diff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.py
index 417f5cbe..075de6ac 100644
--- a/server/services/temporal/activities.py
+++ b/server/services/temporal/activities.py
@@ -415,6 +415,37 @@ async def emit_event_activity(event_payload: Dict[str, Any]) -> Dict[str, Any]:
# stuck on "waiting" with no firing pulse — a UX regression vs legacy.
+async def load_persisted_workflow_graph_activity(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Resolve the current saved graph for a durable trigger firing.
+
+ Listener workflow inputs are immutable deployment snapshots. Dynamic
+ canvas operations can add tools after deployment, so every event resolves
+ the authoritative graph before selecting downstream/config nodes.
+ """
+ from core.container import container
+ from services.workflow_migrations import (
+ normalize_edge_handles,
+ normalize_legacy_android_toolkit,
+ )
+
+ workflow_id = str(payload.get("workflow_id") or "")
+ if not workflow_id:
+ return {"found": False, "nodes": [], "edges": []}
+ saved = await container.database().get_workflow(workflow_id)
+ if saved is None:
+ return {"found": False, "nodes": [], "edges": []}
+ data = saved.data or {}
+ nodes, edges, _params, _warnings = normalize_legacy_android_toolkit(
+ data.get("nodes") or [], data.get("edges") or []
+ )
+ return {
+ "found": True,
+ "nodes": nodes,
+ "edges": normalize_edge_handles(edges),
+ }
+
+
@activity.defn
async def store_node_output_activity(payload: Dict[str, Any]) -> None:
"""Persist a node's output to the workflow output store so
diff --git a/server/services/temporal/polling_trigger_workflow.py b/server/services/temporal/polling_trigger_workflow.py
index d29ed4c6..f2203a52 100644
--- a/server/services/temporal/polling_trigger_workflow.py
+++ b/server/services/temporal/polling_trigger_workflow.py
@@ -207,6 +207,24 @@ class PollingTriggerWorkflow:
edges = listener_data["edges"]
session_id = listener_data.get("session_id", "default")
workflow_id = listener_data.get("workflow_id")
+ try:
+ use_latest_graph = bool(workflow_id) and workflow.patched("trigger-latest-graph-v1")
+ except RuntimeError: # direct unit invocation outside Temporal runtime
+ use_latest_graph = False
+ if use_latest_graph:
+ try:
+ latest = await workflow.execute_activity(
+ "load_persisted_workflow_graph_activity",
+ {"workflow_id": workflow_id},
+ start_to_close_timeout=timedelta(seconds=10),
+ )
+ if latest.get("found"):
+ nodes = latest.get("nodes") or []
+ edges = latest.get("edges") or []
+ except Exception as exc: # snapshot remains a safe fallback
+ workflow.logger.warning(
+ f"Current graph lookup failed for {workflow_id}; using deployment snapshot: {exc}"
+ )
# Human-readable slug prefix for the Temporal Web UI listing.
# Set at deploy time from the workflow's display name.
workflow_slug = listener_data.get("workflow_slug") or workflow_id
diff --git a/server/services/temporal/trigger_listener_workflow.py b/server/services/temporal/trigger_listener_workflow.py
index fcd977ce..a25f9304 100644
--- a/server/services/temporal/trigger_listener_workflow.py
+++ b/server/services/temporal/trigger_listener_workflow.py
@@ -153,6 +153,24 @@ class TriggerListenerWorkflow:
edges = listener_data["edges"]
session_id = listener_data.get("session_id", "default")
workflow_id = listener_data.get("workflow_id")
+ try:
+ use_latest_graph = bool(workflow_id) and workflow.patched("trigger-latest-graph-v1")
+ except RuntimeError: # direct unit invocation outside Temporal runtime
+ use_latest_graph = False
+ if use_latest_graph:
+ try:
+ latest = await workflow.execute_activity(
+ "load_persisted_workflow_graph_activity",
+ {"workflow_id": workflow_id},
+ start_to_close_timeout=timedelta(seconds=10),
+ )
+ if latest.get("found"):
+ nodes = latest.get("nodes") or []
+ edges = latest.get("edges") or []
+ except Exception as exc: # snapshot remains a safe fallback
+ workflow.logger.warning(
+ f"Current graph lookup failed for {workflow_id}; using deployment snapshot: {exc}"
+ )
# Human-readable slug prefix for the Temporal Web UI listing.
# Set at deploy time from the workflow's display name; falls back
# to workflow_id for one-off deploys without a saved DB row.
@@ -343,7 +361,7 @@ def _build_run_graph(
for edge in edges:
target = edge.get("target")
source = edge.get("source")
- handle = edge.get("targetHandle", "")
+ handle = edge.get("targetHandle") or edge.get("target_handle") or ""
is_config = handle and handle.startswith("input-") and handle != "input-main"
if is_config and target in downstream_ids and source not in downstream_ids:
if node_types.get(source, "") in WORKFLOW_TRIGGER_TYPES:
@@ -363,7 +381,8 @@ def _build_run_graph(
for edge in edges:
target = edge.get("target")
source = edge.get("source")
- if target in agent_ids and edge.get("targetHandle", "") == "input-tools" and source not in downstream_ids:
+ handle = edge.get("targetHandle") or edge.get("target_handle") or ""
+ if target in agent_ids and handle == "input-tools" and source not in downstream_ids:
downstream_ids.add(source)
run_filter = {trigger_node_id} | downstream_ids
diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.py
index 7606c6fe..6c260baa 100644
--- a/server/services/temporal/worker.py
+++ b/server/services/temporal/worker.py
@@ -171,6 +171,7 @@ class TemporalWorkerManager:
from services.temporal.agent_workflow import AgentWorkflow, DelegatedTaskWorkflow
from services.temporal.activities import (
broadcast_trigger_status_activity,
+ load_persisted_workflow_graph_activity,
store_node_output_activity,
)
@@ -222,6 +223,7 @@ class TemporalWorkerManager:
activities=[
self._activities.execute_node_activity,
broadcast_trigger_status_activity,
+ load_persisted_workflow_graph_activity,
store_node_output_activity,
*per_type,
*agent_activities,
@@ -600,6 +602,7 @@ async def run_standalone_worker(
from services.temporal.activities import (
broadcast_trigger_status_activity,
+ load_persisted_workflow_graph_activity,
store_node_output_activity,
)
@@ -615,6 +618,7 @@ async def run_standalone_worker(
activities=[
activities.execute_node_activity,
broadcast_trigger_status_activity,
+ load_persisted_workflow_graph_activity,
store_node_output_activity,
],
max_concurrent_activities=pool_size,
@@ -652,6 +656,7 @@ async def create_worker(
activities = NodeExecutionActivities(session)
from services.temporal.activities import (
broadcast_trigger_status_activity,
+ load_persisted_workflow_graph_activity,
store_node_output_activity,
)
@@ -666,6 +671,7 @@ async def create_worker(
activities=[
activities.execute_node_activity,
broadcast_trigger_status_activity,
+ load_persisted_workflow_graph_activity,
store_node_output_activity,
],
max_concurrent_activities=100,
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index 0b25385d..6b2e3d01 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -33,7 +33,7 @@ def _is_config_edge(edge: Dict[str, Any], node_map: Dict[str, Dict[str, Any]]) -
removes both the pre-executed trigger and its payload before dependency
resolution, leaving the downstream agent with an empty prompt.
"""
- handle = edge.get("targetHandle", "")
+ handle = edge.get("targetHandle") or edge.get("target_handle") or ""
if handle not in CONFIG_HANDLES:
return False
source = node_map.get(edge.get("source"), {})
diff --git a/server/services/workflow_migrations.py b/server/services/workflow_migrations.py
index f21e4a93..823665f9 100644
--- a/server/services/workflow_migrations.py
+++ b/server/services/workflow_migrations.py
@@ -7,6 +7,21 @@ from typing import Any, Dict, List, Mapping, Optional, Tuple
from constants import AI_AGENT_TYPES, ANDROID_SERVICE_NODE_TYPES
+def normalize_edge_handles(edges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """Canonicalize legacy ReactFlow handle keys without changing topology."""
+ normalized: List[Dict[str, Any]] = []
+ for edge in edges:
+ item = dict(edge)
+ target_handle = item.pop("target_handle", None)
+ source_handle = item.pop("source_handle", None)
+ if not item.get("targetHandle") and target_handle:
+ item["targetHandle"] = target_handle
+ if not item.get("sourceHandle") and source_handle:
+ item["sourceHandle"] = source_handle
+ normalized.append(item)
+ return normalized
+
+
def normalize_legacy_android_toolkit(
nodes: List[Dict[str, Any]],
edges: List[Dict[str, Any]],
diff --git a/server/tests/services/test_process_service_ports.py b/server/tests/services/test_process_service_ports.py
new file mode 100644
index 00000000..920732ae
--- /dev/null
+++ b/server/tests/services/test_process_service_ports.py
@@ -0,0 +1,71 @@
+from __future__ import annotations
+
+import socket
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from services.process_service import ProcessService
+
+
+def test_requested_ports_combines_explicit_cli_and_environment() -> None:
+ ports = ProcessService._requested_ports(
+ ["server", "--port=4100", "--other", "x", "-p", "4200"],
+ [4300, 4100],
+ {"API_PORT": "4400", "NOT_A_PORT": "text"},
+ )
+
+ assert ports == [4100, 4200, 4300, 4400]
+
+
+def test_requested_ports_does_not_guess_positional_numbers() -> None:
+ assert ProcessService._requested_ports(["python", "-m", "http.server", "8123"], [], {}) == []
+
+
+def test_occupied_ports_reports_listener_without_killing_it() -> None:
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ try:
+ assert port in ProcessService._occupied_ports([port])
+ # Detection is non-destructive: the original socket still owns it.
+ challenger = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ with pytest.raises(OSError):
+ challenger.bind(("127.0.0.1", port))
+ finally:
+ challenger.close()
+ finally:
+ listener.close()
+
+
+async def test_start_rejects_occupied_declared_port_before_spawn(monkeypatch) -> None:
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ service = ProcessService()
+ spawned = False
+
+ async def fake_spawn(*args, **kwargs):
+ nonlocal spawned
+ spawned = True
+ raise AssertionError("spawn must not run for an occupied port")
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_spawn)
+ workspace = Path.cwd().resolve()
+ monkeypatch.setattr("core.config.Settings", lambda: SimpleNamespace(workspace_base_resolved=str(workspace)))
+ monkeypatch.setattr("core.paths.daemons_dir", lambda: workspace / ".opencompany-test-daemons")
+ try:
+ # The collision check happens before subprocess creation; use an
+ # OpenCompany-controlled default cwd supplied by the configured root.
+ result = await service.start("web", "python --port 1", working_directory=str(workspace), ports=[port])
+ assert result["success"] is False
+ assert result["code"] == "PORT_IN_USE"
+ assert result["ports"] == [port]
+ assert spawned is False
+ finally:
+ listener.close()
diff --git a/server/tests/temporal/test_task_trigger_graph.py b/server/tests/temporal/test_task_trigger_graph.py
index 9f4dc87c..f1bf9a3c 100644
--- a/server/tests/temporal/test_task_trigger_graph.py
+++ b/server/tests/temporal/test_task_trigger_graph.py
@@ -1,5 +1,8 @@
"""Regression tests for taskTrigger runtime data entering Temporal agents."""
+import pytest
+from types import SimpleNamespace
+
from services.temporal.workflow import MachinaWorkflow
@@ -35,3 +38,49 @@ def test_non_trigger_input_task_remains_configuration() -> None:
assert nodes == [agent]
assert edges == []
+
+
+async def test_agent_connection_collection_accepts_legacy_todo_handle() -> None:
+ from services.plugin.edge_walker import collect_agent_connections
+
+ class Database:
+ async def get_node_parameters(self, _node_id):
+ return {}
+
+ nodes = [
+ {"id": "lead", "type": "orchestrator_agent", "data": {}},
+ {"id": "todos", "type": "writeTodos", "data": {"label": "Todos"}},
+ ]
+ edges = [{"source": "todos", "target": "lead", "target_handle": "input-tools"}]
+
+ _memory, _skills, tools, _input, _task = await collect_agent_connections(
+ "lead", {"nodes": nodes, "edges": edges, "workflow_id": "workflow-1"}, Database(),
+ )
+
+ assert any(tool["node_id"] == "todos" and tool["node_type"] == "writeTodos" for tool in tools)
+
+
+async def test_latest_graph_activity_returns_canonical_saved_tool_edge(monkeypatch) -> None:
+ from core.container import container
+ from services.temporal.activities import load_persisted_workflow_graph_activity
+
+ saved = SimpleNamespace(data={
+ "nodes": [
+ {"id": "lead", "type": "orchestrator_agent"},
+ {"id": "todos", "type": "writeTodos"},
+ ],
+ "edges": [{"source": "todos", "target": "lead", "target_handle": "input-tools"}],
+ })
+
+ class Database:
+ async def get_workflow(self, workflow_id):
+ assert workflow_id == "workflow-1"
+ return saved
+
+ monkeypatch.setattr(container, "database", lambda: Database())
+ result = await load_persisted_workflow_graph_activity({"workflow_id": "workflow-1"})
+
+ assert result["found"] is True
+ assert result["edges"] == [{"source": "todos", "target": "lead", "targetHandle": "input-tools"}]
diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.py
index 01a049c6..6841a2c1 100644
--- a/server/tests/test_node_spec.py
+++ b/server/tests/test_node_spec.py
@@ -779,6 +779,12 @@ class TestUIHintsInNodeSpec:
assert lead_hints.get("hideInputSection") is not True
assert lead_hints.get("hideOutputSection") is not True
+ def test_process_manager_surfaces_span_the_full_parameter_panel(self):
+ hints = get_node_spec("processManager").get("uiHints", {})
+ assert hints.get("isProcessManagerPanel") is True
+ assert hints.get("hideInputSection") is True
+ assert hints.get("hideOutputSection") is True
+
def test_master_skill_seeded(self):
spec = get_node_spec("masterSkill")
assert spec is not None
@@ -916,6 +922,7 @@ class TestNodeSpecContractInvariants:
"isTodoEditor",
"isMonitorPanel",
"isTaskManagerPanel",
+ "isProcessManagerPanel",
"showLocationPanel",
"isAndroidToolkit",
"isChatTrigger",
diff --git a/server/tests/test_polling_trigger_workflow.py b/server/tests/test_polling_trigger_workflow.py
index 3f3c79d4..a48df1e1 100644
--- a/server/tests/test_polling_trigger_workflow.py
+++ b/server/tests/test_polling_trigger_workflow.py
@@ -372,6 +372,8 @@ class TestPollingTriggerWorkflowBody:
# but don't consume the scripted poll-cycle responses.
if name == "broadcast_trigger_status_activity":
return None
+ if name == "load_persisted_workflow_graph_activity":
+ return {"found": False, "nodes": [], "edges": []}
return next(responses)
sleep_calls: List[Any] = []
@@ -401,6 +403,7 @@ class TestPollingTriggerWorkflowBody:
raise _StopLoop()
monkeypatch.setattr(temporal_workflow, "execute_activity", fake_execute_activity)
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: False)
monkeypatch.setattr(temporal_workflow, "sleep", fake_sleep)
monkeypatch.setattr(temporal_workflow, "start_child_workflow", fake_start_child)
monkeypatch.setattr(temporal_workflow, "continue_as_new", fake_continue_as_new)
diff --git a/server/tests/test_trigger_listener_workflow.py b/server/tests/test_trigger_listener_workflow.py
index e88bba7f..5e4dd9dc 100644
--- a/server/tests/test_trigger_listener_workflow.py
+++ b/server/tests/test_trigger_listener_workflow.py
@@ -52,6 +52,7 @@ def _patch_workflow_logger(monkeypatch):
from temporalio import workflow as temporal_workflow
monkeypatch.setattr(temporal_workflow, "logger", MagicMock())
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: True)
# ---------------------------------------------------------------------------
@@ -227,6 +228,26 @@ class TestBuildRunGraph:
assert {n["id"] for n in filtered_nodes} == {"wh-1", "agent-1", "mem-1"}
+ def test_legacy_tool_handle_is_included_for_triggered_lead(self):
+ from services.temporal.trigger_listener_workflow import _build_run_graph
+
+ nodes = [
+ _node("task-trigger", "taskTrigger"),
+ _node("lead", "orchestrator_agent"),
+ _node("todos", "writeTodos"),
+ ]
+ edges = [
+ _edge("task-trigger", "lead", target_handle="input-task"),
+ {"source": "todos", "target": "lead", "target_handle": "input-tools"},
+ ]
+
+ filtered_nodes, filtered_edges = _build_run_graph(
+ trigger_node_id="task-trigger", trigger_output={}, nodes=nodes, edges=edges,
+ )
+
+ assert {node["id"] for node in filtered_nodes} == {"task-trigger", "lead", "todos"}
+ assert any(edge["source"] == "todos" for edge in filtered_edges)
+
def test_stops_at_downstream_trigger_nodes(self):
"""Downstream collection stops at trigger nodes (n8n pattern):
each trigger is an independent event listener. taskTrigger fires
@@ -330,6 +351,48 @@ class TestSpawnChildRun:
assert wh["_trigger_output"]["path"] == "/hook"
assert wh["_trigger_output"]["_event_envelope"]["id"] == "evt-42"
+ @pytest.mark.asyncio
+ async def test_spawn_uses_latest_saved_graph_tools(self, monkeypatch):
+ from services.temporal import trigger_listener_workflow as tlw
+ from temporalio import workflow as temporal_workflow
+
+ recorded: List[Dict[str, Any]] = []
+ latest_nodes = [
+ _node("task-trigger", "taskTrigger"),
+ _node("lead", "orchestrator_agent"),
+ _node("todos", "writeTodos"),
+ ]
+ latest_edges = [
+ _edge("task-trigger", "lead", "input-task"),
+ _edge("todos", "lead", "input-tools"),
+ ]
+
+ async def fake_execute_activity(name, *args, **kwargs):
+ if name == "load_persisted_workflow_graph_activity":
+ return {"found": True, "nodes": latest_nodes, "edges": latest_edges}
+ return None
+
+ async def fake_start_child_workflow(name, **kwargs):
+ recorded.append({"name": name, **kwargs})
+ return MagicMock()
+
+ monkeypatch.setattr(temporal_workflow, "execute_activity", fake_execute_activity)
+ monkeypatch.setattr(temporal_workflow, "start_child_workflow", fake_start_child_workflow)
+
+ snapshot_nodes = [_node("task-trigger", "taskTrigger"), _node("lead", "orchestrator_agent")]
+ snapshot_edges = [_edge("task-trigger", "lead", "input-task")]
+ await tlw.TriggerListenerWorkflow()._spawn_child_run(
+ {"id": "evt-new-tool", "type": "task", "data": {"task_id": "task-1", "status": "completed"}},
+ {
+ "workflow_id": "workflow-1", "trigger_node_id": "task-trigger",
+ "nodes": snapshot_nodes, "edges": snapshot_edges,
+ },
+ )
+
+ child_graph = recorded[0]["args"][0]
+ assert {node["id"] for node in child_graph["nodes"]} == {"task-trigger", "lead", "todos"}
+ assert any(edge["source"] == "todos" for edge in child_graph["edges"])
+
@pytest.mark.asyncio
async def test_spawn_failure_does_not_kill_listener(self, monkeypatch):
"""An exception inside _spawn_child_run propagates back to the