feat: session refactor (#30)

This commit is contained in:
Carlos Florêncio
2026-01-17 19:02:22 +00:00
committed by GitHub
parent 91a4e0551f
commit fb042e4c59
106 changed files with 4100 additions and 2582 deletions
@@ -65,6 +65,7 @@ export function ToolCallMessage({ comment, taskId }: ToolCallMessageProps) {
const metadata = comment.metadata as ToolCallMetadata | undefined;
const pendingPermissions = useAppStore((state) => state.permissions.pending);
const removePendingPermission = useAppStore((state) => state.removePendingPermission);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const toolCallId = metadata?.tool_call_id;
const toolName = metadata?.tool_name ?? '';
@@ -75,7 +76,11 @@ export function ToolCallMessage({ comment, taskId }: ToolCallMessageProps) {
// Find pending permission for this tool call (only if we have a valid tool_call_id)
const pendingPermission = pendingPermissions.find(
(p) => toolCallId && p.tool_call_id === toolCallId && (!taskId || p.task_id === taskId)
(p) =>
toolCallId &&
p.tool_call_id === toolCallId &&
(!activeSessionId || p.session_id === activeSessionId) &&
(!taskId || p.task_id === taskId)
);
const isPendingApproval = !!pendingPermission;
@@ -93,7 +98,7 @@ export function ToolCallMessage({ comment, taskId }: ToolCallMessageProps) {
try {
await client.request('permission.respond', {
task_id: pendingPermission.task_id,
session_id: pendingPermission.session_id,
pending_id: pendingPermission.pending_id,
option_id: cancelled ? undefined : optionId,
cancelled,
@@ -14,6 +14,9 @@ import {
} from '@kandev/ui/alert-dialog';
import { useAppStore } from '@/components/state-provider';
import { getWebSocketClient } from '@/lib/ws/connection';
import type { Message } from '@/lib/types/http';
const EMPTY_MESSAGES: Message[] = [];
type CommandApprovalDialogProps = {
taskId: string;
@@ -25,7 +28,10 @@ export function CommandApprovalDialog({ taskId, standaloneOnly = false }: Comman
const [isResponding, setIsResponding] = useState(false);
const pendingPermissions = useAppStore((state) => state.permissions.pending);
const removePendingPermission = useAppStore((state) => state.removePendingPermission);
const messages = useAppStore((state) => state.messages.items);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const messages = useAppStore((state) =>
activeSessionId ? state.messages.bySession[activeSessionId] ?? EMPTY_MESSAGES : EMPTY_MESSAGES
);
// Get tool_call_ids from all tool call messages
const toolCallIds = useMemo(() => {
@@ -43,13 +49,17 @@ export function CommandApprovalDialog({ taskId, standaloneOnly = false }: Comman
// If standaloneOnly, filter out permissions that have a matching tool call
const permission = useMemo(() => {
return pendingPermissions.find((p) => {
if (p.task_id !== taskId) return false;
if (activeSessionId) {
if (p.session_id !== activeSessionId) return false;
} else if (p.task_id !== taskId) {
return false;
}
if (standaloneOnly && p.tool_call_id && toolCallIds.has(p.tool_call_id)) {
return false; // This permission will be handled by inline UI
}
return true;
});
}, [pendingPermissions, taskId, standaloneOnly, toolCallIds]);
}, [pendingPermissions, activeSessionId, taskId, standaloneOnly, toolCallIds]);
const handleRespond = useCallback(
async (optionId: string, cancelled: boolean = false) => {
@@ -65,7 +75,7 @@ export function CommandApprovalDialog({ taskId, standaloneOnly = false }: Comman
try {
await client.request('permission.respond', {
task_id: taskId,
session_id: permission.session_id,
pending_id: permission.pending_id,
option_id: cancelled ? undefined : optionId,
cancelled,
@@ -77,7 +87,7 @@ export function CommandApprovalDialog({ taskId, standaloneOnly = false }: Comman
setIsResponding(false);
}
},
[permission, taskId, removePendingPermission]
[permission, removePendingPermission]
);
const handleApprove = useCallback(() => {
+22 -11
View File
@@ -5,14 +5,16 @@ import { IconChevronRight, IconChevronDown, IconFile, IconFolder, IconFolderOpen
import { ScrollArea } from '@kandev/ui/scroll-area';
import { getWebSocketClient } from '@/lib/ws/connection';
import { requestFileTree, requestFileContent } from '@/lib/ws/workspace-files';
import { useSessionAgentctl } from '@/hooks/use-session-agentctl';
import type { FileTreeNode, FileContentResponse, OpenFileTab } from '@/lib/types/backend';
type FileBrowserProps = {
taskId: string;
sessionId: string;
onOpenFile: (file: OpenFileTab) => void;
};
export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
export function FileBrowser({ sessionId, onOpenFile }: FileBrowserProps) {
const { isReady } = useSessionAgentctl(sessionId);
const [tree, setTree] = useState<FileTreeNode | null>(null);
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(new Set());
const [loadingPaths, setLoadingPaths] = useState<Set<string>>(new Set());
@@ -20,12 +22,19 @@ export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
// Load initial tree
useEffect(() => {
setTree(null);
setExpandedPaths(new Set());
setLoadingPaths(new Set());
setIsLoadingTree(true);
if (!isReady) {
return;
}
const loadTree = async () => {
try {
const client = getWebSocketClient();
if (!client) return;
const response = await requestFileTree(client, taskId, '', 1);
const response = await requestFileTree(client, sessionId, '', 1);
setTree(response.root);
} catch (error) {
console.error('Failed to load file tree:', error);
@@ -35,17 +44,18 @@ export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
};
loadTree();
}, [taskId]);
}, [isReady, sessionId]);
// Subscribe to file changes and refresh tree
useEffect(() => {
if (!isReady) return;
const client = getWebSocketClient();
if (!client) return;
const unsubscribe = client.on('workspace.file.changes', async () => {
const unsubscribe = client.on('session.workspace.file.changes', async () => {
// Refresh the root tree when any file changes
try {
const response = await requestFileTree(client, taskId, '', 1);
const response = await requestFileTree(client, sessionId, '', 1);
setTree(response.root);
} catch (error) {
console.error('Failed to refresh file tree:', error);
@@ -53,7 +63,7 @@ export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
});
return unsubscribe;
}, [taskId]);
}, [isReady, sessionId]);
const toggleExpand = useCallback(async (node: FileTreeNode) => {
if (!node.is_dir) return;
@@ -71,7 +81,7 @@ export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
const client = getWebSocketClient();
if (!client) return;
const response = await requestFileTree(client, taskId, node.path, 1);
const response = await requestFileTree(client, sessionId, node.path, 1);
// Update tree with new children
const updateNode = (n: FileTreeNode): FileTreeNode => {
@@ -101,16 +111,17 @@ export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
newExpanded.add(node.path);
setExpandedPaths(newExpanded);
}
}, [expandedPaths, taskId, tree]);
}, [expandedPaths, sessionId, tree]);
const openFile = useCallback(async (node: FileTreeNode) => {
if (node.is_dir) return;
if (!isReady) return;
try {
const client = getWebSocketClient();
if (!client) return;
const response: FileContentResponse = await requestFileContent(client, taskId, node.path);
const response: FileContentResponse = await requestFileContent(client, sessionId, node.path);
onOpenFile({
path: node.path,
@@ -120,7 +131,7 @@ export function FileBrowser({ taskId, onOpenFile }: FileBrowserProps) {
} catch (error) {
console.error('Failed to load file content:', error);
}
}, [taskId, onOpenFile]);
}, [isReady, sessionId, onOpenFile]);
const renderTreeNode = (node: FileTreeNode, depth: number = 0): React.ReactNode => {
const isExpanded = expandedPaths.has(node.path);
@@ -23,7 +23,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { TaskCreateDialog } from '../task-create-dialog';
import { useAppStore } from '@/components/state-provider';
import { getWebSocketClient } from '@/lib/ws/connection';
import { linkToTaskSession } from '@/lib/links';
import { linkToSession } from '@/lib/links';
type SessionStatus = 'running' | 'waiting_input' | 'complete' | 'failed' | 'cancelled';
@@ -184,10 +184,10 @@ export function SessionsDropdown({ taskId, activeSessionId = null, taskTitle = '
try {
await client.request('task.session.resume', {
task_id: taskId,
task_session_id: sessionId,
session_id: sessionId,
}, 15000);
await fetchSessions(taskId);
router.push(linkToTaskSession(taskId, sessionId));
router.push(linkToSession(sessionId));
} catch (error) {
console.error('Failed to resume task session:', error);
}
+31 -61
View File
@@ -6,13 +6,10 @@ import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
import { useAppStore, useAppStoreApi } from '@/components/state-provider';
import { getWebSocketClient } from '@/lib/ws/connection';
import { useSession } from '@/hooks/use-session';
import { useSessionAgentctl } from '@/hooks/use-session-agentctl';
type ShellTerminalProps = {
taskId: string;
sessionId: string | null;
};
export function ShellTerminal({ taskId, sessionId }: ShellTerminalProps) {
export function ShellTerminal() {
const terminalRef = useRef<HTMLDivElement>(null);
const xtermRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
@@ -21,15 +18,14 @@ export function ShellTerminal({ taskId, sessionId }: ShellTerminalProps) {
const onDataDisposableRef = useRef<{ dispose: () => void } | null>(null);
const storeApi = useAppStoreApi();
const shellOutput = useAppStore((state) => state.shell.outputs[taskId] || '');
const sessionState = useAppStore((state) => {
if (sessionId) {
return state.taskSessions.items[sessionId]?.state ?? null;
}
return state.taskSessionStatesByTaskId[taskId] ?? null;
});
const canSubscribe =
Boolean(sessionId) && (sessionState === 'RUNNING' || sessionState === 'WAITING_FOR_INPUT');
const sessionId = useAppStore((state) => state.tasks.activeSessionId);
const { session, isActive } = useSession(sessionId);
const { isReady: isAgentctlReady } = useSessionAgentctl(sessionId);
const taskId = session?.task_id ?? null;
const shellOutput = useAppStore((state) =>
sessionId ? state.shell.outputs[sessionId] || '' : ''
);
const canSubscribe = Boolean(sessionId && isActive && isAgentctlReady);
const send = useCallback(
(action: string, payload: Record<string, unknown>) => {
@@ -101,10 +97,10 @@ export function ShellTerminal({ taskId, sessionId }: ShellTerminalProps) {
onDataDisposableRef.current?.dispose();
onDataDisposableRef.current = null;
if (!sessionId) return;
if (!taskId || !sessionId) return;
onDataDisposableRef.current = xtermRef.current.onData((data) => {
send('shell.input', { task_id: taskId, session_id: sessionId, data });
send('shell.input', { session_id: sessionId, data });
});
return () => {
@@ -125,20 +121,14 @@ export function ShellTerminal({ taskId, sessionId }: ShellTerminalProps) {
}
}, [shellOutput]);
// Subscribe to shell on mount to start the shell stream
// Uses retry logic to handle cases where agent isn't ready yet (e.g., session resumption)
// Subscribe to shell once agentctl is ready.
useEffect(() => {
if (!canSubscribe) return;
if (!taskId || !sessionId || !canSubscribe) return;
// Increment subscription ID to invalidate any pending requests
const currentSubscriptionId = ++subscriptionIdRef.current;
let retryCount = 0;
const maxRetries = 10;
const retryDelay = 1000; // 1 second between retries
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
// Clear any stale output before subscribing to get fresh buffer
storeApi.getState().clearShellOutput(taskId);
storeApi.getState().clearShellOutput(sessionId);
lastOutputLengthRef.current = 0;
// Also clear the terminal display
@@ -146,44 +136,24 @@ export function ShellTerminal({ taskId, sessionId }: ShellTerminalProps) {
xtermRef.current.clear();
}
const attemptSubscribe = () => {
const client = getWebSocketClient();
if (!client) return;
const client = getWebSocketClient();
if (!client) return;
// Check if this subscription is still valid
if (subscriptionIdRef.current !== currentSubscriptionId) return;
client
.request<{ success: boolean; buffer?: string }>('shell.subscribe', { task_id: taskId, session_id: sessionId })
.then((response) => {
// Only process if this is still the current subscription (handles React Strict Mode)
if (subscriptionIdRef.current !== currentSubscriptionId) return;
// Write buffered output from response
if (response.buffer) {
storeApi.getState().appendShellOutput(taskId, response.buffer);
}
})
.catch((err) => {
if (subscriptionIdRef.current !== currentSubscriptionId) return;
// Retry if agent not ready yet (common during session resumption)
if (retryCount < maxRetries) {
retryCount++;
console.log(`[ShellTerminal] Retrying shell subscription (${retryCount}/${maxRetries})...`);
retryTimeout = setTimeout(attemptSubscribe, retryDelay);
} else {
console.error('Failed to subscribe to shell after retries:', err);
}
});
};
attemptSubscribe();
client
.request<{ success: boolean; buffer?: string }>('shell.subscribe', { session_id: sessionId })
.then((response) => {
if (subscriptionIdRef.current !== currentSubscriptionId) return;
if (response.buffer) {
storeApi.getState().appendShellOutput(sessionId, response.buffer);
}
})
.catch((err) => {
if (subscriptionIdRef.current !== currentSubscriptionId) return;
console.error('Failed to subscribe to shell:', err);
});
return () => {
if (retryTimeout) {
clearTimeout(retryTimeout);
}
subscriptionIdRef.current += 1;
};
}, [taskId, sessionId, storeApi, canSubscribe]);
@@ -9,32 +9,27 @@ import { TaskChangesPanel } from './task-changes-panel';
import { FileViewerContent } from './file-viewer-content';
import type { OpenFileTab } from '@/lib/types/backend';
import { FILE_EXTENSION_COLORS } from '@/lib/types/backend';
import { useTaskChatSession } from '@/hooks/use-task-chat-session';
import { useAppStore } from '@/components/state-provider';
const AGENTS = [
{ id: 'codex', label: 'Codex' },
{ id: 'claude', label: 'Claude Code' },
];
type TaskLeftPanelProps = {
taskId: string | null;
onSendMessage: (content: string) => Promise<void>;
type TaskCenterPanelProps = {
selectedDiffPath: string | null;
openFileRequest: OpenFileTab | null;
onDiffPathHandled: () => void;
onFileOpenHandled: () => void;
};
export const TaskLeftPanel = memo(function TaskLeftPanel({
taskId,
onSendMessage,
export const TaskCenterPanel = memo(function TaskCenterPanel({
selectedDiffPath: externalSelectedDiffPath,
openFileRequest,
onDiffPathHandled,
onFileOpenHandled,
}: TaskLeftPanelProps) {
// Get session ID from task ID
const { taskSessionId } = useTaskChatSession(taskId);
}: TaskCenterPanelProps) {
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
const [leftTab, setLeftTab] = useState('chat');
const [selectedDiffPath, setSelectedDiffPath] = useState<string | null>(null);
const [notes, setNotes] = useState('');
@@ -156,12 +151,8 @@ export const TaskLeftPanel = memo(function TaskLeftPanel({
</TabsContent>
<TabsContent value="chat" className="mt-3 flex flex-col min-h-0 flex-1">
{taskId ? (
<TaskChatPanel
agents={AGENTS}
onSend={onSendMessage}
sessionId={taskSessionId}
/>
{activeTaskId ? (
<TaskChatPanel agents={AGENTS} />
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
No task selected
@@ -10,6 +10,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { cn } from '@/lib/utils';
import { getLocalStorage, setLocalStorage } from '@/lib/local-storage';
import { useAppStore } from '@/components/state-provider';
import { useSessionGitStatus } from '@/hooks/use-session-git-status';
type TaskChangesPanelProps = {
selectedDiffPath: string | null;
@@ -26,22 +27,23 @@ const TaskChangesPanel = memo(function TaskChangesPanel({
getLocalStorage('task-diff-view-mode', DEFAULT_DIFF_MODE)
);
const { resolvedTheme } = useTheme();
const gitStatus = useAppStore((state) => state.gitStatus);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const gitStatus = useSessionGitStatus(activeSessionId);
// Convert git status files to array for display
const changedFiles = useMemo(() => {
if (!gitStatus.files || Object.keys(gitStatus.files).length === 0) {
if (!gitStatus?.files || Object.keys(gitStatus.files).length === 0) {
return [];
}
return Object.values(gitStatus.files);
}, [gitStatus.files]);
}, [gitStatus]);
const diffTargets = useMemo(
() => (selectedDiffPath ? [selectedDiffPath] : changedFiles.map((file) => file.path)),
[selectedDiffPath, changedFiles]
);
const diffModeEnum = diffViewMode === 'split' ? DiffModeEnum.Split : DiffModeEnum.Unified;
const diffTheme = resolvedTheme === 'dark' ? 'dark' : 'light';
const selectedFile = selectedDiffPath ? gitStatus.files[selectedDiffPath] : null;
const selectedFile = selectedDiffPath && gitStatus ? gitStatus.files[selectedDiffPath] : null;
const selectedDiffContent = selectedFile?.diff ?? '';
const isSingleDiffSelected = Boolean(selectedDiffPath && selectedFile);
@@ -160,7 +162,7 @@ const TaskChangesPanel = memo(function TaskChangesPanel({
) : (
<div className="space-y-4">
{diffTargets.map((path) => {
const file = gitStatus.files[path];
const file = gitStatus?.files?.[path];
if (!file || !file.diff) {
return null;
}
+37 -16
View File
@@ -15,13 +15,15 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { cn } from '@/lib/utils';
import { useAppStore } from '@/components/state-provider';
import { getWebSocketClient } from '@/lib/ws/connection';
import type { Message } from '@/lib/types/http';
import { SHORTCUTS } from '@/lib/keyboard/constants';
import { KeyboardShortcutTooltip } from '@/components/keyboard-shortcut-tooltip';
import { TaskChatInput } from '@/components/task/task-chat-input';
import { useLazyLoadMessages } from '@/hooks/use-lazy-load-messages';
import { useTaskSession } from '@/hooks/use-task-session';
import { useTaskMessages } from '@/hooks/use-task-messages';
import { useSession } from '@/hooks/use-session';
import { useTask } from '@/hooks/use-task';
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';
@@ -33,14 +35,14 @@ type AgentOption = {
type TaskChatPanelProps = {
agents: AgentOption[];
onSend: (message: string) => void;
sessionId: string | null;
onSend?: (message: string) => void;
sessionId?: string | null;
};
export function TaskChatPanel({
agents,
onSend,
sessionId,
sessionId = null,
}: TaskChatPanelProps) {
const [messageInput, setMessageInput] = useState('');
const [selectedAgent, setSelectedAgent] = useState(agents[0]?.id ?? '');
@@ -50,20 +52,21 @@ export function TaskChatPanel({
const lastAgentMessageCountRef = useRef(0);
const wasAtBottomRef = useRef(true);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const resolvedSessionId = sessionId ?? activeSessionId;
// Get task session details and derived task information from session ID
const { session, taskId, taskDescription, isWorking } = useTaskSession(sessionId);
const { session } = useSession(resolvedSessionId);
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';
// Fetch messages for this session
useTaskMessages(taskId, sessionId);
const messagesState = useAppStore((state) => state.messages);
const messages = messagesState?.items ?? [];
const messagesLoading = messagesState?.isLoading ?? false;
const { messages, isLoading: messagesLoading } = useSessionMessages(resolvedSessionId);
const isInitialLoading = messagesLoading && messages.length === 0;
const showLoadingState = (messagesLoading || isInitialLoading) && !isWorking;
const { loadMore, hasMore, isLoading: isLoadingMore } = useLazyLoadMessages(
messagesState?.sessionId ?? null
);
const { loadMore, hasMore, isLoading: isLoadingMore } = useLazyLoadMessages(resolvedSessionId);
// Filter to only show chat-relevant types.
const visibleMessages = messages.filter((message) =>
@@ -84,7 +87,7 @@ export function TaskChatPanel({
? {
id: 'task-description',
task_id: taskId ?? '',
task_session_id: messagesState?.sessionId ?? '',
session_id: resolvedSessionId ?? '',
author_type: 'user',
content: taskDescription,
type: 'message',
@@ -169,6 +172,20 @@ export function TaskChatPanel({
});
}, [virtualItems, hasMore, isLoadingMore, loadMore]);
const handleSendMessage = useCallback(async (message: string) => {
if (!taskId || !resolvedSessionId) {
console.error('No active task session. Start an agent before sending a message.');
return;
}
const client = getWebSocketClient();
if (!client) return;
await client.request(
'message.add',
{ task_id: taskId, session_id: resolvedSessionId, content: message },
10000
);
}, [resolvedSessionId, taskId]);
const handleSubmit = async (event?: FormEvent) => {
event?.preventDefault();
const trimmed = messageInput.trim();
@@ -178,7 +195,11 @@ export function TaskChatPanel({
setMessageInput('');
});
try {
await onSend(trimmed);
if (onSend) {
await onSend(trimmed);
} else {
await handleSendMessage(trimmed);
}
} finally {
setIsSending(false);
}
@@ -13,6 +13,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@kandev/ui/tabs';
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { LineStat } from '@/components/diff-stat';
import { useAppStore } from '@/components/state-provider';
import { useSessionGitStatus } from '@/hooks/use-session-git-status';
import type { FileInfo } from '@/lib/state/store';
import { FileBrowser } from '@/components/task/file-browser';
@@ -23,7 +24,6 @@ type OpenFileTab = {
};
type TaskFilesPanelProps = {
taskId: string | null;
onSelectDiffPath: (path: string) => void;
onOpenFile: (file: OpenFileTab) => void;
};
@@ -75,13 +75,14 @@ const splitPath = (path: string) => {
};
};
const TaskFilesPanel = memo(function TaskFilesPanel({ taskId, onSelectDiffPath, onOpenFile }: TaskFilesPanelProps) {
const TaskFilesPanel = memo(function TaskFilesPanel({ onSelectDiffPath, onOpenFile }: TaskFilesPanelProps) {
const [topTab, setTopTab] = useState<'diff' | 'files'>('diff');
const gitStatus = useAppStore((state) => state.gitStatus);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const gitStatus = useSessionGitStatus(activeSessionId);
// Convert git status files to array for display
const changedFiles = useMemo(() => {
if (!gitStatus.files || Object.keys(gitStatus.files).length === 0) {
if (!gitStatus?.files || Object.keys(gitStatus.files).length === 0) {
return [];
}
return Object.values(gitStatus.files).map((file) => ({
@@ -91,7 +92,7 @@ const TaskFilesPanel = memo(function TaskFilesPanel({ taskId, onSelectDiffPath,
minus: file.deletions,
oldPath: file.old_path,
}));
}, [gitStatus.files]);
}, [gitStatus]);
return (
<div className="h-full min-h-0 bg-card p-4 flex flex-col rounded-lg border border-border/70 border-l-0">
@@ -174,8 +175,8 @@ const TaskFilesPanel = memo(function TaskFilesPanel({ taskId, onSelectDiffPath,
</TabsContent>
<TabsContent value="files" className="mt-3 flex-1 min-h-0">
<div className="flex-1 min-h-0 overflow-y-auto rounded-lg bg-background h-full">
{taskId ? (
<FileBrowser taskId={taskId} onOpenFile={onOpenFile} />
{activeSessionId ? (
<FileBrowser sessionId={activeSessionId} onOpenFile={onOpenFile} />
) : (
<div className="flex items-center justify-center h-full text-muted-foreground text-sm">
No task selected
+4 -65
View File
@@ -1,58 +1,24 @@
'use client';
import { memo, useMemo, useState } from 'react';
import { memo, useState } from 'react';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@kandev/ui/resizable';
import { getLocalStorage, setLocalStorage } from '@/lib/local-storage';
import { TaskLeftPanel } from './task-left-panel';
import { TaskCenterPanel } from './task-center-panel';
import { TaskRightPanel } from './task-right-panel';
import { TaskFilesPanel } from './task-files-panel';
import { TaskSessionSidebar } from './task-session-sidebar';
import type { OpenFileTab } from '@/lib/types/backend';
import type { TaskSession, TaskState } from '@/lib/types/http';
const DEFAULT_HORIZONTAL_LAYOUT: [number, number, number] = [18, 57, 25];
type TaskLayoutProps = {
taskId: string | null;
sessionId: string | null;
onSendMessage: (content: string) => Promise<void>;
tasks: Array<{
id: string;
title: string;
state?: TaskState;
description?: string;
columnId?: string;
repositoryPath?: string;
}>;
columns: Array<{ id: string; title: string }>;
workspaceId: string | null;
boardId: string | null;
workspaceName: string;
agentLabelsById: Record<string, string>;
activeSessionId: string | null;
sessionsByTask: Record<string, TaskSession[]>;
onSelectSession: (taskId: string, sessionId: string) => void;
onLoadTaskSessions: (taskId: string) => void;
onSelectTask: (taskId: string, sessionId: string | null) => void;
onCreateSession: (taskId: string, data: { prompt: string; agentProfileId: string; executorId: string; environmentId: string }) => void;
};
export const TaskLayout = memo(function TaskLayout({
taskId,
sessionId,
onSendMessage,
tasks,
columns,
workspaceId,
boardId,
workspaceName,
agentLabelsById,
activeSessionId,
sessionsByTask,
onSelectSession,
onLoadTaskSessions,
onSelectTask,
onCreateSession,
}: TaskLayoutProps) {
const [horizontalLayout, setHorizontalLayout] = useState<[number, number, number]>(
getLocalStorage('task-layout-horizontal-v2', DEFAULT_HORIZONTAL_LAYOUT)
@@ -60,19 +26,6 @@ export const TaskLayout = memo(function TaskLayout({
const [selectedDiffPath, setSelectedDiffPath] = useState<string | null>(null);
const [openFileRequest, setOpenFileRequest] = useState<OpenFileTab | null>(null);
const switcherTasks = useMemo(
() =>
tasks.map((task) => ({
id: task.id,
title: task.title,
state: task.state,
description: task.description,
columnId: task.columnId,
repositoryPath: task.repositoryPath,
})),
[tasks]
);
const handleSelectDiffPath = (path: string) => {
setSelectedDiffPath(path);
};
@@ -83,7 +36,6 @@ export const TaskLayout = memo(function TaskLayout({
const topFilesPanel = (
<TaskFilesPanel
taskId={taskId}
onSelectDiffPath={handleSelectDiffPath}
onOpenFile={handleOpenFile}
/>
@@ -101,26 +53,13 @@ export const TaskLayout = memo(function TaskLayout({
>
<ResizablePanel defaultSize={horizontalLayout[0]} minSize={12} className="min-h-0 min-w-0">
<TaskSessionSidebar
workspaceName={workspaceName}
tasks={switcherTasks}
columns={columns}
workspaceId={workspaceId}
boardId={boardId}
activeTaskId={taskId}
activeSessionId={activeSessionId}
sessionsByTask={sessionsByTask}
onSelectSession={onSelectSession}
onLoadTaskSessions={onLoadTaskSessions}
agentLabelsById={agentLabelsById}
onSelectTask={onSelectTask}
onCreateSession={onCreateSession}
/>
</ResizablePanel>
<ResizableHandle className="w-px" />
<ResizablePanel defaultSize={horizontalLayout[1]} minSize={45} className="min-h-0 min-w-0">
<TaskLeftPanel
taskId={taskId}
onSendMessage={onSendMessage}
<TaskCenterPanel
selectedDiffPath={selectedDiffPath}
openFileRequest={openFileRequest}
onDiffPathHandled={() => setSelectedDiffPath(null)}
@@ -129,7 +68,7 @@ export const TaskLayout = memo(function TaskLayout({
</ResizablePanel>
<ResizableHandle className="w-px" />
<ResizablePanel defaultSize={horizontalLayout[2]} minSize={20} className="min-h-0 min-w-0">
<TaskRightPanel topPanel={topFilesPanel} taskId={taskId ?? ''} sessionId={sessionId} />
<TaskRightPanel topPanel={topFilesPanel} />
</ResizablePanel>
</ResizablePanelGroup>
</div>
@@ -12,13 +12,11 @@ import { ShellTerminal } from '@/components/task/shell-terminal';
type TaskRightPanelProps = {
topPanel: ReactNode;
taskId: string;
sessionId: string | null;
};
const DEFAULT_RIGHT_LAYOUT: [number, number] = [55, 45];
const TaskRightPanel = memo(function TaskRightPanel({ topPanel, taskId, sessionId }: TaskRightPanelProps) {
const TaskRightPanel = memo(function TaskRightPanel({ topPanel }: TaskRightPanelProps) {
const [rightLayout, setRightLayout] = useState<[number, number]>(() =>
getLocalStorage('task-layout-right', DEFAULT_RIGHT_LAYOUT)
);
@@ -180,7 +178,7 @@ const TaskRightPanel = memo(function TaskRightPanel({ topPanel, taskId, sessionI
{terminalIds.map((id) => (
<TabsContent key={id} value={`terminal-${id}`} className="flex-1 min-h-0">
<div className="flex-1 min-h-0 h-full p-1">
<ShellTerminal taskId={taskId} sessionId={sessionId} />
<ShellTerminal />
</div>
</TabsContent>
))}
+157 -48
View File
@@ -1,13 +1,18 @@
'use client';
import { useEffect, useState } from 'react';
import type { TaskSession, TaskState } from '@/lib/types/http';
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 { useAppStoreApi } from '@/components/state-provider';
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 = {
id: string;
@@ -19,46 +24,152 @@ type TaskSummary = {
};
type TaskSessionSidebarProps = {
workspaceName: string;
tasks: TaskSummary[];
columns: Array<{ id: string; title: string }>;
workspaceId: string | null;
boardId: string | null;
activeTaskId: string | null;
activeSessionId: string | null;
sessionsByTask: Record<string, TaskSession[]>;
agentLabelsById: Record<string, string>;
onSelectSession: (taskId: string, sessionId: string) => void;
onLoadTaskSessions: (taskId: string) => void;
onSelectTask: (taskId: string, sessionId: string | null) => void;
onCreateSession: (taskId: string, data: { prompt: string; agentProfileId: string; executorId: string; environmentId: string }) => void;
};
export function TaskSessionSidebar({
workspaceName,
tasks,
columns,
workspaceId,
boardId,
activeTaskId,
activeSessionId,
sessionsByTask,
agentLabelsById,
onSelectSession,
onLoadTaskSessions,
onSelectTask,
onCreateSession,
}: TaskSessionSidebarProps) {
const [selectedTaskId, setSelectedTaskId] = useState(activeTaskId);
const selectedSessions = selectedTaskId ? sessionsByTask[selectedTaskId] ?? [] : [];
export function TaskSessionSidebar({ workspaceId, boardId }: TaskSessionSidebarProps) {
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const sessionsById = useAppStore((state) => state.taskSessions.items);
const { tasks } = useTasks(boardId);
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 setTaskSessionsForTask = useAppStore((state) => state.setTaskSessionsForTask);
const setTaskSessionsLoading = useAppStore((state) => state.setTaskSessionsLoading);
const selectedTaskId = useMemo(() => {
if (activeSessionId) {
return sessionsById[activeSessionId]?.task_id ?? activeTaskId;
}
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(() => {
if (!workspaceId) return 'Workspace';
return workspaces.find((workspace) => workspace.id === workspaceId)?.name ?? 'Workspace';
}, [workspaceId, workspaces]);
const tasksWithRepositories = useMemo(() => {
const repositories = workspaceId ? repositoriesByWorkspace[workspaceId] ?? [] : [];
const repositoryPathsById = new Map(repositories.map((repo) => [repo.id, repo.local_path]));
return tasks.map((task) => ({
id: task.id,
title: task.title,
state: task.state as TaskState | undefined,
description: task.description,
columnId: task.columnId,
repositoryPath: task.repositoryId ? repositoryPathsById.get(task.repositoryId) : undefined,
}));
}, [repositoriesByWorkspace, tasks, workspaceId]);
useEffect(() => {
setSelectedTaskId(activeTaskId);
}, [activeTaskId]);
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));
}, []);
const loadTaskSessionsForTask = useCallback(
async (taskId: string) => {
const state = store.getState();
if (state.taskSessionsByTask.loadedByTaskId[taskId]) {
return state.taskSessionsByTask.itemsByTaskId[taskId] ?? [];
}
if (state.taskSessionsByTask.loadingByTaskId[taskId]) {
return state.taskSessionsByTask.itemsByTaskId[taskId] ?? [];
}
setTaskSessionsLoading(taskId, true);
try {
const response = await listTaskSessions(taskId, { cache: 'no-store' });
setTaskSessionsForTask(taskId, response.sessions ?? []);
return response.sessions ?? [];
} catch (error) {
console.error('Failed to load task sessions:', error);
setTaskSessionsForTask(taskId, []);
return [];
} finally {
setTaskSessionsLoading(taskId, false);
}
},
[setTaskSessionsForTask, setTaskSessionsLoading, store]
);
const handleSelectSession = useCallback(
(taskId: string, sessionId: string) => {
setActiveSession(taskId, sessionId);
updateUrl(sessionId);
},
[setActiveSession, updateUrl]
);
const handleSelectTask = useCallback(
async (taskId: string) => {
const sessions = await loadTaskSessionsForTask(taskId);
const sessionId = sessions[0]?.id ?? null;
if (!sessionId) {
setActiveTask(taskId);
return;
}
setActiveSession(taskId, sessionId);
updateUrl(sessionId);
},
[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 },
15000
);
if (response?.session_id && data.prompt.trim()) {
await client.request(
'message.add',
{ task_id: taskId, session_id: response.session_id, content: data.prompt.trim() },
10000
);
}
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 (
<>
@@ -78,28 +189,23 @@ export function TaskSessionSidebar({
<div className="flex-1 min-h-0 overflow-y-auto space-y-4 pt-3">
<TaskSessionSwitcher
taskId={selectedTaskId}
activeSessionId={activeSessionId}
sessions={selectedSessions}
agentLabelsById={agentLabelsById}
onSelectSession={onSelectSession}
onSelectSession={handleSelectSession}
onCreateSession={() => {
if (!selectedTaskId) return;
const task = tasks.find((item) => item.id === selectedTaskId) ?? null;
const task = tasksWithRepositories.find((item) => item.id === selectedTaskId) ?? null;
setSessionTask(task);
setSessionDialogOpen(true);
}}
/>
<TaskSwitcher
tasks={tasks}
columns={columns}
tasks={tasksWithRepositories}
columns={columns.map((column) => ({ id: column.id, title: column.title }))}
activeTaskId={activeTaskId}
selectedTaskId={selectedTaskId}
sessionsByTask={sessionsByTask}
onSelectTask={(taskId, sessionId) => {
setSelectedTaskId(taskId);
onSelectTask(taskId, sessionId);
onSelectTask={(taskId) => {
handleSelectTask(taskId);
}}
onLoadTaskSessions={onLoadTaskSessions}
/>
</div>
</div>
@@ -111,7 +217,7 @@ export function TaskSessionSidebar({
boardId={boardId}
defaultColumnId={columns[0]?.id ?? null}
columns={columns.map((column) => ({ id: column.id, title: column.title }))}
onSuccess={(task) => {
onSuccess={(task, _mode, meta) => {
store.setState((state) => {
if (state.kanban.boardId !== task.board_id) return state;
const nextTask = {
@@ -133,8 +239,11 @@ export function TaskSessionSidebar({
},
};
});
setSelectedTaskId(task.id);
onSelectTask(task.id, null);
setActiveTask(task.id);
if (meta?.taskSessionId) {
setActiveSession(task.id, meta.taskSessionId);
updateUrl(meta.taskSessionId);
}
}}
/>
<TaskCreateDialog
@@ -151,7 +260,7 @@ export function TaskSessionSidebar({
}}
onCreateSession={(data) => {
if (!sessionTask) return;
onCreateSession(sessionTask.id, data);
handleCreateSession(sessionTask.id, data);
}}
/>
</>
@@ -6,12 +6,11 @@ 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;
activeSessionId: string | null;
sessions: TaskSession[];
agentLabelsById: Record<string, string>;
onSelectSession: (taskId: string, sessionId: string) => void;
showHeader?: boolean;
onCreateSession?: () => void;
@@ -88,13 +87,16 @@ function formatDuration(startedAt: string, isRunning: boolean, now: number) {
export function TaskSessionSwitcher({
taskId,
activeSessionId,
sessions,
agentLabelsById,
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) => {
+4 -13
View File
@@ -2,7 +2,7 @@
import { useMemo, useState } from 'react';
import { IconChevronRight } from '@tabler/icons-react';
import type { TaskSession, TaskState } from '@/lib/types/http';
import type { TaskState } from '@/lib/types/http';
import {
Item,
ItemActions,
@@ -28,9 +28,7 @@ type TaskSwitcherProps = {
columns: Array<{ id: string; title: string }>;
activeTaskId: string | null;
selectedTaskId: string | null;
sessionsByTask: Record<string, TaskSession[]>;
onLoadTaskSessions: (taskId: string) => void;
onSelectTask: (taskId: string, sessionId: string | null) => void;
onSelectTask: (taskId: string) => void;
};
export function TaskSwitcher({
@@ -38,8 +36,6 @@ export function TaskSwitcher({
columns,
activeTaskId,
selectedTaskId,
sessionsByTask,
onLoadTaskSessions,
onSelectTask,
}: TaskSwitcherProps) {
const [collapsedColumnIds, setCollapsedColumnIds] = useState<Set<string>>(() => new Set());
@@ -107,7 +103,6 @@ export function TaskSwitcher({
<ItemGroup className="gap-2">
{columnTasks.map((task) => {
const isActive = task.id === activeTaskId;
const sessions = sessionsByTask[task.id] ?? [];
const isSelected = task.id === selectedTaskId || isActive;
const repoLabel = task.repositoryPath ? truncateRepoPath(task.repositoryPath) : 'No repository';
return (
@@ -123,16 +118,12 @@ export function TaskSwitcher({
href="#"
onClick={(event) => {
event.preventDefault();
const firstSessionId = sessions[0]?.id ?? null;
onSelectTask(task.id, firstSessionId);
onLoadTaskSessions(task.id);
onSelectTask(task.id);
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
const firstSessionId = sessions[0]?.id ?? null;
onSelectTask(task.id, firstSessionId);
onLoadTaskSessions(task.id);
onSelectTask(task.id);
}
}}
className="flex w-full items-center gap-2"
+17 -22
View File
@@ -38,6 +38,7 @@ 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';
import { formatUserHomePath } from '@/lib/utils';
type TaskTopBarProps = {
@@ -78,8 +79,7 @@ const TaskTopBar = memo(function TaskTopBar({
const [startDialogOpen, setStartDialogOpen] = useState(false);
const [selectedAgentProfileId, setSelectedAgentProfileId] = useState<string | null>(null);
// Get git status from store
const gitStatus = useAppStore((state) => state.gitStatus);
const gitStatus = useSessionGitStatus(activeSessionId ?? null);
const agentProfiles = useAppStore((state) => state.agentProfiles.items);
const resolvedAgentProfileId = useMemo(() => {
@@ -94,20 +94,15 @@ const TaskTopBar = memo(function TaskTopBar({
// Use worktree branch if available, otherwise fall back to base branch
const displayBranch = worktreeBranch || baseBranch;
// Calculate total additions and deletions from all files
const { totalAdditions, totalDeletions } = useMemo(() => {
if (!gitStatus.files || Object.keys(gitStatus.files).length === 0) {
return { totalAdditions: 0, totalDeletions: 0 };
// Calculate total additions and deletions from all files.
let totalAdditions = 0;
let totalDeletions = 0;
if (gitStatus?.files && Object.keys(gitStatus.files).length > 0) {
for (const file of Object.values(gitStatus.files)) {
totalAdditions += file.additions || 0;
totalDeletions += file.deletions || 0;
}
return Object.values(gitStatus.files).reduce(
(acc, file) => ({
totalAdditions: acc.totalAdditions + (file.additions || 0),
totalDeletions: acc.totalDeletions + (file.deletions || 0),
}),
{ totalAdditions: 0, totalDeletions: 0 }
);
}, [gitStatus.files]);
}
const handleBranchClick = (e: React.MouseEvent) => {
e.stopPropagation();
@@ -236,29 +231,29 @@ const TaskTopBar = memo(function TaskTopBar({
)}
{/* Git Status: Ahead/Behind */}
{(gitStatus.ahead > 0 || gitStatus.behind > 0) && (
{((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0) && (
<div className="flex items-center gap-1">
{gitStatus.ahead > 0 && (
{(gitStatus?.ahead ?? 0) > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-default">
<CommitStatBadge label={`${gitStatus.ahead} ahead`} tone="ahead" />
<CommitStatBadge label={`${gitStatus?.ahead ?? 0} ahead`} tone="ahead" />
</span>
</TooltipTrigger>
<TooltipContent>
{gitStatus.ahead} commit{gitStatus.ahead !== 1 ? 's' : ''} ahead of {gitStatus.remote_branch || 'remote'}
{gitStatus?.ahead ?? 0} commit{(gitStatus?.ahead ?? 0) !== 1 ? 's' : ''} ahead of {gitStatus?.remote_branch || 'remote'}
</TooltipContent>
</Tooltip>
)}
{gitStatus.behind > 0 && (
{(gitStatus?.behind ?? 0) > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-default">
<CommitStatBadge label={`${gitStatus.behind} behind`} tone="behind" />
<CommitStatBadge label={`${gitStatus?.behind ?? 0} behind`} tone="behind" />
</span>
</TooltipTrigger>
<TooltipContent>
{gitStatus.behind} commit{gitStatus.behind !== 1 ? 's' : ''} behind {gitStatus.remote_branch || 'remote'}
{gitStatus?.behind ?? 0} commit{(gitStatus?.behind ?? 0) !== 1 ? 's' : ''} behind {gitStatus?.remote_branch || 'remote'}
</TooltipContent>
</Tooltip>
)}