refactor: integrate TodoListMiddleware and update related components

- Removed the write_todos tool as it is now included by default through TodoListMiddleware in the deep agent.
- Updated the system prompt and documentation to reflect the integration of TodoListMiddleware, clarifying its capabilities for managing planning and todo lists.
- Enhanced the chat handling logic to extract todos directly from the deep agent's command output, ensuring seamless user experience.
- Refactored UI components to align with the new data structure and improve rendering of todo items, including updates to the Plan and TodoItem components.
- Cleaned up code for better maintainability and readability, following recent refactoring efforts.
This commit is contained in:
Anish Sarkar 2025-12-27 15:18:34 +05:30
parent 8a3ab3dfac
commit c28a90fc29
10 changed files with 172 additions and 419 deletions

View file

@ -14,73 +14,30 @@ import {
import { Plan, PlanErrorBoundary, parseSerializablePlan, TodoStatusSchema } from "./plan";
// ============================================================================
// Zod Schemas
// Zod Schemas - Matching deepagents TodoListMiddleware output
// ============================================================================
/**
* Schema for a single todo item in the args
* Note: Using nullish() with transform to convert null undefined for Plan compatibility
* Schema for a single todo item (matches deepagents output)
*/
const WriteTodosArgsTodoSchema = z.object({
id: z.string(),
const TodoItemSchema = z.object({
content: z.string(),
status: TodoStatusSchema,
description: z
.string()
.nullish()
.transform((v) => v ?? undefined),
});
/**
* Schema for write_todos tool arguments
* Note: Using nullish() with transform to convert null undefined for Plan compatibility
* Schema for write_todos tool args/result (matches deepagents output)
* deepagents provides: { todos: [{ content, status }] }
*/
const WriteTodosArgsSchema = z.object({
title: z
.string()
.nullish()
.transform((v) => v ?? undefined),
description: z
.string()
.nullish()
.transform((v) => v ?? undefined),
todos: z.array(WriteTodosArgsTodoSchema).nullish(),
});
/**
* Schema for a single todo item in the result
* Note: Using nullish() with transform to convert null undefined for Plan compatibility
*/
const WriteTodosResultTodoSchema = z.object({
id: z.string(),
label: z.string(),
status: TodoStatusSchema,
description: z
.string()
.nullish()
.transform((v) => v ?? undefined),
});
/**
* Schema for write_todos tool result
* Note: Using nullish() with transform to convert null undefined for Plan compatibility
*/
const WriteTodosResultSchema = z.object({
id: z.string(),
title: z.string(),
description: z
.string()
.nullish()
.transform((v) => v ?? undefined),
todos: z.array(WriteTodosResultTodoSchema),
const WriteTodosSchema = z.object({
todos: z.array(TodoItemSchema).nullish(),
});
// ============================================================================
// Types
// ============================================================================
type WriteTodosArgs = z.infer<typeof WriteTodosArgsSchema>;
type WriteTodosResult = z.infer<typeof WriteTodosResultSchema>;
type WriteTodosData = z.infer<typeof WriteTodosSchema>;
/**
* Loading state component
@ -96,103 +53,65 @@ function WriteTodosLoading() {
);
}
/**
* Transform tool args to result format
* This handles the case where the LLM is streaming the tool call
*/
function transformArgsToResult(args: WriteTodosArgs): WriteTodosResult | null {
if (!args.todos || !Array.isArray(args.todos) || args.todos.length === 0) {
return null;
}
return {
id: `plan-${Date.now()}`,
title: args.title || "Planning Approach",
description: args.description,
todos: args.todos.map((todo, index) => ({
id: todo.id || `todo-${index}`,
label: todo.content || "Task",
status: todo.status || "pending",
description: todo.description,
})),
};
}
/**
* WriteTodos Tool UI Component
*
* Displays the agent's planning/todo list with a beautiful UI.
* Shows progress, status indicators, and expandable details.
* Uses deepagents TodoListMiddleware output directly: { todos: [{ content, status }] }
*
* FIXED POSITION: When the same plan (by title) is updated multiple times,
* FIXED POSITION: When multiple write_todos calls happen in a conversation,
* only the FIRST component renders. Subsequent updates just update the
* shared state, and the first component reads from it. This prevents
* layout shift when plans are updated.
* shared state, and the first component reads from it.
*/
export const WriteTodosToolUI = makeAssistantToolUI<WriteTodosArgs, WriteTodosResult>({
export const WriteTodosToolUI = makeAssistantToolUI<WriteTodosData, WriteTodosData>({
toolName: "write_todos",
render: function WriteTodosUI({ args, result, status, toolCallId }) {
const updatePlanState = useSetAtom(updatePlanStateAtom);
const planStates = useAtomValue(planStatesAtom);
// Check if the THREAD is running (not just this tool)
// This hook subscribes to state changes, so it re-renders when thread stops
// Check if the THREAD is running
const isThreadRunning = useAssistantState(({ thread }) => thread.isRunning);
// Get the plan data (from result or args)
const planData = result || transformArgsToResult(args);
const rawTitle = planData?.title || args.title || "Planning Approach";
// Use result if available, otherwise args (for streaming)
const data = result || args;
const hasTodos = data?.todos && data.todos.length > 0;
// SYNCHRONOUS ownership check - happens immediately, no race conditions
// ONE PLAN PER CONVERSATION: Only first write_todos call becomes owner
// Fixed title for all plans in conversation
const planTitle = "Plan";
// SYNCHRONOUS ownership check
const isOwner = useMemo(() => {
return registerPlanOwner(rawTitle, toolCallId);
}, [rawTitle, toolCallId]);
return registerPlanOwner(planTitle, toolCallId);
}, [planTitle, toolCallId]);
// Get canonical title - always use the FIRST plan's title
// This ensures all updates go to the same plan state
const planTitle = useMemo(() => getCanonicalPlanTitle(rawTitle), [rawTitle]);
// Get canonical title
const canonicalTitle = useMemo(() => getCanonicalPlanTitle(planTitle), [planTitle]);
// Register/update the plan state - ALWAYS use canonical title
// Register/update the plan state
useEffect(() => {
if (planData) {
if (hasTodos) {
const normalizedPlan = parseSerializablePlan({ todos: data.todos });
updatePlanState({
id: planData.id,
title: planTitle, // Use canonical title, not raw title
description: planData.description,
todos: planData.todos,
id: normalizedPlan.id,
title: canonicalTitle,
todos: normalizedPlan.todos,
toolCallId,
});
}
}, [planData, planTitle, updatePlanState, toolCallId]);
}, [data, hasTodos, canonicalTitle, updatePlanState, toolCallId]);
// Update when result changes (for streaming updates)
useEffect(() => {
if (result) {
updatePlanState({
id: result.id,
title: planTitle, // Use canonical title, not raw title
description: result.description,
todos: result.todos,
toolCallId,
});
}
}, [result, planTitle, updatePlanState, toolCallId]);
// Get the current plan state
const currentPlanState = planStates.get(canonicalTitle);
// Get the current plan state (may be updated by other components)
const currentPlanState = planStates.get(planTitle);
// If we're NOT the owner, render nothing (the owner will render)
// If we're NOT the owner, render nothing
if (!isOwner) {
return null;
}
// Loading state - tool is still running (no data yet)
// Loading state
if (status.type === "running" || status.type === "requires-action") {
// Try to show partial results from args while streaming
const partialResult = transformArgsToResult(args);
if (partialResult) {
const plan = parseSerializablePlan(partialResult);
if (hasTodos) {
const plan = parseSerializablePlan({ todos: data.todos });
return (
<div className="my-4">
<PlanErrorBoundary>
@ -206,11 +125,8 @@ export const WriteTodosToolUI = makeAssistantToolUI<WriteTodosArgs, WriteTodosRe
// Incomplete/cancelled state
if (status.type === "incomplete") {
// For cancelled or errors, try to show what we have from args or shared state
// Use isThreadRunning to determine if we should still animate
const fallbackResult = currentPlanState || transformArgsToResult(args);
if (fallbackResult) {
const plan = parseSerializablePlan(fallbackResult);
if (currentPlanState || hasTodos) {
const plan = currentPlanState || parseSerializablePlan({ todos: data?.todos || [] });
return (
<div className="my-4">
<PlanErrorBoundary>
@ -222,23 +138,20 @@ export const WriteTodosToolUI = makeAssistantToolUI<WriteTodosArgs, WriteTodosRe
return null;
}
// Success - render the plan using the LATEST shared state
// Use isThreadRunning to determine if we should animate in_progress items
// (LLM may still be working on tasks even though this tool call completed)
const planToRender = currentPlanState || result;
// Success - render the plan
const planToRender = currentPlanState || (hasTodos ? parseSerializablePlan({ todos: data.todos }) : null);
if (!planToRender) {
return <WriteTodosLoading />;
}
const plan = parseSerializablePlan(planToRender);
return (
<div className="my-4">
<PlanErrorBoundary>
<Plan {...plan} showProgress={true} isStreaming={isThreadRunning} />
<Plan {...planToRender} showProgress={true} isStreaming={isThreadRunning} />
</PlanErrorBoundary>
</div>
);
},
});
export { WriteTodosArgsSchema, WriteTodosResultSchema, type WriteTodosArgs, type WriteTodosResult };
export { WriteTodosSchema, type WriteTodosData };