From 16b3fb5b92a7ca6885433ab87692dec028ee05a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Sun, 18 Jan 2026 17:26:41 +0000 Subject: [PATCH] feat: improve chat UX (#38) --- apps/backend/internal/orchestrator/service.go | 66 +-- .../task/handlers/message_handlers.go | 53 ++- apps/landing/next-env.d.ts | 6 - apps/packages/ui/src/resizable.tsx | 2 +- apps/web/app/globals.css | 30 ++ apps/web/app/task/[id]/page-client.tsx | 4 +- apps/web/components/kanban-card.tsx | 27 +- .../chat/messages/permission-action-row.tsx | 48 +++ .../messages/permission-request-message.tsx | 46 +-- .../task/chat/messages/tool-call-message.tsx | 37 +- .../web/components/task/sessions-dropdown.tsx | 390 ++++++++---------- apps/web/components/task/task-chat-panel.tsx | 41 +- .../components/task/task-session-sidebar.tsx | 87 +--- .../components/task/task-session-switcher.tsx | 222 ---------- .../components/task/task-state-actions.tsx | 28 +- apps/web/components/task/task-top-bar.tsx | 98 ----- ...use-task-agent.ts => use-session-agent.ts} | 14 +- apps/web/lib/ui/state-icons.tsx | 52 +++ 18 files changed, 453 insertions(+), 798 deletions(-) delete mode 100644 apps/landing/next-env.d.ts create mode 100644 apps/web/components/task/chat/messages/permission-action-row.tsx delete mode 100644 apps/web/components/task/task-session-switcher.tsx rename apps/web/hooks/{use-task-agent.ts => use-session-agent.ts} (92%) create mode 100644 apps/web/lib/ui/state-icons.tsx diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index da42fe509b..10e5cc7d5f 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -629,7 +629,7 @@ func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prom if sessionID == "" { return nil, fmt.Errorf("session_id is required") } - s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateRunning, "", true) + s.setSessionRunning(ctx, taskID, sessionID, nil) result, err := s.executor.Prompt(ctx, taskID, sessionID, prompt) if err != nil { return nil, err @@ -671,6 +671,17 @@ func (s *Service) RespondToPermission(ctx context.Context, sessionID, pendingID, } } + if !cancelled { + session, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + s.logger.Warn("failed to load task session after permission response", + zap.String("session_id", sessionID), + zap.Error(err)) + return nil + } + s.setSessionRunning(ctx, session.TaskID, sessionID, nil) + } + return nil } @@ -1090,6 +1101,32 @@ func (s *Service) updateTaskSessionState(ctx context.Context, taskID, sessionID } } +func (s *Service) setSessionWaitingForInput(ctx context.Context, taskID, sessionID string, _ *v1.TaskState) { + s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateWaitingForInput, "", false) + + if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateReview); err != nil { + s.logger.Error("failed to update task state to REVIEW", + zap.String("task_id", taskID), + zap.Error(err)) + } else { + s.logger.Info("task moved to REVIEW state", + zap.String("task_id", taskID)) + } +} + +func (s *Service) setSessionRunning(ctx context.Context, taskID, sessionID string, _ *v1.TaskState) { + s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateRunning, "", true) + + if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateInProgress); err != nil { + s.logger.Error("failed to update task state to IN_PROGRESS", + zap.String("task_id", taskID), + zap.Error(err)) + } else { + s.logger.Info("task moved to IN_PROGRESS state", + zap.String("task_id", taskID)) + } +} + func (s *Service) finalizeAgentReady(taskID, sessionID string) { ctx := context.Background() if sessionID == "" { @@ -1098,30 +1135,7 @@ func (s *Service) finalizeAgentReady(taskID, sessionID string) { return } - s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateWaitingForInput, "", false) - - task, err := s.taskRepo.GetTask(ctx, taskID) - if err != nil { - s.logger.Error("failed to get task for state check", - zap.String("task_id", taskID), - zap.Error(err)) - return - } - - if task.State == v1.TaskStateInProgress { - if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateReview); err != nil { - s.logger.Error("failed to update task state to REVIEW", - zap.String("task_id", taskID), - zap.Error(err)) - } else { - s.logger.Info("task moved to REVIEW state", - zap.String("task_id", taskID)) - } - } else { - s.logger.Debug("task not in IN_PROGRESS state, skipping REVIEW transition", - zap.String("task_id", taskID), - zap.String("current_state", string(task.State))) - } + s.setSessionWaitingForInput(ctx, taskID, sessionID, nil) } // handleGitStatusUpdated handles git status updates and persists them to agent session metadata @@ -1191,6 +1205,8 @@ func (s *Service) handlePermissionRequest(ctx context.Context, data watcher.Perm return } + s.setSessionWaitingForInput(ctx, data.TaskID, data.TaskSessionID, nil) + if s.messageCreator != nil { _, err := s.messageCreator.CreatePermissionRequestMessage( ctx, diff --git a/apps/backend/internal/task/handlers/message_handlers.go b/apps/backend/internal/task/handlers/message_handlers.go index 66b55a11a3..ff09f8d077 100644 --- a/apps/backend/internal/task/handlers/message_handlers.go +++ b/apps/backend/internal/task/handlers/message_handlers.go @@ -171,36 +171,47 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create message", nil) } - // Auto-forward message as prompt to running agent if orchestrator is available + response, err := ws.NewResponse(msg.ID, msg.Action, message) + if err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to encode response", nil) + } + + // Auto-forward message as prompt to running agent if orchestrator is available. + // This runs async so the WS request can respond immediately. // Use context.WithoutCancel so the prompt continues even if the WebSocket client disconnects. // The user's message is already saved, and agent responses are broadcast via notifications. if h.orchestrator != nil { - promptCtx := context.WithoutCancel(ctx) - _, err := h.orchestrator.PromptTask(promptCtx, req.TaskID, req.TaskSessionID, req.Content) - if err != nil { - if errors.Is(err, executor.ErrExecutionNotFound) { - if resumeErr := h.orchestrator.ResumeTaskSession(promptCtx, req.TaskID, req.TaskSessionID); resumeErr != nil { - h.logger.Warn("failed to resume task session for prompt", - zap.String("task_id", req.TaskID), - zap.String("session_id", req.TaskSessionID), - zap.Error(resumeErr)) - } else { - for attempt := 0; attempt < 3; attempt++ { - time.Sleep(500 * time.Millisecond) - _, err = h.orchestrator.PromptTask(promptCtx, req.TaskID, req.TaskSessionID, req.Content) - if err == nil { - break + taskID := req.TaskID + sessionID := req.TaskSessionID + content := req.Content + go func() { + promptCtx := context.WithoutCancel(ctx) + _, err := h.orchestrator.PromptTask(promptCtx, taskID, sessionID, content) + if err != nil { + if errors.Is(err, executor.ErrExecutionNotFound) { + if resumeErr := h.orchestrator.ResumeTaskSession(promptCtx, taskID, sessionID); resumeErr != nil { + h.logger.Warn("failed to resume task session for prompt", + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.Error(resumeErr)) + } else { + for attempt := 0; attempt < 3; attempt++ { + time.Sleep(500 * time.Millisecond) + _, err = h.orchestrator.PromptTask(promptCtx, taskID, sessionID, content) + if err == nil { + break + } } } } + h.logger.Warn("failed to forward message as prompt to agent", + zap.String("task_id", taskID), + zap.Error(err)) } - h.logger.Warn("failed to forward message as prompt to agent", - zap.String("task_id", req.TaskID), - zap.Error(err)) - } + }() } - return ws.NewResponse(msg.ID, msg.Action, message) + return response, nil } type wsListMessagesRequest struct { diff --git a/apps/landing/next-env.d.ts b/apps/landing/next-env.d.ts deleted file mode 100644 index c4b7818fbb..0000000000 --- a/apps/landing/next-env.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -/// -import "./.next/dev/types/routes.d.ts"; - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/packages/ui/src/resizable.tsx b/apps/packages/ui/src/resizable.tsx index 54deba492b..7be8a0e349 100644 --- a/apps/packages/ui/src/resizable.tsx +++ b/apps/packages/ui/src/resizable.tsx @@ -38,7 +38,7 @@ function ResizableHandle({ div]:rotate-90", + "focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90", className )} {...props} diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index bee55cc7b0..68974cf7bd 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -89,6 +89,9 @@ --sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-border: oklch(0.922 0 0); --sidebar-ring: oklch(0.708 0 0); + --scrollbar-thumb: oklch(0.78 0 0); + --scrollbar-thumb-hover: oklch(0.66 0 0); + --scrollbar-track: oklch(0.96 0 0 / 0.6); } .dark { @@ -123,17 +126,44 @@ --sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-border: oklch(1 0 0 / 10%); --sidebar-ring: oklch(0.556 0 0); + --scrollbar-thumb: oklch(0.48 0 0 / 0.7); + --scrollbar-thumb-hover: oklch(0.62 0 0 / 0.8); + --scrollbar-track: oklch(0.2 0 0 / 0.6); } @layer base { * { @apply border-border outline-ring/50; + scrollbar-width: thin; + scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track); } body { @apply bg-background text-foreground; } } +*::-webkit-scrollbar { + width: 10px; + height: 10px; +} + +*::-webkit-scrollbar-track { + background: var(--scrollbar-track); + border-radius: 999px; +} + +*::-webkit-scrollbar-thumb { + background: var(--scrollbar-thumb); + border-radius: 999px; + border: 2px solid transparent; + background-clip: padding-box; +} + +*::-webkit-scrollbar-thumb:hover { + background: var(--scrollbar-thumb-hover); + background-clip: padding-box; +} + @layer utilities { .kanban-task-pulse { animation: kanban-task-pulse 5s ease-in-out infinite; diff --git a/apps/web/app/task/[id]/page-client.tsx b/apps/web/app/task/[id]/page-client.tsx index be0245c1b8..89d22d29d6 100644 --- a/apps/web/app/task/[id]/page-client.tsx +++ b/apps/web/app/task/[id]/page-client.tsx @@ -9,7 +9,7 @@ import { DebugOverlay } from '@/components/debug-overlay'; import type { Repository, Task } from '@/lib/types/http'; import { DEBUG_UI } from '@/lib/config'; import { useRepositories } from '@/hooks/use-repositories'; -import { useTaskAgent } from '@/hooks/use-task-agent'; +import { useSessionAgent } from '@/hooks/use-session-agent'; import { useSessionResumption } from '@/hooks/use-session-resumption'; import { useSessionAgentctl } from '@/hooks/use-session-agentctl'; import { useAppStore } from '@/components/state-provider'; @@ -64,7 +64,7 @@ export default function TaskPage({ taskSessionState: agentSessionState, handleStartAgent, handleStopAgent, - } = useTaskAgent(task); + } = useSessionAgent(task); const initialSessionId = sessionId ?? taskSessionId ?? null; const effectiveSessionId = activeSessionId ?? initialSessionId; diff --git a/apps/web/components/kanban-card.tsx b/apps/web/components/kanban-card.tsx index 377abd264e..e0a68abea4 100644 --- a/apps/web/components/kanban-card.tsx +++ b/apps/web/components/kanban-card.tsx @@ -2,7 +2,7 @@ import { useDraggable } from '@dnd-kit/core'; import { CSS } from '@dnd-kit/utilities'; -import { IconAlertTriangle, IconCircleCheck, IconCircleX, IconDots, IconLoader2, IconArrowsMaximize } from '@tabler/icons-react'; +import { IconDots, IconArrowsMaximize } from '@tabler/icons-react'; import { Card, CardContent } from '@kandev/ui/card'; import { DropdownMenu, @@ -12,13 +12,15 @@ import { } from '@kandev/ui/dropdown-menu'; import { useMemo } from 'react'; import { useAppStore } from '@/components/state-provider'; +import type { TaskState } from '@/lib/types/http'; import { cn, getRepositoryDisplayName } from '@/lib/utils'; +import { getTaskStateIcon } from '@/lib/ui/state-icons'; export interface Task { id: string; title: string; columnId: string; - state?: string; + state?: TaskState; description?: string; position?: number; repositoryId?: string; @@ -91,26 +93,7 @@ export function KanbanCard({ task, onClick, onEdit, onDelete, onOpenFullPage }: ); const repoName = getRepositoryDisplayName(repository?.local_path); - const statusIcon = (() => { - switch (task.state) { - case 'IN_PROGRESS': - case 'SCHEDULING': - return ; - case 'COMPLETED': - return ; - case 'FAILED': - case 'CANCELLED': - return ; - case 'BLOCKED': - case 'WAITING_FOR_INPUT': - return ; - case 'CREATED': - case 'TODO': - case 'REVIEW': - default: - return null - } - })(); + const statusIcon = getTaskStateIcon(task.state, 'h-4 w-4'); const style = { transform: CSS.Translate.toString(transform), diff --git a/apps/web/components/task/chat/messages/permission-action-row.tsx b/apps/web/components/task/chat/messages/permission-action-row.tsx new file mode 100644 index 0000000000..92bdda7936 --- /dev/null +++ b/apps/web/components/task/chat/messages/permission-action-row.tsx @@ -0,0 +1,48 @@ +'use client'; + +import { IconCheck, IconLoader2, IconX } from '@tabler/icons-react'; +import { Button } from '@kandev/ui/button'; + +type PermissionActionRowProps = { + onApprove: () => void; + onReject: () => void; + isResponding?: boolean; +}; + +export function PermissionActionRow({ + onApprove, + onReject, + isResponding = false, +}: PermissionActionRowProps) { + return ( +
+ + Approve this action? + + + +
+ ); +} diff --git a/apps/web/components/task/chat/messages/permission-request-message.tsx b/apps/web/components/task/chat/messages/permission-request-message.tsx index 0050d65de8..01bd2e1e11 100644 --- a/apps/web/components/task/chat/messages/permission-request-message.tsx +++ b/apps/web/components/task/chat/messages/permission-request-message.tsx @@ -1,16 +1,11 @@ 'use client'; import { useCallback, useState } from 'react'; -import { - IconAlertTriangle, - IconCheck, - IconX, - IconLoader2, -} from '@tabler/icons-react'; -import { Button } from '@kandev/ui/button'; +import { IconAlertTriangle, IconCheck, IconX, IconLoader2 } from '@tabler/icons-react'; import { cn } from '@/lib/utils'; import { getWebSocketClient } from '@/lib/ws/connection'; import type { Message } from '@/lib/types/http'; +import { PermissionActionRow } from './permission-action-row'; type PermissionOption = { option_id: string; @@ -106,7 +101,7 @@ export function PermissionRequestMessage({ comment }: PermissionRequestMessagePr } return ( - Pending Approval + Pending Approval ); }; @@ -134,37 +129,12 @@ export function PermissionRequestMessage({ comment }: PermissionRequestMessagePr {/* Approval buttons - only show when pending */} {isPending && ( -
- - Approve this action? - - - -
+ )} ); } - diff --git a/apps/web/components/task/chat/messages/tool-call-message.tsx b/apps/web/components/task/chat/messages/tool-call-message.tsx index 5359721934..8af25ad0cf 100644 --- a/apps/web/components/task/chat/messages/tool-call-message.tsx +++ b/apps/web/components/task/chat/messages/tool-call-message.tsx @@ -14,11 +14,11 @@ import { IconTerminal2, IconX, } from '@tabler/icons-react'; -import { Button } from '@kandev/ui/button'; import { cn } from '@/lib/utils'; import { getWebSocketClient } from '@/lib/ws/connection'; import type { Message } from '@/lib/types/http'; import type { ToolCallMetadata } from '@/components/task/chat/types'; +import { PermissionActionRow } from './permission-action-row'; type PermissionOption = { option_id: string; @@ -74,7 +74,6 @@ function getStatusIcon(status?: string, permissionStatus?: string) { case 'error': return ; case 'running': - return ; default: return null; } @@ -230,35 +229,11 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP {/* Inline permission approval UI */} {isPermissionPending && ( -
- - Approve this action? - - - -
+ )} ); diff --git a/apps/web/components/task/sessions-dropdown.tsx b/apps/web/components/task/sessions-dropdown.tsx index 1e6674a1fc..18fec250a8 100644 --- a/apps/web/components/task/sessions-dropdown.tsx +++ b/apps/web/components/task/sessions-dropdown.tsx @@ -1,16 +1,7 @@ 'use client'; -import { useCallback, useState, useEffect } from 'react'; -import { useRouter } from 'next/navigation'; -import { - IconStack2, - IconLoader2, - IconCheck, - IconAlertCircle, - IconX, - IconPlus, - IconPlayerStopFilled, -} from '@tabler/icons-react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { IconStack2, IconPlus } from '@tabler/icons-react'; import { Button } from '@kandev/ui/button'; import { DropdownMenu, @@ -24,33 +15,26 @@ import { TaskCreateDialog } from '../task-create-dialog'; import { useAppStore } from '@/components/state-provider'; import { getWebSocketClient } from '@/lib/ws/connection'; import { linkToSession } from '@/lib/links'; +import { useTaskSessions } from '@/hooks/use-task-sessions'; +import type { TaskSession, TaskSessionState } from '@/lib/types/http'; +import { getSessionStateIcon } from '@/lib/ui/state-icons'; type SessionStatus = 'running' | 'waiting_input' | 'complete' | 'failed' | 'cancelled'; -type Session = { - id: string; - number: number; - agentProfile: string; - startedAt: Date; - status: SessionStatus; -}; - -type TaskSessionResponse = { - id: string; - agent_profile_id?: string; - started_at: string; - state: string; -}; - -type ListTaskSessionsResponse = { - sessions: TaskSessionResponse[]; - total: number; +const STATUS_ORDER: Record = { + RUNNING: 1, + STARTING: 1, + WAITING_FOR_INPUT: 2, + CREATED: 3, + COMPLETED: 4, + FAILED: 5, + CANCELLED: 6, }; // Format duration from start time -function formatDuration(startedAt: Date, isRunning: boolean): string { - const now = isRunning ? Date.now() : startedAt.getTime(); - const diff = Math.floor((now - startedAt.getTime()) / 1000); +function formatDuration(startedAt: string, isRunning: boolean, now: number): string { + const start = new Date(startedAt).getTime(); + const diff = Math.floor(((isRunning ? now : start) - start) / 1000); const hours = Math.floor(diff / 3600); const minutes = Math.floor((diff % 3600) / 60); @@ -58,25 +42,11 @@ function formatDuration(startedAt: Date, isRunning: boolean): string { if (hours > 0) { return `${hours}h ${minutes}m`; - } else if (minutes > 0) { + } + if (minutes > 0) { return `${minutes}m ${seconds}s`; - } else { - return `${seconds}s`; - } -} - -function getStatusIcon(status: SessionStatus) { - switch (status) { - case 'running': - return ; - case 'complete': - return ; - case 'waiting_input': - return ; - case 'failed': - case 'cancelled': - return ; } + return `${seconds}s`; } function getStatusLabel(status: SessionStatus) { @@ -94,7 +64,7 @@ function getStatusLabel(status: SessionStatus) { } } -function mapSessionStatus(state: string): SessionStatus { +function mapSessionStatus(state: TaskSessionState): SessionStatus { switch (state) { case 'RUNNING': case 'STARTING': @@ -119,48 +89,37 @@ type SessionsDropdownProps = { taskDescription?: string; }; -export function SessionsDropdown({ taskId, activeSessionId = null, taskTitle = '', taskDescription = '' }: SessionsDropdownProps) { - const [sessions, setSessions] = useState([]); +export function SessionsDropdown({ + taskId, + activeSessionId = null, + taskTitle = '', + taskDescription = '', +}: SessionsDropdownProps) { const [currentTime, setCurrentTime] = useState(() => Date.now()); const [showNewSessionDialog, setShowNewSessionDialog] = useState(false); + const [open, setOpen] = useState(false); const agentProfiles = useAppStore((state) => state.agentProfiles.items); - const router = useRouter(); - const visibleSessions = taskId ? sessions : []; + const setActiveSession = useAppStore((state) => state.setActiveSession); + const { sessions, loadSessions } = useTaskSessions(taskId); - const fetchSessions = useCallback(async (targetTaskId: string) => { - const client = getWebSocketClient(); - if (!client) return; - try { - const response = await client.request('task.session.list', { - task_id: targetTaskId, - }); - const total = response.sessions.length; - const mapped = response.sessions.map((session, index) => { - const label = agentProfiles.find((profile) => profile.id === session.agent_profile_id)?.label - ?? session.agent_profile_id - ?? 'Unknown agent'; - return { - id: session.id, - number: total - index, - agentProfile: label, - startedAt: new Date(session.started_at), - status: mapSessionStatus(session.state), - }; - }); - setSessions(mapped); - } catch (error) { - console.error('Failed to load task sessions:', error); - } + const agentLabelsById = useMemo(() => { + return Object.fromEntries(agentProfiles.map((profile) => [profile.id, profile.label])); }, [agentProfiles]); - const handleOpenChange = useCallback((open: boolean) => { - if (!open || !taskId) return; - fetchSessions(taskId); - }, [fetchSessions, taskId]); + const handleOpenChange = useCallback( + (nextOpen: boolean) => { + setOpen(nextOpen); + if (!nextOpen || !taskId) return; + loadSessions(true); + }, + [loadSessions, taskId] + ); // Update timer every second for running sessions useEffect(() => { - const hasRunningSessions = sessions.some(s => s.status === 'running'); + const hasRunningSessions = sessions.some( + (session) => session.state === 'RUNNING' || session.state === 'STARTING' + ); if (!hasRunningSessions) return; const interval = setInterval(() => { @@ -170,154 +129,169 @@ export function SessionsDropdown({ taskId, activeSessionId = null, taskTitle = ' return () => clearInterval(interval); }, [sessions]); - const handleCancelSession = (e: React.MouseEvent, sessionId: string) => { - e.stopPropagation(); - // TODO: Implement session cancellation - console.log('Cancel session:', sessionId); - }; + const updateUrl = useCallback((sessionId: string) => { + if (typeof window === 'undefined') return; + window.history.replaceState({}, '', linkToSession(sessionId)); + }, []); - const handleSelectSession = async (sessionId: string) => { + const handleSelectSession = (sessionId: string) => { if (!taskId) return; - const client = getWebSocketClient(); - if (!client) return; - - try { - await client.request('task.session.resume', { - task_id: taskId, - session_id: sessionId, - }, 15000); - await fetchSessions(taskId); - router.push(linkToSession(sessionId)); - } catch (error) { - console.error('Failed to resume task session:', error); - } + setActiveSession(taskId, sessionId); + updateUrl(sessionId); + setOpen(false); }; - const handleCreateSession = (data: { + const handleCreateSession = async (data: { prompt: string; agentProfileId: string; executorId: string; environmentId: string; }) => { - // TODO: Implement session creation - console.log('Create new session:', data); + if (!taskId) return; + const client = getWebSocketClient(); + if (!client) return; + + try { + const response = await client.request<{ + success: boolean; + task_id: string; + agent_instance_id: string; + session_id?: string; + state: string; + }>( + 'orchestrator.start', + { + task_id: taskId, + agent_profile_id: data.agentProfileId, + prompt: data.prompt.trim(), + }, + 15000 + ); + + await loadSessions(true); + + if (response?.session_id) { + setActiveSession(taskId, response.session_id); + updateUrl(response.session_id); + } + } catch (error) { + console.error('Failed to create task session:', error); + } + }; + + const sortedSessions = useMemo(() => { + const visibleSessions = taskId ? sessions : []; + return [...visibleSessions].sort((a, b) => { + const orderDelta = (STATUS_ORDER[a.state] ?? 99) - (STATUS_ORDER[b.state] ?? 99); + if (orderDelta !== 0) return orderDelta; + return new Date(b.started_at).getTime() - new Date(a.started_at).getTime(); + }); + }, [sessions, taskId]); + + const resolveAgentLabel = (session: TaskSession) => { + if (session.agent_profile_id && agentLabelsById[session.agent_profile_id]) { + return agentLabelsById[session.agent_profile_id]; + } + return 'Unknown agent'; }; return ( <> - - - - - -
- Task Sessions - -
- -
- {visibleSessions.length === 0 ? ( -
- No sessions yet -
- ) : ( -
- {visibleSessions.map((session) => { - const duration = formatDuration(session.startedAt, session.status === 'running'); - // Use currentTime to force re-render when timer updates - void currentTime; + + + {sortedSessions.length} + + + + +
+ Sessions + +
+ +
+ {sortedSessions.length === 0 ? ( +
+ No sessions yet +
+ ) : ( +
+ {sortedSessions.map((session, index) => { + const status = mapSessionStatus(session.state); + const duration = formatDuration( + session.started_at, + status === 'running', + currentTime + ); + const showDuration = duration !== '0s'; + const number = sortedSessions.length - index; - return ( -
handleSelectSession(session.id)} - className={`w-full flex items-center gap-3 px-2 py-1.5 hover:bg-muted/50 rounded-sm cursor-pointer transition-colors ${ - activeSessionId === session.id ? 'bg-muted/50' : '' - }`} - > - {/* Session Number - Fixed width */} - - #{session.number} - + return ( +
handleSelectSession(session.id)} + className={`w-full flex items-center gap-3 px-2 py-1.5 hover:bg-muted/50 rounded-sm cursor-pointer transition-colors ${activeSessionId === session.id ? 'bg-muted/50' : '' + }`} + > + + #{number} + - {/* Agent Profile - Flexible width */} - - {session.agentProfile} - + + {resolveAgentLabel(session)} + - {/* Duration - Fixed width */} - - {duration} - + {showDuration ? + + {duration} + + : ''} - {/* Status Icon - Fixed width with tooltip */} -
- - -
{getStatusIcon(session.status)}
-
- - {getStatusLabel(session.status)} - -
-
- - {/* Cancel Button - Only for running sessions */} -
- {session.status === 'running' && ( +
- +
{getSessionStateIcon(session.state, 'h-3.5 w-3.5')}
- Cancel session + {getStatusLabel(status)}
- )} +
-
- ); - })} -
- )} -
- - + ); + })} +
+ )} +
+ + - - + + ); } diff --git a/apps/web/components/task/task-chat-panel.tsx b/apps/web/components/task/task-chat-panel.tsx index 0921e3e7bc..b986ae9cb8 100644 --- a/apps/web/components/task/task-chat-panel.tsx +++ b/apps/web/components/task/task-chat-panel.tsx @@ -27,6 +27,7 @@ import { useSessionMessages } from '@/hooks/use-session-messages'; import { MessageRenderer } from '@/components/task/chat/message-renderer'; import { RunningIndicator } from '@/components/task/chat/messages/running-indicator'; import { TodoSummary } from '@/components/task/chat/todo-summary'; +import { SessionsDropdown } from '@/components/task/sessions-dropdown'; type AgentOption = { id: string; @@ -60,7 +61,9 @@ export function TaskChatPanel({ const task = useTask(session?.task_id ?? null); const taskId = session?.task_id ?? null; const taskDescription = task?.description ?? null; - const isWorking = session?.state === 'STARTING' || session?.state === 'RUNNING'; + const isStarting = session?.state === 'STARTING'; + const isWorking = isStarting || session?.state === 'RUNNING'; + const isAgentBusy = session?.state === 'CREATED' || session?.state === 'RUNNING'; // Fetch messages for this session const { messages, isLoading: messagesLoading } = useSessionMessages(resolvedSessionId); @@ -317,7 +320,11 @@ export function TaskChatPanel({ value={messageInput} onChange={setMessageInput} onSubmit={() => handleSubmit()} - placeholder="Write to submit work to the agent..." + placeholder={ + agentMessageCount > 0 + ? 'Continue working on this task...' + : 'Write to submit work to the agent...' + } planModeEnabled={planModeEnabled} />
@@ -338,7 +345,7 @@ export function TaskChatPanel({ - @@ -360,7 +367,7 @@ export function TaskChatPanel({ variant="outline" size="icon" className={cn( - 'h-9 w-9 cursor-pointer', + 'h-7 w-7 cursor-pointer', planModeEnabled && 'bg-primary/15 text-primary border-primary/40 shadow-[0_0_0_1px_rgba(59,130,246,0.35)]' )} @@ -377,16 +384,36 @@ export function TaskChatPanel({
+ - Add attachments - - + +
diff --git a/apps/web/components/task/task-session-sidebar.tsx b/apps/web/components/task/task-session-sidebar.tsx index b52fc7fa80..135096ce99 100644 --- a/apps/web/components/task/task-session-sidebar.tsx +++ b/apps/web/components/task/task-session-sidebar.tsx @@ -2,16 +2,13 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import type { TaskState } from '@/lib/types/http'; -import { TaskSessionSwitcher } from './task-session-switcher'; import { TaskSwitcher } from './task-switcher'; import { Button } from '@kandev/ui/button'; import { IconPlus } from '@tabler/icons-react'; import { TaskCreateDialog } from '@/components/task-create-dialog'; import { useAppStore, useAppStoreApi } from '@/components/state-provider'; -import { getWebSocketClient } from '@/lib/ws/connection'; import { linkToSession } from '@/lib/links'; import { listTaskSessions } from '@/lib/http'; -import { useTaskSessions } from '@/hooks/use-task-sessions'; import { useTasks } from '@/hooks/use-tasks'; type TaskSummary = { @@ -36,8 +33,8 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP const columns = useAppStore((state) => state.kanban.columns); const workspaces = useAppStore((state) => state.workspaces.items); const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId); - const setActiveSession = useAppStore((state) => state.setActiveSession); const setActiveTask = useAppStore((state) => state.setActiveTask); + const setActiveSession = useAppStore((state) => state.setActiveSession); const setTaskSessionsForTask = useAppStore((state) => state.setTaskSessionsForTask); const setTaskSessionsLoading = useAppStore((state) => state.setTaskSessionsLoading); const selectedTaskId = useMemo(() => { @@ -46,10 +43,7 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP } return activeTaskId; }, [activeSessionId, activeTaskId, sessionsById]); - const { sessions: selectedSessions, loadSessions: loadSelectedSessions } = useTaskSessions(selectedTaskId ?? null); const [taskDialogOpen, setTaskDialogOpen] = useState(false); - const [sessionDialogOpen, setSessionDialogOpen] = useState(false); - const [sessionTask, setSessionTask] = useState(null); const store = useAppStoreApi(); const workspaceName = useMemo(() => { @@ -70,16 +64,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP })); }, [repositoriesByWorkspace, tasks, workspaceId]); - useEffect(() => { - if (!selectedTaskId) return; - const client = getWebSocketClient(); - if (!client) return; - const unsubscribers = selectedSessions.map((session) => client.subscribeSession(session.id)); - return () => { - unsubscribers.forEach((unsubscribe) => unsubscribe()); - }; - }, [selectedSessions, selectedTaskId]); - const updateUrl = useCallback((sessionId: string) => { if (typeof window === 'undefined') return; window.history.replaceState({}, '', linkToSession(sessionId)); @@ -110,13 +94,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP [setTaskSessionsForTask, setTaskSessionsLoading, store] ); - const handleSelectSession = useCallback( - (taskId: string, sessionId: string) => { - setActiveSession(taskId, sessionId); - updateUrl(sessionId); - }, - [setActiveSession, updateUrl] - ); const handleSelectTask = useCallback( async (taskId: string) => { @@ -132,40 +109,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP [loadTaskSessionsForTask, setActiveSession, setActiveTask, updateUrl] ); - const handleCreateSession = useCallback( - async (taskId: string, data: { prompt: string; agentProfileId: string; executorId: string; environmentId: string }) => { - const client = getWebSocketClient(); - if (!client) return; - - try { - const response = await client.request<{ - success: boolean; - task_id: string; - agent_instance_id: string; - session_id?: string; - state: string; - }>( - 'orchestrator.start', - { - task_id: taskId, - agent_profile_id: data.agentProfileId, - prompt: data.prompt.trim(), - }, - 15000 - ); - - await loadSelectedSessions(true); - - if (response?.session_id) { - setActiveSession(taskId, response.session_id); - updateUrl(response.session_id); - } - } catch (error) { - console.error('Failed to create task session:', error); - } - }, - [loadSelectedSessions, setActiveSession, updateUrl] - ); return ( <> @@ -183,17 +126,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP
- { - if (!selectedTaskId) return; - const task = tasksWithRepositories.find((item) => item.id === selectedTaskId) ?? null; - setSessionTask(task); - setSessionDialogOpen(true); - }} - /> ({ id: column.id, title: column.title }))} @@ -242,23 +174,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP } }} /> - ({ id: column.id, title: column.title }))} - initialValues={{ - title: sessionTask?.title ?? '', - description: sessionTask?.description ?? '', - }} - onCreateSession={(data) => { - if (!sessionTask) return; - handleCreateSession(sessionTask.id, data); - }} - /> ); } diff --git a/apps/web/components/task/task-session-switcher.tsx b/apps/web/components/task/task-session-switcher.tsx deleted file mode 100644 index 607f7aa5bc..0000000000 --- a/apps/web/components/task/task-session-switcher.tsx +++ /dev/null @@ -1,222 +0,0 @@ -'use client'; - -import { useEffect, useMemo, useState } from 'react'; -import { IconCheck, IconLoader2, IconAlertCircle, IconPlayerStopFilled, IconPlus, IconX } from '@tabler/icons-react'; -import type { TaskSession, TaskSessionState } from '@/lib/types/http'; -import { Badge } from '@kandev/ui/badge'; -import { Command, CommandGroup, CommandItem, CommandList } from '@kandev/ui/command'; -import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; -import { useAppStore } from '@/components/state-provider'; - -type SessionSwitcherProps = { - taskId: string | null; - sessions: TaskSession[]; - onSelectSession: (taskId: string, sessionId: string) => void; - showHeader?: boolean; - onCreateSession?: () => void; -}; - -const STATUS_ORDER: Record = { - RUNNING: 1, - STARTING: 1, - WAITING_FOR_INPUT: 2, - CREATED: 3, - COMPLETED: 4, - FAILED: 5, - CANCELLED: 6, -}; - -type SessionStatus = 'running' | 'waiting_input' | 'complete' | 'failed' | 'cancelled' | 'starting'; - -function getSessionStatus(state: TaskSessionState): SessionStatus { - switch (state) { - case 'RUNNING': - return 'running'; - case 'STARTING': - return 'starting'; - case 'WAITING_FOR_INPUT': - return 'waiting_input'; - case 'COMPLETED': - return 'complete'; - case 'FAILED': - return 'failed'; - case 'CANCELLED': - return 'cancelled'; - default: - return 'waiting_input'; - } -} - -function getSessionIcon(status: SessionStatus) { - switch (status) { - case 'running': - case 'starting': - return ; - case 'waiting_input': - return ; - case 'complete': - return ; - case 'failed': - case 'cancelled': - return ; - default: - return null; - } -} - -function formatSessionLabel(index: number, total: number) { - const number = total - index; - return `#${number}`; -} - -function formatDuration(startedAt: string, isRunning: boolean, now: number) { - const start = new Date(startedAt).getTime(); - const diff = Math.floor(((isRunning ? now : start) - start) / 1000); - const hours = Math.floor(diff / 3600); - const minutes = Math.floor((diff % 3600) / 60); - const seconds = diff % 60; - - if (hours > 0) { - return `${hours}h ${minutes}m`; - } - if (minutes > 0) { - return `${minutes}m ${seconds}s`; - } - return `${seconds}s`; -} - -export function TaskSessionSwitcher({ - taskId, - sessions, - onSelectSession, - showHeader = true, - onCreateSession, -}: SessionSwitcherProps) { - const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); - const agentProfiles = useAppStore((state) => state.agentProfiles.items); - const agentLabelsById = useMemo(() => { - return Object.fromEntries(agentProfiles.map((profile) => [profile.id, profile.label])); - }, [agentProfiles]); - const [currentTime, setCurrentTime] = useState(() => Date.now()); - const sortedSessions = useMemo(() => { - return [...sessions].sort((a, b) => { - const orderDelta = (STATUS_ORDER[a.state] ?? 99) - (STATUS_ORDER[b.state] ?? 99); - if (orderDelta !== 0) return orderDelta; - return new Date(b.started_at).getTime() - new Date(a.started_at).getTime(); - }); - }, [sessions]); - - const resolveAgentLabel = (session: TaskSession) => { - if (session.agent_profile_id && agentLabelsById[session.agent_profile_id]) { - return agentLabelsById[session.agent_profile_id]; - } - return 'Unknown agent'; - }; - - useEffect(() => { - const hasRunning = sortedSessions.some((session) => - ['RUNNING', 'STARTING'].includes(session.state) - ); - if (!hasRunning) return; - const interval = setInterval(() => { - setCurrentTime(Date.now()); - }, 1000); - return () => clearInterval(interval); - }, [sortedSessions]); - - return ( -
- {showHeader ? ( -
- Sessions -
- {onCreateSession ? ( - - - - - New session - - ) : null} - - {sortedSessions.length} - -
-
- ) : null} - {sortedSessions.length === 0 ? ( -
No sessions yet.
- ) : ( - - - - {sortedSessions.map((session, index) => { - const isActive = session.id === activeSessionId; - const agentLabel = resolveAgentLabel(session); - const status = getSessionStatus(session.state); - const duration = formatDuration( - session.started_at, - status === 'running' || status === 'starting', - currentTime - ); - return ( - { - if (!taskId) return; - onSelectSession(taskId, session.id); - }} - className={`group flex w-full cursor-pointer items-center gap-3 px-2 py-1.5 rounded-sm text-left transition-colors ${ - isActive ? 'bg-muted' : 'hover:bg-muted/30' - }`} - > - - {formatSessionLabel(index, sortedSessions.length)} - - - {agentLabel} - - - {duration} - -
-
- {getSessionIcon(status)} -
- {(status === 'running' || status === 'starting') && ( - - - - - Stop session - - )} -
- -
- ); - })} -
-
-
- )} -
- ); -} diff --git a/apps/web/components/task/task-state-actions.tsx b/apps/web/components/task/task-state-actions.tsx index 5f77bc7e2a..f5fdd647c6 100644 --- a/apps/web/components/task/task-state-actions.tsx +++ b/apps/web/components/task/task-state-actions.tsx @@ -1,40 +1,20 @@ 'use client'; -import { IconAlertCircle, IconCheck, IconEye, IconLoader2, IconX } from '@tabler/icons-react'; -import type { TaskState } from '@/lib/types/http'; +import { IconCheck } from '@tabler/icons-react'; import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; +import { getTaskStateIcon } from '@/lib/ui/state-icons'; +import type { TaskState } from '@/lib/types/http'; type TaskStateActionsProps = { state?: TaskState; onMarkDone?: () => void; }; -function getStateIcon(state?: TaskState) { - switch (state) { - case 'CREATED': - case 'SCHEDULING': - case 'IN_PROGRESS': - return ; - case 'REVIEW': - return ; - case 'WAITING_FOR_INPUT': - case 'BLOCKED': - return ; - case 'COMPLETED': - return ; - case 'FAILED': - case 'CANCELLED': - return ; - default: - return ; - } -} - export function TaskStateActions({ state, onMarkDone }: TaskStateActionsProps) { return (
- {getStateIcon(state)} + {getTaskStateIcon(state)}
diff --git a/apps/web/components/task/task-top-bar.tsx b/apps/web/components/task/task-top-bar.tsx index 2eaa3b87d3..67c368b582 100644 --- a/apps/web/components/task/task-top-bar.tsx +++ b/apps/web/components/task/task-top-bar.tsx @@ -35,7 +35,6 @@ import { import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@kandev/ui/select'; import { Popover, PopoverContent, PopoverTrigger } from '@kandev/ui/popover'; -import { SessionsDropdown } from './sessions-dropdown'; import { CommitStatBadge, LineStat } from '@/components/diff-stat'; import { useAppStore } from '@/components/state-provider'; import { useSessionGitStatus } from '@/hooks/use-session-git-status'; @@ -58,10 +57,8 @@ type TaskTopBarProps = { }; const TaskTopBar = memo(function TaskTopBar({ - taskId, activeSessionId, taskTitle, - taskDescription, baseBranch, onStartAgent, onStopAgent, @@ -147,12 +144,6 @@ const TaskTopBar = memo(function TaskTopBar({ )} {taskTitle ?? 'Task details'} - {displayBranch && ( @@ -274,95 +265,6 @@ const TaskTopBar = memo(function TaskTopBar({
- {/* Start/Stop Agent Button */} - {isAgentRunning ? ( - - - - - Stop the agent - - ) : ( - - - - - - {agentProfiles.length === 0 ? 'Add an agent profile to start.' : 'Start the agent on this task'} - - - )} - - - - - Start Agent - -
-
- Select an agent profile to start a new session. -
- -
- - - - -
-
- {/* Editor Button */} diff --git a/apps/web/hooks/use-task-agent.ts b/apps/web/hooks/use-session-agent.ts similarity index 92% rename from apps/web/hooks/use-task-agent.ts rename to apps/web/hooks/use-session-agent.ts index dcb8ffc998..78bde25e09 100644 --- a/apps/web/hooks/use-task-agent.ts +++ b/apps/web/hooks/use-session-agent.ts @@ -5,7 +5,7 @@ import type { TaskSessionState, Task, TaskSession } from '@/lib/types/http'; const EMPTY_SESSIONS: TaskSession[] = []; -interface UseTaskAgentReturn { +interface UseSessionAgentReturn { isAgentRunning: boolean; isAgentLoading: boolean; taskSessionId: string | null; @@ -16,7 +16,7 @@ interface UseTaskAgentReturn { handleStopAgent: () => Promise; } -export function useTaskAgent(task: Task | null): UseTaskAgentReturn { +export function useSessionAgent(task: Task | null): UseSessionAgentReturn { const [isAgentRunning, setIsAgentRunning] = useState(false); const [isAgentLoading, setIsAgentLoading] = useState(false); const [taskSessionId, setAgentSessionId] = useState(null); @@ -45,7 +45,7 @@ export function useTaskAgent(task: Task | null): UseTaskAgentReturn { setWorktreePath(activeSession.worktree_path ?? null); setWorktreeBranch(activeSession.worktree_branch ?? null); } - }, [activeSession?.worktree_path, activeSession?.worktree_branch]); + }, [activeSession]); useEffect(() => { setIsAgentRunning(false); @@ -77,7 +77,7 @@ export function useTaskAgent(task: Task | null): UseTaskAgentReturn { session_id?: string; }>('task.execution', { task_id: task.id }); - console.log('[useTaskAgent] Task execution check:', response); + console.log('[useSessionAgent] Task execution check:', response); if (response.has_execution) { setIsAgentRunning(true); if (response.state) { @@ -92,7 +92,7 @@ export function useTaskAgent(task: Task | null): UseTaskAgentReturn { setTaskSessionState(null); } } catch (err) { - console.error('[useTaskAgent] Failed to check task execution:', err); + console.error('[useSessionAgent] Failed to check task execution:', err); } }; @@ -124,7 +124,7 @@ export function useTaskAgent(task: Task | null): UseTaskAgentReturn { worktree_path?: string; worktree_branch?: string; } - console.log('[useTaskAgent] orchestrator.start request', { + console.log('[useSessionAgent] orchestrator.start request', { taskId: task.id, agentProfileId, promptLength: prompt?.length ?? 0, @@ -134,7 +134,7 @@ export function useTaskAgent(task: Task | null): UseTaskAgentReturn { agent_profile_id: agentProfileId, prompt: prompt ?? task.description ?? '', }, 15000); - console.log('[useTaskAgent] orchestrator.start response', response); + console.log('[useSessionAgent] orchestrator.start response', response); setIsAgentRunning(true); setTaskSessionState(response.state as TaskSessionState); if (response?.session_id) { diff --git a/apps/web/lib/ui/state-icons.tsx b/apps/web/lib/ui/state-icons.tsx new file mode 100644 index 0000000000..b93b4146fa --- /dev/null +++ b/apps/web/lib/ui/state-icons.tsx @@ -0,0 +1,52 @@ +import type { ComponentType } from 'react'; +import { IconAlertCircle, IconCheck, IconLoader2, IconX } from '@tabler/icons-react'; +import type { TaskSessionState, TaskState } from '@/lib/types/http'; +import { cn } from '@/lib/utils'; + +type IconConfig = { + Icon: ComponentType<{ className?: string }>; + className: string; +}; + +const TASK_STATE_ICONS: Record = { + CREATED: { Icon: IconLoader2, className: 'text-blue-500 animate-spin' }, + SCHEDULING: { Icon: IconLoader2, className: 'text-blue-500 animate-spin' }, + IN_PROGRESS: { Icon: IconLoader2, className: 'text-blue-500 animate-spin' }, + REVIEW: { Icon: IconCheck, className: 'text-yellow-500' }, + BLOCKED: { Icon: IconAlertCircle, className: 'text-yellow-500' }, + WAITING_FOR_INPUT: { Icon: IconCheck, className: 'text-yellow-500' }, + COMPLETED: { Icon: IconCheck, className: 'text-green-500' }, + FAILED: { Icon: IconX, className: 'text-red-500' }, + CANCELLED: { Icon: IconX, className: 'text-red-500' }, + TODO: { Icon: IconAlertCircle, className: 'text-muted-foreground' }, +}; + +const SESSION_STATE_ICONS: Record = { + CREATED: { Icon: IconLoader2, className: 'text-blue-500 animate-spin' }, + STARTING: { Icon: IconLoader2, className: 'text-blue-500 animate-spin' }, + RUNNING: { Icon: IconLoader2, className: 'text-blue-500 animate-spin' }, + WAITING_FOR_INPUT: { Icon: IconCheck, className: 'text-yellow-500' }, + COMPLETED: { Icon: IconCheck, className: 'text-green-500' }, + FAILED: { Icon: IconX, className: 'text-red-500' }, + CANCELLED: { Icon: IconX, className: 'text-red-500' }, +}; + +const DEFAULT_TASK_ICON: IconConfig = { + Icon: IconAlertCircle, + className: 'text-muted-foreground', +}; + +const DEFAULT_SESSION_ICON: IconConfig = { + Icon: IconAlertCircle, + className: 'text-muted-foreground', +}; + +export function getTaskStateIcon(state?: TaskState, className?: string) { + const config = state ? TASK_STATE_ICONS[state] ?? DEFAULT_TASK_ICON : DEFAULT_TASK_ICON; + return ; +} + +export function getSessionStateIcon(state?: TaskSessionState, className?: string) { + const config = state ? SESSION_STATE_ICONS[state] ?? DEFAULT_SESSION_ICON : DEFAULT_SESSION_ICON; + return ; +}