feat: chat improvements (#280)
This commit is contained in:
@@ -11,7 +11,6 @@ import {
|
||||
type ChatInputContainerHandle,
|
||||
type MessageAttachment,
|
||||
} from "@/components/task/chat/chat-input-container";
|
||||
import { type QueuedMessageIndicatorHandle } from "@/components/task/chat/queued-message-indicator";
|
||||
import {
|
||||
formatReviewCommentsAsMarkdown,
|
||||
formatPRFeedbackAsMarkdown,
|
||||
@@ -243,7 +242,6 @@ After completing the implementation, provide a summary of what was done.
|
||||
|
||||
type ChatInputAreaProps = {
|
||||
chatInputRef: React.RefObject<ChatInputContainerHandle | null>;
|
||||
queuedMessageRef: React.RefObject<QueuedMessageIndicatorHandle | null>;
|
||||
clarificationKey: number;
|
||||
onClarificationResolved: () => void;
|
||||
handleSubmit: (
|
||||
@@ -253,8 +251,6 @@ type ChatInputAreaProps = {
|
||||
inlineMentions?: ContextFile[],
|
||||
) => Promise<void>;
|
||||
handleCancelTurn: () => Promise<void>;
|
||||
handleCancelQueue: () => Promise<void>;
|
||||
handleQueueEditComplete: () => void;
|
||||
showRequestChangesTooltip: boolean;
|
||||
onRequestChangesTooltipDismiss?: () => void;
|
||||
isPanelFocused?: boolean;
|
||||
@@ -264,13 +260,10 @@ type ChatInputAreaProps = {
|
||||
|
||||
export function ChatInputArea({
|
||||
chatInputRef,
|
||||
queuedMessageRef,
|
||||
clarificationKey,
|
||||
onClarificationResolved,
|
||||
handleSubmit,
|
||||
handleCancelTurn,
|
||||
handleCancelQueue,
|
||||
handleQueueEditComplete,
|
||||
showRequestChangesTooltip,
|
||||
onRequestChangesTooltipDismiss,
|
||||
isPanelFocused,
|
||||
@@ -294,9 +287,6 @@ export function ChatInputArea({
|
||||
pendingCommentsByFile,
|
||||
chatSubmitKey,
|
||||
agentCommands,
|
||||
isQueued,
|
||||
queuedMessage,
|
||||
updateQueueContent,
|
||||
contextItems,
|
||||
planContextEnabled,
|
||||
todoItems,
|
||||
@@ -345,18 +335,12 @@ export function ChatInputArea({
|
||||
submitKey={chatSubmitKey}
|
||||
hasAgentCommands={!!(agentCommands && agentCommands.length > 0)}
|
||||
isFailed={isFailed}
|
||||
isQueued={isQueued}
|
||||
contextItems={contextItems}
|
||||
planContextEnabled={planContextEnabled}
|
||||
contextFiles={contextFiles}
|
||||
onToggleContextFile={handleToggleContextFile}
|
||||
onAddContextFile={handleAddContextFile}
|
||||
todoItems={todoItems}
|
||||
queuedMessage={queuedMessage?.content}
|
||||
onCancelQueue={handleCancelQueue}
|
||||
updateQueueContent={updateQueueContent}
|
||||
queuedMessageRef={queuedMessageRef}
|
||||
onQueueEditComplete={handleQueueEditComplete}
|
||||
isPanelFocused={isPanelFocused}
|
||||
onImplementPlan={handleImplementPlan}
|
||||
/>
|
||||
|
||||
@@ -6,10 +6,6 @@ import { TipTapInput } from "./tiptap-input";
|
||||
import { ChatInputFocusHint } from "./chat-input-focus-hint";
|
||||
import { ResizeHandle } from "./resize-handle";
|
||||
import { TodoSummary } from "./todo-summary";
|
||||
import {
|
||||
QueuedMessageIndicator,
|
||||
type QueuedMessageIndicatorHandle,
|
||||
} from "./queued-message-indicator";
|
||||
import { ChatInputToolbar } from "./chat-input-toolbar";
|
||||
import { ContextZone } from "./context-items/context-zone";
|
||||
import type { ContextItem } from "@/lib/types/context";
|
||||
@@ -146,12 +142,6 @@ export type ChatInputContextAreaProps = {
|
||||
hasContextZone: boolean;
|
||||
allItems: ContextItem[];
|
||||
sessionId: string | null;
|
||||
hasQueuedMessage: boolean;
|
||||
queuedMessage?: string | null;
|
||||
onCancelQueue?: () => void;
|
||||
updateQueueContent?: (content: string) => Promise<void>;
|
||||
queuedMessageRef?: React.RefObject<QueuedMessageIndicatorHandle | null>;
|
||||
onQueueEditComplete?: () => void;
|
||||
hasTodos: boolean;
|
||||
todoItems: TodoItem[];
|
||||
};
|
||||
@@ -160,30 +150,12 @@ export function ChatInputContextArea({
|
||||
hasContextZone,
|
||||
allItems,
|
||||
sessionId,
|
||||
hasQueuedMessage,
|
||||
queuedMessage,
|
||||
onCancelQueue,
|
||||
updateQueueContent,
|
||||
queuedMessageRef,
|
||||
onQueueEditComplete,
|
||||
hasTodos,
|
||||
todoItems,
|
||||
}: ChatInputContextAreaProps) {
|
||||
if (!hasContextZone) return null;
|
||||
const queueSlot = hasQueuedMessage ? (
|
||||
<QueuedMessageIndicator
|
||||
ref={queuedMessageRef}
|
||||
content={queuedMessage!}
|
||||
onCancel={onCancelQueue!}
|
||||
onUpdate={updateQueueContent!}
|
||||
isVisible={true}
|
||||
onEditComplete={onQueueEditComplete}
|
||||
/>
|
||||
) : undefined;
|
||||
const todoSlot = hasTodos ? <TodoSummary todos={todoItems} /> : undefined;
|
||||
return (
|
||||
<ContextZone items={allItems} sessionId={sessionId} queueSlot={queueSlot} todoSlot={todoSlot} />
|
||||
);
|
||||
return <ContextZone items={allItems} sessionId={sessionId} todoSlot={todoSlot} />;
|
||||
}
|
||||
|
||||
export type ChatInputBodyProps = {
|
||||
@@ -217,7 +189,6 @@ export function ChatInputBody({
|
||||
contextAreaProps,
|
||||
editorAreaProps,
|
||||
}: ChatInputBodyProps) {
|
||||
console.log("[ChatInputBody] planModeEnabled:", planModeEnabled);
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
|
||||
@@ -7,7 +7,6 @@ import { TaskCreateDialog } from "@/components/task-create-dialog";
|
||||
import type { ContextFile } from "@/lib/state/context-files-store";
|
||||
import type { Message } from "@/lib/types/http";
|
||||
import type { DiffComment } from "@/lib/diff/types";
|
||||
import type { QueuedMessageIndicatorHandle } from "./queued-message-indicator";
|
||||
import { useChatInputContainer } from "./use-chat-input-container";
|
||||
import {
|
||||
ChatInputBody,
|
||||
@@ -66,18 +65,12 @@ type ChatInputContainerProps = {
|
||||
submitKey?: "enter" | "cmd_enter";
|
||||
hasAgentCommands?: boolean;
|
||||
isFailed?: boolean;
|
||||
isQueued?: boolean;
|
||||
contextItems?: ContextItem[];
|
||||
planContextEnabled?: boolean;
|
||||
contextFiles?: ContextFile[];
|
||||
onToggleContextFile?: (file: ContextFile) => void;
|
||||
onAddContextFile?: (file: ContextFile) => void;
|
||||
todoItems?: TodoItem[];
|
||||
queuedMessage?: string | null;
|
||||
onCancelQueue?: () => void;
|
||||
updateQueueContent?: (content: string) => Promise<void>;
|
||||
queuedMessageRef?: React.RefObject<QueuedMessageIndicatorHandle | null>;
|
||||
onQueueEditComplete?: () => void;
|
||||
isPanelFocused?: boolean;
|
||||
onImplementPlan?: () => void;
|
||||
};
|
||||
@@ -139,12 +132,6 @@ function buildContextAreaProps(
|
||||
hasContextZone: s.hasContextZone,
|
||||
allItems: s.allItems,
|
||||
sessionId: p.sessionId,
|
||||
hasQueuedMessage: s.hasQueuedMessage,
|
||||
queuedMessage: p.queuedMessage,
|
||||
onCancelQueue: p.onCancelQueue,
|
||||
updateQueueContent: p.updateQueueContent,
|
||||
queuedMessageRef: p.queuedMessageRef,
|
||||
onQueueEditComplete: p.onQueueEditComplete,
|
||||
hasTodos: s.hasTodos,
|
||||
todoItems: p.todoItems ?? [],
|
||||
};
|
||||
@@ -207,7 +194,6 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
|
||||
const p = {
|
||||
...props,
|
||||
isFailed: isFailed ?? false,
|
||||
isQueued: props.isQueued ?? false,
|
||||
hasAgentCommands: props.hasAgentCommands ?? false,
|
||||
submitKey: props.submitKey ?? "cmd_enter",
|
||||
planContextEnabled: props.planContextEnabled ?? false,
|
||||
@@ -225,21 +211,16 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
|
||||
isFailed: p.isFailed,
|
||||
isAgentBusy,
|
||||
hasAgentCommands: p.hasAgentCommands,
|
||||
isQueued: p.isQueued,
|
||||
placeholder: props.placeholder,
|
||||
contextItems: p.contextItems,
|
||||
pendingClarification: props.pendingClarification,
|
||||
onClarificationResolved: props.onClarificationResolved,
|
||||
pendingCommentsByFile: props.pendingCommentsByFile,
|
||||
hasContextComments: props.hasContextComments ?? false,
|
||||
queuedMessage: props.queuedMessage,
|
||||
onCancelQueue: props.onCancelQueue,
|
||||
updateQueueContent: props.updateQueueContent,
|
||||
todoItems: p.todoItems,
|
||||
showRequestChangesTooltip,
|
||||
onRequestChangesTooltipDismiss: props.onRequestChangesTooltipDismiss,
|
||||
onSubmit: props.onSubmit,
|
||||
queuedMessageRef: props.queuedMessageRef,
|
||||
});
|
||||
|
||||
if (p.isFailed) {
|
||||
|
||||
@@ -7,18 +7,16 @@ import { ContextItemRenderer } from "./context-item-renderer";
|
||||
type ContextZoneProps = {
|
||||
items: ContextItem[];
|
||||
sessionId?: string | null;
|
||||
queueSlot?: ReactNode;
|
||||
todoSlot?: ReactNode;
|
||||
};
|
||||
|
||||
export function ContextZone({ items, sessionId, queueSlot, todoSlot }: ContextZoneProps) {
|
||||
const hasContent = !!queueSlot || !!todoSlot || items.length > 0;
|
||||
export function ContextZone({ items, sessionId, todoSlot }: ContextZoneProps) {
|
||||
const hasContent = !!todoSlot || items.length > 0;
|
||||
if (!hasContent) return null;
|
||||
|
||||
return (
|
||||
<div className="overflow-y-auto max-h-[40%] border-b border-border/50 shrink-0">
|
||||
<div className="px-2 pt-2 pb-1 space-y-1.5">
|
||||
{queueSlot}
|
||||
{todoSlot}
|
||||
{items.length > 0 && (
|
||||
<div className="flex items-center gap-1 flex-wrap px-0 py-0.5">
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, memo } from "react";
|
||||
import { SessionPanelContent } from "@kandev/ui/pannel-session";
|
||||
import type { Message } from "@/lib/types/http";
|
||||
import { AgentStatus } from "@/components/task/chat/messages/agent-status";
|
||||
import { PrepareProgress } from "@/components/session/prepare-progress";
|
||||
import { useLazyLoadMessages } from "@/hooks/use-lazy-load-messages";
|
||||
import {
|
||||
type MessageListProps,
|
||||
MessageListStatus,
|
||||
MessageItem,
|
||||
getItemKey,
|
||||
getSessionRunningState,
|
||||
getLastTurnGroupId,
|
||||
} from "./message-list-shared";
|
||||
|
||||
/**
|
||||
* Continuously captures scroll state via scroll listener.
|
||||
* On prepend (itemCount increases), restores scroll position so the user
|
||||
* stays at the same visual spot.
|
||||
*/
|
||||
function useScrollPositionOnPrepend(
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>,
|
||||
itemCount: number,
|
||||
) {
|
||||
const scrollState = useRef({ scrollHeight: 0, scrollTop: 0 });
|
||||
const prevItemCount = useRef(itemCount);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const onScroll = () => {
|
||||
scrollState.current.scrollHeight = el.scrollHeight;
|
||||
scrollState.current.scrollTop = el.scrollTop;
|
||||
};
|
||||
onScroll();
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", onScroll);
|
||||
}, [scrollRef]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el || itemCount <= prevItemCount.current) {
|
||||
prevItemCount.current = itemCount;
|
||||
return;
|
||||
}
|
||||
const prev = scrollState.current;
|
||||
const delta = el.scrollHeight - prev.scrollHeight;
|
||||
if (delta > 0) {
|
||||
el.scrollTop = prev.scrollTop + delta;
|
||||
}
|
||||
prevItemCount.current = itemCount;
|
||||
}, [itemCount, scrollRef]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Observes a sentinel element at the top of the list to trigger lazy loading.
|
||||
* Uses a callback ref so the observer reconnects when the sentinel remounts.
|
||||
*
|
||||
* Handles the timing issue where the sentinel DOM node mounts (callback ref fires)
|
||||
* before the useEffect creates the IntersectionObserver. The sentinelNodeRef bridges
|
||||
* the gap: the callback ref stores the node, and the effect observes it if present.
|
||||
*/
|
||||
function useLazyLoadSentinel(
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>,
|
||||
hasMore: boolean,
|
||||
isLoadingMore: boolean,
|
||||
loadMore: () => Promise<number>,
|
||||
) {
|
||||
const stateRef = useRef({ hasMore, isLoadingMore });
|
||||
useEffect(() => {
|
||||
stateRef.current = { hasMore, isLoadingMore };
|
||||
}, [hasMore, isLoadingMore]);
|
||||
|
||||
const observerRef = useRef<IntersectionObserver | null>(null);
|
||||
const sentinelNodeRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// Create/destroy observer when scroll container changes
|
||||
useEffect(() => {
|
||||
const root = scrollRef.current;
|
||||
if (!root) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
const { hasMore, isLoadingMore } = stateRef.current;
|
||||
const isIntersecting = entries[0]?.isIntersecting;
|
||||
if (isIntersecting && hasMore && !isLoadingMore) {
|
||||
loadMore();
|
||||
}
|
||||
},
|
||||
{ root, rootMargin: "200px 0px 0px 0px" },
|
||||
);
|
||||
observerRef.current = observer;
|
||||
// If sentinel already mounted before this effect ran, observe it now
|
||||
if (sentinelNodeRef.current) {
|
||||
observer.observe(sentinelNodeRef.current);
|
||||
}
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
observerRef.current = null;
|
||||
};
|
||||
}, [scrollRef, loadMore]);
|
||||
|
||||
// Callback ref — stores node and observes if observer already exists
|
||||
const sentinelRef = useCallback((node: HTMLDivElement | null) => {
|
||||
sentinelNodeRef.current = node;
|
||||
const observer = observerRef.current;
|
||||
if (observer) {
|
||||
observer.disconnect();
|
||||
if (node) {
|
||||
observer.observe(node);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return sentinelRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-scrolls to bottom when new messages arrive (if user is near bottom)
|
||||
* or when the agent starts working (isWorking transitions to true).
|
||||
*/
|
||||
function useAutoScroll(
|
||||
scrollRef: React.RefObject<HTMLDivElement | null>,
|
||||
messages: Message[],
|
||||
isWorking: boolean,
|
||||
) {
|
||||
const isNearBottomRef = useRef(true);
|
||||
const prevIsWorkingRef = useRef(isWorking);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const onScroll = () => {
|
||||
isNearBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 100;
|
||||
};
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", onScroll);
|
||||
}, [scrollRef]);
|
||||
|
||||
// When isWorking transitions to true, force scroll to bottom
|
||||
useEffect(() => {
|
||||
if (isWorking && !prevIsWorkingRef.current) {
|
||||
const el = scrollRef.current;
|
||||
if (el) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
isNearBottomRef.current = true;
|
||||
}
|
||||
}
|
||||
prevIsWorkingRef.current = isWorking;
|
||||
}, [isWorking, scrollRef]);
|
||||
|
||||
// Auto-scroll on new messages if near bottom
|
||||
useLayoutEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el && isNearBottomRef.current) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
}, [messages, scrollRef]);
|
||||
}
|
||||
|
||||
function useScrollToMessage() {
|
||||
return useCallback((messageId: string) => {
|
||||
const el = document.getElementById(`msg-${messageId}`);
|
||||
el?.scrollIntoView({ block: "center", behavior: "smooth" });
|
||||
}, []);
|
||||
}
|
||||
|
||||
export const NativeMessageList = memo(function NativeMessageList({
|
||||
items,
|
||||
messages,
|
||||
permissionsByToolCallId,
|
||||
childrenByParentToolCallId,
|
||||
taskId,
|
||||
sessionId,
|
||||
messagesLoading,
|
||||
isWorking,
|
||||
sessionState,
|
||||
worktreePath,
|
||||
onOpenFile,
|
||||
}: MessageListProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const isInitialLoading = messagesLoading && messages.length === 0;
|
||||
const isNonLoadableSession =
|
||||
!sessionState || ["CREATED", "FAILED", "COMPLETED", "CANCELLED"].includes(sessionState);
|
||||
const showLoadingState = isInitialLoading && !isWorking && !isNonLoadableSession;
|
||||
const { loadMore, hasMore, isLoading: isLoadingMore } = useLazyLoadMessages(sessionId);
|
||||
const isRunning = getSessionRunningState(sessionState);
|
||||
const lastTurnGroupId = useMemo(() => getLastTurnGroupId(items), [items]);
|
||||
const handleScrollToMessage = useScrollToMessage();
|
||||
|
||||
useScrollPositionOnPrepend(scrollRef, items.length);
|
||||
const sentinelRef = useLazyLoadSentinel(scrollRef, hasMore, isLoadingMore, loadMore);
|
||||
useAutoScroll(scrollRef, messages, isWorking);
|
||||
|
||||
// Scroll to bottom on initial load
|
||||
const didInitialScroll = useRef(false);
|
||||
useEffect(() => {
|
||||
if (didInitialScroll.current || items.length === 0) return;
|
||||
const el = scrollRef.current;
|
||||
if (el) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
didInitialScroll.current = true;
|
||||
}
|
||||
}, [items.length]);
|
||||
|
||||
return (
|
||||
<SessionPanelContent ref={scrollRef} className="relative p-4 chat-message-list">
|
||||
{/* Sentinel for lazy loading older messages */}
|
||||
{hasMore && <div ref={sentinelRef} className="h-px" />}
|
||||
|
||||
<MessageListStatus
|
||||
isLoadingMore={isLoadingMore}
|
||||
hasMore={hasMore}
|
||||
showLoadingState={showLoadingState}
|
||||
messagesLoading={messagesLoading}
|
||||
isInitialLoading={isInitialLoading}
|
||||
messagesCount={messages.length}
|
||||
/>
|
||||
|
||||
{items.map((item) => {
|
||||
const key = getItemKey(item);
|
||||
return (
|
||||
<div key={key} id={`msg-${key}`} className="pb-2" style={{ overflowAnchor: "none" }}>
|
||||
<MessageItem
|
||||
item={item}
|
||||
sessionId={sessionId}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
taskId={taskId}
|
||||
worktreePath={worktreePath}
|
||||
onOpenFile={onOpenFile}
|
||||
isLastGroup={item.type === "turn_group" && item.id === lastTurnGroupId}
|
||||
isTurnActive={isRunning}
|
||||
messages={messages}
|
||||
sessionState={sessionState}
|
||||
onScrollToMessage={handleScrollToMessage}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{sessionId && <PrepareProgress sessionId={sessionId} />}
|
||||
<AgentStatus sessionState={sessionState} sessionId={sessionId} messages={messages} />
|
||||
|
||||
{/* Bottom anchor — browser keeps scroll pinned here when new content appends */}
|
||||
<div style={{ overflowAnchor: "auto", height: 1 }} />
|
||||
</SessionPanelContent>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import { GridSpinner } from "@/components/grid-spinner";
|
||||
import type { Message, TaskSessionState } from "@/lib/types/http";
|
||||
import type { RenderItem } from "@/hooks/use-processed-messages";
|
||||
import { MessageRenderer } from "@/components/task/chat/message-renderer";
|
||||
import { TurnGroupMessage } from "@/components/task/chat/messages/turn-group-message";
|
||||
|
||||
export type MessageListProps = {
|
||||
items: RenderItem[];
|
||||
messages: Message[];
|
||||
permissionsByToolCallId: Map<string, Message>;
|
||||
childrenByParentToolCallId: Map<string, Message[]>;
|
||||
taskId?: string;
|
||||
sessionId: string | null;
|
||||
messagesLoading: boolean;
|
||||
isWorking: boolean;
|
||||
sessionState?: TaskSessionState;
|
||||
worktreePath?: string;
|
||||
onOpenFile?: (path: string) => void;
|
||||
};
|
||||
|
||||
export function getItemKey(item: RenderItem): string {
|
||||
return item.type === "turn_group" ? item.id : item.message.id;
|
||||
}
|
||||
|
||||
export function getSessionRunningState(sessionState: string | null | undefined) {
|
||||
return sessionState === "CREATED" || sessionState === "STARTING" || sessionState === "RUNNING";
|
||||
}
|
||||
|
||||
export function getLastTurnGroupId(items: RenderItem[]) {
|
||||
for (let i = items.length - 1; i >= 0; i--) {
|
||||
const item = items[i];
|
||||
if (item.type === "turn_group") return item.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function MessageListStatus({
|
||||
isLoadingMore,
|
||||
hasMore,
|
||||
showLoadingState,
|
||||
messagesLoading,
|
||||
isInitialLoading,
|
||||
messagesCount,
|
||||
}: {
|
||||
isLoadingMore: boolean;
|
||||
hasMore: boolean;
|
||||
showLoadingState: boolean;
|
||||
messagesLoading: boolean;
|
||||
isInitialLoading: boolean;
|
||||
messagesCount: number;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{isLoadingMore && hasMore && (
|
||||
<div className="text-center text-xs text-muted-foreground py-2">
|
||||
Loading older messages...
|
||||
</div>
|
||||
)}
|
||||
{showLoadingState && (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<GridSpinner className="text-primary mr-2" />
|
||||
<span>Loading messages...</span>
|
||||
</div>
|
||||
)}
|
||||
{!messagesLoading && !isInitialLoading && messagesCount === 0 && (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<span>No messages yet. Start the conversation!</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function MessageItem({
|
||||
item,
|
||||
sessionId,
|
||||
permissionsByToolCallId,
|
||||
childrenByParentToolCallId,
|
||||
taskId,
|
||||
worktreePath,
|
||||
onOpenFile,
|
||||
isLastGroup,
|
||||
isTurnActive,
|
||||
messages,
|
||||
sessionState,
|
||||
onScrollToMessage,
|
||||
}: {
|
||||
item: RenderItem;
|
||||
sessionId: string | null;
|
||||
permissionsByToolCallId: Map<string, Message>;
|
||||
childrenByParentToolCallId: Map<string, Message[]>;
|
||||
taskId?: string;
|
||||
worktreePath?: string;
|
||||
onOpenFile?: (path: string) => void;
|
||||
isLastGroup: boolean;
|
||||
isTurnActive: boolean;
|
||||
messages: Message[];
|
||||
sessionState?: TaskSessionState;
|
||||
onScrollToMessage: (id: string) => void;
|
||||
}) {
|
||||
if (item.type === "turn_group") {
|
||||
return (
|
||||
<TurnGroupMessage
|
||||
group={item}
|
||||
sessionId={sessionId}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
taskId={taskId}
|
||||
worktreePath={worktreePath}
|
||||
onOpenFile={onOpenFile}
|
||||
isLastGroup={isLastGroup}
|
||||
isTurnActive={isTurnActive}
|
||||
allMessages={messages}
|
||||
onScrollToMessage={onScrollToMessage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<MessageRenderer
|
||||
comment={item.message}
|
||||
isTaskDescription={item.message.id === "task-description"}
|
||||
sessionState={sessionState}
|
||||
taskId={taskId}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
worktreePath={worktreePath}
|
||||
sessionId={sessionId ?? undefined}
|
||||
onOpenFile={onOpenFile}
|
||||
allMessages={messages}
|
||||
onScrollToMessage={onScrollToMessage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, memo } from "react";
|
||||
import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";
|
||||
import { SessionPanelContent } from "@kandev/ui/pannel-session";
|
||||
import type { RenderItem } from "@/hooks/use-processed-messages";
|
||||
import { AgentStatus } from "@/components/task/chat/messages/agent-status";
|
||||
import { PrepareProgress } from "@/components/session/prepare-progress";
|
||||
import { useLazyLoadMessages } from "@/hooks/use-lazy-load-messages";
|
||||
import {
|
||||
type MessageListProps,
|
||||
MessageListStatus,
|
||||
MessageItem,
|
||||
getItemKey,
|
||||
getSessionRunningState,
|
||||
getLastTurnGroupId,
|
||||
} from "./message-list-shared";
|
||||
|
||||
const FIRST_INDEX_BASE = 100_000;
|
||||
|
||||
type VirtuosoBodyProps = MessageListProps & {
|
||||
scrollParent: HTMLDivElement;
|
||||
isRunning: boolean;
|
||||
lastTurnGroupId: string | null;
|
||||
hasMore: boolean;
|
||||
isLoadingMore: boolean;
|
||||
loadMore: () => Promise<number>;
|
||||
Header: () => React.ReactNode;
|
||||
Footer: () => React.ReactNode;
|
||||
};
|
||||
|
||||
function computeFirstItemIndex(prevKeys: string[], prevIndex: number, keys: string[]): number {
|
||||
if (prevKeys.length > 0 && keys.length > prevKeys.length) {
|
||||
const oldFirstKey = prevKeys[0];
|
||||
const newPos = keys.indexOf(oldFirstKey);
|
||||
if (newPos > 0) return prevIndex - newPos;
|
||||
if (newPos === -1) {
|
||||
for (let i = 0; i < prevKeys.length; i++) {
|
||||
const idx = keys.indexOf(prevKeys[i]);
|
||||
if (idx >= 0) return prevIndex - (idx - i);
|
||||
}
|
||||
}
|
||||
return prevIndex;
|
||||
}
|
||||
if (prevKeys.length === 0 && keys.length > 0) {
|
||||
return FIRST_INDEX_BASE - keys.length + 1;
|
||||
}
|
||||
return prevIndex;
|
||||
}
|
||||
|
||||
type IndexState = { keys: string[]; firstItemIndex: number };
|
||||
|
||||
function useStableFirstItemIndex(items: RenderItem[]) {
|
||||
const keys = useMemo(() => items.map(getItemKey), [items]);
|
||||
|
||||
const [state, setState] = useState<IndexState>(() => ({
|
||||
keys,
|
||||
firstItemIndex: FIRST_INDEX_BASE - keys.length + 1,
|
||||
}));
|
||||
|
||||
if (keys !== state.keys) {
|
||||
const nextIndex = computeFirstItemIndex(state.keys, state.firstItemIndex, keys);
|
||||
setState({ keys, firstItemIndex: nextIndex });
|
||||
return nextIndex;
|
||||
}
|
||||
|
||||
return state.firstItemIndex;
|
||||
}
|
||||
|
||||
function useVirtuosoCallbacks(props: VirtuosoBodyProps) {
|
||||
const { items, sessionId, permissionsByToolCallId, childrenByParentToolCallId, taskId } = props;
|
||||
const { worktreePath, onOpenFile, lastTurnGroupId, isRunning, messages, sessionState } = props;
|
||||
const { hasMore, isLoadingMore, loadMore } = props;
|
||||
const virtuosoRef = useRef<VirtuosoHandle>(null);
|
||||
const itemCount = items.length;
|
||||
const firstItemIndex = useStableFirstItemIndex(items);
|
||||
|
||||
const loadCooldownRef = useRef(false);
|
||||
const handleStartReached = useCallback(() => {
|
||||
if (hasMore && !isLoadingMore && !loadCooldownRef.current) {
|
||||
loadCooldownRef.current = true;
|
||||
loadMore().finally(() => {
|
||||
setTimeout(() => {
|
||||
loadCooldownRef.current = false;
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
}, [hasMore, isLoadingMore, loadMore]);
|
||||
|
||||
const handleScrollToMessage = useCallback(
|
||||
(messageId: string) => {
|
||||
const idx = items.findIndex((item) => {
|
||||
if (item.type === "turn_group") return item.messages.some((m) => m.id === messageId);
|
||||
return item.message?.id === messageId;
|
||||
});
|
||||
if (idx >= 0)
|
||||
virtuosoRef.current?.scrollToIndex({ index: firstItemIndex + idx, align: "center" });
|
||||
},
|
||||
[items, firstItemIndex],
|
||||
);
|
||||
|
||||
const computeItemKey = useCallback(
|
||||
(index: number) => {
|
||||
const item = items[index - firstItemIndex];
|
||||
if (!item) return index;
|
||||
return getItemKey(item);
|
||||
},
|
||||
[items, firstItemIndex],
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
(index: number) => {
|
||||
const item = items[index - firstItemIndex];
|
||||
if (!item) return <div />;
|
||||
|
||||
return (
|
||||
<div className="pb-2">
|
||||
<MessageItem
|
||||
item={item}
|
||||
sessionId={sessionId}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
taskId={taskId}
|
||||
worktreePath={worktreePath}
|
||||
onOpenFile={onOpenFile}
|
||||
isLastGroup={item.type === "turn_group" && item.id === lastTurnGroupId}
|
||||
isTurnActive={isRunning}
|
||||
messages={messages}
|
||||
sessionState={sessionState}
|
||||
onScrollToMessage={handleScrollToMessage}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
[
|
||||
items,
|
||||
firstItemIndex,
|
||||
sessionId,
|
||||
permissionsByToolCallId,
|
||||
childrenByParentToolCallId,
|
||||
taskId,
|
||||
worktreePath,
|
||||
onOpenFile,
|
||||
lastTurnGroupId,
|
||||
isRunning,
|
||||
messages,
|
||||
sessionState,
|
||||
handleScrollToMessage,
|
||||
],
|
||||
);
|
||||
|
||||
return { virtuosoRef, itemCount, firstItemIndex, handleStartReached, computeItemKey, renderItem };
|
||||
}
|
||||
|
||||
const FOLLOW_SMOOTH = "smooth" as const;
|
||||
const followOutput = (isAtBottom: boolean) => (isAtBottom ? FOLLOW_SMOOTH : false);
|
||||
|
||||
function VirtuosoBody(props: VirtuosoBodyProps) {
|
||||
const { scrollParent, Header, Footer } = props;
|
||||
const { virtuosoRef, itemCount, firstItemIndex, handleStartReached, computeItemKey, renderItem } =
|
||||
useVirtuosoCallbacks(props);
|
||||
|
||||
return (
|
||||
<Virtuoso
|
||||
ref={virtuosoRef}
|
||||
/* Suppress Virtuoso's verbose internal logging in all environments */
|
||||
logLevel={Number.MAX_SAFE_INTEGER}
|
||||
customScrollParent={scrollParent}
|
||||
totalCount={itemCount}
|
||||
firstItemIndex={firstItemIndex}
|
||||
initialTopMostItemIndex={itemCount - 1}
|
||||
computeItemKey={computeItemKey}
|
||||
itemContent={renderItem}
|
||||
followOutput={followOutput}
|
||||
startReached={handleStartReached}
|
||||
increaseViewportBy={200}
|
||||
atBottomThreshold={100}
|
||||
components={{ Header, Footer }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Defer providing scroll parent to Virtuoso until the element has non-zero size. */
|
||||
function useVisibleScrollParent() {
|
||||
const [scrollParent, setScrollParent] = useState<HTMLDivElement | null>(null);
|
||||
const nodeRef = useRef<HTMLDivElement | null>(null);
|
||||
const setScrollRef = useCallback((node: HTMLDivElement | null) => {
|
||||
nodeRef.current = node;
|
||||
if (node && node.offsetHeight > 0) setScrollParent(node);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const node = nodeRef.current;
|
||||
if (!node || scrollParent) return;
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.contentRect.height > 0) {
|
||||
setScrollParent(node);
|
||||
ro.disconnect();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
ro.observe(node);
|
||||
return () => ro.disconnect();
|
||||
}, [scrollParent]);
|
||||
return { scrollParent, setScrollRef };
|
||||
}
|
||||
|
||||
export const VirtuosoMessageList = memo(function VirtuosoMessageList(props: MessageListProps) {
|
||||
const { items, messages, sessionId, messagesLoading, isWorking, sessionState } = props;
|
||||
const { scrollParent, setScrollRef } = useVisibleScrollParent();
|
||||
const isInitialLoading = messagesLoading && messages.length === 0;
|
||||
const isNonLoadableSession =
|
||||
!sessionState || ["CREATED", "FAILED", "COMPLETED", "CANCELLED"].includes(sessionState);
|
||||
const showLoadingState =
|
||||
(messagesLoading || isInitialLoading) && !isWorking && !isNonLoadableSession;
|
||||
const { loadMore, hasMore, isLoading: isLoadingMore } = useLazyLoadMessages(sessionId);
|
||||
const isRunning = getSessionRunningState(sessionState);
|
||||
const lastTurnGroupId = useMemo(() => getLastTurnGroupId(items), [items]);
|
||||
|
||||
const Header = useCallback(
|
||||
() => (
|
||||
<MessageListStatus
|
||||
isLoadingMore={isLoadingMore}
|
||||
hasMore={hasMore}
|
||||
showLoadingState={showLoadingState}
|
||||
messagesLoading={messagesLoading}
|
||||
isInitialLoading={isInitialLoading}
|
||||
messagesCount={messages.length}
|
||||
/>
|
||||
),
|
||||
[isLoadingMore, hasMore, showLoadingState, messagesLoading, isInitialLoading, messages.length],
|
||||
);
|
||||
|
||||
const Footer = useCallback(
|
||||
() => (
|
||||
<>
|
||||
{sessionId && <PrepareProgress sessionId={sessionId} />}
|
||||
<AgentStatus sessionState={sessionState} sessionId={sessionId} messages={messages} />
|
||||
</>
|
||||
),
|
||||
[sessionId, sessionState, messages],
|
||||
);
|
||||
|
||||
if (isInitialLoading || items.length === 0) {
|
||||
return (
|
||||
<SessionPanelContent className="relative p-4 chat-message-list">
|
||||
<MessageListStatus
|
||||
isLoadingMore={isLoadingMore}
|
||||
hasMore={hasMore}
|
||||
showLoadingState={showLoadingState}
|
||||
messagesLoading={messagesLoading}
|
||||
isInitialLoading={isInitialLoading}
|
||||
messagesCount={messages.length}
|
||||
/>
|
||||
{sessionId && <PrepareProgress sessionId={sessionId} />}
|
||||
<AgentStatus sessionState={sessionState} sessionId={sessionId} messages={messages} />
|
||||
</SessionPanelContent>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SessionPanelContent ref={setScrollRef} className="relative p-4 chat-message-list">
|
||||
{scrollParent && (
|
||||
<VirtuosoBody
|
||||
{...props}
|
||||
scrollParent={scrollParent}
|
||||
isRunning={isRunning}
|
||||
lastTurnGroupId={lastTurnGroupId}
|
||||
hasMore={hasMore}
|
||||
isLoadingMore={isLoadingMore}
|
||||
loadMore={loadMore}
|
||||
Header={Header}
|
||||
Footer={Footer}
|
||||
/>
|
||||
)}
|
||||
</SessionPanelContent>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
import { memo } from "react";
|
||||
import { NativeMessageList } from "./message-list-native";
|
||||
import { VirtuosoMessageList } from "./message-list-virtuoso";
|
||||
import type { MessageListProps } from "./message-list-shared";
|
||||
|
||||
const strategies: Record<string, ComponentType<MessageListProps>> = {
|
||||
native: NativeMessageList,
|
||||
virtuoso: VirtuosoMessageList,
|
||||
};
|
||||
|
||||
/**
|
||||
* Rendering strategy for the message list.
|
||||
* - "native": simple DOM rendering with overflow-anchor for scroll pinning.
|
||||
* Better for short/medium conversations; avoids Virtuoso measurement quirks.
|
||||
* - "virtuoso": react-virtuoso windowed rendering.
|
||||
* Better for very long conversations (1000+ messages) where DOM node count matters.
|
||||
*/
|
||||
const STRATEGY = "native";
|
||||
|
||||
export const MessageList = memo(function MessageList(props: MessageListProps) {
|
||||
const Renderer = strategies[STRATEGY] ?? NativeMessageList;
|
||||
return <Renderer {...props} />;
|
||||
});
|
||||
@@ -75,7 +75,7 @@ function renderContentWithFileRefs(content: string): React.ReactNode[] {
|
||||
parts.push(
|
||||
<code
|
||||
key={`file-ref-${keyIndex++}`}
|
||||
className="px-1 py-0.5 bg-emerald-500/20 text-emerald-400 rounded font-mono text-[0.9em]"
|
||||
className="px-1 py-0.5 bg-foreground/[0.06] text-foreground/80 rounded font-mono text-[0.9em]"
|
||||
>
|
||||
@{filePath}
|
||||
</code>,
|
||||
@@ -105,26 +105,28 @@ const markdownComponents = {
|
||||
return <InlineCode>{content}</InlineCode>;
|
||||
},
|
||||
ol: ({ children }: { children?: ReactNode }) => (
|
||||
<ol className="list-decimal pl-6 mb-2">{children}</ol>
|
||||
<ol className="list-decimal pl-5 my-4">{children}</ol>
|
||||
),
|
||||
ul: ({ children }: { children?: ReactNode }) => (
|
||||
<ul className="list-disc pl-6 mb-2">{children}</ul>
|
||||
<ul className="list-disc pl-5 my-4">{children}</ul>
|
||||
),
|
||||
li: ({ children }: { children?: ReactNode }) => <li className="my-0.5">{children}</li>,
|
||||
p: ({ children }: { children?: ReactNode }) => (
|
||||
<p className="leading-relaxed mb-1.5">{children}</p>
|
||||
),
|
||||
p: ({ children }: { children?: ReactNode }) => <p className="leading-[1.625]">{children}</p>,
|
||||
h1: ({ children }: { children?: ReactNode }) => (
|
||||
<p className="my-3 font-bold text-sm">{children}</p>
|
||||
<h1 className="mt-5 mb-1.5 font-bold text-xl first:mt-0">{children}</h1>
|
||||
),
|
||||
h2: ({ children }: { children?: ReactNode }) => (
|
||||
<p className="my-2 font-bold text-sm">{children}</p>
|
||||
<h2 className="mt-5 mb-1.5 font-bold text-[1.0625rem] first:mt-0">{children}</h2>
|
||||
),
|
||||
h3: ({ children }: { children?: ReactNode }) => (
|
||||
<p className="my-2 font-bold text-sm">{children}</p>
|
||||
<h3 className="mt-5 mb-1.5 font-bold text-[0.9375rem] first:mt-0">{children}</h3>
|
||||
),
|
||||
h4: ({ children }: { children?: ReactNode }) => (
|
||||
<h4 className="mt-5 mb-1.5 font-bold first:mt-0">{children}</h4>
|
||||
),
|
||||
h5: ({ children }: { children?: ReactNode }) => (
|
||||
<h5 className="mt-5 mb-1.5 font-bold first:mt-0">{children}</h5>
|
||||
),
|
||||
h4: ({ children }: { children?: ReactNode }) => <p className="my-2 font-bold">{children}</p>,
|
||||
h5: ({ children }: { children?: ReactNode }) => <p className="my-2 font-bold">{children}</p>,
|
||||
hr: ({ children }: { children?: ReactNode }) => <hr className="my-5">{children}</hr>,
|
||||
table: ({ children }: { children?: ReactNode }) => (
|
||||
<div className="my-3 overflow-x-auto">
|
||||
|
||||
@@ -30,8 +30,8 @@ export function InlineCode({ children }: InlineCodeProps) {
|
||||
<code
|
||||
onClick={handleClick}
|
||||
className={cn(
|
||||
"px-0.5 py-0.5 text-indigo-400 rounded font-mono",
|
||||
"cursor-pointer hover:bg-indigo-500/30 transition-colors",
|
||||
"px-1 py-0.5 bg-foreground/[0.06] text-foreground/80 rounded font-mono",
|
||||
"cursor-pointer hover:bg-foreground/10 transition-colors",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
@@ -41,14 +41,14 @@ export function InlineCode({ children }: InlineCodeProps) {
|
||||
<span
|
||||
className={cn(
|
||||
"absolute bottom-full left-1/2 -translate-x-1/2 mb-1",
|
||||
"px-2 py-1 text-xs text-white bg-gray-900 rounded whitespace-nowrap",
|
||||
"px-2 py-1 text-xs text-popover-foreground bg-popover border border-border rounded shadow-md whitespace-nowrap",
|
||||
"pointer-events-none transition-opacity duration-200",
|
||||
"opacity-0 group-hover/inline-code:opacity-100",
|
||||
showTooltip && "opacity-100",
|
||||
)}
|
||||
>
|
||||
{tooltipText}
|
||||
<span className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-gray-900" />
|
||||
<span className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-border" />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState, useEffect, useImperativeHandle } from "react";
|
||||
import { useCallback, useRef, useState, useEffect, useImperativeHandle } from "react";
|
||||
import type React from "react";
|
||||
import { useResizableInput } from "@/hooks/use-resizable-input";
|
||||
import { useChatInputState } from "./use-chat-input-state";
|
||||
import type { QueuedMessageIndicatorHandle } from "./queued-message-indicator";
|
||||
import type { TipTapInputHandle } from "./tiptap-input";
|
||||
import type { ContextItem } from "@/lib/types/context";
|
||||
import type { ContextFile } from "@/lib/state/context-files-store";
|
||||
@@ -20,16 +19,12 @@ type UseChatInputContainerParams = {
|
||||
isFailed: boolean;
|
||||
isAgentBusy: boolean;
|
||||
hasAgentCommands: boolean;
|
||||
isQueued: boolean;
|
||||
placeholder: string | undefined;
|
||||
contextItems: ContextItem[];
|
||||
pendingClarification: Message | null | undefined;
|
||||
onClarificationResolved: (() => void) | undefined;
|
||||
pendingCommentsByFile: Record<string, DiffComment[]> | undefined;
|
||||
hasContextComments: boolean;
|
||||
queuedMessage: string | null | undefined;
|
||||
onCancelQueue: (() => void) | undefined;
|
||||
updateQueueContent: ((content: string) => Promise<void>) | undefined;
|
||||
todoItems: { text: string; done?: boolean }[];
|
||||
showRequestChangesTooltip: boolean;
|
||||
onRequestChangesTooltipDismiss: (() => void) | undefined;
|
||||
@@ -39,7 +34,6 @@ type UseChatInputContainerParams = {
|
||||
attachments?: MessageAttachment[],
|
||||
inlineMentions?: ContextFile[],
|
||||
) => void;
|
||||
queuedMessageRef?: React.RefObject<QueuedMessageIndicatorHandle | null>;
|
||||
};
|
||||
|
||||
function useInputHandle(
|
||||
@@ -80,10 +74,6 @@ function computeDerivedState(params: {
|
||||
pendingClarification: Message | null | undefined;
|
||||
onClarificationResolved: (() => void) | undefined;
|
||||
pendingCommentsByFile: Record<string, DiffComment[]> | undefined;
|
||||
isQueued: boolean;
|
||||
queuedMessage: string | null | undefined;
|
||||
onCancelQueue: (() => void) | undefined;
|
||||
updateQueueContent: ((content: string) => Promise<void>) | undefined;
|
||||
todoItems: { text: string }[];
|
||||
allItemsLength: number;
|
||||
isInputFocused: boolean;
|
||||
@@ -96,14 +86,8 @@ function computeDerivedState(params: {
|
||||
const hasPendingComments = !!(
|
||||
params.pendingCommentsByFile && Object.keys(params.pendingCommentsByFile).length > 0
|
||||
);
|
||||
const hasQueuedMessage = !!(
|
||||
params.isQueued &&
|
||||
params.queuedMessage &&
|
||||
params.onCancelQueue &&
|
||||
params.updateQueueContent
|
||||
);
|
||||
const hasTodos = params.todoItems.length > 0;
|
||||
const hasContextZone = hasQueuedMessage || hasTodos || params.allItemsLength > 0;
|
||||
const hasContextZone = hasTodos || params.allItemsLength > 0;
|
||||
const showFocusHint = !params.isInputFocused && !hasClarification && !hasPendingComments;
|
||||
const inputPlaceholder = getInputPlaceholder(
|
||||
params.placeholder,
|
||||
@@ -114,7 +98,6 @@ function computeDerivedState(params: {
|
||||
isDisabled,
|
||||
hasClarification,
|
||||
hasPendingComments,
|
||||
hasQueuedMessage,
|
||||
hasTodos,
|
||||
hasContextZone,
|
||||
showFocusHint,
|
||||
@@ -131,15 +114,11 @@ export function useChatInputContainer(params: UseChatInputContainerParams) {
|
||||
isFailed,
|
||||
isAgentBusy,
|
||||
hasAgentCommands,
|
||||
isQueued,
|
||||
placeholder,
|
||||
contextItems,
|
||||
pendingClarification,
|
||||
onClarificationResolved,
|
||||
pendingCommentsByFile,
|
||||
queuedMessage,
|
||||
onCancelQueue,
|
||||
updateQueueContent,
|
||||
todoItems,
|
||||
showRequestChangesTooltip,
|
||||
onRequestChangesTooltipDismiss,
|
||||
@@ -150,8 +129,11 @@ export function useChatInputContainer(params: UseChatInputContainerParams) {
|
||||
const [showNewSessionDialog, setShowNewSessionDialog] = useState(false);
|
||||
const [contextPopoverOpen, setContextPopoverOpen] = useState(false);
|
||||
|
||||
const tiptapRef = useRef<TipTapInputHandle | null>(null);
|
||||
const getContentElement = useCallback(() => tiptapRef.current?.getTextareaElement() ?? null, []);
|
||||
const { height, resetHeight, autoExpand, containerRef, resizeHandleProps } = useResizableInput(
|
||||
sessionId ?? undefined,
|
||||
getContentElement,
|
||||
);
|
||||
const { value, inputRef, handleImagePaste, handleChange, handleSubmit, allItems } =
|
||||
useChatInputState({
|
||||
@@ -165,6 +147,10 @@ export function useChatInputContainer(params: UseChatInputContainerParams) {
|
||||
onSubmit,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
tiptapRef.current = inputRef.current;
|
||||
});
|
||||
|
||||
useInputHandle(ref, inputRef);
|
||||
|
||||
// Auto-expand the input container as the user types more lines
|
||||
@@ -198,10 +184,6 @@ export function useChatInputContainer(params: UseChatInputContainerParams) {
|
||||
pendingClarification,
|
||||
onClarificationResolved,
|
||||
pendingCommentsByFile,
|
||||
isQueued,
|
||||
queuedMessage,
|
||||
onCancelQueue,
|
||||
updateQueueContent,
|
||||
todoItems,
|
||||
allItemsLength: allItems.length,
|
||||
isInputFocused,
|
||||
|
||||
@@ -1,401 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, memo } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import type { Virtualizer } from "@tanstack/react-virtual";
|
||||
import { GridSpinner } from "@/components/grid-spinner";
|
||||
import { SessionPanelContent } from "@kandev/ui/pannel-session";
|
||||
import type { Message, TaskSessionState } from "@/lib/types/http";
|
||||
import type { RenderItem } from "@/hooks/use-processed-messages";
|
||||
import { MessageRenderer } from "@/components/task/chat/message-renderer";
|
||||
import { TurnGroupMessage } from "@/components/task/chat/messages/turn-group-message";
|
||||
import { AgentStatus } from "@/components/task/chat/messages/agent-status";
|
||||
import { PrepareProgress } from "@/components/session/prepare-progress";
|
||||
import { useLazyLoadMessages } from "@/hooks/use-lazy-load-messages";
|
||||
|
||||
type ContainerResizeContext = {
|
||||
isHiddenRef: React.RefObject<boolean>;
|
||||
previousHeightRef: React.RefObject<number>;
|
||||
previousWidthRef: React.RefObject<number>;
|
||||
wasAtBottomRef: React.RefObject<boolean>;
|
||||
virtualizerRef: React.RefObject<MessageVirtualizer>;
|
||||
scrollSnapshot: React.RefObject<{ wasAtBottom: boolean; firstVisibleIndex: number }>;
|
||||
};
|
||||
|
||||
type MessageVirtualizer = Virtualizer<HTMLDivElement, Element>;
|
||||
|
||||
function handleContainerResize(
|
||||
entry: ResizeObserverEntry,
|
||||
element: HTMLDivElement,
|
||||
ctx: ContainerResizeContext,
|
||||
): void {
|
||||
const {
|
||||
isHiddenRef,
|
||||
previousHeightRef,
|
||||
previousWidthRef,
|
||||
wasAtBottomRef,
|
||||
virtualizerRef,
|
||||
scrollSnapshot,
|
||||
} = ctx;
|
||||
const currentHeight = entry.contentRect.height;
|
||||
const currentWidth = entry.contentRect.width;
|
||||
const previousHeight = previousHeightRef.current;
|
||||
const previousWidth = previousWidthRef.current;
|
||||
|
||||
if (currentWidth === 0 || currentHeight === 0) {
|
||||
isHiddenRef.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isHiddenRef.current) {
|
||||
isHiddenRef.current = false;
|
||||
previousHeightRef.current = currentHeight;
|
||||
previousWidthRef.current = currentWidth;
|
||||
const virt = virtualizerRef.current;
|
||||
const snapshot = scrollSnapshot.current;
|
||||
virt.measure();
|
||||
requestAnimationFrame(() => {
|
||||
if (snapshot.wasAtBottom) {
|
||||
const count = virt.options.count;
|
||||
if (count > 0) virt.scrollToIndex(count - 1, { align: "end" });
|
||||
} else {
|
||||
virt.scrollToIndex(snapshot.firstVisibleIndex, { align: "start" });
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousWidth > 0 && Math.abs(currentWidth - previousWidth) > 20)
|
||||
virtualizerRef.current.measure();
|
||||
if (previousHeight > 0 && currentHeight < previousHeight && wasAtBottomRef.current) {
|
||||
requestAnimationFrame(() => {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
});
|
||||
}
|
||||
previousHeightRef.current = currentHeight;
|
||||
previousWidthRef.current = currentWidth;
|
||||
}
|
||||
|
||||
function useVirtualListScrolling(
|
||||
sessionId: string | null,
|
||||
virtualizer: MessageVirtualizer,
|
||||
messagesContainerRef: React.RefObject<HTMLDivElement | null>,
|
||||
) {
|
||||
const wasAtBottomRef = useRef(true);
|
||||
const savedScrollTopRef = useRef(0);
|
||||
const previousHeightRef = useRef(0);
|
||||
const previousWidthRef = useRef(0);
|
||||
const isHiddenRef = useRef(false);
|
||||
const scrollSnapshot = useRef<{ wasAtBottom: boolean; firstVisibleIndex: number }>({
|
||||
wasAtBottom: true,
|
||||
firstVisibleIndex: 0,
|
||||
});
|
||||
const { loadMore, hasMore, isLoading: isLoadingMore } = useLazyLoadMessages(sessionId);
|
||||
const loadingRef = useRef({ hasMore, isLoadingMore });
|
||||
loadingRef.current = { hasMore, isLoadingMore };
|
||||
const virtualizerRef = useRef(virtualizer);
|
||||
virtualizerRef.current = virtualizer;
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const element = messagesContainerRef.current;
|
||||
if (!element || isHiddenRef.current) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = element;
|
||||
wasAtBottomRef.current = scrollHeight - scrollTop - clientHeight < 100;
|
||||
savedScrollTopRef.current = scrollTop;
|
||||
const virt = virtualizerRef.current;
|
||||
const visibleItems = virt.getVirtualItems();
|
||||
scrollSnapshot.current = {
|
||||
wasAtBottom: wasAtBottomRef.current,
|
||||
firstVisibleIndex: visibleItems.length > 0 ? visibleItems[0].index : 0,
|
||||
};
|
||||
if (scrollTop < 40 && loadingRef.current.hasMore && !loadingRef.current.isLoadingMore) {
|
||||
const prevScrollHeight = scrollHeight;
|
||||
const prevScrollTop = scrollTop;
|
||||
loadMore().then((added) => {
|
||||
if (!added) return;
|
||||
requestAnimationFrame(() => {
|
||||
const nextScrollHeight = element.scrollHeight;
|
||||
element.scrollTop = prevScrollTop + (nextScrollHeight - prevScrollHeight);
|
||||
});
|
||||
});
|
||||
}
|
||||
}, [loadMore, messagesContainerRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = messagesContainerRef.current;
|
||||
if (!element) return;
|
||||
element.addEventListener("scroll", handleScroll);
|
||||
return () => element.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll, messagesContainerRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = messagesContainerRef.current;
|
||||
if (!element) return;
|
||||
const resizeCtx: ContainerResizeContext = {
|
||||
isHiddenRef,
|
||||
previousHeightRef,
|
||||
previousWidthRef,
|
||||
wasAtBottomRef,
|
||||
virtualizerRef,
|
||||
scrollSnapshot,
|
||||
};
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) handleContainerResize(entry, element, resizeCtx);
|
||||
});
|
||||
resizeObserver.observe(element);
|
||||
return () => resizeObserver.disconnect();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return { wasAtBottomRef, hasMore, isLoadingMore };
|
||||
}
|
||||
|
||||
type VirtualizedMessageListProps = {
|
||||
items: RenderItem[];
|
||||
messages: Message[];
|
||||
permissionsByToolCallId: Map<string, Message>;
|
||||
childrenByParentToolCallId: Map<string, Message[]>;
|
||||
taskId?: string;
|
||||
sessionId: string | null;
|
||||
messagesLoading: boolean;
|
||||
isWorking: boolean;
|
||||
sessionState?: TaskSessionState;
|
||||
worktreePath?: string;
|
||||
onOpenFile?: (path: string) => void;
|
||||
};
|
||||
|
||||
type MessageListBodyProps = {
|
||||
items: RenderItem[];
|
||||
messages: Message[];
|
||||
permissionsByToolCallId: Map<string, Message>;
|
||||
childrenByParentToolCallId: Map<string, Message[]>;
|
||||
taskId?: string;
|
||||
sessionId: string | null;
|
||||
sessionState?: TaskSessionState;
|
||||
worktreePath?: string;
|
||||
onOpenFile?: (path: string) => void;
|
||||
isInitialLoading: boolean;
|
||||
virtualizer: MessageVirtualizer;
|
||||
lastTurnGroupId: string | null;
|
||||
isRunning: boolean;
|
||||
handleScrollToMessage: (messageId: string) => void;
|
||||
};
|
||||
|
||||
function MessageListBody({
|
||||
items,
|
||||
messages,
|
||||
permissionsByToolCallId,
|
||||
childrenByParentToolCallId,
|
||||
taskId,
|
||||
sessionId,
|
||||
sessionState,
|
||||
worktreePath,
|
||||
onOpenFile,
|
||||
isInitialLoading,
|
||||
virtualizer,
|
||||
lastTurnGroupId,
|
||||
isRunning,
|
||||
handleScrollToMessage,
|
||||
}: MessageListBodyProps) {
|
||||
const itemCount = items.length;
|
||||
if (isInitialLoading || itemCount === 0) return null;
|
||||
return (
|
||||
<div className="relative w-full" style={{ height: `${virtualizer.getTotalSize()}px` }}>
|
||||
{virtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const item = items[virtualRow.index];
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
ref={virtualizer.measureElement}
|
||||
data-index={virtualRow.index}
|
||||
className="absolute left-0 top-0 w-full"
|
||||
style={{ transform: `translateY(${virtualRow.start}px)` }}
|
||||
>
|
||||
<div className="pb-2">
|
||||
{item.type === "turn_group" ? (
|
||||
<TurnGroupMessage
|
||||
group={item}
|
||||
sessionId={sessionId}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
taskId={taskId}
|
||||
worktreePath={worktreePath}
|
||||
onOpenFile={onOpenFile}
|
||||
isLastGroup={item.id === lastTurnGroupId}
|
||||
isTurnActive={isRunning}
|
||||
allMessages={messages}
|
||||
onScrollToMessage={handleScrollToMessage}
|
||||
/>
|
||||
) : (
|
||||
<MessageRenderer
|
||||
comment={item.message}
|
||||
isTaskDescription={item.message.id === "task-description"}
|
||||
sessionState={sessionState}
|
||||
taskId={taskId}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
worktreePath={worktreePath}
|
||||
sessionId={sessionId ?? undefined}
|
||||
onOpenFile={onOpenFile}
|
||||
allMessages={messages}
|
||||
onScrollToMessage={handleScrollToMessage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getSessionRunningState(sessionState: string | null | undefined) {
|
||||
return sessionState === "CREATED" || sessionState === "STARTING" || sessionState === "RUNNING";
|
||||
}
|
||||
|
||||
function getLastTurnGroupId(items: RenderItem[]) {
|
||||
for (let i = items.length - 1; i >= 0; i--) {
|
||||
const item = items[i];
|
||||
if (item.type === "turn_group") return item.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function MessageListStatus({
|
||||
isLoadingMore,
|
||||
hasMore,
|
||||
showLoadingState,
|
||||
messagesLoading,
|
||||
isInitialLoading,
|
||||
messagesCount,
|
||||
}: {
|
||||
isLoadingMore: boolean;
|
||||
hasMore: boolean;
|
||||
showLoadingState: boolean;
|
||||
messagesLoading: boolean;
|
||||
isInitialLoading: boolean;
|
||||
messagesCount: number;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{isLoadingMore && hasMore && (
|
||||
<div className="absolute top-2 left-1/2 -translate-x-1/2 text-xs text-muted-foreground">
|
||||
Loading older messages...
|
||||
</div>
|
||||
)}
|
||||
{showLoadingState && (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<GridSpinner className="text-primary mr-2" />
|
||||
<span>Loading messages...</span>
|
||||
</div>
|
||||
)}
|
||||
{!messagesLoading && !isInitialLoading && messagesCount === 0 && (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<span>No messages yet. Start the conversation!</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const VirtualizedMessageList = memo(function VirtualizedMessageList({
|
||||
items,
|
||||
messages,
|
||||
permissionsByToolCallId,
|
||||
childrenByParentToolCallId,
|
||||
taskId,
|
||||
sessionId,
|
||||
messagesLoading,
|
||||
isWorking,
|
||||
sessionState,
|
||||
worktreePath,
|
||||
onOpenFile,
|
||||
}: VirtualizedMessageListProps) {
|
||||
const messagesContainerRef = useRef<HTMLDivElement>(null);
|
||||
const isInitialLoading = messagesLoading && messages.length === 0;
|
||||
const isNonLoadableSession =
|
||||
!sessionState || ["CREATED", "FAILED", "COMPLETED", "CANCELLED"].includes(sessionState);
|
||||
const showLoadingState =
|
||||
(messagesLoading || isInitialLoading) && !isWorking && !isNonLoadableSession;
|
||||
const itemCount = items.length;
|
||||
|
||||
// eslint-disable-next-line react-hooks/incompatible-library
|
||||
const virtualizer = useVirtualizer({
|
||||
count: itemCount,
|
||||
getScrollElement: () => messagesContainerRef.current,
|
||||
estimateSize: () => 96,
|
||||
overscan: 6,
|
||||
});
|
||||
const { wasAtBottomRef, hasMore, isLoadingMore } = useVirtualListScrolling(
|
||||
sessionId,
|
||||
virtualizer,
|
||||
messagesContainerRef,
|
||||
);
|
||||
|
||||
const handleScrollToMessage = useCallback(
|
||||
(messageId: string) => {
|
||||
const index = items.findIndex((item) => {
|
||||
if (item.type === "turn_group") return item.messages.some((msg) => msg.id === messageId);
|
||||
return item.message?.id === messageId;
|
||||
});
|
||||
if (index >= 0) virtualizer.scrollToIndex(index, { align: "center" });
|
||||
},
|
||||
[items, virtualizer],
|
||||
);
|
||||
|
||||
const lastMessageContent = useMemo(() => {
|
||||
if (items.length === 0) return "";
|
||||
const lastItem = items[items.length - 1];
|
||||
if (lastItem.type === "turn_group")
|
||||
return lastItem.messages[lastItem.messages.length - 1]?.content ?? "";
|
||||
return lastItem.message?.content ?? "";
|
||||
}, [items]);
|
||||
|
||||
useEffect(() => {
|
||||
if (itemCount === 0) return;
|
||||
if (wasAtBottomRef.current) virtualizer.scrollToIndex(itemCount - 1, { align: "end" });
|
||||
}, [itemCount, lastMessageContent, virtualizer, wasAtBottomRef]);
|
||||
|
||||
const isRunning = getSessionRunningState(sessionState);
|
||||
const lastTurnGroupId = useMemo(() => getLastTurnGroupId(items), [items]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRunning) return;
|
||||
const element = messagesContainerRef.current;
|
||||
if (!element) return;
|
||||
requestAnimationFrame(() => {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
});
|
||||
}, [isRunning]);
|
||||
|
||||
return (
|
||||
<SessionPanelContent ref={messagesContainerRef} className="relative p-4 chat-message-list">
|
||||
<MessageListStatus
|
||||
isLoadingMore={isLoadingMore}
|
||||
hasMore={hasMore}
|
||||
showLoadingState={showLoadingState}
|
||||
messagesLoading={messagesLoading}
|
||||
isInitialLoading={isInitialLoading}
|
||||
messagesCount={messages.length}
|
||||
/>
|
||||
<MessageListBody
|
||||
items={items}
|
||||
messages={messages}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
taskId={taskId}
|
||||
sessionId={sessionId}
|
||||
sessionState={sessionState}
|
||||
worktreePath={worktreePath}
|
||||
onOpenFile={onOpenFile}
|
||||
isInitialLoading={isInitialLoading}
|
||||
virtualizer={virtualizer}
|
||||
lastTurnGroupId={lastTurnGroupId}
|
||||
isRunning={isRunning}
|
||||
handleScrollToMessage={handleScrollToMessage}
|
||||
/>
|
||||
{sessionId && <PrepareProgress sessionId={sessionId} />}
|
||||
<AgentStatus sessionState={sessionState} sessionId={sessionId} messages={messages} />
|
||||
</SessionPanelContent>
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { type IDockviewHeaderActionsProps } from "dockview-react";
|
||||
import {
|
||||
IconPlus,
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
IconLayoutRows,
|
||||
IconX,
|
||||
IconBrandVscode,
|
||||
IconArrowsMaximize,
|
||||
IconArrowsMinimize,
|
||||
} from "@tabler/icons-react";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
@@ -154,11 +156,23 @@ export function LeftHeaderActions(props: IDockviewHeaderActionsProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Faded split-vertical, split-horizontal, and close buttons for any non-sidebar group. */
|
||||
const ACTION_BTN =
|
||||
"h-5 w-5 inline-flex items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer";
|
||||
|
||||
/** Faded maximize, split, and close buttons for any non-sidebar group. */
|
||||
function GroupSplitCloseActions({ group, containerApi }: IDockviewHeaderActionsProps) {
|
||||
const centerGroupId = useDockviewStore((s) => s.centerGroupId);
|
||||
const isChatGroup = group.id === centerGroupId;
|
||||
|
||||
const handleMaximize = useCallback(() => {
|
||||
if (containerApi.hasMaximizedGroup()) {
|
||||
containerApi.exitMaximizedGroup();
|
||||
} else {
|
||||
const panel = group.activePanel;
|
||||
if (panel) containerApi.maximizeGroup(panel);
|
||||
}
|
||||
}, [group, containerApi]);
|
||||
|
||||
const handleSplitRight = useCallback(() => {
|
||||
containerApi.addGroup({ referenceGroup: group, direction: "right" });
|
||||
}, [group, containerApi]);
|
||||
@@ -186,28 +200,40 @@ function GroupSplitCloseActions({ group, containerApi }: IDockviewHeaderActionsP
|
||||
}
|
||||
}, [group, containerApi]);
|
||||
|
||||
const [isMaximized, setIsMaximized] = useState(() => containerApi.hasMaximizedGroup());
|
||||
useEffect(() => {
|
||||
const disposable = containerApi.onDidMaximizedGroupChange(() => {
|
||||
setIsMaximized(containerApi.hasMaximizedGroup());
|
||||
});
|
||||
return () => disposable.dispose();
|
||||
}, [containerApi]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="h-6 w-6 inline-flex items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer"
|
||||
onClick={handleSplitRight}
|
||||
>
|
||||
<IconLayoutColumns className="h-3.5 w-3.5" />
|
||||
<button type="button" className={ACTION_BTN} onClick={handleMaximize}>
|
||||
{isMaximized ? (
|
||||
<IconArrowsMinimize className="h-3 w-3" />
|
||||
) : (
|
||||
<IconArrowsMaximize className="h-3 w-3" />
|
||||
)}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{isMaximized ? "Restore" : "Maximize"}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className={ACTION_BTN} onClick={handleSplitRight}>
|
||||
<IconLayoutColumns className="h-3 w-3" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Split right</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="h-6 w-6 inline-flex items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer"
|
||||
onClick={handleSplitDown}
|
||||
>
|
||||
<IconLayoutRows className="h-3.5 w-3.5" />
|
||||
<button type="button" className={ACTION_BTN} onClick={handleSplitDown}>
|
||||
<IconLayoutRows className="h-3 w-3" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Split down</TooltipContent>
|
||||
@@ -215,12 +241,8 @@ function GroupSplitCloseActions({ group, containerApi }: IDockviewHeaderActionsP
|
||||
{!isChatGroup && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="h-6 w-6 inline-flex items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer"
|
||||
onClick={handleCloseGroup}
|
||||
>
|
||||
<IconX className="h-3.5 w-3.5" />
|
||||
<button type="button" className={ACTION_BTN} onClick={handleCloseGroup}>
|
||||
<IconX className="h-3 w-3" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Close group</TooltipContent>
|
||||
@@ -308,14 +330,13 @@ function RightTopGroupActions() {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-6 w-6 p-0 cursor-pointer"
|
||||
<button
|
||||
type="button"
|
||||
className="h-6 w-6 inline-flex items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer"
|
||||
onClick={toggleRightPanels}
|
||||
>
|
||||
<IconLayoutSidebarRightCollapse className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Hide right panels</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
@@ -149,7 +149,7 @@ function getGitStatusTextClass(status: GitFileStatus): string {
|
||||
switch (status) {
|
||||
case "added":
|
||||
case "untracked":
|
||||
return "text-emerald-600";
|
||||
return "text-green-700 dark:text-green-600";
|
||||
case "modified":
|
||||
return "text-yellow-600";
|
||||
default:
|
||||
@@ -157,24 +157,6 @@ function getGitStatusTextClass(status: GitFileStatus): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getGitStatusDotClass(status: GitFileStatus): string {
|
||||
switch (status) {
|
||||
case "added":
|
||||
case "untracked":
|
||||
return "bg-emerald-500";
|
||||
case "modified":
|
||||
return "bg-yellow-500";
|
||||
default:
|
||||
return "bg-transparent";
|
||||
}
|
||||
}
|
||||
|
||||
function TreeNodeGitStatusDot({ status }: { status: GitFileStatus }) {
|
||||
if (!status || (status !== "added" && status !== "untracked" && status !== "modified"))
|
||||
return null;
|
||||
return <span className={cn("h-1.5 w-1.5 rounded-full", getGitStatusDotClass(status))} />;
|
||||
}
|
||||
|
||||
/** Delete button shown on hover for file nodes. */
|
||||
function TreeNodeDeleteButton({
|
||||
node,
|
||||
@@ -266,17 +248,14 @@ export function TreeNodeItem({
|
||||
>
|
||||
{node.name}
|
||||
</span>
|
||||
{!node.is_dir && (
|
||||
{!node.is_dir && onDeleteFile && (
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<TreeNodeGitStatusDot status={gitStatus} />
|
||||
{onDeleteFile && (
|
||||
<TreeNodeDeleteButton
|
||||
node={node}
|
||||
tree={tree}
|
||||
setTree={setTree}
|
||||
onDeleteFile={onDeleteFile}
|
||||
/>
|
||||
)}
|
||||
<TreeNodeDeleteButton
|
||||
node={node}
|
||||
tree={tree}
|
||||
setTree={setTree}
|
||||
onDeleteFile={onDeleteFile}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -365,9 +344,6 @@ export function SearchResultsList({
|
||||
{folder && <span>{folder}/</span>}
|
||||
<span>{name}</span>
|
||||
</span>
|
||||
<div className="ml-auto flex items-center">
|
||||
<TreeNodeGitStatusDot status={gitStatus} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo, useCallback, useRef, useState } from "react";
|
||||
import React, { useEffect, useMemo, useCallback, useRef, useState } from "react";
|
||||
import { ScrollArea } from "@kandev/ui/scroll-area";
|
||||
import type { FileTreeNode, OpenFileTab } from "@/lib/types/backend";
|
||||
import { useSession } from "@/hooks/domains/session/use-session";
|
||||
import { useRepository } from "@/hooks/domains/workspace/use-repository";
|
||||
import { useSessionGitStatus } from "@/hooks/domains/session/use-session-git-status";
|
||||
import { useOpenSessionFolder } from "@/hooks/use-open-session-folder";
|
||||
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
|
||||
@@ -165,6 +166,7 @@ export function FileBrowser({
|
||||
activeFilePath,
|
||||
}: FileBrowserProps) {
|
||||
const { session, isFailed: isSessionFailed, errorMessage: sessionError } = useSession(sessionId);
|
||||
const repository = useRepository(session?.repository_id ?? null);
|
||||
const gitStatus = useSessionGitStatus(sessionId);
|
||||
const { open: openFolder } = useOpenSessionFolder(sessionId);
|
||||
const { copied, copy: copyPath } = useCopyToClipboard(1000);
|
||||
@@ -180,7 +182,7 @@ export function FileBrowser({
|
||||
new Map(Object.entries(gitStatus?.files ?? {}).map(([path, info]) => [path, info.status])),
|
||||
[gitStatus?.files],
|
||||
);
|
||||
const fullPath = session?.worktree_path ?? "";
|
||||
const fullPath = session?.worktree_path || repository?.local_path || "";
|
||||
const displayPath = fullPath.replace(/^\/(?:Users|home)\/[^/]+\//, "~/");
|
||||
|
||||
const {
|
||||
@@ -193,6 +195,24 @@ export function FileBrowser({
|
||||
handleCancelCreate,
|
||||
} = useFileBrowserHandlers(sessionId, onOpenFile, onCreateFile, treeState);
|
||||
|
||||
// Auto-expand ancestor directories when the active file changes
|
||||
useEffect(() => {
|
||||
if (!activeFilePath) return;
|
||||
const parts = activeFilePath.split("/");
|
||||
if (parts.length <= 1) return;
|
||||
const ancestors: string[] = [];
|
||||
for (let i = 1; i < parts.length; i++) {
|
||||
ancestors.push(parts.slice(0, i).join("/"));
|
||||
}
|
||||
treeState.setExpandedPaths((prev) => {
|
||||
const allExpanded = ancestors.every((p) => prev.has(p));
|
||||
if (allExpanded) return prev;
|
||||
const next = new Set(prev);
|
||||
for (const p of ancestors) next.add(p);
|
||||
return next;
|
||||
});
|
||||
}, [activeFilePath, treeState]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<FileBrowserHeader
|
||||
|
||||
@@ -4,6 +4,7 @@ import { memo, useCallback } from "react";
|
||||
import { PanelRoot, PanelBody } from "./panel-primitives";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useFileOperations } from "@/hooks/use-file-operations";
|
||||
import { useDockviewStore } from "@/lib/state/dockview-store";
|
||||
import { FileBrowser } from "@/components/task/file-browser";
|
||||
import type { OpenFileTab } from "@/lib/types/backend";
|
||||
import { useIsTaskArchived, ArchivedPanelPlaceholder } from "./task-archived-context";
|
||||
@@ -14,6 +15,7 @@ type FilesPanelProps = {
|
||||
|
||||
const FilesPanel = memo(function FilesPanel({ onOpenFile }: FilesPanelProps) {
|
||||
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
|
||||
const activeFilePath = useDockviewStore((s) => s.activeFilePath);
|
||||
const isArchived = useIsTaskArchived();
|
||||
const { createFile, deleteFile } = useFileOperations(activeSessionId ?? null);
|
||||
|
||||
@@ -49,6 +51,7 @@ const FilesPanel = memo(function FilesPanel({ onOpenFile }: FilesPanelProps) {
|
||||
onOpenFile={onOpenFile}
|
||||
onCreateFile={handleCreateFile}
|
||||
onDeleteFile={deleteFile}
|
||||
activeFilePath={activeFilePath}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground text-xs">
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useTaskActions } from "@/hooks/use-task-actions";
|
||||
import { useTaskRemoval } from "@/hooks/use-task-removal";
|
||||
import type {
|
||||
TaskState,
|
||||
TaskSessionState,
|
||||
Workspace,
|
||||
Repository,
|
||||
TaskSession,
|
||||
@@ -51,6 +52,7 @@ function mapSnapshotToKanban(snapshot: WorkflowSnapshot, newWorkflowId: string)
|
||||
state: task.state,
|
||||
repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
|
||||
primarySessionId: task.primary_session_id ?? undefined,
|
||||
primarySessionState: task.primary_session_state ?? undefined,
|
||||
sessionCount: task.session_count ?? undefined,
|
||||
reviewStatus: task.review_status ?? undefined,
|
||||
primaryExecutorId: task.primary_executor_id ?? undefined,
|
||||
@@ -91,13 +93,18 @@ function useSheetData(workspaceId: string | null, workflowId: string | null) {
|
||||
const getSessionInfoForTask = useCallback(
|
||||
(taskId: string) => {
|
||||
const sessions = sessionsByTaskId[taskId] ?? [];
|
||||
if (sessions.length === 0) return { diffStats: undefined, updatedAt: undefined };
|
||||
if (sessions.length === 0) {
|
||||
return { diffStats: undefined, updatedAt: undefined, sessionState: undefined };
|
||||
}
|
||||
const primarySession = sessions.find((s: TaskSession) => s.is_primary);
|
||||
const latestSession = primarySession ?? sessions[0];
|
||||
if (!latestSession) return { diffStats: undefined, updatedAt: undefined };
|
||||
if (!latestSession) {
|
||||
return { diffStats: undefined, updatedAt: undefined, sessionState: undefined };
|
||||
}
|
||||
const updatedAt = latestSession.updated_at;
|
||||
const sessionState = latestSession.state as TaskSessionState | undefined;
|
||||
const gitStatus = gitStatusBySessionId[latestSession.id];
|
||||
if (!gitStatus?.files) return { diffStats: undefined, updatedAt };
|
||||
if (!gitStatus?.files) return { diffStats: undefined, updatedAt, sessionState };
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const file of Object.values(gitStatus.files)) {
|
||||
@@ -105,7 +112,7 @@ function useSheetData(workspaceId: string | null, workflowId: string | null) {
|
||||
deletions += file.deletions ?? 0;
|
||||
}
|
||||
const diffStats = additions === 0 && deletions === 0 ? undefined : { additions, deletions };
|
||||
return { diffStats, updatedAt };
|
||||
return { diffStats, updatedAt, sessionState };
|
||||
},
|
||||
[sessionsByTaskId, gitStatusBySessionId],
|
||||
);
|
||||
@@ -121,6 +128,8 @@ function useSheetData(workspaceId: string | null, workflowId: string | null) {
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
state: task.state as TaskState | undefined,
|
||||
sessionState:
|
||||
sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined),
|
||||
description: task.description,
|
||||
workflowStepId: task.workflowStepId,
|
||||
repositoryPath: task.repositoryId ? repositoryPathsById.get(task.repositoryId) : undefined,
|
||||
|
||||
@@ -64,20 +64,6 @@ function buildModelOptions(
|
||||
return options;
|
||||
}
|
||||
|
||||
function NoModelButton() {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 gap-1 px-2 cursor-not-allowed opacity-50 whitespace-nowrap"
|
||||
disabled
|
||||
>
|
||||
<span className="text-xs">No model</span>
|
||||
<IconChevronDown className="h-3 w-3 text-muted-foreground shrink-0" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export const ModelSelector = memo(function ModelSelector({ sessionId }: ModelSelectorProps) {
|
||||
useSettingsData(true);
|
||||
|
||||
@@ -103,7 +89,7 @@ export const ModelSelector = memo(function ModelSelector({ sessionId }: ModelSel
|
||||
setActiveModel(sessionId, modelId);
|
||||
};
|
||||
|
||||
if (!sessionId || !currentModel) return <NoModelButton />;
|
||||
if (!sessionId || !currentModel) return null;
|
||||
|
||||
const displayName = modelOptions.find((m) => m.id === currentModel)?.name || currentModel;
|
||||
|
||||
|
||||
@@ -4,13 +4,50 @@ import { useCallback, useEffect, useRef, useState, memo } from "react";
|
||||
import { PanelRoot, PanelBody } from "./panel-primitives";
|
||||
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
|
||||
import { type ChatInputContainerHandle } from "@/components/task/chat/chat-input-container";
|
||||
import { type QueuedMessageIndicatorHandle } from "@/components/task/chat/queued-message-indicator";
|
||||
import { VirtualizedMessageList } from "@/components/task/chat/virtualized-message-list";
|
||||
import {
|
||||
QueuedMessageIndicator,
|
||||
type QueuedMessageIndicatorHandle,
|
||||
} from "@/components/task/chat/queued-message-indicator";
|
||||
import { MessageList } from "@/components/task/chat/message-list";
|
||||
import { useIsTaskArchived } from "./task-archived-context";
|
||||
import { useChatPanelState } from "./chat/use-chat-panel-state";
|
||||
import { ChatInputArea, useSubmitHandler, useChatPanelHandlers } from "./chat/chat-input-area";
|
||||
import { ClarificationInputOverlay } from "./chat/clarification-input-overlay";
|
||||
|
||||
type QueuedOverlayProps = {
|
||||
isQueued: boolean;
|
||||
queuedMessage: { content: string } | null | undefined;
|
||||
isArchived: boolean;
|
||||
indicatorRef: React.RefObject<QueuedMessageIndicatorHandle | null>;
|
||||
onCancel: () => void;
|
||||
onUpdate: (content: string) => Promise<void>;
|
||||
onEditComplete: () => void;
|
||||
};
|
||||
|
||||
function QueuedMessageOverlay({
|
||||
isQueued,
|
||||
queuedMessage,
|
||||
isArchived,
|
||||
indicatorRef,
|
||||
onCancel,
|
||||
onUpdate,
|
||||
onEditComplete,
|
||||
}: QueuedOverlayProps) {
|
||||
if (!isQueued || !queuedMessage || isArchived) return null;
|
||||
return (
|
||||
<div className="flex-shrink-0 border-t border-blue-400/30 bg-card px-3 py-1">
|
||||
<QueuedMessageIndicator
|
||||
ref={indicatorRef}
|
||||
content={queuedMessage.content}
|
||||
onCancel={onCancel}
|
||||
onUpdate={onUpdate}
|
||||
isVisible={true}
|
||||
onEditComplete={onEditComplete}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type TaskChatPanelProps = {
|
||||
onSend?: (message: string) => void;
|
||||
sessionId?: string | null;
|
||||
@@ -54,6 +91,9 @@ export const TaskChatPanel = memo(function TaskChatPanel({
|
||||
agentMessageCount,
|
||||
cancelQueue,
|
||||
pendingClarification,
|
||||
isQueued,
|
||||
queuedMessage,
|
||||
updateQueueContent,
|
||||
} = panelState;
|
||||
const { handleCancelTurn, handleCancelQueue, handleQueueEditComplete } = useChatPanelHandlers(
|
||||
resolvedSessionId,
|
||||
@@ -70,7 +110,7 @@ export const TaskChatPanel = memo(function TaskChatPanel({
|
||||
return (
|
||||
<PanelRoot>
|
||||
<PanelBody padding={false}>
|
||||
<VirtualizedMessageList
|
||||
<MessageList
|
||||
items={groupedItems}
|
||||
messages={allMessages}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
@@ -92,6 +132,15 @@ export const TaskChatPanel = memo(function TaskChatPanel({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<QueuedMessageOverlay
|
||||
isQueued={isQueued}
|
||||
queuedMessage={queuedMessage}
|
||||
isArchived={isArchived}
|
||||
indicatorRef={queuedMessageRef}
|
||||
onCancel={handleCancelQueue}
|
||||
onUpdate={updateQueueContent}
|
||||
onEditComplete={handleQueueEditComplete}
|
||||
/>
|
||||
{isArchived ? (
|
||||
<div className="bg-muted/50 flex-shrink-0 px-4 py-3 text-center text-sm text-muted-foreground border-t">
|
||||
This task is archived and read-only.
|
||||
@@ -99,13 +148,10 @@ export const TaskChatPanel = memo(function TaskChatPanel({
|
||||
) : (
|
||||
<ChatInputArea
|
||||
chatInputRef={chatInputRef}
|
||||
queuedMessageRef={queuedMessageRef}
|
||||
clarificationKey={clarificationKey}
|
||||
onClarificationResolved={handleClarificationResolved}
|
||||
handleSubmit={handleSubmit}
|
||||
handleCancelTurn={handleCancelTurn}
|
||||
handleCancelQueue={handleCancelQueue}
|
||||
handleQueueEditComplete={handleQueueEditComplete}
|
||||
showRequestChangesTooltip={showRequestChangesTooltip}
|
||||
onRequestChangesTooltipDismiss={onRequestChangesTooltipDismiss}
|
||||
isPanelFocused={isPanelFocused}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@kandev/ui/dialog";
|
||||
import { Input } from "@kandev/ui/input";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
|
||||
type TaskRenameDialogProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
currentTitle: string;
|
||||
onSubmit: (newTitle: string) => void;
|
||||
};
|
||||
|
||||
function TaskRenameForm({
|
||||
currentTitle,
|
||||
onSubmit,
|
||||
onClose,
|
||||
}: {
|
||||
currentTitle: string;
|
||||
onSubmit: (newTitle: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [value, setValue] = useState(currentTitle);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const trimmed = value.trim();
|
||||
const canSubmit = trimmed.length > 0 && trimmed !== currentTitle;
|
||||
|
||||
const handleSubmit = useCallback(() => {
|
||||
if (!canSubmit) return;
|
||||
onSubmit(trimmed);
|
||||
onClose();
|
||||
}, [canSubmit, trimmed, onSubmit, onClose]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rename task</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
autoFocus
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleSubmit();
|
||||
}}
|
||||
onFocus={(e) => e.target.select()}
|
||||
placeholder="Task title"
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" className="cursor-pointer" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className="cursor-pointer" disabled={!canSubmit} onClick={handleSubmit}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskRenameDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
currentTitle,
|
||||
onSubmit,
|
||||
}: TaskRenameDialogProps): React.JSX.Element {
|
||||
const handleClose = useCallback(() => onOpenChange(false), [onOpenChange]);
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
{open && (
|
||||
<TaskRenameForm currentTitle={currentTitle} onSubmit={onSubmit} onClose={handleClose} />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useCallback, useMemo, useState, memo } from "react";
|
||||
import type { TaskState, TaskSessionState, Repository, TaskSession, Task } from "@/lib/types/http";
|
||||
import type { KanbanState } from "@/lib/state/slices";
|
||||
import { TaskSwitcher } from "./task-switcher";
|
||||
import { TaskRenameDialog } from "./task-rename-dialog";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { PanelRoot, PanelBody } from "./panel-primitives";
|
||||
import { IconPlus } from "@tabler/icons-react";
|
||||
@@ -169,7 +170,8 @@ function useSidebarData(workspaceId: string | null) {
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
state: task.state as TaskState | undefined,
|
||||
sessionState: sessionInfo.sessionState,
|
||||
sessionState:
|
||||
sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined),
|
||||
description: task.description,
|
||||
workflowStepId: task.workflowStepId as string | undefined,
|
||||
repositoryPath: task.repositoryId ? repositoryPathsById.get(task.repositoryId) : undefined,
|
||||
@@ -221,7 +223,7 @@ function useSidebarActions(store: ReturnType<typeof useAppStoreApi>) {
|
||||
const setActiveTask = useAppStore((state) => state.setActiveTask);
|
||||
const setActiveSession = useAppStore((state) => state.setActiveSession);
|
||||
const [deletingTaskId, setDeletingTaskId] = useState<string | null>(null);
|
||||
const { deleteTaskById, archiveTaskById } = useTaskActions();
|
||||
const { deleteTaskById, archiveTaskById, renameTaskById } = useTaskActions();
|
||||
const { removeTaskFromBoard, loadTaskSessionsForTask } = useTaskRemoval({
|
||||
store,
|
||||
useLayoutSwitch: true,
|
||||
@@ -288,7 +290,35 @@ function useSidebarActions(store: ReturnType<typeof useAppStoreApi>) {
|
||||
[deleteTaskById, removeTaskFromBoard],
|
||||
);
|
||||
|
||||
return { deletingTaskId, handleSelectTask, handleArchiveTask, handleDeleteTask };
|
||||
const [renamingTask, setRenamingTask] = useState<{ id: string; title: string } | null>(null);
|
||||
|
||||
const handleRenameTask = useCallback((taskId: string, currentTitle: string) => {
|
||||
setRenamingTask({ id: taskId, title: currentTitle });
|
||||
}, []);
|
||||
|
||||
const handleRenameSubmit = useCallback(
|
||||
async (newTitle: string) => {
|
||||
if (!renamingTask) return;
|
||||
try {
|
||||
await renameTaskById(renamingTask.id, newTitle);
|
||||
} catch (error) {
|
||||
console.error("Failed to rename task:", error);
|
||||
}
|
||||
setRenamingTask(null);
|
||||
},
|
||||
[renamingTask, renameTaskById],
|
||||
);
|
||||
|
||||
return {
|
||||
deletingTaskId,
|
||||
handleSelectTask,
|
||||
handleArchiveTask,
|
||||
handleDeleteTask,
|
||||
renamingTask,
|
||||
setRenamingTask,
|
||||
handleRenameTask,
|
||||
handleRenameSubmit,
|
||||
};
|
||||
}
|
||||
|
||||
export const TaskSessionSidebar = memo(function TaskSessionSidebar({
|
||||
@@ -299,8 +329,16 @@ export const TaskSessionSidebar = memo(function TaskSessionSidebar({
|
||||
|
||||
const { activeTaskId, selectedTaskId, allSteps, isLoadingWorkflow, tasksWithRepositories } =
|
||||
useSidebarData(workspaceId);
|
||||
const { deletingTaskId, handleSelectTask, handleArchiveTask, handleDeleteTask } =
|
||||
useSidebarActions(store);
|
||||
const {
|
||||
deletingTaskId,
|
||||
handleSelectTask,
|
||||
handleArchiveTask,
|
||||
handleDeleteTask,
|
||||
renamingTask,
|
||||
setRenamingTask,
|
||||
handleRenameTask,
|
||||
handleRenameSubmit,
|
||||
} = useSidebarActions(store);
|
||||
|
||||
return (
|
||||
<PanelRoot>
|
||||
@@ -311,12 +349,21 @@ export const TaskSessionSidebar = memo(function TaskSessionSidebar({
|
||||
activeTaskId={activeTaskId}
|
||||
selectedTaskId={selectedTaskId}
|
||||
onSelectTask={handleSelectTask}
|
||||
onRenameTask={handleRenameTask}
|
||||
onArchiveTask={handleArchiveTask}
|
||||
onDeleteTask={handleDeleteTask}
|
||||
deletingTaskId={deletingTaskId}
|
||||
isLoading={isLoadingWorkflow}
|
||||
/>
|
||||
</PanelBody>
|
||||
<TaskRenameDialog
|
||||
open={renamingTask !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setRenamingTask(null);
|
||||
}}
|
||||
currentTitle={renamingTask?.title ?? ""}
|
||||
onSubmit={handleRenameSubmit}
|
||||
/>
|
||||
</PanelRoot>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { memo, useMemo } from "react";
|
||||
import type { ComponentType } from "react";
|
||||
import { IconCircleCheck, IconCircleDashed, IconProgress } from "@tabler/icons-react";
|
||||
import type { TaskState, TaskSessionState } from "@/lib/types/http";
|
||||
import { truncateRepoPath } from "@/lib/utils";
|
||||
import { TaskItem } from "./task-item";
|
||||
|
||||
const SECTION_ICONS: Record<
|
||||
string,
|
||||
{ Icon: ComponentType<{ className?: string }>; className: string }
|
||||
> = {
|
||||
Review: { Icon: IconCircleCheck, className: "text-green-500" },
|
||||
"In Progress": { Icon: IconProgress, className: "text-yellow-500" },
|
||||
Backlog: { Icon: IconCircleDashed, className: "text-muted-foreground" },
|
||||
};
|
||||
|
||||
type DiffStats = {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
@@ -33,6 +44,7 @@ type TaskSwitcherProps = {
|
||||
activeTaskId: string | null;
|
||||
selectedTaskId: string | null;
|
||||
onSelectTask: (taskId: string) => void;
|
||||
onRenameTask?: (taskId: string, currentTitle: string) => void;
|
||||
onArchiveTask?: (taskId: string) => void;
|
||||
onDeleteTask?: (taskId: string) => void;
|
||||
deletingTaskId?: string | null;
|
||||
@@ -75,9 +87,11 @@ function TaskSwitcherSkeleton() {
|
||||
}
|
||||
|
||||
function SectionHeader({ label, count }: { label: string; count: number }) {
|
||||
const icon = SECTION_ICONS[label];
|
||||
return (
|
||||
<div className="flex items-center justify-between px-3 py-1.5 bg-foreground/[0.03]">
|
||||
<span className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">
|
||||
<span className="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground uppercase tracking-wide">
|
||||
{icon && <icon.Icon className={`h-3 w-3 ${icon.className}`} />}
|
||||
{label}
|
||||
</span>
|
||||
<span className="text-[11px] text-muted-foreground/60">{count}</span>
|
||||
@@ -91,6 +105,7 @@ function TaskSwitcherSection({
|
||||
activeTaskId,
|
||||
selectedTaskId,
|
||||
onSelectTask,
|
||||
onRenameTask,
|
||||
onArchiveTask,
|
||||
onDeleteTask,
|
||||
deletingTaskId,
|
||||
@@ -100,6 +115,7 @@ function TaskSwitcherSection({
|
||||
activeTaskId: string | null;
|
||||
selectedTaskId: string | null;
|
||||
onSelectTask: (taskId: string) => void;
|
||||
onRenameTask?: (taskId: string, currentTitle: string) => void;
|
||||
onArchiveTask?: (taskId: string) => void;
|
||||
onDeleteTask?: (taskId: string) => void;
|
||||
deletingTaskId?: string | null;
|
||||
@@ -131,6 +147,7 @@ function TaskSwitcherSection({
|
||||
primarySessionId={task.primarySessionId ?? null}
|
||||
updatedAt={task.updatedAt}
|
||||
onClick={() => onSelectTask(task.id)}
|
||||
onRename={onRenameTask ? () => onRenameTask(task.id, task.title) : undefined}
|
||||
onArchive={onArchiveTask ? () => onArchiveTask(task.id) : undefined}
|
||||
onDelete={onDeleteTask ? () => onDeleteTask(task.id) : undefined}
|
||||
isDeleting={deletingTaskId === task.id}
|
||||
@@ -147,6 +164,7 @@ export const TaskSwitcher = memo(function TaskSwitcher({
|
||||
activeTaskId,
|
||||
selectedTaskId,
|
||||
onSelectTask,
|
||||
onRenameTask,
|
||||
onArchiveTask,
|
||||
onDeleteTask,
|
||||
deletingTaskId,
|
||||
@@ -172,10 +190,15 @@ export const TaskSwitcher = memo(function TaskSwitcher({
|
||||
else backlog.push(task);
|
||||
}
|
||||
|
||||
const byTitle = (a: TaskSwitcherItem, b: TaskSwitcherItem) => a.title.localeCompare(b.title);
|
||||
review.sort(byTitle);
|
||||
inProgress.sort(byTitle);
|
||||
backlog.sort(byTitle);
|
||||
const byRecent = (a: TaskSwitcherItem, b: TaskSwitcherItem) => {
|
||||
const ta = a.updatedAt ?? "";
|
||||
const tb = b.updatedAt ?? "";
|
||||
if (ta !== tb) return tb.localeCompare(ta);
|
||||
return a.title.localeCompare(b.title);
|
||||
};
|
||||
review.sort(byRecent);
|
||||
inProgress.sort(byRecent);
|
||||
backlog.sort(byRecent);
|
||||
|
||||
return [
|
||||
{ label: "Review", tasks: review },
|
||||
@@ -202,6 +225,7 @@ export const TaskSwitcher = memo(function TaskSwitcher({
|
||||
activeTaskId={activeTaskId}
|
||||
selectedTaskId={selectedTaskId}
|
||||
onSelectTask={onSelectTask}
|
||||
onRenameTask={onRenameTask}
|
||||
onArchiveTask={onArchiveTask}
|
||||
onDeleteTask={onDeleteTask}
|
||||
deletingTaskId={deletingTaskId}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import { memo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
IconBug,
|
||||
IconCopy,
|
||||
@@ -87,7 +86,6 @@ const TaskTopBar = memo(function TaskTopBar({
|
||||
remoteCheckedAt,
|
||||
remoteStatusError,
|
||||
}: TaskTopBarProps) {
|
||||
const router = useRouter();
|
||||
const git = useSessionGit(activeSessionId);
|
||||
const displayBranch = worktreeBranch || baseBranch;
|
||||
|
||||
@@ -123,7 +121,6 @@ const TaskTopBar = memo(function TaskTopBar({
|
||||
showDebugOverlay={showDebugOverlay}
|
||||
onToggleDebugOverlay={onToggleDebugOverlay}
|
||||
isArchived={isArchived}
|
||||
router={router}
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
@@ -394,7 +391,6 @@ function TopBarRight({
|
||||
showDebugOverlay,
|
||||
onToggleDebugOverlay,
|
||||
isArchived,
|
||||
router,
|
||||
}: {
|
||||
activeSessionId?: string | null;
|
||||
baseBranch?: string;
|
||||
@@ -402,7 +398,6 @@ function TopBarRight({
|
||||
showDebugOverlay?: boolean;
|
||||
onToggleDebugOverlay?: () => void;
|
||||
isArchived?: boolean;
|
||||
router: ReturnType<typeof useRouter>;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
@@ -435,13 +430,10 @@ function TopBarRight({
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="cursor-pointer px-2"
|
||||
onClick={() => router.push("/settings/general")}
|
||||
>
|
||||
<IconSettings className="h-4 w-4" />
|
||||
<Button size="sm" variant="outline" className="cursor-pointer px-2" asChild>
|
||||
<Link href="/settings/general">
|
||||
<IconSettings className="h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Settings</TooltipContent>
|
||||
|
||||
Reference in New Issue
Block a user