An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: implement todo tools with artifact panel integration
Yoshiki Miura5139829773ab
diff --git a/components/artifact/artifact-content.tsx b/components/artifact/artifact-content.tsxindex 13a8a8bb..690ef76b 100644--- a/components/artifact/artifact-content.tsx+++ b/components/artifact/artifact-content.tsx@@ -3,6 +3,7 @@import { Part } from '@/lib/types/ai'import { ReasoningContent } from './reasoning-content'+import { TodoInvocationContent } from './todo-invocation-content'import { ToolInvocationContent } from './tool-invocation-content'export function ArtifactContent({ part }: { part: Part | null }) {@@ -13,6 +14,9 @@ export function ArtifactContent({ part }: { part: Part | null }) {case 'tool-fetch':case 'tool-askQuestion':return <ToolInvocationContent part={part} />+ case 'tool-todoWrite':+ case 'tool-todoRead':+ return <TodoInvocationContent part={part as any} />case 'reasoning':return <ReasoningContent reasoning={part.text} />default:diff --git a/components/artifact/todo-invocation-content.tsx b/components/artifact/todo-invocation-content.tsxnew file mode 100644index 00000000..5e7193f5--- /dev/null+++ b/components/artifact/todo-invocation-content.tsx@@ -0,0 +1,103 @@+'use client'++import { AlertCircle, Check } from 'lucide-react'++import { TodoItem } from '@/lib/types/ai'+import { cn } from '@/lib/utils'++interface TodoInvocationContentProps {+ part: {+ type: 'tool-todoWrite' | 'tool-todoRead'+ toolCallId: string+ state:+ | 'input-streaming'+ | 'input-available'+ | 'output-available'+ | 'output-error'+ input?: { todos?: TodoItem[] }+ output?: {+ todos?: TodoItem[]+ message?: string+ completedCount?: number+ totalCount?: number+ }+ errorText?: string+ }+}++export function TodoInvocationContent({ part }: TodoInvocationContentProps) {+ const todos = part.output?.todos || part.input?.todos || []+ const completedCount =+ part.output?.completedCount ??+ todos.filter(t => t.status === 'completed').length+ const totalCount = part.output?.totalCount ?? todos.length++ const getStatusIcon = (status: TodoItem['status']) => {+ switch (status) {+ case 'completed':+ return <Check className="h-4 w-4 text-green-600" />+ case 'in_progress':+ return (+ <div className="relative h-4 w-4 flex items-center justify-center">+ <div className="h-2 w-2 bg-blue-600 rounded-full animate-ping absolute" />+ <div className="h-2 w-2 bg-blue-600 rounded-full" />+ </div>+ )+ default:+ return (+ <div className="h-4 w-4 flex items-center justify-center">+ <div className="h-2 w-2 bg-muted-foreground rounded-full" />+ </div>+ )+ }+ }++ if (part.state === 'output-error') {+ return (+ <div className="flex items-center gap-2 p-4 text-red-600">+ <AlertCircle className="size-4" />+ <span>Error: {part.errorText || 'Failed to process todos'}</span>+ </div>+ )+ }++ return (+ <div className="space-y-4">+ {/* Summary */}+ <div className="flex items-center justify-between text-sm text-muted-foreground">+ <span className="truncate">{part.output?.message || 'Todo List'}</span>+ <span className="font-medium whitespace-nowrap">+ ({completedCount}/{totalCount})+ </span>+ </div>++ {/* Todo List */}+ <div className="space-y-2">+ {todos.map((todo, index) => (+ <div+ key={todo.id || index}+ className="flex items-center justify-between gap-2 p-3 rounded-lg border bg-card"+ >+ <div className="flex items-center gap-2">+ {getStatusIcon(todo.status)}+ <p+ className={cn(+ 'text-sm',+ todo.status === 'completed' && 'text-muted-foreground'+ )}+ >+ {todo.content}+ </p>+ </div>+ </div>+ ))}+ </div>++ {todos.length === 0 && (+ <div className="text-center py-8 text-muted-foreground">+ No todos available+ </div>+ )}+ </div>+ )+}diff --git a/components/inspector/inspector-panel.tsx b/components/inspector/inspector-panel.tsxindex d05cebd7..4e60a0bd 100644--- a/components/inspector/inspector-panel.tsx+++ b/components/inspector/inspector-panel.tsx@@ -1,6 +1,12 @@'use client'-import { LightbulbIcon, MessageSquare, Minimize2, Search } from 'lucide-react'+import {+ LightbulbIcon,+ ListTodo,+ MessageSquare,+ Minimize2,+ Search+} from 'lucide-react'import { Separator } from '@/components/ui/separator'import { TooltipProvider } from '@/components/ui/tooltip'@@ -24,6 +30,12 @@ export function InspectorPanel() {icon: <Search size={18} />,title: toolName}+ case 'tool-todoWrite':+ case 'tool-todoRead':+ return {+ icon: <ListTodo size={18} />,+ title: 'Todo List'+ }case 'reasoning':return {icon: <LightbulbIcon size={18} />,diff --git a/components/render-message.tsx b/components/render-message.tsxindex a717f670..7766b3f3 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -82,6 +82,8 @@ export function RenderMessage({case 'tool-search':case 'tool-fetch':case 'tool-askQuestion':+ case 'tool-todoWrite':+ case 'tool-todoRead':return (<ToolSectionkey={`${messageId}-tool-${index}`}@@ -145,6 +147,9 @@ export function RenderMessage({onQuerySelect={onQuerySelect}/>)+ case 'data-todos':+ // Handled by TodoPanel in ChatPanel+ return nulldefault:return null}diff --git a/components/tool-section.tsx b/components/tool-section.tsxindex 26fc57bc..ba619538 100644--- a/components/tool-section.tsx+++ b/components/tool-section.tsx@@ -7,6 +7,7 @@ import type { ToolPart, UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'import FetchSection from './fetch-section'import { QuestionConfirmation } from './question-confirmation'import { SearchSection } from './search-section'+import { ToolTodoDisplay } from './tool-todo-display'interface ToolSectionProps {tool: ToolPart@@ -82,6 +83,28 @@ export function ToolSection({status={status}/>)+ case 'tool-todoWrite':+ return (+ <ToolTodoDisplay+ tool="todoWrite"+ state={tool.state}+ input={tool.input}+ output={tool.output}+ errorText={tool.errorText}+ toolCallId={tool.toolCallId}+ />+ )+ case 'tool-todoRead':+ return (+ <ToolTodoDisplay+ tool="todoRead"+ state={tool.state}+ input={tool.input}+ output={tool.output}+ errorText={tool.errorText}+ toolCallId={tool.toolCallId}+ />+ )default:return null}diff --git a/components/tool-todo-display.tsx b/components/tool-todo-display.tsxnew file mode 100644index 00000000..5f4a7425--- /dev/null+++ b/components/tool-todo-display.tsx@@ -0,0 +1,89 @@+import { Check, ListTodo } from 'lucide-react'++import { TodoItem } from '@/lib/types/ai'++import { useArtifact } from './artifact/artifact-context'++interface ToolTodoDisplayProps {+ tool: 'todoWrite' | 'todoRead'+ state:+ | 'input-streaming'+ | 'input-available'+ | 'output-available'+ | 'output-error'+ input?: {+ todos?: TodoItem[]+ }+ output?: {+ todos?: TodoItem[]+ message?: string+ completedCount?: number+ totalCount?: number+ }+ errorText?: string+ toolCallId: string+}++export function ToolTodoDisplay({+ tool,+ state,+ output,+ toolCallId+}: ToolTodoDisplayProps) {+ const { open: openArtifact } = useArtifact()+ // Calculate counts for display+ const completedCount =+ output?.completedCount ??+ (output?.todos+ ? output.todos.filter(t => t.status === 'completed').length+ : 0)+ const totalCount =+ output?.totalCount ?? (output?.todos ? output.todos.length : 0)++ const isLoading = state === 'input-streaming' || state === 'input-available'++ const handleClick = () => {+ if (state === 'output-available' && output) {+ openArtifact({+ type:+ tool === 'todoWrite' ? 'tool-todoWrite' : ('tool-todoRead' as any),+ toolCallId: toolCallId,+ state: state as any,+ input: { todos: output.todos || [] },+ output: output+ })+ }+ }++ return (+ <div+ className={`rounded-lg border bg-card ${isLoading ? 'animate-pulse' : ''} ${+ state === 'output-available' && output+ ? 'cursor-pointer hover:bg-accent/50 transition-colors'+ : ''+ }`}+ onClick={handleClick}+ >+ <div className="flex items-center justify-between gap-2 px-3 py-2 text-sm">+ <div className="flex items-center gap-2">+ <ListTodo className="size-4 text-muted-foreground" />+ <span className="text-muted-foreground">+ {state === 'output-available'+ ? output?.message || 'Todo list updated'+ : tool === 'todoWrite'+ ? 'Updating tasks...'+ : 'Reading tasks...'}+ </span>+ </div>+ {state === 'output-available' && totalCount > 0 && (+ <span className="flex items-center gap-1 text-xs text-muted-foreground">+ {completedCount === totalCount && (+ <Check className="size-4 text-green-500" />+ )}+ ({completedCount}/{totalCount})+ </span>+ )}+ </div>+ </div>+ )+}diff --git a/drizzle/0006_add_todo_tools.sql b/drizzle/0006_add_todo_tools.sqlnew file mode 100644index 00000000..7dc60e90--- /dev/null+++ b/drizzle/0006_add_todo_tools.sql@@ -0,0 +1,5 @@+-- Add todo tool columns+ALTER TABLE "parts" ADD COLUMN "tool_todoWrite_input" json;+ALTER TABLE "parts" ADD COLUMN "tool_todoWrite_output" json;+ALTER TABLE "parts" ADD COLUMN "tool_todoRead_input" json;+ALTER TABLE "parts" ADD COLUMN "tool_todoRead_output" json;\ No newline at end of filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex cb468fe0..52390448 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -5,8 +5,36 @@{"idx": 0,"version": "7",- "when": 1754133183597,- "tag": "0000_rich_ravenous",+ "when": 1753666852574,+ "tag": "0001_persistence_v5",+ "breakpoints": true+ },+ {+ "idx": 1,+ "version": "7",+ "when": 1753684227255,+ "tag": "0003_rename_mcp_to_dynamic",+ "breakpoints": true+ },+ {+ "idx": 2,+ "version": "7",+ "when": 1753688930677,+ "tag": "0004_rename_retrieve_to_fetch",+ "breakpoints": true+ },+ {+ "idx": 3,+ "version": "7",+ "when": 1753822953434,+ "tag": "0005_remove_video_search",+ "breakpoints": true+ },+ {+ "idx": 4,+ "version": "7",+ "when": 1754133183602,+ "tag": "0006_add_todo_tools","breakpoints": true}]diff --git a/lib/agents/researcher.ts b/lib/agents/researcher.tsindex 9a2bd174..cdf1ba1c 100644--- a/lib/agents/researcher.ts+++ b/lib/agents/researcher.ts@@ -3,6 +3,7 @@ import { Experimental_Agent as Agent, stepCountIs } from 'ai'import { fetchTool } from '../tools/fetch'import { createQuestionTool } from '../tools/question'import { createSearchTool } from '../tools/search'+import { createTodoTools } from '../tools/todo'import { getModel } from '../utils/registry'const SYSTEM_PROMPT = `@@ -56,16 +57,25 @@ IMPORTANT: Citations must appear INLINE within your response text, not separatelExample: "Nvidia's stock has risen 200% due to strong AI chip demand [1](#toolu_abc123)."Example with multiple sources: "The company reported record revenue [1](#toolu_abc123), while analysts predict continued growth [2](#toolu_abc123)."Example with multiple searches: "Initial data shows positive trends [1](#toolu_abc123), while recent updates indicate acceleration [1](#toolu_def456)."++TASK MANAGEMENT:+For complex queries requiring systematic investigation:+- Use todoWrite to create and track tasks ONLY for complex, multi-faceted research+- Simple queries (2-3 searches) do NOT need task tracking+- Update task progress after every 2-3 tool calls+- Mark all tasks as completed before finishing your work`export function researcher({model,searchMode,- abortSignal+ abortSignal,+ writer}: {model: stringsearchMode: booleanabortSignal?: AbortSignal+ writer?: any}) {try {const currentDate = new Date().toLocaleString()@@ -74,16 +84,34 @@ export function researcher({const searchTool = createSearchTool(model)const askQuestionTool = createQuestionTool(model)+ // Create todo tools if writer is provided+ const todoTools = writer ? createTodoTools() : {}++ // Build tools object+ const tools = {+ search: searchTool,+ fetch: fetchTool,+ askQuestion: askQuestionTool,+ ...todoTools+ }++ // Build activeTools array based on available tools+ type ToolNames = keyof typeof tools+ const activeToolsList: ToolNames[] = []++ if (searchMode) {+ activeToolsList.push('search', 'fetch')+ if (writer && 'todoWrite' in todoTools) {+ activeToolsList.push('todoWrite' as ToolNames, 'todoRead' as ToolNames)+ }+ }+// Return an agent instancereturn new Agent({model: getModel(model),system: `${SYSTEM_PROMPT}\nCurrent date and time: ${currentDate}`,- tools: {- search: searchTool,- fetch: fetchTool,- askQuestion: askQuestionTool- },- activeTools: searchMode ? ['search', 'fetch'] : undefined,+ tools,+ activeTools: searchMode ? activeToolsList : undefined,stopWhen: searchMode ? stepCountIs(20) : stepCountIs(1),abortSignal})diff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 361dff1b..8e33e917 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -129,6 +129,12 @@ export const parts = pgTable(tool_question_input: json('tool_question_input').$type<any>(),tool_question_output: json('tool_question_output').$type<any>(),+ // Todo tool columns+ tool_todoWrite_input: json('tool_todoWrite_input').$type<any>(),+ tool_todoWrite_output: json('tool_todoWrite_output').$type<any>(),+ tool_todoRead_input: json('tool_todoRead_input').$type<any>(),+ tool_todoRead_output: json('tool_todoRead_output').$type<any>(),+// Dynamic tools (includes MCP and other runtime-defined tools)tool_dynamic_input: json('tool_dynamic_input').$type<any>(),tool_dynamic_output: json('tool_dynamic_output').$type<any>(),diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex 7ded70e2..faf1b449 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -82,7 +82,8 @@ export async function createChatStreamResponse(const researchAgent = researcher({model: context.modelId,searchMode,- abortSignal+ abortSignal,+ writer})// Convert to model messages and apply context window managementdiff --git a/lib/tools/todo.ts b/lib/tools/todo.tsnew file mode 100644index 00000000..e9b03fb6--- /dev/null+++ b/lib/tools/todo.ts@@ -0,0 +1,89 @@+import { tool } from 'ai'+import { z } from 'zod'++// Todo item schema+export const todoItemSchema = z.object({+ id: z.string().describe('Unique identifier for the todo item'),+ content: z.string().describe('The task description'),+ status: z+ .enum(['pending', 'in_progress', 'completed'])+ .describe('Current status of the task'),+ priority: z+ .enum(['high', 'medium', 'low'])+ .default('medium')+ .describe('Priority level of the task'),+ timestamp: z.string().describe('ISO timestamp when the todo was created')+})++export type TodoItem = z.infer<typeof todoItemSchema>++// Global todos storage (persists during the session)+let globalTodos: TodoItem[] = []++// Schema for todo write tool+export const todoWriteInputSchema = z.object({+ todos: z.array(todoItemSchema).describe('The complete list of todos'),+ progressMessage: z+ .string()+ .optional()+ .describe('A brief message about the current progress')+})++// Schema for todo read tool+export const todoReadOutputSchema = z.object({+ todos: z.array(todoItemSchema),+ summary: z.string().describe('Summary of current progress'),+ completedCount: z.number(),+ totalCount: z.number()+})++// Create todo tools+export function createTodoTools() {+ const todoWrite = tool({+ description:+ 'Create or update todos to track progress on complex tasks. Use this to maintain a list of action items.',+ inputSchema: todoWriteInputSchema,+ execute: async ({ todos, progressMessage }) => {+ // Update global todos - ensure priority is always set+ globalTodos = todos.map(todo => ({+ ...todo,+ priority: todo.priority || 'medium'+ }))++ // Calculate progress+ const completedCount = todos.filter(t => t.status === 'completed').length+ const totalCount = todos.length++ return {+ success: true,+ message: progressMessage || `Updated ${totalCount} todos`,+ completedCount,+ totalCount,+ todos: globalTodos+ }+ }+ })++ const todoRead = tool({+ description: 'Read the current list of todos and their status',+ inputSchema: z.object({}),+ execute: async () => {+ const completedCount = globalTodos.filter(+ t => t.status === 'completed'+ ).length+ const totalCount = globalTodos.length++ return {+ todos: globalTodos,+ summary:+ totalCount > 0+ ? `${completedCount} of ${totalCount} tasks completed`+ : 'No tasks created yet',+ completedCount,+ totalCount+ }+ }+ })++ return { todoWrite, todoRead }+}diff --git a/lib/types/ai.ts b/lib/types/ai.tsindex 640184ba..f49b887c 100644--- a/lib/types/ai.ts+++ b/lib/types/ai.ts@@ -3,6 +3,10 @@ import type { InferUITool, UIMessage as AIMessage } from 'ai'import { fetchTool } from '@/lib/tools/fetch'import { askQuestionTool } from '@/lib/tools/question'import { searchTool } from '@/lib/tools/search'+import { type TodoItem } from '@/lib/tools/todo'++// Re-export TodoItem for external use+export type { TodoItem }export type UIMessage<TMetadata = unknown,diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.tsindex b748da1a..6c32e79b 100644--- a/lib/utils/message-mapping.ts+++ b/lib/utils/message-mapping.ts@@ -251,26 +251,79 @@ export function mapUIMessagePartsToDBParts(// Tool-specific parts that are not tool-call or tool-resultcase 'tool-search':+ // These are tool parts with state tracking+ if (!isExtendedToolPart(part)) {+ console.error('Invalid extended tool part:', part)+ return null+ }+ return {+ ...basePart,+ type: part.type,+ tool_toolCallId: part.toolCallId || generateId(),+ tool_state: part.state || ('input-available' as ToolState),+ tool_errorText: part.errorText,+ tool_search_input: part.input,+ tool_search_output: part.output+ }+case 'tool-fetch':+ if (!isExtendedToolPart(part)) {+ console.error('Invalid extended tool part:', part)+ return null+ }+ return {+ ...basePart,+ type: part.type,+ tool_toolCallId: part.toolCallId || generateId(),+ tool_state: part.state || ('input-available' as ToolState),+ tool_errorText: part.errorText,+ tool_fetch_input: part.input,+ tool_fetch_output: part.output+ }+case 'tool-question':- // These are tool parts with state trackingif (!isExtendedToolPart(part)) {console.error('Invalid extended tool part:', part)return null}- const toolPartName = part.type.replace('tool-', '') // Remove 'tool-' prefix- const inputColumn = `tool_${toolPartName}_input` as keyof DBMessagePart- const outputColumn =- `tool_${toolPartName}_output` as keyof DBMessagePart+ return {+ ...basePart,+ type: part.type,+ tool_toolCallId: part.toolCallId || generateId(),+ tool_state: part.state || ('input-available' as ToolState),+ tool_errorText: part.errorText,+ tool_question_input: part.input,+ tool_question_output: part.output+ }++ case 'tool-todoWrite':+ if (!isExtendedToolPart(part)) {+ console.error('Invalid extended tool part:', part)+ return null+ }+ return {+ ...basePart,+ type: part.type,+ tool_toolCallId: part.toolCallId || generateId(),+ tool_state: part.state || ('input-available' as ToolState),+ tool_errorText: part.errorText,+ tool_todoWrite_input: part.input,+ tool_todoWrite_output: part.output+ }+ case 'tool-todoRead':+ if (!isExtendedToolPart(part)) {+ console.error('Invalid extended tool part:', part)+ return null+ }return {...basePart,type: part.type,tool_toolCallId: part.toolCallId || generateId(),tool_state: part.state || ('input-available' as ToolState),tool_errorText: part.errorText,- [inputColumn]: part.input,- [outputColumn]: part.output+ tool_todoRead_input: part.input,+ tool_todoRead_output: part.output}// Data parts@@ -493,6 +546,88 @@ export function mapDBPartToUIMessagePart(}}+ if (toolName === 'todoWrite') {+ if (!part.tool_state) {+ throw new Error(`tool_state is undefined for ${toolName}`)+ }++ switch (part.tool_state) {+ case 'input-streaming':+ return {+ type: 'tool-todoWrite',+ state: 'input-streaming',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoWrite_input!+ }+ case 'input-available':+ return {+ type: 'tool-todoWrite',+ state: 'input-available',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoWrite_input!+ }+ case 'output-available':+ return {+ type: 'tool-todoWrite',+ state: 'output-available',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoWrite_input!,+ output: part.tool_todoWrite_output!+ }+ case 'output-error':+ return {+ type: 'tool-todoWrite',+ state: 'output-error',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoWrite_input!,+ errorText: part.tool_errorText!+ }+ default:+ throw new Error(`Unknown tool state: ${part.tool_state}`)+ }+ }++ if (toolName === 'todoRead') {+ if (!part.tool_state) {+ throw new Error(`tool_state is undefined for ${toolName}`)+ }++ switch (part.tool_state) {+ case 'input-streaming':+ return {+ type: 'tool-todoRead',+ state: 'input-streaming',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoRead_input!+ }+ case 'input-available':+ return {+ type: 'tool-todoRead',+ state: 'input-available',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoRead_input!+ }+ case 'output-available':+ return {+ type: 'tool-todoRead',+ state: 'output-available',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoRead_input!,+ output: part.tool_todoRead_output!+ }+ case 'output-error':+ return {+ type: 'tool-todoRead',+ state: 'output-error',+ toolCallId: part.tool_toolCallId || '',+ input: part.tool_todoRead_input!,+ errorText: part.tool_errorText!+ }+ default:+ throw new Error(`Unknown tool state: ${part.tool_state}`)+ }+ }+// Standard tool-call/tool-result patternif (part.tool_state === 'input-available' ||@@ -554,7 +689,9 @@ function getToolNameFromType(toolName: string): string {search: 'search',fetch: 'fetch',askQuestion: 'question',- question: 'question'+ question: 'question',+ todoWrite: 'todoWrite',+ todoRead: 'todoRead'}// For dynamic tools (MCP and others)@@ -593,6 +730,8 @@ function getOriginalToolName(dbToolName: string): string {search: 'search',fetch: 'fetch',question: 'askQuestion',+ todoWrite: 'todoWrite',+ todoRead: 'todoRead',dynamic: 'dynamic' // For dynamic tools, the actual tool name is stored separately}