'use client';
import { useRef, useCallback, useState, useEffect, memo, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import {
IconArrowUp,
IconBrain,
IconListCheck,
IconPlayerStopFilled,
} from '@tabler/icons-react';
import { GridSpinner } from '@/components/grid-spinner';
import { Button } from '@kandev/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@kandev/ui/dropdown-menu';
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { cn } from '@/lib/utils';
import { SHORTCUTS } from '@/lib/keyboard/constants';
import { KeyboardShortcutTooltip } from '@/components/keyboard-shortcut-tooltip';
import { TokenUsageDisplay } from '@/components/task/chat/token-usage-display';
import { SessionsDropdown } from '@/components/task/sessions-dropdown';
import { ModelSelector } from '@/components/task/model-selector';
import { RichTextInput, type RichTextInputHandle } from './rich-text-input';
import { MentionMenu } from './mention-menu';
import { SlashCommandMenu } from './slash-command-menu';
import { ClarificationInputOverlay } from './clarification-input-overlay';
import { CommentBlocksContainer } from './comment-block';
import { useInlineMention } from '@/hooks/use-inline-mention';
import { useInlineSlash } from '@/hooks/use-inline-slash';
import type { Message } from '@/lib/types/http';
import type { DiffComment } from '@/lib/diff/types';
// Memoized toolbar to prevent re-renders on input value changes
type ChatInputToolbarProps = {
planModeEnabled: boolean;
onPlanModeChange: (enabled: boolean) => void;
sessionId: string | null;
taskId: string | null;
taskTitle?: string;
taskDescription: string;
isAgentBusy: boolean;
isDisabled: boolean;
isSending: boolean;
onCancel: () => void;
onSubmit: () => void;
};
const ChatInputToolbar = memo(function ChatInputToolbar({
planModeEnabled,
onPlanModeChange,
sessionId,
taskId,
taskTitle,
taskDescription,
isAgentBusy,
isDisabled,
isSending,
onCancel,
onSubmit,
}: ChatInputToolbarProps) {
return (
{/* Left: Plan, Thinking, Context */}
{/* Plan mode toggle */}
Toggle plan mode
{/* Thinking level dropdown */}
Thinking level
High
Medium
Low
Off
{/* Spacer */}
{/* Right: Sessions, Model, Submit */}
{/* Token usage display */}
{/* Submit/Stop button */}
{isAgentBusy ? (
) : (
)}
);
});
type ChatInputContainerProps = {
onSubmit: (message: string, reviewComments?: DiffComment[]) => void;
sessionId: string | null;
taskId: string | null;
taskTitle?: string;
taskDescription: string;
planModeEnabled: boolean;
onPlanModeChange: (enabled: boolean) => void;
isAgentBusy: boolean;
isStarting: boolean;
isSending: boolean;
onCancel: () => void;
placeholder?: string;
pendingClarification?: Message | null;
onClarificationResolved?: () => void;
showRequestChangesTooltip?: boolean;
onRequestChangesTooltipDismiss?: () => void;
/** Pending review comments grouped by file */
pendingCommentsByFile?: Record;
/** Callback to remove comments for a file */
onRemoveCommentFile?: (filePath: string) => void;
/** Callback to remove a specific comment */
onRemoveComment?: (sessionId: string, filePath: string, commentId: string) => void;
/** Callback when a comment is clicked (for jump-to-line) */
onCommentClick?: (comment: DiffComment) => void;
};
export function ChatInputContainer({
onSubmit,
sessionId,
taskId,
taskTitle,
taskDescription,
planModeEnabled,
onPlanModeChange,
isAgentBusy,
isStarting,
isSending,
onCancel,
placeholder,
pendingClarification,
onClarificationResolved,
showRequestChangesTooltip = false,
onRequestChangesTooltipDismiss,
pendingCommentsByFile,
onRemoveCommentFile,
onRemoveComment,
onCommentClick,
}: ChatInputContainerProps) {
// Keep input state local to avoid re-rendering parent on every keystroke
const [value, setValue] = useState('');
const inputRef = useRef(null);
// Focus input when request changes tooltip is shown
useEffect(() => {
if (showRequestChangesTooltip && inputRef.current) {
inputRef.current.focus();
}
}, [showRequestChangesTooltip]);
// Use ref for value to keep handleSubmit stable (doesn't change on every keystroke)
const valueRef = useRef(value);
useEffect(() => {
valueRef.current = value;
}, [value]);
// Mention menu hook
const mention = useInlineMention(inputRef, value, setValue, sessionId);
// Handler for agent slash commands - sends /{commandName} as a message
const handleAgentCommand = useCallback(
(commandName: string) => {
onSubmit(`/${commandName}`);
},
[onSubmit]
);
// Slash command menu hook
const slash = useInlineSlash(inputRef, value, setValue, {
sessionId,
onAgentCommand: handleAgentCommand,
});
// Use refs for menu state to keep handleSubmit stable
const menuStateRef = useRef({ mentionOpen: mention.isOpen, slashOpen: slash.isOpen });
useEffect(() => {
menuStateRef.current = { mentionOpen: mention.isOpen, slashOpen: slash.isOpen };
}, [mention.isOpen, slash.isOpen]);
// Ref for pending comments
const pendingCommentsRef = useRef(pendingCommentsByFile);
useEffect(() => {
pendingCommentsRef.current = pendingCommentsByFile;
}, [pendingCommentsByFile]);
// Combined change handler
const handleChange = useCallback(
(newValue: string) => {
mention.handleChange(newValue);
slash.handleChange(newValue);
// Dismiss the request changes tooltip when user starts typing
if (showRequestChangesTooltip && onRequestChangesTooltipDismiss) {
onRequestChangesTooltipDismiss();
}
},
[mention, slash, showRequestChangesTooltip, onRequestChangesTooltipDismiss]
);
// Combined keydown handler
const handleKeyDown = useCallback(
(event: ReactKeyboardEvent) => {
// Let menus handle navigation first
if (mention.isOpen) {
mention.handleKeyDown(event);
if (event.defaultPrevented) return;
}
if (slash.isOpen) {
slash.handleKeyDown(event);
if (event.defaultPrevented) return;
}
},
[mention, slash]
);
// Stable submit handler using refs - doesn't change on value/menu state changes
const handleSubmit = useCallback(() => {
// Don't submit if a menu is open
if (menuStateRef.current.mentionOpen || menuStateRef.current.slashOpen) return;
const trimmed = valueRef.current.trim();
const comments = pendingCommentsRef.current;
// Collect all pending comments
const allComments: DiffComment[] = [];
if (comments) {
for (const filePath of Object.keys(comments)) {
allComments.push(...comments[filePath]);
}
}
// Allow submission if there's text OR comments
if (!trimmed && allComments.length === 0) return;
onSubmit(trimmed, allComments.length > 0 ? allComments : undefined);
setValue('');
}, [onSubmit]);
const isDisabled = isStarting || isSending;
const hasPendingClarification = pendingClarification && onClarificationResolved;
const hasPendingComments = pendingCommentsByFile && Object.keys(pendingCommentsByFile).length > 0;
return (
{/* Popup menus */}
{/* Pending comment blocks */}
{hasPendingComments && sessionId && onRemoveCommentFile && onRemoveComment && (
)}
{/* Clarification inline (replaces input area when pending) */}
{hasPendingClarification ? (
) : (
/* Normal input area */
Write your changes here
)}
{/* Integrated toolbar - memoized to prevent re-renders on input changes */}
);
}