Merge pull request #292 from langflow-ai/fix/chat-input-design

fix: makes chat input design, adds context files the right way
This commit is contained in:
Sebastián Estévez 2025-10-24 02:34:57 -04:00 committed by GitHub
commit 3dc0d5d35d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 735 additions and 672 deletions

View file

@ -1,15 +1,15 @@
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context"; import { ArrowRight, Search, X } from "lucide-react";
import { import {
ChangeEvent, type ChangeEvent,
FormEvent, type FormEvent,
useCallback, useCallback,
useEffect, useEffect,
useState, useState,
} from "react"; } from "react";
import { filterAccentClasses } from "./knowledge-filter-panel";
import { ArrowRight, Search, X } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { filterAccentClasses } from "./knowledge-filter-panel";
export const KnowledgeSearchInput = () => { export const KnowledgeSearchInput = () => {
const { const {
@ -27,7 +27,7 @@ export const KnowledgeSearchInput = () => {
if (e) e.preventDefault(); if (e) e.preventDefault();
setQueryOverride(searchQueryInput.trim()); setQueryOverride(searchQueryInput.trim());
}, },
[searchQueryInput, setQueryOverride] [searchQueryInput, setQueryOverride],
); );
// Reset the query text when the selected filter changes // Reset the query text when the selected filter changes
@ -48,7 +48,7 @@ export const KnowledgeSearchInput = () => {
filterAccentClasses[parsedFilterData?.color || "zinc"] filterAccentClasses[parsedFilterData?.color || "zinc"]
}`} }`}
> >
<span className="truncate">{selectedFilter?.name}</span> <span className="truncate text-xs font-medium">{selectedFilter?.name}</span>
<X <X
aria-label="Remove filter" aria-label="Remove filter"
className="h-4 w-4 flex-shrink-0 cursor-pointer" className="h-4 w-4 flex-shrink-0 cursor-pointer"
@ -88,7 +88,7 @@ export const KnowledgeSearchInput = () => {
variant="ghost" variant="ghost"
className={cn( className={cn(
"h-full rounded-sm !px-1.5 !py-0 hidden group-focus-within/input:block", "h-full rounded-sm !px-1.5 !py-0 hidden group-focus-within/input:block",
searchQueryInput && "block" searchQueryInput && "block",
)} )}
type="submit" type="submit"
> >

View file

@ -22,6 +22,7 @@ import {
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { type EndpointType, useChat } from "@/contexts/chat-context"; import { type EndpointType, useChat } from "@/contexts/chat-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context"; import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { FILES_REGEX } from "@/lib/constants";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useLoadingStore } from "@/stores/loadingStore"; import { useLoadingStore } from "@/stores/loadingStore";
import { DeleteSessionModal } from "./delete-session-modal"; import { DeleteSessionModal } from "./delete-session-modal";
@ -81,6 +82,7 @@ export function Navigation({
setCurrentConversationId, setCurrentConversationId,
startNewConversation, startNewConversation,
conversationDocs, conversationDocs,
conversationData,
addConversationDoc, addConversationDoc,
refreshConversations, refreshConversations,
placeholderConversation, placeholderConversation,
@ -110,7 +112,7 @@ export function Navigation({
) { ) {
// Filter out the deleted conversation and find the next one // Filter out the deleted conversation and find the next one
const remainingConversations = conversations.filter( const remainingConversations = conversations.filter(
conv => conv.response_id !== conversationToDelete.response_id (conv) => conv.response_id !== conversationToDelete.response_id,
); );
if (remainingConversations.length > 0) { if (remainingConversations.length > 0) {
@ -131,7 +133,7 @@ export function Navigation({
setDeleteModalOpen(false); setDeleteModalOpen(false);
setConversationToDelete(null); setConversationToDelete(null);
}, },
onError: error => { onError: (error) => {
toast.error(`Failed to delete conversation: ${error.message}`); toast.error(`Failed to delete conversation: ${error.message}`);
}, },
}); });
@ -163,7 +165,7 @@ export function Navigation({
window.dispatchEvent( window.dispatchEvent(
new CustomEvent("fileUploadStart", { new CustomEvent("fileUploadStart", {
detail: { filename: file.name }, detail: { filename: file.name },
}) }),
); );
try { try {
@ -187,7 +189,7 @@ export function Navigation({
filename: file.name, filename: file.name,
error: "Failed to process document", error: "Failed to process document",
}, },
}) }),
); );
// Trigger loading end event // Trigger loading end event
@ -207,7 +209,7 @@ export function Navigation({
window.dispatchEvent( window.dispatchEvent(
new CustomEvent("fileUploaded", { new CustomEvent("fileUploaded", {
detail: { file, result }, detail: { file, result },
}) }),
); );
// Trigger loading end event // Trigger loading end event
@ -221,7 +223,7 @@ export function Navigation({
window.dispatchEvent( window.dispatchEvent(
new CustomEvent("fileUploadError", { new CustomEvent("fileUploadError", {
detail: { filename: file.name, error: "Failed to process document" }, detail: { filename: file.name, error: "Failed to process document" },
}) }),
); );
} }
}; };
@ -243,7 +245,7 @@ export function Navigation({
const handleDeleteConversation = ( const handleDeleteConversation = (
conversation: ChatConversation, conversation: ChatConversation,
event?: React.MouseEvent event?: React.MouseEvent,
) => { ) => {
if (event) { if (event) {
event.preventDefault(); event.preventDefault();
@ -255,7 +257,7 @@ export function Navigation({
const handleContextMenuAction = ( const handleContextMenuAction = (
action: string, action: string,
conversation: ChatConversation conversation: ChatConversation,
) => { ) => {
switch (action) { switch (action) {
case "delete": case "delete":
@ -329,11 +331,19 @@ export function Navigation({
setCurrentConversationId, setCurrentConversationId,
]); ]);
const newConversationFiles = conversationData?.messages
.filter(
(message) =>
message.role === "user" &&
(message.content.match(FILES_REGEX)?.[0] ?? null) !== null,
)
.map((message) => message.content.match(FILES_REGEX)?.[0] ?? null);
return ( return (
<div className="flex flex-col h-full bg-background"> <div className="flex flex-col h-full bg-background">
<div className="px-4 py-2 flex-shrink-0"> <div className="px-4 py-2 flex-shrink-0">
<div className="space-y-1"> <div className="space-y-1">
{routes.map(route => ( {routes.map((route) => (
<div key={route.href}> <div key={route.href}>
<Link <Link
href={route.href} href={route.href}
@ -341,7 +351,7 @@ export function Navigation({
"text-[13px] group flex p-3 w-full justify-start font-medium cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-lg transition-all", "text-[13px] group flex p-3 w-full justify-start font-medium cursor-pointer hover:bg-accent hover:text-accent-foreground rounded-lg transition-all",
route.active route.active
? "bg-accent text-accent-foreground shadow-sm" ? "bg-accent text-accent-foreground shadow-sm"
: "text-foreground hover:text-accent-foreground" : "text-foreground hover:text-accent-foreground",
)} )}
> >
<div className="flex items-center flex-1"> <div className="flex items-center flex-1">
@ -350,7 +360,7 @@ export function Navigation({
"h-[18px] w-[18px] mr-2 shrink-0", "h-[18px] w-[18px] mr-2 shrink-0",
route.active route.active
? "text-muted-foreground" ? "text-muted-foreground"
: "text-muted-foreground group-hover:text-muted-foreground" : "text-muted-foreground group-hover:text-muted-foreground",
)} )}
/> />
{route.label} {route.label}
@ -428,7 +438,7 @@ export function Navigation({
No conversations yet No conversations yet
</div> </div>
) : ( ) : (
conversations.map(conversation => ( conversations.map((conversation) => (
<button <button
key={conversation.response_id} key={conversation.response_id}
type="button" type="button"
@ -466,10 +476,10 @@ export function Navigation({
title="More options" title="More options"
role="button" role="button"
tabIndex={0} tabIndex={0}
onClick={e => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
}} }}
onKeyDown={e => { onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") { if (e.key === "Enter" || e.key === " ") {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@ -483,14 +493,14 @@ export function Navigation({
side="bottom" side="bottom"
align="end" align="end"
className="w-48" className="w-48"
onClick={e => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
<DropdownMenuItem <DropdownMenuItem
onClick={e => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
handleContextMenuAction( handleContextMenuAction(
"delete", "delete",
conversation conversation,
); );
}} }}
className="cursor-pointer text-destructive focus:text-destructive" className="cursor-pointer text-destructive focus:text-destructive"
@ -508,7 +518,7 @@ export function Navigation({
)} )}
</div> </div>
{/* Conversation Knowledge Section - appears right after last conversation */} {/* Conversation Knowledge Section - appears right after last conversation
<div className="flex-shrink-0 mt-4"> <div className="flex-shrink-0 mt-4">
<div className="flex items-center justify-between mb-3 mx-3"> <div className="flex items-center justify-between mb-3 mx-3">
<h3 className="text-xs font-medium text-muted-foreground"> <h3 className="text-xs font-medium text-muted-foreground">
@ -551,6 +561,28 @@ export function Navigation({
)) ))
)} )}
</div> </div>
</div> */}
<div className="flex-shrink-0 mt-4">
<div className="flex items-center justify-between mb-3 mx-3">
<h3 className="text-xs font-medium text-muted-foreground">
Files
</h3>
</div>
<div className="overflow-y-auto scrollbar-hide space-y-1">
{newConversationFiles?.length === 0 ? (
<div className="text-[13px] text-muted-foreground py-2 px-3">
No documents yet
</div>
) : (
newConversationFiles?.map((file) => (
<div key={`${file}`} className="flex-1 min-w-0 px-3">
<div className="text-mmd font-medium text-foreground truncate">
{file}
</div>
</div>
))
)}
</div>
</div> </div>
</div> </div>
</div> </div>

View file

@ -1,4 +1,4 @@
import { Check, Funnel, Loader2, Plus, X } from "lucide-react"; import { ArrowRight, Check, Funnel, Loader2, Plus, X } from "lucide-react";
import { forwardRef, useImperativeHandle, useRef } from "react"; import { forwardRef, useImperativeHandle, useRef } from "react";
import TextareaAutosize from "react-textarea-autosize"; import TextareaAutosize from "react-textarea-autosize";
import type { FilterColor } from "@/components/filter-icon-popover"; import type { FilterColor } from "@/components/filter-icon-popover";
@ -82,69 +82,33 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
})); }));
return ( return (
<div className="pb-8 flex px-6">
<div className="w-full"> <div className="w-full">
<form onSubmit={onSubmit} className="relative"> <form onSubmit={onSubmit} className="relative">
<div className="relative w-full bg-muted/20 rounded-lg border border-border/50 focus-within:ring-1 focus-within:ring-ring"> <div className="relative flex items-center w-full p-2 gap-2 rounded-xl border border-input focus-within:ring-1 focus-within:ring-ring">
{selectedFilter && ( {selectedFilter ? (
<div className="flex items-center gap-2 px-4 pt-3 pb-1">
<span <span
className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium transition-colors ${ className={`inline-flex items-center p-1 rounded-sm text-xs font-medium transition-colors ${
filterAccentClasses[parsedFilterData?.color || "zinc"] filterAccentClasses[parsedFilterData?.color || "zinc"]
}`} }`}
> >
@filter:{selectedFilter.name} {selectedFilter.name}
<button <button
type="button" type="button"
onClick={() => { onClick={() => {
setSelectedFilter(null); setSelectedFilter(null);
setIsFilterHighlighted(false); setIsFilterHighlighted(false);
}} }}
className="ml-1 rounded-full p-0.5" className="ml-0.5 rounded-full p-0.5"
> >
<X className="h-3 w-3" /> <X className="h-4 w-4" />
</button> </button>
</span> </span>
</div> ) : (
)}
<div
className="relative"
style={{ height: `${textareaHeight + 60}px` }}
>
<TextareaAutosize
ref={inputRef}
value={input}
onChange={onChange}
onKeyDown={onKeyDown}
onHeightChange={onHeightChange}
maxRows={7}
minRows={2}
placeholder="Type to ask a question..."
disabled={loading}
className={`w-full bg-transparent px-4 ${
selectedFilter ? "pt-2" : "pt-4"
} focus-visible:outline-none resize-none`}
rows={2}
/>
{/* Safe area at bottom for buttons */}
<div
className="absolute bottom-0 left-0 right-0 bg-transparent pointer-events-none"
style={{ height: "60px" }}
/>
</div>
</div>
<input
ref={fileInputRef}
type="file"
onChange={onFilePickerChange}
className="hidden"
accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt"
/>
<Button <Button
type="button" type="button"
variant="outline" variant="ghost"
size="iconSm" size="iconSm"
className="absolute bottom-3 left-3 h-8 w-8 p-0 rounded-full hover:bg-muted/50" className="h-8 w-8 p-0 rounded-md hover:bg-muted/50"
onMouseDown={(e) => { onMouseDown={(e) => {
e.preventDefault(); e.preventDefault();
}} }}
@ -153,6 +117,57 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
> >
<Funnel className="h-4 w-4" /> <Funnel className="h-4 w-4" />
</Button> </Button>
)}
<div
className="relative flex-1"
style={{ height: `${textareaHeight}px` }}
>
<TextareaAutosize
ref={inputRef}
value={input}
onChange={onChange}
onKeyDown={onKeyDown}
onHeightChange={onHeightChange}
maxRows={7}
minRows={1}
placeholder="Ask a question..."
disabled={loading}
className={`w-full text-sm bg-transparent focus-visible:outline-none resize-none`}
rows={1}
/>
</div>
<Button
type="button"
variant="ghost"
size="iconSm"
onClick={onFilePickerClick}
disabled={isUploading}
className="h-8 w-8 p-0 !rounded-md hover:bg-muted/50"
>
<Plus className="h-4 w-4" />
</Button>
<Button
variant="default"
type="submit"
size="iconSm"
disabled={!input.trim() || loading}
className="!rounded-md h-8 w-8 p-0"
>
{loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<ArrowRight className="h-4 w-4" />
)}
</Button>
</div>
<input
ref={fileInputRef}
type="file"
onChange={onFilePickerChange}
className="hidden"
accept=".pdf,.doc,.docx,.txt,.md,.rtf,.odt"
/>
<Popover <Popover
open={isFilterDropdownOpen} open={isFilterDropdownOpen}
onOpenChange={(open) => { onOpenChange={(open) => {
@ -257,26 +272,8 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
</div> </div>
</PopoverContent> </PopoverContent>
</Popover> </Popover>
<Button
type="button"
variant="outline"
size="iconSm"
onClick={onFilePickerClick}
disabled={isUploading}
className="absolute bottom-3 left-12 h-8 w-8 p-0 rounded-full hover:bg-muted/50"
>
<Plus className="h-4 w-4" />
</Button>
<Button
type="submit"
disabled={!input.trim() || loading}
className="absolute bottom-3 right-3 rounded-lg h-10 px-4"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Send"}
</Button>
</form> </form>
</div> </div>
</div>
); );
}, },
); );

View file

@ -1,4 +1,4 @@
import { User } from "lucide-react"; import { FileText, User } from "lucide-react";
import { motion } from "motion/react"; import { motion } from "motion/react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useAuth } from "@/contexts/auth-context"; import { useAuth } from "@/contexts/auth-context";
@ -9,12 +9,12 @@ interface UserMessageProps {
content: string; content: string;
isCompleted?: boolean; isCompleted?: boolean;
animate?: boolean; animate?: boolean;
files?: string;
} }
export function UserMessage({ content, isCompleted, animate = true }: UserMessageProps) { export function UserMessage({ content, isCompleted, animate = true, files }: UserMessageProps) {
const { user } = useAuth(); const { user } = useAuth();
console.log("animate", animate);
return ( return (
<motion.div <motion.div
@ -38,6 +38,12 @@ export function UserMessage({ content, isCompleted, animate = true }: UserMessag
</Avatar> </Avatar>
} }
> >
{files && (
<p className="text-muted-foreground flex items-center gap-2 font-normal text-mmd py-1.5 whitespace-pre-wrap break-words overflow-wrap-anywhere transition-colors duration-300">
<FileText className="h-4 w-4" />
{files}
</p>
)}
<p <p
className={cn( className={cn(
"text-foreground text-sm py-1.5 whitespace-pre-wrap break-words overflow-wrap-anywhere transition-colors duration-300", "text-foreground text-sm py-1.5 whitespace-pre-wrap break-words overflow-wrap-anywhere transition-colors duration-300",

View file

@ -9,6 +9,7 @@ import { type EndpointType, useChat } from "@/contexts/chat-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context"; import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { useTask } from "@/contexts/task-context"; import { useTask } from "@/contexts/task-context";
import { useChatStreaming } from "@/hooks/useChatStreaming"; import { useChatStreaming } from "@/hooks/useChatStreaming";
import { FILES_REGEX } from "@/lib/constants";
import { useLoadingStore } from "@/stores/loadingStore"; import { useLoadingStore } from "@/stores/loadingStore";
import { useGetNudgesQuery } from "../api/queries/useGetNudgesQuery"; import { useGetNudgesQuery } from "../api/queries/useGetNudgesQuery";
import { AssistantMessage } from "./components/assistant-message"; import { AssistantMessage } from "./components/assistant-message";
@ -1182,17 +1183,40 @@ function ChatPage() {
) : ( ) : (
<> <>
{messages.map((message, index) => ( {messages.map((message, index) => (
<>
{message.role === "user" &&
(messages[index]?.content.match(FILES_REGEX)?.[0] ??
null) === null && (
<div <div
key={`${ key={`${
message.role message.role
}-${index}-${message.timestamp?.getTime()}`} }-${index}-${message.timestamp?.getTime()}`}
className="space-y-6 group" className="space-y-6 group"
> >
{message.role === "user" && ( <UserMessage
<UserMessage animate={message.source !== "langflow"} content={message.content} /> animate={message.source !== "langflow"}
content={message.content}
files={
index >= 2
? (messages[index - 2]?.content.match(
FILES_REGEX,
)?.[0] ?? undefined)
: undefined
}
/>
</div>
)} )}
{message.role === "assistant" && ( {message.role === "assistant" &&
(index < 1 ||
(messages[index - 1]?.content.match(FILES_REGEX)?.[0] ??
null) === null) && (
<div
key={`${
message.role
}-${index}-${message.timestamp?.getTime()}`}
className="space-y-6 group"
>
<AssistantMessage <AssistantMessage
content={message.content} content={message.content}
functionCalls={message.functionCalls} functionCalls={message.functionCalls}
@ -1203,8 +1227,9 @@ function ChatPage() {
onFork={(e) => handleForkConversation(index, e)} onFork={(e) => handleForkConversation(index, e)}
animate={false} animate={false}
/> />
)}
</div> </div>
)}
</>
))} ))}
{/* Streaming Message Display */} {/* Streaming Message Display */}
@ -1231,7 +1256,7 @@ function ChatPage() {
)} )}
</div> </div>
</StickToBottom.Content> </StickToBottom.Content>
<div className="p-6 pt-0 max-w-[960px] mx-auto w-full">
{/* Input Area - Fixed at bottom */} {/* Input Area - Fixed at bottom */}
<ChatInput <ChatInput
ref={chatInputRef} ref={chatInputRef}
@ -1258,6 +1283,7 @@ function ChatPage() {
setIsFilterHighlighted={setIsFilterHighlighted} setIsFilterHighlighted={setIsFilterHighlighted}
setIsFilterDropdownOpen={setIsFilterDropdownOpen} setIsFilterDropdownOpen={setIsFilterDropdownOpen}
/> />
</div>
</> </>
); );
} }

View file

@ -33,3 +33,6 @@ export const TOTAL_ONBOARDING_STEPS = 3;
* Local Storage Keys * Local Storage Keys
*/ */
export const ONBOARDING_STEP_KEY = "onboarding_current_step"; export const ONBOARDING_STEP_KEY = "onboarding_current_step";
export const FILES_REGEX =
/(?<=I'm uploading a document called ['"])[^'"]+\.[^.]+(?=['"]\. Here is its content:)/;

View file

@ -100,12 +100,11 @@ async def upload_context(
previous_response_id = form.get("previous_response_id") previous_response_id = form.get("previous_response_id")
endpoint = form.get("endpoint", "langflow") endpoint = form.get("endpoint", "langflow")
jwt_token = session_manager.get_effective_jwt_token(user_id, request.state.jwt_token)
# Get user info from request state (set by auth middleware) # Get user info from request state (set by auth middleware)
user = request.state.user user = request.state.user
user_id = user.user_id if user else None user_id = user.user_id if user else None
jwt_token = session_manager.get_effective_jwt_token(user_id, request.state.jwt_token)
# Process document and extract content # Process document and extract content
doc_result = await document_service.process_upload_context(upload_file, filename) doc_result = await document_service.process_upload_context(upload_file, filename)