A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat(app): updates on chat
dextmorgn137d16e1fce9
diff --git a/flowsint-app/src/api/chat-transport.ts b/flowsint-app/src/api/chat-transport.tsindex 1330a94d..57d0094d 100644--- a/flowsint-app/src/api/chat-transport.ts+++ b/flowsint-app/src/api/chat-transport.ts@@ -11,15 +11,16 @@ export function createChatTransport(chatId: string) {if (token) return { Authorization: `Bearer ${token}` }return {}},- prepareSendMessagesRequest: ({ messages }) => {+ prepareSendMessagesRequest: ({ messages, body }) => {const lastUserMessage = [...messages].reverse().find((m) => m.role === 'user')const prompt = lastUserMessage?.parts?.filter((p): p is { type: 'text'; text: string } => p.type === 'text').map((p) => p.text).join('') ?? ''+ const context = (body as Record<string, unknown> | undefined)?.contextreturn {- body: { prompt },+ body: { prompt, ...(context ? { context } : {}) },}},})diff --git a/flowsint-app/src/components/chat/chat-prompt.tsx b/flowsint-app/src/components/chat/chat-prompt.tsxindex 1ed1d59c..8cb4ae18 100644--- a/flowsint-app/src/components/chat/chat-prompt.tsx+++ b/flowsint-app/src/components/chat/chat-prompt.tsx@@ -5,15 +5,20 @@ import { XIcon, ArrowUp } from 'lucide-react'import { useGraphStore } from '@/stores/graph-store'import { useRef, useEffect, memo, useState } from 'react'import { useNodesDisplaySettings } from '@/stores/node-display-settings'+import { ChatContextFormat } from '@/types'interface ChatPanelProps {- onSend: (text: string) => void+ onSend: (text: string, context?: string[]) => voidisLoading: boolean}+const formatContext = (context: ChatContextFormat[]): string[] => {+ return context.map((item) => `${item.fromLabel} -> ${item.label} -> ${item.toLabel}`)+}+export const ChatPanel = ({ onSend, isLoading }: ChatPanelProps) => {const [input, setInput] = useState('')- const selectedNodes = useGraphStore((s) => s.selectedNodes)+ const selectedNodes = useGraphStore((s) => s.getSelectedNodesWithEdgesAsList)()const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)const textareaRef = useRef<HTMLTextAreaElement>(null)@@ -36,7 +41,7 @@ export const ChatPanel = ({ onSend, isLoading }: ChatPanelProps) => {const handleSubmit = () => {if (input.trim() && !isLoading) {- onSend(input.trim())+ onSend(input.trim(), selectedNodes.length > 0 ? formatContext(selectedNodes) : undefined)setInput('')}}@@ -76,7 +81,7 @@ export const ChatPanel = ({ onSend, isLoading }: ChatPanelProps) => {onChange={(e) => setInput(e.target.value)}onKeyDown={handleKeyDown}className={`- min-h-[44px] max-h-[120px] resize-none+ min-h-11 max-h-[120px] resize-noneborder border-border bg-backgroundfocus:ring-2 focus:ring-primary/20 focus:border-primarytransition-all duration-200@@ -113,20 +118,24 @@ export const ChatPanel = ({ onSend, isLoading }: ChatPanelProps) => {)}-export const ContextList = memo(({ context }: { context: any }) => {+export const ContextList = memo(({ context }: { context: ChatContextFormat[] }) => {const colors = useNodesDisplaySettings((s) => s.colors)return (<div className="flex flex-nowrap overflow-x-auto hide-scrollbar gap-1.5 items-center px-1">- {context.map((item: any, index: number) => {- const color = colors[item?.data?.type || item?.type]+ {context.map((item: ChatContextFormat, index: number) => {+ const fromColor = item.fromColor ?? colors[item?.fromType]+ const toColor = item.toColor ?? colors[item?.toType]+return (<Badgekey={index}variant="secondary"className="flex items-center border border-border gap-1.5 text-xs">- <span style={{ background: color }} className="w-1.5 h-1.5 rounded-full" />- {item.data?.label || 'Unknown'}+ <span style={{ background: fromColor }} className="w-1.5 h-1.5 rounded-full" />+ {item.fromLabel || 'Unknown'} {'->'}+ <span style={{ background: toColor }} className="w-1.5 h-1.5 rounded-full" />+ {item.toLabel || 'Unknown'}</Badge>)})}diff --git a/flowsint-app/src/components/chat/floating-chat.tsx b/flowsint-app/src/components/chat/floating-chat.tsxindex 83fd8ed4..8c611acb 100644--- a/flowsint-app/src/components/chat/floating-chat.tsx+++ b/flowsint-app/src/components/chat/floating-chat.tsx@@ -30,7 +30,7 @@ function FloatingChat() {isLoadingChat,createNewChat,deleteChatMutation,- currentChatId,+ currentChatId} = useChat()const isStreaming = status === 'streaming' || status === 'submitted'@@ -38,13 +38,13 @@ function FloatingChat() {const { isMac } = useKeyboardShortcut({key: 'e',ctrlOrCmd: true,- callback: toggleChat,+ callback: toggleChat})useKeyboardShortcut({key: 'Escape',ctrlOrCmd: false,- callback: closeChat,+ callback: closeChat})const handleCreateNewChat = () => {@@ -92,9 +92,9 @@ function FloatingChat() {{/* Chat Panel */}{isOpenChat && (- <div className="fixed bottom-12 overflow-hidden rounded-2xl right-4 shadow z-21">+ <div className="fixed bottom-12 overflow-hidden rounded-2xl right-4 shadow-xl z-50"><ResizableChat minWidth={400} minHeight={400} maxWidth={800} maxHeight={800}>- <Card className="overflow-hidden !backdrop-blur bg-background/90 rounded-2xl gap-0 py-0 h-full">+ <Card className="overflow-hidden backdrop-blur! bg-background/90 rounded-2xl gap-0 py-0 h-full">{view === 'history' ? (<ChatHistorysetView={setView}@@ -103,7 +103,7 @@ function FloatingChat() {/>) : (<>- <div className="flex items-center justify-between p-3 border-b">+ <div className="flex items-center justify-between h-10 p-3 border-b"><div className="flex w-full items-center justify-between gap-1"><div className="flex items-center gap-2 truncate text-ellipsis"><Button@@ -155,8 +155,8 @@ function FloatingChat() {{!currentChatId ? (<><div className="relative mb-6">- <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>- <div className="relative bg-gradient-to-br from-primary/10 to-primary/5 rounded-full p-4 border border-primary/20">+ <div className="absolute inset-0 bg-linear-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>+ <div className="relative bg-linear-to-br from-primary/10 to-primary/5 rounded-full p-4 border border-primary/20"><imgsrc="/icon.png"alt="Flowsint"@@ -178,7 +178,7 @@ function FloatingChat() {variant="outline"size="sm"onClick={handleCreateNewChat}- className="bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20 hover:from-primary/20 hover:to-primary/10"+ className="bg-linear-to-r from-primary/10 to-primary/5 border-primary/20 hover:from-primary/20 hover:to-primary/10">Start your first chat</Button>@@ -244,8 +244,8 @@ const ChatMessageComponent = ({ message }: { message: UIMessage }) => {if (message.role === 'assistant')return (<MessageContainer copyContent={content}>- <div className={cn('justify-start', 'flex w-full')}>- <div className={cn('w-full', 'p-3 rounded-xl max-w-full', 'flex flex-col gap-2')}>+ <div className={cn('justify-start', 'flex w-full border rounded-lg')}>+ <div className={cn('w-full', 'p-3 rounded-xl max-w-full', 'flex flex-col')}><MemoizedMarkdown id={message.id} content={content} /></div></div>@@ -274,10 +274,10 @@ const ChatMessageComponent = ({ message }: { message: UIMessage }) => {const MessageContainer = memo(({ children, copyContent }: { children: React.ReactNode; copyContent?: string }) => {return (- <div className="relative group">+ <div className="relative group/msg">{children}- <div className="-mt-1 group-hover:opacity-100 opacity-0 flex items-center justify-end z-1">- <div className="border rounded-md bg-background ">+ <div className="flex items-center justify-end z-1 ">+ <div className="group-hover/msg:opacity-100 border -mt-1 opacity-0 bg-background rounded"><CopyButton content={copyContent ?? ''} /></div></div>diff --git a/flowsint-app/src/components/chat/memoized-markdown.tsx b/flowsint-app/src/components/chat/memoized-markdown.tsxindex e4278a35..019fcf48 100644--- a/flowsint-app/src/components/chat/memoized-markdown.tsx+++ b/flowsint-app/src/components/chat/memoized-markdown.tsx@@ -26,7 +26,7 @@ const MemoizedMarkdownBlock = memo(style={dracula}language={match[1]}PreTag="div"- className="rounded border border-border bg-muted px-1 py-0.5 !m-0 text-sm w-auto not-prose"+ className="rounded border border-border bg-muted px-1 py-0.5 m-0! text-sm w-auto not-prose"{...props}/><div className="absolute top-2 right-2">@@ -64,7 +64,7 @@ export const MemoizedMarkdown = memo(({ content, id }: { content: string; id: stconst blocks = useMemo(() => parseMarkdownIntoBlocks(content), [content])return (- <div className="prose max-w-none dark:prose-invert">+ <div className="prose max-w-none dark:prose-invert text-sm">{blocks.map((block, index) => (<MemoizedMarkdownBlock content={block} key={`${id}-block_${index}`} />))}diff --git a/flowsint-app/src/components/chat/resizable-chat.tsx b/flowsint-app/src/components/chat/resizable-chat.tsxindex ac43c0ff..efbadca9 100644--- a/flowsint-app/src/components/chat/resizable-chat.tsx+++ b/flowsint-app/src/components/chat/resizable-chat.tsx@@ -101,7 +101,10 @@ export const ResizableChat: React.FC<ResizableChatProps> = ({return (<divref={containerRef}- className={cn('relative group overflow-hidden', isResizing && 'pointer-events-none')}+ className={cn(+ 'relative group/resize overflow-hidden max-h-[calc(100vh-60px)]',+ isResizing && 'pointer-events-none'+ )}style={{width: chatWidth,height: chatHeight@@ -119,8 +122,8 @@ export const ResizableChat: React.FC<ResizableChatProps> = ({className={cn('absolute bottom-0 right-0 w-4 h-4 cursor-se-resize','bg-transparent hover:bg-primary/20 transition-colors',- 'rounded-tl-md border-r border-b border-primary/20',- 'group-hover:border-primary/40',+ 'rounded-tl-md border-primary/20',+ 'group-hover/resize:border-primary/40',isResizing && 'bg-primary/30 border-primary/50')}onMouseDown={handleMouseDown('se')}@@ -130,8 +133,8 @@ export const ResizableChat: React.FC<ResizableChatProps> = ({className={cn('absolute bottom-0 left-0 w-4 h-4 cursor-sw-resize','bg-transparent hover:bg-primary/20 transition-colors',- 'rounded-tr-md border-l border-b border-primary/20',- 'group-hover:border-primary/40',+ 'rounded-tr-md border-primary/20',+ 'group-hover/resize:border-primary/40',isResizing && 'bg-primary/30 border-primary/50')}onMouseDown={handleMouseDown('sw')}@@ -141,8 +144,8 @@ export const ResizableChat: React.FC<ResizableChatProps> = ({className={cn('absolute top-0 right-0 w-4 h-4 cursor-ne-resize','bg-transparent hover:bg-primary/20 transition-colors',- 'rounded-bl-md border-r border-t border-primary/20',- 'group-hover:border-primary/40',+ 'rounded-bl-md border-primary/20',+ 'group-hover/resize:border-primary/40',isResizing && 'bg-primary/30 border-primary/50')}onMouseDown={handleMouseDown('ne')}@@ -152,8 +155,8 @@ export const ResizableChat: React.FC<ResizableChatProps> = ({className={cn('absolute top-0 left-0 w-4 h-4 cursor-nw-resize','bg-transparent hover:bg-primary/20 transition-colors',- 'rounded-br-md border-l border-t border-primary/20',- 'group-hover:border-primary/40',+ 'rounded-br-md border-primary/20',+ 'group-hover/resize:border-primary/40',isResizing && 'bg-primary/30 border-primary/50')}onMouseDown={handleMouseDown('nw')}diff --git a/flowsint-app/src/hooks/use-chat.ts b/flowsint-app/src/hooks/use-chat.tsindex 515c324a..1cb52eeb 100644--- a/flowsint-app/src/hooks/use-chat.ts+++ b/flowsint-app/src/hooks/use-chat.ts@@ -9,6 +9,7 @@ import { useChatState } from '@/stores/use-chat-store'import { useParams } from '@tanstack/react-router'import { queryKeys } from '@/api/query-keys'import { toUIMessage } from '@/types/chat'+import type { ChatContextFormat } from '@/types'export const useChat = () => {const selectedNodes = useGraphStore((s) => s.selectedNodes)@@ -28,17 +29,11 @@ export const useChat = () => {queryKey: queryKeys.chats.detail(currentChatId!),queryFn: () => chatCRUDService.getById(currentChatId!),enabled: !!currentChatId,- refetchOnWindowFocus: false,+ refetchOnWindowFocus: false})// AI SDK useChat- const {- messages,- status,- sendMessage,- stop,- setMessages,- } = useAIChat({+ const { messages, status, sendMessage, stop, setMessages } = useAIChat({id: currentChatId ?? undefined,transport,onFinish: () => {@@ -51,7 +46,7 @@ export const useChat = () => {toast.error('Failed to get AI response: ' + (error instanceof Error ? error.message : 'Unknown error'))- },+ }})// Sync server-loaded messages when switching chats@@ -75,7 +70,7 @@ export const useChat = () => {const chatData = {title,description: description || '',- investigation_id: investigationId,+ investigation_id: investigationId}return await chatCRUDService.create(JSON.stringify(chatData))},@@ -89,7 +84,7 @@ export const useChat = () => {toast.error('Failed to create chat: ' + (error instanceof Error ? error.message : 'Unknown error'))- },+ }})// Mutation to delete a chat@@ -107,67 +102,59 @@ export const useChat = () => {toast.error('Failed to delete chat: ' + (error instanceof Error ? error.message : 'Unknown error'))- },+ }})- const handleSendMessage = async (text: string) => {+ const handleSendMessage = async (text: string, context?: string[]) => {if (!text.trim()) {toast.error('Please enter a prompt')return}+ const bodyOptions = context?.length ? { body: { context } } : undefined+// Auto-create chat if none existsif (!currentChatId) {- const chatTitle =- selectedNodes.length > 0- ? selectedNodes- .map((node) => node.data.label)- .join(', ')- .slice(0, 100)- : 'New Chat'+ const chatTitle = 'New Chat'try {const newChat = await createChatMutation.mutateAsync({title: chatTitle,- description: 'Chat created from analysis',+ description: 'Chat created from analysis'})if (!newChat?.id) return// sendMessage will fire once transport updates via the new currentChatId// but we need to wait for the next render, so we queue the send- queuedMessageRef.current = text+ queuedMessageRef.current = { text, context }} catch (error) {console.error('Failed to create chat:', error)}return}- sendMessage({ role: 'user', parts: [{ type: 'text', text }] })+ sendMessage({ role: 'user', parts: [{ type: 'text', text }] }, bodyOptions)}// Handle queued message after chat creation- const queuedMessageRef = useRef<string | null>(null)+ const queuedMessageRef = useRef<{ text: string; context?: string[] } | null>(null)useEffect(() => {if (queuedMessageRef.current && currentChatId && transport) {- const text = queuedMessageRef.current+ const { text, context } = queuedMessageRef.currentqueuedMessageRef.current = null- // Small delay to allow transport to settle+ const bodyOptions = context?.length ? { body: { context } } : undefinedsetTimeout(() => {- sendMessage({ role: 'user', parts: [{ type: 'text', text }] })+ sendMessage({ role: 'user', parts: [{ type: 'text', text }] }, bodyOptions)}, 50)}}, [currentChatId, transport, sendMessage])const createNewChat = async (title?: string) => {- const chatTitle =- title ||- (selectedNodes.length > 0- ? selectedNodes[0].data.label- : 'New Chat #' + (Math.floor(Math.random() * 900) + 1000))+ const chatTitle = title || 'New Chat #' + (Math.floor(Math.random() * 900) + 1000)try {await createChatMutation.mutateAsync({title: chatTitle,- description: 'Chat created from analysis',+ description: 'Chat created from analysis'})} catch (error) {console.error('Failed to create new chat:', error)@@ -203,6 +190,6 @@ export const useChat = () => {switchToChat,currentChatId,createChatMutation,- deleteChatMutation,+ deleteChatMutation}}diff --git a/flowsint-app/src/stores/graph-store.ts b/flowsint-app/src/stores/graph-store.tsindex 76eb6d77..9d67e0b3 100644--- a/flowsint-app/src/stores/graph-store.ts+++ b/flowsint-app/src/stores/graph-store.ts@@ -1,6 +1,6 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'-import type { GraphNode, GraphEdge, NodeProperties } from '@/types'+import type { GraphNode, GraphEdge, NodeProperties, ChatContextFormat } from '@/types'import { type ActionItem } from '@/lib/action-items'import { Filters, TypeFilter } from '@/types/filter'@@ -76,6 +76,7 @@ interface GraphState {edgesLength: numbergetNodesLength: () => numbergetEdgesLength: () => number+ getSelectedNodesWithEdgesAsList: () => ChatContextFormat[]}// --- Helpers ---@@ -438,6 +439,26 @@ export const useGraphStore = create<GraphState>()(filteredEdges: get().edges})},+ getSelectedNodesWithEdgesAsList: () => {+ const { selectedNodes, edgesMapping } = get()+ let context: ChatContextFormat[] = []+ const selectedNodesMapping = new Map(selectedNodes.map((node) => [node.id, node]))+ edgesMapping.forEach((edge) => {+ const fromNode = selectedNodesMapping.get(edge.source)+ const toNode = selectedNodesMapping.get(edge.target)+ if (fromNode && toNode)+ context.push({+ fromLabel: fromNode.nodeLabel,+ fromType: fromNode.nodeType,+ fromColor: fromNode.nodeColor,+ toLabel: toNode.nodeLabel,+ toType: toNode.nodeType,+ toColor: toNode.nodeColor,+ label: edge.label+ })+ })+ return context+ },// === Utils ===nodesLength: 0,diff --git a/flowsint-app/src/types/chat.ts b/flowsint-app/src/types/chat.tsindex 90b7ab50..66fce917 100644--- a/flowsint-app/src/types/chat.ts+++ b/flowsint-app/src/types/chat.ts@@ -9,6 +9,16 @@ export interface ChatMessage {chatId?: string}+export type ChatContextFormat = {+ fromType: string+ fromLabel: string+ fromColor: string | null+ toType: string+ toLabel: string+ toColor: string | null+ label: string+}+export interface Chat {id: stringtitle: string@@ -21,6 +31,6 @@ export function toUIMessage(msg: ChatMessage): UIMessage {return {id: msg.id,role: msg.is_bot ? 'assistant' : 'user',- parts: [{ type: 'text', text: msg.content }],+ parts: [{ type: 'text', text: msg.content }]}}diff --git a/flowsint-app/src/workers/layout.worker.ts b/flowsint-app/src/workers/layout.worker.tsindex f0b3f2a2..ff5da03e 100644--- a/flowsint-app/src/workers/layout.worker.ts+++ b/flowsint-app/src/workers/layout.worker.ts@@ -76,7 +76,7 @@ function computeDagreLayout(nodes.forEach((node) =>g.setNode(node.id, {- width: nodeWidth,+ width: nodeWidth + node.nodeLabel.length / 2.5,height: nodeHeight}))