Skip to content

Self-improving AI Employees for everyone

fix(todos): scope live lists to physical nodes

trohitgb8a88bed8444
diff --git a/client/src/components/parameterPanel/TodoEditor.tsx b/client/src/components/parameterPanel/TodoEditor.tsx
index a68bf0b4..e481c95e 100644
--- a/client/src/components/parameterPanel/TodoEditor.tsx
+++ b/client/src/components/parameterPanel/TodoEditor.tsx
@@ -2,14 +2,13 @@
* TodoEditor — editable Current Todos manager for the writeTodos node.
*
* Replaces the empty generic-params card ("Todos — No properties") in the
- * parameter panel's middle section. Sourced from the LIVE workflow todos in
- * the backend TodoService (keyed by the open workflow, node_id fallback) via
+ * parameter panel's middle section. Sourced from the LIVE node todos in the
+ * backend TodoService (keyed by workflow + writeTodos node) via
* the `get_todos` / `set_todos` WS handlers — NOT from `parameters.todos`.
*
- * Because TodoService keys by workflow, all writeTodos nodes in one workflow
- * share a single list (surfaced in the header). The list updates live when an
- * agent calls the write_todos tool mid-run (the `todos_updated` CloudEvent
- * lands in this query's cache via WebSocketContext).
+ * Each writeTodos node owns an independent list. The list updates live when
+ * an agent calls the write_todos tool mid-run (the `todos_updated` CloudEvent
+ * lands in this node's exact query cache via WebSocketContext).
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
@@ -20,6 +19,7 @@ import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { ActionButton } from '@/components/ui/action-button';
import { cn } from '@/lib/utils';
+import { todoQueryKey } from '@/lib/todoQuery';
import { useWebSocket } from '../../contexts/WebSocketContext';
import { useAppStore } from '../../store/useAppStore';
@@ -60,11 +60,10 @@ const TodoEditor: React.FC<Props> = ({ nodeId }) => {
const currentWorkflowId = useAppStore((s) => s.currentWorkflow?.id);
const queryClient = useQueryClient();
- // Session key mirrors the backend write op (`workflow_id or node_id`).
- const sessionKey = currentWorkflowId ?? nodeId;
+ const queryKey = todoQueryKey(currentWorkflowId, nodeId);
const { data: serverTodos } = useQuery<ServerTodo[]>({
- queryKey: ['todos', sessionKey],
+ queryKey,
queryFn: async () => {
const resp = await sendRequest<{ todos?: ServerTodo[] }>('get_todos', {
workflow_id: currentWorkflowId,
@@ -82,6 +81,14 @@ const TodoEditor: React.FC<Props> = ({ nodeId }) => {
// credentials Default-Parameters fix).
const editingRef = useRef<string | null>(null);
+ // This component instance is reused while the parameter panel switches
+ // nodes. Drop node-A's draft/edit lock immediately so it cannot suppress
+ // the node-B query sync or remain visible while B is loading.
+ useEffect(() => {
+ editingRef.current = null;
+ setRows([]);
+ }, [currentWorkflowId, nodeId]);
+
// Sync local rows from the server query — only when not actively editing.
useEffect(() => {
if (editingRef.current !== null) return;
@@ -97,7 +104,7 @@ const TodoEditor: React.FC<Props> = ({ nodeId }) => {
.filter((r) => r.content.trim() !== '')
.map((r) => ({ content: r.content.trim(), status: r.status }));
// Optimistic cache update so other consumers (and a reopen) see it now.
- queryClient.setQueryData(['todos', sessionKey], payload);
+ queryClient.setQueryData(queryKey, payload);
void sendRequest('set_todos', {
workflow_id: currentWorkflowId,
node_id: nodeId,
@@ -107,7 +114,7 @@ const TodoEditor: React.FC<Props> = ({ nodeId }) => {
// get_todos / todos_updated reconciles. Surface nothing noisy here.
});
},
- [queryClient, sendRequest, currentWorkflowId, nodeId, sessionKey],
+ [queryClient, sendRequest, currentWorkflowId, nodeId, queryKey],
);
const addTodo = useCallback(() => {
@@ -169,7 +176,7 @@ const TodoEditor: React.FC<Props> = ({ nodeId }) => {
</div>
<p className="mb-3 text-xs text-muted-foreground">
- Live todo list for this workflow (shared by every Write Todos node in the workflow).
+ Live todo list for this Write Todos node.
</p>
<div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto">
diff --git a/client/src/lib/todoQuery.ts b/client/src/lib/todoQuery.ts
new file mode 100644
index 00000000..b375162e
--- /dev/null
+++ b/client/src/lib/todoQuery.ts
@@ -0,0 +1,27 @@
+/** Shared React Query identity for live writeTodos state. */
+
+export interface TodoEventIdentity {
+ workflow_id?: string | null;
+ node_id?: string | null;
+ session_key?: string | null;
+}
+
+/** One cache entry per workflow + writeTodos node. */
+export const todoQueryKey = (workflowId: string | null | undefined, nodeId: string) =>
+ ['todos', 'v2', workflowId ?? 'unsaved', nodeId] as const;
+
+/**
+ * Route a todos_updated event to the exact node cache. Events from legacy
+ * servers that omit node_id retain their historical session-key route.
+ */
+export const todoQueryKeyFromEvent = (
+ identity: TodoEventIdentity | null | undefined,
+ subject?: string | null,
+) => {
+ if (identity?.node_id) {
+ return todoQueryKey(identity.workflow_id, identity.node_id);
+ }
+
+ const legacySessionKey = identity?.session_key || subject;
+ return legacySessionKey ? (['todos', legacySessionKey] as const) : null;
+};
diff --git a/server/nodes/tool/write_todos/__init__.py b/server/nodes/tool/write_todos/__init__.py
index 9a4a8e90..fde81a91 100644
--- a/server/nodes/tool/write_todos/__init__.py
+++ b/server/nodes/tool/write_todos/__init__.py
@@ -84,9 +84,9 @@ class WriteTodosNode(ToolNode):
async def write(self, ctx: NodeContext, params: WriteTodosParams) -> Any:
"""Inlined from handlers/todo.py (Wave 11.D.1)."""
from core.logging import get_logger
- from services.todo_service import get_todo_service
+ from services.todo_service import get_todo_service, todo_session_key
- session_key = ctx.workflow_id or ctx.node_id or "default"
+ session_key = todo_session_key(ctx.workflow_id, ctx.node_id)
service = get_todo_service()
stored = service.write(session_key, [t.model_dump() for t in params.todos])
@@ -103,12 +103,11 @@ class WriteTodosNode(ToolNode):
# Typed todos_updated CloudEvent via the centralized dispatcher so an
# open Current Todos panel refreshes live during the run. (The
# node_status broadcast above drives canvas glow; this drives the
- # panel's ['todos', session_key] query — same wire frame the panel's
+ # panel's exact workflow + node query — same wire frame the panel's
# manual set_todos edits emit.)
from ._events import dispatch_todos_updated
await dispatch_todos_updated(
- session_key=session_key,
todos=stored,
node_id=ctx.node_id,
workflow_id=ctx.workflow_id,
diff --git a/server/nodes/tool/write_todos/_events.py b/server/nodes/tool/write_todos/_events.py
index a57b05a1..52f0b934 100644
--- a/server/nodes/tool/write_todos/_events.py
+++ b/server/nodes/tool/write_todos/_events.py
@@ -29,14 +29,14 @@ _TODOS_UPDATED_WIRE_KEY = "todos_updated"
def todos_updated(
*,
- session_key: str,
todos: List[dict],
node_id: Optional[str] = None,
workflow_id: Optional[str] = None,
) -> WorkflowEvent:
- """Todo-list-changed envelope. ``subject`` is the session key (the
- workflow the list is shared under) so the FE can route the update to
- the right ``['todos', session_key]`` query."""
+ """Build an exactly routable todo-list-changed envelope."""
+ from services.todo_service import todo_session_key
+
+ session_key = todo_session_key(workflow_id, node_id)
data: Dict[str, Any] = {
"session_key": session_key,
"todos": todos,
@@ -53,7 +53,6 @@ def todos_updated(
async def dispatch_todos_updated(
*,
- session_key: str,
todos: List[dict],
node_id: Optional[str] = None,
workflow_id: Optional[str] = None,
@@ -64,7 +63,6 @@ async def dispatch_todos_updated(
await emit(
todos_updated(
- session_key=session_key,
todos=todos,
node_id=node_id,
workflow_id=workflow_id,
diff --git a/server/nodes/tool/write_todos/_handlers.py b/server/nodes/tool/write_todos/_handlers.py
index 8721e03b..3759d86f 100644
--- a/server/nodes/tool/write_todos/_handlers.py
+++ b/server/nodes/tool/write_todos/_handlers.py
@@ -6,9 +6,9 @@ core router needs no edit (same self-containment pattern as
``nodes/telegram/_handlers.py``).
These give the parameter-panel Current Todos editor a read/write path
-into the live ``TodoService`` state, which is keyed by ``workflow_id``
-(``node_id`` fallback) — the same precedence the ``write`` op uses, so
-the panel sees exactly what the agent wrote at runtime.
+into the live ``TodoService`` state, keyed by the workflow + ``writeTodos``
+node pair. Legacy requests that omit ``node_id`` retain the historical
+workflow-only fallback.
"""
from __future__ import annotations
@@ -23,14 +23,15 @@ from ._events import dispatch_todos_updated
def _session_key(data: Dict[str, Any]) -> str:
- """Mirror the write op's keying precedence
- (``__init__.py``: ``ctx.workflow_id or ctx.node_id or "default"``)."""
- return data.get("workflow_id") or data.get("node_id") or "default"
+ """Mirror the write op's canonical workflow + node key."""
+ from services.todo_service import todo_session_key
+
+ return todo_session_key(data.get("workflow_id"), data.get("node_id"))
@ws_response
async def handle_get_todos(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Return the current todo list for the open workflow (node_id fallback)."""
+ """Return the current todo list for the selected writeTodos node."""
from services.todo_service import get_todo_service
session_key = _session_key(data)
@@ -55,7 +56,6 @@ async def handle_set_todos(data: Dict[str, Any], websocket: WebSocket) -> Dict[s
stored = get_todo_service().write(session_key, data.get("todos", []) or [])
await dispatch_todos_updated(
- session_key=session_key,
todos=stored,
node_id=data.get("node_id"),
workflow_id=data.get("workflow_id"),
diff --git a/server/services/handlers/todo.py b/server/services/handlers/todo.py
index 8ab6ea89..06eedfde 100644
--- a/server/services/handlers/todo.py
+++ b/server/services/handlers/todo.py
@@ -11,7 +11,7 @@ from __future__ import annotations
from typing import Any, Dict
-from services.todo_service import get_todo_service
+from services.todo_service import get_todo_service, todo_session_key
async def execute_write_todos(
@@ -20,11 +20,11 @@ async def execute_write_todos(
) -> Dict[str, Any]:
"""Legacy (args, config) -> dict contract.
- session_key picks config.workflow_id > config.node_id > 'default'
- (matches pre-refactor handler precedence).
+ Modern calls use a workflow + node composite key. Calls missing node
+ identity keep the pre-refactor workflow/default fallback.
"""
config = config or {}
- session_key = config.get("workflow_id") or config.get("node_id") or "default"
+ session_key = todo_session_key(config.get("workflow_id"), config.get("node_id"))
todos = args.get("todos", [])
service = get_todo_service()
stored = service.write(session_key, todos)
@@ -39,6 +39,16 @@ async def execute_write_todos(
workflow_id=config.get("workflow_id"),
)
+ # Keep compatibility callers on the same event path as the plugin so an
+ # open Current Todos panel receives only this workflow+node update.
+ from nodes.tool.write_todos._events import dispatch_todos_updated
+
+ await dispatch_todos_updated(
+ todos=stored,
+ node_id=node_id,
+ workflow_id=config.get("workflow_id"),
+ )
+
return {
"success": True,
"message": f"Updated todo list ({len(stored)} items)",
diff --git a/server/services/todo_service.py b/server/services/todo_service.py
index ba7f120e..c6f21b4b 100644
--- a/server/services/todo_service.py
+++ b/server/services/todo_service.py
@@ -1,9 +1,12 @@
-"""Todo list service -- JSON-based per-session todo state management.
+"""Todo list service -- JSON-based per-node todo state management.
Provides the write_todos tool capability for AI agents to create and manage
structured task lists during complex multi-step operations.
-State is persisted as JSON strings, keyed by session identifier.
+State is persisted as JSON strings. Modern callers use a workflow + node
+composite key so two ``writeTodos`` nodes on one canvas remain independent;
+legacy callers that do not provide ``node_id`` retain the historical
+workflow-only fallback.
Follows the singleton pattern used by browser_service.py and the
TelegramService inside ``nodes/telegram/_service.py``.
"""
@@ -16,10 +19,35 @@ from core.logging import get_logger
logger = get_logger(__name__)
VALID_STATUSES = frozenset(("pending", "in_progress", "completed"))
+TODO_KEY_VERSION = "todo:v2"
+UNSAVED_WORKFLOW_ID = "unsaved"
+
+
+def todo_session_key(
+ workflow_id: Optional[str] = None,
+ node_id: Optional[str] = None,
+) -> str:
+ """Return the canonical storage key for a todo-list owner.
+
+ A workflow can contain more than one ``writeTodos`` node, so workflow
+ identity alone is not sufficient. Whenever ``node_id`` is present the key
+ is versioned and node-scoped; unsaved workflows use an explicit stable
+ scope. Missing-node callers intentionally keep the pre-v2 fallback for
+ compatibility with older agents and WS clients.
+ """
+ if node_id:
+ workflow_scope = workflow_id or UNSAVED_WORKFLOW_ID
+ return f"{TODO_KEY_VERSION}:{workflow_scope}:{node_id}"
+ return workflow_id or "default"
+
+
+def todo_workflow_prefix(workflow_id: str) -> str:
+ """Return the prefix shared by all v2 todo keys in ``workflow_id``."""
+ return f"{TODO_KEY_VERSION}:{workflow_id}:"
class TodoService:
- """Manages per-session todo lists stored as JSON.
+ """Manages independently keyed todo lists stored as JSON.
Each session maintains an independent todo list that persists across
tool calls within the same execution.
@@ -34,7 +62,7 @@ class TodoService:
Validates each item, serializes to JSON, and stores.
Args:
- session_key: Session identifier (workflow_id or node_id).
+ session_key: Canonical workflow + node key, or a legacy fallback.
todos: List of todo dicts with 'content' and 'status' keys.
Returns:
@@ -81,6 +109,20 @@ class TodoService:
"""Clear todos for a session."""
self._store.pop(session_key, None)
+ def clear_workflow(self, workflow_id: str) -> List[str]:
+ """Clear every v2 node-scoped todo list in a workflow.
+
+ Returns the concrete keys removed so memory-clear callers can expose
+ accurate diagnostics. The legacy workflow-only key is deliberately
+ left to the caller because that compatibility key may be part of a
+ broader legacy clear set.
+ """
+ prefix = todo_workflow_prefix(workflow_id)
+ cleared = [key for key in self._store if key.startswith(prefix)]
+ for key in cleared:
+ self.clear(key)
+ return cleared
+
def format_for_llm(self, session_key: str) -> str:
"""Format todos as JSON string for LLM consumption."""
return self.get_json(session_key)