feat: improve chat UX (#38)

This commit is contained in:
Carlos Florêncio
2026-01-18 17:26:41 +00:00
committed by GitHub
parent 18f4b4e6fb
commit 16b3fb5b92
18 changed files with 453 additions and 798 deletions
+41 -25
View File
@@ -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,
@@ -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 {
-6
View File
@@ -1,6 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
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.
+1 -1
View File
@@ -38,7 +38,7 @@ function ResizableHandle({
<ResizablePrimitive.PanelResizeHandle
data-slot="resizable-handle"
className={cn(
"bg-border 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",
"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}
+30
View File
@@ -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;
+2 -2
View File
@@ -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;
+5 -22
View File
@@ -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 <IconLoader2 className="h-4 w-4 animate-spin text-[color:var(--accent)]" />;
case 'COMPLETED':
return <IconCircleCheck className="h-4 w-4 text-emerald-500" />;
case 'FAILED':
case 'CANCELLED':
return <IconCircleX className="h-4 w-4 text-red-500" />;
case 'BLOCKED':
case 'WAITING_FOR_INPUT':
return <IconAlertTriangle className="h-4 w-4 text-yellow-500" />;
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),
@@ -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 (
<div className="flex items-center gap-2 px-3 py-2 border-t border-amber-500/30 bg-amber-500/10">
<span className="text-xs text-amber-600 dark:text-amber-400 flex-1">
Approve this action?
</span>
<Button
size="sm"
variant="outline"
onClick={onReject}
disabled={isResponding}
className="h-7 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
>
<IconX className="h-4 w-4 mr-1 text-red-500" />
Deny
</Button>
<Button
size="sm"
variant="outline"
onClick={onApprove}
disabled={isResponding}
className="h-7 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
>
{isResponding ? (
<IconLoader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<IconCheck className="h-4 w-4 mr-1 text-green-500" />
)}
Approve
</Button>
</div>
);
}
@@ -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 (
<span className="inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400">
<IconLoader2 className="h-3 w-3 animate-spin" /> Pending Approval
Pending Approval
</span>
);
};
@@ -134,37 +129,12 @@ export function PermissionRequestMessage({ comment }: PermissionRequestMessagePr
{/* Approval buttons - only show when pending */}
{isPending && (
<div className="flex items-center gap-2 px-3 py-2 border-t border-amber-500/30 bg-amber-500/10">
<span className="text-xs text-amber-600 dark:text-amber-400 flex-1">
Approve this action?
</span>
<Button
size="sm"
variant="ghost"
onClick={handleReject}
disabled={isResponding}
className="h-7 px-2 text-red-600 hover:text-red-700 hover:bg-red-500/10"
>
<IconX className="h-4 w-4 mr-1" />
Deny
</Button>
<Button
size="sm"
variant="ghost"
onClick={handleApprove}
disabled={isResponding}
className="h-7 px-2 text-green-600 hover:text-green-700 hover:bg-green-500/10"
>
{isResponding ? (
<IconLoader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<IconCheck className="h-4 w-4 mr-1" />
)}
Approve
</Button>
</div>
<PermissionActionRow
onApprove={handleApprove}
onReject={handleReject}
isResponding={isResponding}
/>
)}
</div>
);
}
@@ -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 <IconX className="h-3.5 w-3.5 text-red-500" />;
case 'running':
return <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
default:
return null;
}
@@ -230,35 +229,11 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP
{/* Inline permission approval UI */}
{isPermissionPending && (
<div className="flex items-center gap-2 px-3 py-2 border-t border-amber-500/30 bg-amber-500/10">
<span className="text-xs text-amber-600 dark:text-amber-400 flex-1">
Approve this action?
</span>
<Button
size="sm"
variant="ghost"
onClick={handleReject}
disabled={isResponding}
className="h-7 px-2 text-red-600 hover:text-red-700 hover:bg-red-500/10"
>
<IconX className="h-4 w-4 mr-1" />
Deny
</Button>
<Button
size="sm"
variant="ghost"
onClick={handleApprove}
disabled={isResponding}
className="h-7 px-2 text-green-600 hover:text-green-700 hover:bg-green-500/10"
>
{isResponding ? (
<IconLoader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<IconCheck className="h-4 w-4 mr-1" />
)}
Approve
</Button>
</div>
<PermissionActionRow
onApprove={handleApprove}
onReject={handleReject}
isResponding={isResponding}
/>
)}
</div>
);
+182 -208
View File
@@ -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<TaskSessionState, number> = {
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 <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
case 'complete':
return <IconCheck className="h-3.5 w-3.5 text-green-500" />;
case 'waiting_input':
return <IconAlertCircle className="h-3.5 w-3.5 text-yellow-500" />;
case 'failed':
case 'cancelled':
return <IconX className="h-3.5 w-3.5 text-red-500" />;
}
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<Session[]>([]);
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<ListTaskSessionsResponse>('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 (
<>
<DropdownMenu onOpenChange={handleOpenChange}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 gap-1.5 px-2 cursor-pointer hover:bg-muted/40 border border-border"
>
<IconStack2 className="h-4 w-4 text-muted-foreground" />
<Badge variant="secondary" className="h-5 px-1.5 text-xs font-normal">
{visibleSessions.length}
</Badge>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-[480px]">
<div className="flex items-center justify-between px-2 py-1.5">
<span className="text-xs font-medium text-muted-foreground">Task Sessions</span>
<button
type="button"
onClick={() => setShowNewSessionDialog(true)}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
<DropdownMenu open={open} onOpenChange={handleOpenChange}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40 border border-border"
>
<IconPlus className="h-3.5 w-3.5" />
New session
</button>
</div>
<DropdownMenuSeparator />
<div className="max-h-[300px] overflow-y-auto">
{visibleSessions.length === 0 ? (
<div className="px-2 py-6 text-center text-sm text-muted-foreground">
No sessions yet
</div>
) : (
<div className="space-y-0.5">
{visibleSessions.map((session) => {
const duration = formatDuration(session.startedAt, session.status === 'running');
// Use currentTime to force re-render when timer updates
void currentTime;
<IconStack2 className="h-4 w-4 text-muted-foreground" />
<Badge variant="secondary" className="h-5 px-1.5 text-xs font-normal">
{sortedSessions.length}
</Badge>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-auto min-w-[240px] max-w-[420px]">
<div className="flex items-center justify-between px-2 py-0">
<span className="text-xs font-medium text-muted-foreground">Sessions</span>
<button
type="button"
onClick={() => setShowNewSessionDialog(true)}
className="flex items-center gap-1 rounded-md border border-border/60 px-2 py-1 text-xs text-muted-foreground hover:text-foreground hover:border-border transition-colors cursor-pointer"
>
<IconPlus className="h-3.5 w-3.5" />
New
</button>
</div>
<DropdownMenuSeparator />
<div className="max-h-[300px] overflow-y-auto">
{sortedSessions.length === 0 ? (
<div className="px-2 py-6 text-center text-sm text-muted-foreground">
No sessions yet
</div>
) : (
<div className="space-y-0.5">
{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 (
<div
key={session.id}
onClick={() => 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 */}
<span className="text-xs font-medium text-muted-foreground w-8 shrink-0">
#{session.number}
</span>
return (
<div
key={session.id}
onClick={() => 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' : ''
}`}
>
<span className="text-xs font-medium text-muted-foreground w-8 shrink-0">
#{number}
</span>
{/* Agent Profile - Flexible width */}
<span className="text-xs text-foreground flex-1 text-left truncate">
{session.agentProfile}
</span>
<span className="text-xs text-foreground flex-1 text-left">
{resolveAgentLabel(session)}
</span>
{/* Duration - Fixed width */}
<span className="text-xs text-muted-foreground w-16 text-right shrink-0">
{duration}
</span>
{showDuration ?
<span className="text-xs text-muted-foreground w-16 text-right shrink-0">
{duration}
</span>
: ''}
{/* Status Icon - Fixed width with tooltip */}
<div className="w-5 shrink-0 flex items-center justify-center">
<Tooltip>
<TooltipTrigger asChild>
<div>{getStatusIcon(session.status)}</div>
</TooltipTrigger>
<TooltipContent side="left">
{getStatusLabel(session.status)}
</TooltipContent>
</Tooltip>
</div>
{/* Cancel Button - Only for running sessions */}
<div className="w-7 shrink-0 flex items-center justify-center">
{session.status === 'running' && (
<div className="w-5 shrink-0 flex items-center justify-center">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={(e) => handleCancelSession(e, session.id)}
className="h-5 w-5 flex items-center justify-center rounded-md border border-border bg-background text-muted-foreground hover:text-destructive hover:border-destructive transition-colors cursor-pointer"
>
<IconPlayerStopFilled className="h-3 w-3" />
</button>
<div>{getSessionStateIcon(session.state, 'h-3.5 w-3.5')}</div>
</TooltipTrigger>
<TooltipContent side="left">Cancel session</TooltipContent>
<TooltipContent side="left">{getStatusLabel(status)}</TooltipContent>
</Tooltip>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
</DropdownMenuContent>
</DropdownMenu>
);
})}
</div>
)}
</div>
</DropdownMenuContent>
</DropdownMenu>
<TaskCreateDialog
open={showNewSessionDialog}
onOpenChange={setShowNewSessionDialog}
mode="session"
workspaceId={null}
boardId={null}
defaultColumnId={null}
columns={[]}
onCreateSession={handleCreateSession}
initialValues={{
title: taskTitle,
description: taskDescription,
}}
/>
</>
<TaskCreateDialog
open={showNewSessionDialog}
onOpenChange={setShowNewSessionDialog}
mode="session"
workspaceId={null}
boardId={null}
defaultColumnId={null}
columns={[]}
onCreateSession={handleCreateSession}
initialValues={{
title: taskTitle,
description: taskDescription,
}}
/>
</>
);
}
+34 -7
View File
@@ -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}
/>
<div className="flex items-center justify-between gap-2">
@@ -338,7 +345,7 @@ export function TaskChatPanel({
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button type="button" variant="outline" size="icon" className="h-9 w-9 cursor-pointer">
<Button type="button" variant="outline" size="icon" className="h-7 w-7 cursor-pointer">
<IconBrain className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
@@ -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({
</Tooltip>
</div>
<div className="flex items-center gap-2">
<SessionsDropdown
taskId={taskId}
activeSessionId={resolvedSessionId}
taskTitle={task?.title}
taskDescription={taskDescription ?? ''}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button type="button" variant="outline" size="icon" className="h-9 w-9 cursor-pointer">
<Button type="button" variant="outline" size="icon" className="h-7 w-7 cursor-pointer">
<IconPaperclip className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Add attachments</TooltipContent>
</Tooltip>
<KeyboardShortcutTooltip shortcut={SHORTCUTS.SUBMIT}>
<Button type="submit">Submit</Button>
<KeyboardShortcutTooltip shortcut={SHORTCUTS.SUBMIT} enabled={!isAgentBusy && !isStarting}>
<Button
type={isAgentBusy ? 'button' : 'submit'}
variant={isAgentBusy ? 'destructive' : 'default'}
className={cn('h-7', isAgentBusy && 'gap-2')}
disabled={isStarting || isSending}
>
{isAgentBusy ? (
<>
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
Stop
</>
) : (
'Submit'
)}
</Button>
</KeyboardShortcutTooltip>
</div>
</div>
@@ -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<TaskSummary | null>(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
</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto space-y-4 pt-3">
<TaskSessionSwitcher
taskId={selectedTaskId}
sessions={selectedSessions}
onSelectSession={handleSelectSession}
onCreateSession={() => {
if (!selectedTaskId) return;
const task = tasksWithRepositories.find((item) => item.id === selectedTaskId) ?? null;
setSessionTask(task);
setSessionDialogOpen(true);
}}
/>
<TaskSwitcher
tasks={tasksWithRepositories}
columns={columns.map((column) => ({ id: column.id, title: column.title }))}
@@ -242,23 +174,6 @@ export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarP
}
}}
/>
<TaskCreateDialog
open={sessionDialogOpen}
onOpenChange={setSessionDialogOpen}
mode="session"
workspaceId={workspaceId}
boardId={boardId}
defaultColumnId={columns[0]?.id ?? null}
columns={columns.map((column) => ({ id: column.id, title: column.title }))}
initialValues={{
title: sessionTask?.title ?? '',
description: sessionTask?.description ?? '',
}}
onCreateSession={(data) => {
if (!sessionTask) return;
handleCreateSession(sessionTask.id, data);
}}
/>
</>
);
}
@@ -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<TaskSessionState, number> = {
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 <IconLoader2 className="h-3.5 w-3.5 text-blue-500 animate-spin" />;
case 'waiting_input':
return <IconAlertCircle className="h-3.5 w-3.5 text-yellow-500" />;
case 'complete':
return <IconCheck className="h-3.5 w-3.5 text-green-500" />;
case 'failed':
case 'cancelled':
return <IconX className="h-3.5 w-3.5 text-red-500" />;
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 (
<div className="space-y-2">
{showHeader ? (
<div className="flex items-center justify-between">
<span className="text-xs uppercase tracking-wide text-muted-foreground">Sessions</span>
<div className="flex items-center gap-1.5">
{onCreateSession ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onCreateSession}
className="text-muted-foreground hover:text-foreground rounded-md p-1 hover:bg-muted/50 cursor-pointer"
aria-label="New session"
>
<IconPlus className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="left">New session</TooltipContent>
</Tooltip>
) : null}
<Badge variant="secondary" className="text-[10px] px-1.5">
{sortedSessions.length}
</Badge>
</div>
</div>
) : null}
{sortedSessions.length === 0 ? (
<div className="text-xs text-muted-foreground">No sessions yet.</div>
) : (
<Command className="bg-transparent p-0 shadow-none">
<CommandList>
<CommandGroup className="p-0">
{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 (
<CommandItem
key={session.id}
value={session.id}
onSelect={() => {
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'
}`}
>
<span className="text-xs font-medium text-muted-foreground w-8 shrink-0">
{formatSessionLabel(index, sortedSessions.length)}
</span>
<span className="text-xs text-foreground flex-1 text-left truncate">
{agentLabel}
</span>
<span className="text-xs text-muted-foreground w-16 text-right shrink-0">
{duration}
</span>
<div className="ml-auto group/status relative h-5 w-5 shrink-0 flex items-center justify-center">
<div className="transition-opacity group-hover/status:opacity-0">
{getSessionIcon(status)}
</div>
{(status === 'running' || status === 'starting') && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
aria-label="Stop session"
className="absolute h-5 w-5 flex items-center justify-center rounded-md border border-border bg-background text-muted-foreground hover:text-destructive hover:border-destructive transition-colors opacity-0 group-hover/status:opacity-100"
onClick={(event) => {
event.stopPropagation();
}}
>
<IconPlayerStopFilled className="h-3 w-3" />
</button>
</TooltipTrigger>
<TooltipContent side="left">Stop session</TooltipContent>
</Tooltip>
)}
</div>
<span data-slot="command-shortcut" className="hidden" />
</CommandItem>
);
})}
</CommandGroup>
</CommandList>
</Command>
)}
</div>
);
}
@@ -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 <IconLoader2 className="h-4 w-4 animate-spin text-blue-500" />;
case 'REVIEW':
return <IconEye className="h-4 w-4 text-yellow-500" />;
case 'WAITING_FOR_INPUT':
case 'BLOCKED':
return <IconAlertCircle className="h-4 w-4 text-yellow-500" />;
case 'COMPLETED':
return <IconCheck className="h-4 w-4 text-green-500" />;
case 'FAILED':
case 'CANCELLED':
return <IconX className="h-4 w-4 text-red-500" />;
default:
return <IconAlertCircle className="h-4 w-4 text-muted-foreground" />;
}
}
export function TaskStateActions({ state, onMarkDone }: TaskStateActionsProps) {
return (
<div className="group relative flex items-center justify-end">
<div className="transition-opacity group-hover:opacity-0">
{getStateIcon(state)}
{getTaskStateIcon(state)}
</div>
<div className="absolute right-0 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<Tooltip>
-98
View File
@@ -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({
</>
)}
<span className="text-sm font-medium">{taskTitle ?? 'Task details'}</span>
<SessionsDropdown
taskId={taskId ?? null}
activeSessionId={activeSessionId ?? null}
taskTitle={taskTitle}
taskDescription={taskDescription}
/>
{displayBranch && (
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
<Tooltip>
@@ -274,95 +265,6 @@ const TaskTopBar = memo(function TaskTopBar({
</div>
<div className="flex items-center gap-2">
{/* Start/Stop Agent Button */}
{isAgentRunning ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
size="sm"
variant="destructive"
className="cursor-pointer"
onClick={onStopAgent}
disabled={isAgentLoading}
>
{isAgentLoading ? (
<IconLoader2 className="h-4 w-4 animate-spin" />
) : (
<IconPlayerStop className="h-4 w-4" />
)}
Stop Agent
</Button>
</TooltipTrigger>
<TooltipContent>Stop the agent</TooltipContent>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger asChild>
<Button
size="sm"
variant="default"
className="cursor-pointer"
onClick={() => setStartDialogOpen(true)}
disabled={isAgentLoading || agentProfiles.length === 0}
>
{isAgentLoading ? (
<IconLoader2 className="h-4 w-4 animate-spin" />
) : (
<IconPlayerPlay className="h-4 w-4" />
)}
Start Agent
</Button>
</TooltipTrigger>
<TooltipContent>
{agentProfiles.length === 0 ? 'Add an agent profile to start.' : 'Start the agent on this task'}
</TooltipContent>
</Tooltip>
)}
<Dialog open={startDialogOpen} onOpenChange={setStartDialogOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Start Agent</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<div className="text-sm text-muted-foreground">
Select an agent profile to start a new session.
</div>
<Select
value={resolvedAgentProfileId}
onValueChange={(value) => setSelectedAgentProfileId(value)}
>
<SelectTrigger>
<SelectValue placeholder="Select agent profile" />
</SelectTrigger>
<SelectContent>
{agentProfiles.map((profile) => (
<SelectItem key={profile.id} value={profile.id}>
{profile.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<DialogFooter>
<Button variant="outline" type="button" onClick={() => setStartDialogOpen(false)}>
Cancel
</Button>
<Button
type="button"
onClick={() => {
if (!resolvedAgentProfileId) return;
onStartAgent?.(resolvedAgentProfileId);
setStartDialogOpen(false);
}}
disabled={!resolvedAgentProfileId || isAgentLoading}
>
Start Agent
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Editor Button */}
<Tooltip>
<TooltipTrigger asChild>
@@ -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<void>;
}
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<string | null>(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) {
+52
View File
@@ -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<TaskState, IconConfig> = {
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<TaskSessionState, IconConfig> = {
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 <config.Icon className={cn('h-4 w-4', config.className, className)} />;
}
export function getSessionStateIcon(state?: TaskSessionState, className?: string) {
const config = state ? SESSION_STATE_ICONS[state] ?? DEFAULT_SESSION_ICON : DEFAULT_SESSION_ICON;
return <config.Icon className={cn('h-4 w-4', config.className, className)} />;
}