A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat: global settings, prototype of nodes merging
dextmorgn1d6ee46fb22d
diff --git a/flowsint-api/app/api/routes/chat.py b/flowsint-api/app/api/routes/chat.pyindex b7fd1cb8..f13c1ac1 100644--- a/flowsint-api/app/api/routes/chat.py+++ b/flowsint-api/app/api/routes/chat.py@@ -83,6 +83,7 @@ def get_chats_by_investigation(.filter(Chat.investigation_id == investigation_id, Chat.owner_id == current_user.id)+ .order_by(Chat.created_at.asc()).all())diff --git a/flowsint-api/app/api/routes/flows.py b/flowsint-api/app/api/routes/flows.pyindex 2c5bed95..7eadfd2a 100644--- a/flowsint-api/app/api/routes/flows.py+++ b/flowsint-api/app/api/routes/flows.py@@ -6,7 +6,7 @@ from datetime import datetimefrom flowsint_core.utils import extract_input_schema_flowfrom flowsint_core.core.registry import TransformRegistryfrom flowsint_core.core.celery import celery-from flowsint_types import Domain, Phrase, Ip, SocialProfile, Organization, Email+from flowsint_types import Domain, Phrase, Ip, SocialProfile, Organization, Email, Phonefrom flowsint_core.core.types import Node, Edge, FlowStep, FlowBranchfrom sqlalchemy.orm import Sessionfrom flowsint_core.core.postgre_db import get_db@@ -102,6 +102,7 @@ async def get_material_list():extract_input_schema_flow(Domain),extract_input_schema_flow(Website),extract_input_schema_flow(Ip),+ extract_input_schema_flow(Phone),extract_input_schema_flow(ASN),extract_input_schema_flow(CIDR),extract_input_schema_flow(SocialProfile),@@ -172,7 +173,7 @@ def update_flow(flow = db.query(Flow).filter(Flow.id == flow_id).first()if not flow:raise HTTPException(status_code=404, detail="flow not found")- update_data = payload.dict(exclude_unset=True)+ update_data = payload.model_dump(exclude_unset=True)for key, value in update_data.items():print(f"only update {key}")if key == "category":diff --git a/flowsint-api/app/api/routes/sketches.py b/flowsint-api/app/api/routes/sketches.pyindex e3712a45..79d5e7f0 100644--- a/flowsint-api/app/api/routes/sketches.py+++ b/flowsint-api/app/api/routes/sketches.py@@ -17,6 +17,45 @@ from app.api.deps import get_current_userrouter = APIRouter()+class NodeData(BaseModel):+ label: str = Field(default="Node", description="Label/name of the node")+ color: str = Field(default="Node", description="Color of the node")+ type: str = Field(default="Node", description="Type of the node")+ # Add any other specific data fields that might be common across nodes++ class Config:+ extra = "allow" # Accept any additional fields+++class NodeInput(BaseModel):+ type: str = Field(..., description="Type of the node")+ data: NodeData = Field(+ default_factory=NodeData, description="Additional data for the node"+ )+++def dict_to_cypher_props(props: dict, prefix: str = "") -> str:+ return ", ".join(f"{key}: ${prefix}{key}" for key in props)+++class NodeDeleteInput(BaseModel):+ nodeIds: List[str]+++class NodeEditInput(BaseModel):+ nodeId: str+ data: NodeData = Field(+ default_factory=NodeData, description="Updated data for the node"+ )+++class NodeMergeInput(BaseModel):+ id: str+ data: NodeData = Field(+ default_factory=NodeData, description="Updated data for the node"+ )++@router.post("/create", response_model=SketchRead, status_code=status.HTTP_201_CREATED)def create_sketch(data: SketchCreate,@@ -54,14 +93,19 @@ def get_sketch_by_id(@router.put("/{id}", response_model=SketchRead)def update_sketch(id: UUID,- data: SketchUpdate,+ payload: SketchUpdate,db: Session = Depends(get_db),current_user: Profile = Depends(get_current_user),):- sketch = db.query(Sketch).filter(Sketch.owner_id == current_user.id).get(id)+ sketch = (+ db.query(Sketch)+ .filter(Sketch.owner_id == current_user.id)+ .filter(Sketch.id == id)+ .first()+ )if not sketch:raise HTTPException(status_code=404, detail="Sketch not found")- for key, value in data.dict(exclude_unset=True).items():+ for key, value in payload.model_dump(exclude_unset=True).items():setattr(sketch, key, value)db.commit()db.refresh(sketch)@@ -177,27 +221,6 @@ async def get_sketch_nodes(return {"nds": nodes, "rls": rels}-class NodeData(BaseModel):- label: str = Field(default="Node", description="Label/name of the node")- color: str = Field(default="Node", description="Color of the node")- type: str = Field(default="Node", description="Type of the node")- # Add any other specific data fields that might be common across nodes-- class Config:- extra = "allow" # Accept any additional fields---class NodeInput(BaseModel):- type: str = Field(..., description="Type of the node")- data: NodeData = Field(- default_factory=NodeData, description="Additional data for the node"- )---def dict_to_cypher_props(props: dict, prefix: str = "") -> str:- return ", ".join(f"{key}: ${prefix}{key}" for key in props)--@router.post("/{sketch_id}/nodes/add")def add_node(sketch_id: str, node: NodeInput, current_user: Profile = Depends(get_current_user)@@ -254,8 +277,8 @@ def add_node(class RelationInput(BaseModel):- source: Any- target: Any+ source: str+ target: strtype: Literal["one-way", "two-way"]label: str = "RELATED_TO" # Optionnel : nom de la relation@@ -275,8 +298,8 @@ def add_edge("""params = {- "from_id": relation.source["id"],- "to_id": relation.target["id"],+ "from_id": relation.source,+ "to_id": relation.target,"sketch_id": sketch_id,}@@ -295,17 +318,6 @@ def add_edge(}-class NodeDeleteInput(BaseModel):- nodeIds: List[str]---class NodeEditInput(BaseModel):- nodeId: str- data: NodeData = Field(- default_factory=NodeData, description="Updated data for the node"- )--@router.put("/{sketch_id}/nodes/edit")def edit_node(sketch_id: str,@@ -394,6 +406,112 @@ def delete_nodes(return {"status": "nodes deleted", "count": len(nodes.nodeIds)}[email protected]("/{sketch_id}/nodes/merge")+def merge_nodes(+ sketch_id: str,+ oldNodes: List[str],+ newNode: NodeMergeInput,+ db: Session = Depends(get_db),+ current_user: Profile = Depends(get_current_user),+):+ # 1. Vérifier le sketch+ sketch = db.query(Sketch).filter(Sketch.id == sketch_id).first()+ if not sketch:+ raise HTTPException(status_code=404, detail="Sketch not found")++ oldNodeIds = [id for id in oldNodes]++ # 2. Préparer le node unique (utiliser nodeId)+ node_id = getattr(newNode, "id", None)+ if not node_id:+ raise HTTPException(status_code=400, detail="newNode.id is required")++ properties = {}+ if newNode.data:+ flattened_data = flatten(newNode.data.dict())+ properties.update(flattened_data)++ cypher_props = dict_to_cypher_props(properties)+ node_type = getattr(newNode, "type", "Node")++ # 3. Créer ou merger le nouveau node+ create_query = f"""+ MERGE (new:`{node_type}` {{nodeId: $nodeId}})+ SET new += $nodeData+ RETURN elementId(new) as newElementId+ """+ try:+ result = neo4j_connection.query(+ create_query, {"nodeId": node_id, "nodeData": cypher_props}+ )+ new_node_element_id = result[0]["newElementId"]+ except Exception as e:+ print(f"Error creating/merging new node: {e}")+ raise HTTPException(status_code=500, detail="Failed to create new node")++ # 4. Récupérer tous les types de relations des oldNodes+ rel_types_query = """+ MATCH (old)+ WHERE elementId(old) IN $oldNodeIds AND old.sketch_id = $sketch_id+ MATCH (old)-[r]-()+ RETURN DISTINCT type(r) AS relType+ """+ try:+ rel_types_result = neo4j_connection.query(+ rel_types_query, {"oldNodeIds": oldNodeIds, "sketch_id": sketch_id}+ )+ rel_types = [row["relType"] for row in rel_types_result] or []+ except Exception as e:+ print(f"Error fetching relation types: {e}")+ raise HTTPException(status_code=500, detail="Failed to fetch relation types")++ # 5. Construire la query pour copier les relations+ blocks = []+ for rel_type in rel_types:+ block = f"""+ // Relations entrantes+ MATCH (new) WHERE elementId(new) = $newElementId+ MATCH (old) WHERE elementId(old) IN $oldNodeIds+ OPTIONAL MATCH (src)-[r:`{rel_type}`]->(old)+ WITH src, new, r WHERE src IS NOT NULL+ MERGE (src)-[newRel:`{rel_type}`]->(new)+ ON CREATE SET newRel = r+ ON MATCH SET newRel += r+ WITH DISTINCT new++ // Relations sortantes+ MATCH (new) WHERE elementId(new) = $newElementId+ MATCH (old) WHERE elementId(old) IN $oldNodeIds+ OPTIONAL MATCH (old)-[r:`{rel_type}`]->(dst)+ WITH dst, new, r WHERE dst IS NOT NULL+ MERGE (new)-[newRel2:`{rel_type}`]->(dst)+ ON CREATE SET newRel2 = r+ ON MATCH SET newRel2 += r+ WITH DISTINCT new+ """+ blocks.append(block)++ # 6. Supprimer les anciens nodes+ delete_query = """+ MATCH (old)+ WHERE elementId(old) IN $oldNodeIds+ DETACH DELETE old+ """++ full_query = "\n".join(blocks) + delete_query++ # 7. Exécuter la query+ try:+ neo4j_connection.query(+ full_query, {"newElementId": new_node_element_id, "oldNodeIds": oldNodeIds}+ )+ except Exception as e:+ print(f"Node merging error: {e}")+ raise HTTPException(status_code=500, detail="Failed to merge node relations")++ return {"status": "nodes merged", "count": len(oldNodeIds)}++@router.get("/{sketch_id}/nodes/{node_id}")def get_related_nodes(sketch_id: str,diff --git a/flowsint-app/package.json b/flowsint-app/package.jsonindex bcea71c7..152007fd 100644--- a/flowsint-app/package.json+++ b/flowsint-app/package.json@@ -33,6 +33,7 @@"@electron-toolkit/preload": "^3.0.1","@electron-toolkit/utils": "^3.0.0","@hookform/resolvers": "^5.0.1",+ "@lukemorales/query-key-factory": "^1.3.4","@radix-ui/react-accordion": "^1.2.11","@radix-ui/react-alert-dialog": "^1.1.14","@radix-ui/react-aspect-ratio": "^1.1.7",diff --git a/flowsint-app/src/renderer/index.html b/flowsint-app/src/renderer/index.htmlindex 153b424e..c41e6577 100644--- a/flowsint-app/src/renderer/index.html+++ b/flowsint-app/src/renderer/index.html@@ -1,11 +1,11 @@<!DOCTYPE html><html lang="en" theme="dark"><head>- <script+ <!-- <scriptcrossOrigin="anonymous"src="//unpkg.com/react-scan/dist/auto.global.js">- </script>+ </script> --><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />diff --git a/flowsint-app/src/renderer/src/api/README-query-keys.md b/flowsint-app/src/renderer/src/api/README-query-keys.mdnew file mode 100644index 00000000..bd0b0b9b--- /dev/null+++ b/flowsint-app/src/renderer/src/api/README-query-keys.md@@ -0,0 +1,234 @@+# Query Key Factory Implementation++This project now uses the [@lukemorales/query-key-factory](https://tanstack.com/query/v4/docs/framework/react/community/lukemorales-query-key-factory) library to manage TanStack Query keys in a type-safe and organized way.++## Overview++Query Key Factory provides:+- **Type-safe query keys** with auto-completion+- **Centralized key management** - all keys in one place+- **Easy invalidation** - no more hardcoded key strings+- **Consistent patterns** across your application++## Files structure++```+src/api/+├── query-keys.ts # Main query key definitions+├── query-keys-examples.ts # Usage examples and custom hooks+└── README-query-keys.md # This documentation+```++## How to use++### 1. Basic query usage++```tsx+import { useQuery } from '@tanstack/react-query'+import { queryKeys } from '@/api/query-keys'+import { investigationService } from '@/api/investigation-service'++// Before (hardcoded keys)+const { data } = useQuery({+ queryKey: ['investigations', 'list'],+ queryFn: investigationService.get,+})++// After (using query key factory)+const { data } = useQuery({+ queryKey: queryKeys.investigations.list,+ queryFn: investigationService.get,+})+```++### 2. Dynamic Keys with Parameters++```tsx+// Before+const { data } = useQuery({+ queryKey: ['investigations', investigationId],+ queryFn: () => investigationService.getById(investigationId),+})++// After+const { data } = useQuery({+ queryKey: queryKeys.investigations.detail(investigationId),+ queryFn: () => investigationService.getById(investigationId),+})+```++### 3. Mutation with Invalidation++```tsx+import { useMutation, useQueryClient } from '@tanstack/react-query'++const createAnalysisMutation = useMutation({+ mutationFn: analysisService.create,+ onSuccess: (data, variables) => {+ const queryClient = useQueryClient()++ // Invalidate specific queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.analyses(variables.investigation_id)+ })++ // Invalidate general lists+ queryClient.invalidateQueries({+ queryKey: queryKeys.analyses.list+ })+ },+})+```++### 4. Cache Updates++```tsx+const updateAnalysisMutation = useMutation({+ mutationFn: analysisService.update,+ onSuccess: (data, variables) => {+ const queryClient = useQueryClient()++ // Update cache directly for better UX+ queryClient.setQueryData(+ queryKeys.analyses.detail(variables.analysisId),+ data+ )++ // Invalidate related queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.analyses.byInvestigation(data.investigation_id)+ })+ },+})+```++## Available Query Keys++### Auth+- `queryKeys.auth.session`+- `queryKeys.auth.currentUser`++### Investigations+- `queryKeys.investigations.list`+- `queryKeys.investigations.detail(investigationId)`+- `queryKeys.investigations.sketches(investigationId)`+- `queryKeys.investigations.analyses(investigationId)`+- `queryKeys.investigations.flows(investigationId)`++### Sketches/Graphs+- `queryKeys.sketches.list`+- `queryKeys.sketches.detail(sketchId)`+- `queryKeys.sketches.byInvestigation(investigationId)`+- `queryKeys.sketches.graph(investigationId, sketchId)`+- `queryKeys.sketches.types`++### Analyses+- `queryKeys.analyses.list`+- `queryKeys.analyses.detail(analysisId)`+- `queryKeys.analyses.byInvestigation(investigationId)`++### Flows+- `queryKeys.flows.list`+- `queryKeys.flows.detail(flowId)`+- `queryKeys.flows.byInvestigation(investigationId)`++### Chats+- `queryKeys.chats.list`+- `queryKeys.chats.detail(chatId)`+- `queryKeys.chats.byInvestigation(investigationId)`+- `queryKeys.chats.messages(chatId)`++### API Keys+- `queryKeys.keys.list`+- `queryKeys.keys.detail(keyId)`++### Logs/Events+- `queryKeys.logs.bySketch(sketchId)`++### Action Items+- `queryKeys.actionItems`++### Scans+- `queryKeys.scans.list`+- `queryKeys.scans.detail(scanId)`++### Transforms+- `queryKeys.transforms.list`+- `queryKeys.transforms.detail(transformId)`++## Migration Guide++### Step 1: Update Existing Hooks++Find your existing `useQuery` calls and replace hardcoded keys:++```tsx+// Before+queryKey: ['investigations', 'list']++// After+queryKey: queryKeys.investigations.list+```++### Step 2: Update Mutations++Replace hardcoded invalidation keys:++```tsx+// Before+queryClient.invalidateQueries({ queryKey: ['investigations'] })++// After+queryClient.invalidateQueries({ queryKey: queryKeys.investigations.list })+```++### Step 3: Update Cache Operations++Replace hardcoded keys in `setQueryData` and `removeQueries`:++```tsx+// Before+queryClient.setQueryData(['analyses', analysisId], data)++// After+queryClient.setQueryData(queryKeys.analyses.detail(analysisId), data)+```++## Benefits++1. **Type Safety**: TypeScript will catch typos and provide autocomplete+2. **Refactoring**: Change a key structure in one place+3. **Consistency**: All keys follow the same pattern+4. **Maintainability**: Easy to see all available keys+5. **IDE Support**: Better autocomplete and IntelliSense++## Best Practices++1. **Always use the factory**: Don't hardcode query keys+2. **Group related keys**: Use the logical grouping provided+3. **Invalidate properly**: Use the exact key for invalidation+4. **Update cache**: Use `setQueryData` with the factory keys+5. **Consistent naming**: Follow the established patterns++## Troubleshooting++### Common Issues++1. **Type errors**: Make sure you're calling the key function with parameters+2. **Invalidation not working**: Ensure you're using the exact same key structure+3. **Cache updates failing**: Verify the key matches the query key exactly++### Debug Tips++1. **Console log keys**: `console.log(queryKeys.investigations.list)`+2. **Check key structure**: Compare generated keys with existing ones+3. **Verify imports**: Ensure you're importing from the correct path++## Examples++See `query-keys-examples.ts` for comprehensive usage examples including:+- Basic queries+- Mutations with invalidation+- Cache updates+- Complex invalidation patterns+- Prefetching strategiesdiff --git a/flowsint-app/src/renderer/src/api/query-keys-examples.ts b/flowsint-app/src/renderer/src/api/query-keys-examples.tsnew file mode 100644index 00000000..4e8b7320--- /dev/null+++ b/flowsint-app/src/renderer/src/api/query-keys-examples.ts@@ -0,0 +1,216 @@+// Examples of how to use the Query Key Factory with your existing hooks+// This file demonstrates the proper usage patterns++import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'+import { queryKeys } from './query-keys'+import { analysisService } from './analysis-service'+import { investigationService } from './investigation-service'+import { sketchService } from './sketch-service'+import { chatCRUDService } from './chat-service'+import { KeyService } from './key-service'+import { logService } from './log-service'+import { scanService } from './scan-service'+import { transformService } from './transform-service'++// Example 1: Using the query keys directly+export const useInvestigationsList = () => {+ return useQuery({+ queryKey: queryKeys.investigations.list,+ queryFn: investigationService.get,+ })+}++export const useInvestigationDetail = (investigationId: string) => {+ return useQuery({+ queryKey: queryKeys.investigations.detail(investigationId),+ queryFn: () => investigationService.getById(investigationId),+ enabled: !!investigationId,+ })+}++export const useInvestigationAnalyses = (investigationId: string) => {+ return useQuery({+ queryKey: queryKeys.investigations.analyses(investigationId),+ queryFn: () => analysisService.getByInvestigationId(investigationId),+ enabled: !!investigationId,+ })+}++// Example 2: Using the individual key groups+export const useSketchesList = () => {+ return useQuery({+ queryKey: queryKeys.sketches.list,+ queryFn: sketchService.get,+ })+}++export const useSketchDetail = (sketchId: string) => {+ return useQuery({+ queryKey: queryKeys.sketches.detail(sketchId),+ queryFn: () => sketchService.getById(sketchId),+ enabled: !!sketchId,+ })+}++export const useSketchGraph = (investigationId: string, sketchId: string) => {+ return useQuery({+ queryKey: queryKeys.sketches.graph(investigationId, sketchId),+ queryFn: () => sketchService.getById(sketchId),+ enabled: !!investigationId && !!sketchId,+ })+}++// Example 3: Using with mutations and invalidation+export const useCreateAnalysis = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: async (data: { title: string; investigation_id: string; content: any }) => {+ return analysisService.create(JSON.stringify(data))+ },+ onSuccess: (data, variables) => {+ // Invalidate the specific investigation's analyses+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.analyses(variables.investigation_id)+ })++ // Also invalidate the general analyses list+ queryClient.invalidateQueries({+ queryKey: queryKeys.analyses.list+ })+ },+ })+}++export const useUpdateAnalysis = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: async ({ analysisId, data }: { analysisId: string; data: any }) => {+ return analysisService.update(analysisId, JSON.stringify(data))+ },+ onSuccess: (data, variables) => {+ // Update the cache directly for better UX+ queryClient.setQueryData(+ queryKeys.analyses.detail(variables.analysisId),+ data+ )++ // Invalidate related queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.analyses.byInvestigation(data.investigation_id)+ })+ },+ })+}++// Example 4: Using with chat functionality+export const useChatDetail = (chatId: string) => {+ return useQuery({+ queryKey: queryKeys.chats.detail(chatId),+ queryFn: () => chatCRUDService.getById(chatId),+ enabled: !!chatId,+ })+}++export const useChatsByInvestigation = (investigationId: string) => {+ return useQuery({+ queryKey: queryKeys.chats.byInvestigation(investigationId),+ queryFn: () => chatCRUDService.getByInvestigationId(investigationId),+ enabled: !!investigationId,+ })+}++// Example 5: Using with logs and events+export const useLogsBySketch = (sketchId: string) => {+ return useQuery({+ queryKey: queryKeys.logs.bySketch(sketchId),+ queryFn: () => logService.get(sketchId),+ enabled: !!sketchId,+ staleTime: 30_000, // 30 seconds+ })+}++// Example 6: Using with API keys+export const useKeysList = () => {+ return useQuery({+ queryKey: queryKeys.keys.list,+ queryFn: KeyService.get,+ })+}++export const useKeyDetail = (keyId: string) => {+ return useQuery({+ queryKey: queryKeys.keys.detail(keyId),+ queryFn: () => KeyService.getById(keyId),+ enabled: !!keyId,+ })+}++// Example 7: Using with scans+export const useScanDetail = (scanId: string) => {+ return useQuery({+ queryKey: queryKeys.scans.detail(scanId),+ queryFn: () => scanService.get(scanId),+ enabled: !!scanId,+ })+}++// Example 8: Using with transforms+export const useTransformsList = () => {+ return useQuery({+ queryKey: queryKeys.transforms.list,+ queryFn: transformService.get,+ })+}++// Example 9: Complex invalidation patterns+export const useDeleteInvestigation = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: investigationService.delete,+ onSuccess: (data, variables) => {+ // Invalidate all investigation-related queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.list+ })++ // Invalidate all related data+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.detail(variables)+ })++ // Clear related caches+ queryClient.removeQueries({+ queryKey: queryKeys.investigations.analyses(variables)+ })++ queryClient.removeQueries({+ queryKey: queryKeys.investigations.sketches(variables)+ })++ queryClient.removeQueries({+ queryKey: queryKeys.investigations.flows(variables)+ })+ },+ })+}++// Example 10: Prefetching with query keys+export const usePrefetchInvestigation = () => {+ const queryClient = useQueryClient()++ return (investigationId: string) => {+ queryClient.prefetchQuery({+ queryKey: queryKeys.investigations.detail(investigationId),+ queryFn: () => investigationService.getById(investigationId),+ })++ // Also prefetch related data+ queryClient.prefetchQuery({+ queryKey: queryKeys.investigations.analyses(investigationId),+ queryFn: () => analysisService.getByInvestigationId(investigationId),+ })+ }+}diff --git a/flowsint-app/src/renderer/src/api/query-keys.ts b/flowsint-app/src/renderer/src/api/query-keys.tsnew file mode 100644index 00000000..5424f9af--- /dev/null+++ b/flowsint-app/src/renderer/src/api/query-keys.ts@@ -0,0 +1,91 @@+// Simple query key factory that actually works+export const queryKeys = {+ // Auth related queries+ auth: {+ session: ['auth', 'session'],+ currentUser: ['auth', 'currentUser'],+ },++ // Investigations+ investigations: {+ list: ['investigations', 'list'],+ detail: (investigationId: string) => ['investigations', investigationId],+ sketches: (investigationId: string) => [investigationId, 'sketches'],+ analyses: (investigationId: string) => [investigationId, 'analyses'],+ flows: (investigationId: string) => [investigationId, 'flows'],+ dashboard: ['investigations', 'dashboard'],+ selector: (investigationId: string) => ['dashboard', 'selector', investigationId],+ },++ // Sketches/Graphs+ sketches: {+ list: ['sketches', 'list'],+ detail: (sketchId: string) => ['sketches', sketchId],+ byInvestigation: (investigationId: string) => [investigationId, 'sketches'],+ graph: (investigationId: string, sketchId: string) => [investigationId, 'graph', sketchId],+ types: ['sketches', 'types'],+ dashboard: (investigationId: string) => ['dashboard', 'investigation', investigationId],+ },++ // Analyses+ analyses: {+ list: ['analyses', 'list'],+ detail: (analysisId: string) => ['analyses', analysisId],+ byInvestigation: (investigationId: string) => [investigationId, 'analyses'],+ dashboard: (investigationId: string) => ['analyses', investigationId],+ },++ // Flows+ flows: {+ list: ['flows', 'list'],+ detail: (flowId: string) => ['flows', flowId],+ byInvestigation: (investigationId: string) => [investigationId, 'flows'],+ },++ // Chats+ chats: {+ list: ['chats', 'list'],+ detail: (chatId: string) => ['chats', chatId],+ byInvestigation: (investigationId: string) => [investigationId, 'chats'],+ messages: (chatId: string) => [chatId, 'messages'],+ },++ // API Keys+ keys: {+ list: ['keys'],+ detail: (keyId: string) => ['keys', keyId],+ },++ // Logs/Events+ logs: {+ bySketch: (sketchId: string) => [sketchId, 'logs'],+ },++ // Action Items+ actionItems: ['actionItems'],++ // Scans+ scans: {+ list: ['scans', 'list'],+ detail: (scanId: string) => ['scans', scanId],+ },++ // Transforms+ transforms: {+ list: ['transforms', 'list'],+ detail: (transformId: string) => ['transforms', transformId],+ },+}++// Export individual key groups for easier imports+export const authKeys = queryKeys.auth+export const investigationKeys = queryKeys.investigations+export const sketchKeys = queryKeys.sketches+export const analysisKeys = queryKeys.analyses+export const flowKeys = queryKeys.flows+export const chatKeys = queryKeys.chats+export const keyKeys = queryKeys.keys+export const logKeys = queryKeys.logs+export const actionItemKeys = queryKeys.actionItems+export const scanKeys = queryKeys.scans+export const transformKeys = queryKeys.transformsdiff --git a/flowsint-app/src/renderer/src/api/sketch-service.ts b/flowsint-app/src/renderer/src/api/sketch-service.tsindex fc9d8c41..9be7ebf0 100644--- a/flowsint-app/src/renderer/src/api/sketch-service.ts+++ b/flowsint-app/src/renderer/src/api/sketch-service.ts@@ -40,6 +40,12 @@ export const sketchService = {body: body});},+ mergeNodes: async (sketchId: string, body: BodyInit): Promise<any> => {+ return fetchWithAuth(`/api/sketches/${sketchId}/nodes/merge`, {+ method: 'POST',+ body: body+ });+ },deleteNodes: async (sketchId: string, body: BodyInit): Promise<any> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes`, {method: 'DELETE',@@ -62,4 +68,10 @@ export const sketchService = {method: 'GET'});},+ update: async (sketchId: string, body: BodyInit): Promise<any> => {+ return fetchWithAuth(`/api/sketches/${sketchId}`, {+ method: 'PUT',+ body: body+ });+ },};\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/api/transfrom-service.ts b/flowsint-app/src/renderer/src/api/transform-service.tssimilarity index 100%rename from flowsint-app/src/renderer/src/api/transfrom-service.tsrename to flowsint-app/src/renderer/src/api/transform-service.tsdiff --git a/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx b/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsxindex f770d47c..dc73bd5b 100644--- a/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx+++ b/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx@@ -11,6 +11,7 @@ import { cn } from "@/lib/utils"import { useMutation, useQueryClient } from "@tanstack/react-query"import { toast } from "sonner"import { formatDistanceToNow } from "date-fns"+import { queryKeys } from "@/api/query-keys"const AnalysisItem = ({ analysis, active }: { analysis: Analysis, active: boolean }) => {return (@@ -44,8 +45,8 @@ const AnalysisList = () => {const navigate = useNavigate()// Fetch all analyses for this investigation- const { data: analyses, error, isLoading } = useQuery<Analysis[]>({- queryKey: ["analyses", investigationId],+ const { data: analyses, isLoading, error } = useQuery({+ queryKey: queryKeys.analyses.byInvestigation(investigationId || ""),queryFn: () => analysisService.getByInvestigationId(investigationId || ""),enabled: !!investigationId,})@@ -62,7 +63,7 @@ const AnalysisList = () => {)}, [analyses, searchQuery])- const createAnalysisMutation = useMutation({+ const createMutation = useMutation({mutationFn: async () => {const newAnalysis: Partial<Analysis> = {title: "Untitled Analysis",@@ -72,8 +73,8 @@ const AnalysisList = () => {return analysisService.create(JSON.stringify(newAnalysis))},onSuccess: async (data) => {- queryClient.invalidateQueries({ queryKey: ["analyses", investigationId] })- toast.success("New analysis created")+ queryClient.invalidateQueries({ queryKey: queryKeys.analyses.byInvestigation(investigationId || "") })+ toast.success("Analysis created successfully")investigationId && navigate({ to: "/dashboard/investigations/$investigationId/$type/$id", params: { investigationId, type: "analysis", id: data.id } })},onError: (error) => {@@ -89,8 +90,8 @@ const AnalysisList = () => {variant="ghost"size="icon"className="h-7 w-7"- onClick={() => createAnalysisMutation.mutate()}- disabled={createAnalysisMutation.isPending}+ onClick={() => createMutation.mutate()}+ disabled={createMutation.isPending}title="Create new analysis"><PlusIcon className="h-4 w-4" />@@ -136,8 +137,8 @@ const AnalysisList = () => {<Buttonsize="sm"variant="outline"- onClick={() => createAnalysisMutation.mutate()}- disabled={createAnalysisMutation.isPending}+ onClick={() => createMutation.mutate()}+ disabled={createMutation.isPending}><PlusIcon className="w-4 h-4 mr-2" />Create your first analysisdiff --git a/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx b/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsxindex d71b69a4..6404a432 100644--- a/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx+++ b/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx@@ -25,6 +25,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"+import { queryKeys } from "@/api/query-keys"interface AnalysisEditorProps {// Core data@@ -125,7 +126,7 @@ export const AnalysisEditor = ({return res},onSuccess: async () => {- queryClient.invalidateQueries({ queryKey: ["analyses", investigationId] })+ queryClient.invalidateQueries({ queryKey: queryKeys.analyses.byInvestigation(investigationId || "") })onAnalysisCreate?.(investigationId)toast.success("New analysis created")},@@ -144,8 +145,8 @@ export const AnalysisEditor = ({}))},onSuccess: async (data) => {- // Use more specific query invalidation- queryClient.setQueryData(["analyses", investigationId], (oldData: Analysis[] | undefined) => {+ // Use more specific query invalidation with query key factory+ queryClient.setQueryData(queryKeys.analyses.byInvestigation(investigationId || ""), (oldData: Analysis[] | undefined) => {if (!oldData) return oldDatareturn oldData.map(item => item.id === data.id ? data : item)})@@ -163,8 +164,8 @@ export const AnalysisEditor = ({return analysisService.delete(id)},onSuccess: async () => {- queryClient.invalidateQueries({ queryKey: ["analyses", investigationId] })- onAnalysisDelete?.(analysis?.id || "")+ queryClient.invalidateQueries({ queryKey: queryKeys.analyses.byInvestigation(investigationId || "") })+ onAnalysisDelete?.(investigationId)toast.success("Analysis deleted")},onError: (error) => {diff --git a/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx b/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsxindex f05ed06e..00e1c4fb 100644--- a/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx+++ b/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx@@ -5,9 +5,10 @@ import { Card, CardContent } from "@/components/ui/card";import { Button } from "@/components/ui/button";import { Badge } from "@/components/ui/badge";import { Skeleton } from "@/components/ui/skeleton";-import { FolderOpen, Plus, Clock, FileText, BarChart3 } from "lucide-react";+import { FolderOpen, Plus, Clock, FileText, BarChart3, Search } from "lucide-react";import { formatDistanceToNow } from "date-fns";import NewInvestigation from "@/components/investigations/new-investigation";+import { queryKeys } from "@/api/query-keys";interface InvestigationCardProps {investigation: any;@@ -17,7 +18,7 @@ function InvestigationCard({ investigation }: InvestigationCardProps) {const sketchCount = investigation.sketches?.length || 0;const analysisCount = investigation.analyses?.length || 0;const totalItems = sketchCount + analysisCount;-+return (<Linkto="/dashboard/investigations/$investigationId"@@ -30,7 +31,7 @@ function InvestigationCard({ investigation }: InvestigationCardProps) {<div className="flex items-start justify-between mb-3"><div className="flex items-center gap-3 flex-1 min-w-0"><div className="w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center flex-shrink-0">- <FolderOpen className="w-4 h-4 text-primary" />+ <Search className="w-4 h-4 text-primary" /></div><div className="flex-1 min-w-0"><h3 className="font-semibold text-sm truncate group-hover:text-primary transition-colors">@@ -45,7 +46,7 @@ function InvestigationCard({ investigation }: InvestigationCardProps) {{totalItems}</Badge></div>-+{/* Stats row */}<div className="flex items-center gap-4 text-xs text-muted-foreground mb-3"><div className="flex items-center gap-1">@@ -57,7 +58,7 @@ function InvestigationCard({ investigation }: InvestigationCardProps) {<span>{analysisCount} docs</span></div></div>-+{/* Footer with timestamp */}<div className="mt-auto"><div className="flex items-center gap-2 text-xs text-muted-foreground">@@ -86,7 +87,7 @@ function InvestigationCardsSkeleton() {<div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">{Array.from({ length: 8 }).map((_, i) => (<Card key={i} className="w-full">- <CardContent className="p-4 h-full flex flex-col">+ <CardContent className="p-4 h-full flex flex-col"><div className="flex items-start justify-between mb-3"><div className="flex items-center gap-3"><Skeleton className="w-8 h-8 rounded-lg" />@@ -114,7 +115,7 @@ function InvestigationCardsSkeleton() {export function InvestigationCards() {const { data: investigations, isLoading } = useQuery({- queryKey: ["investigations", "dashboard"],+ queryKey: queryKeys.investigations.dashboard,queryFn: investigationService.get,staleTime: 30000, // 30 secondsrefetchOnWindowFocus: false,@@ -130,7 +131,7 @@ export function InvestigationCards() {<div className="space-y-4"><div className="flex items-center justify-between"><div className="flex items-center gap-2">- <FolderOpen className="h-6 w-6 text-muted-foreground" />+ <Search className="h-6 w-6 text-muted-foreground" /><h2 className="text-xl font-semibold">Investigations</h2></div><NewInvestigation noDropDown>@@ -161,7 +162,7 @@ export function InvestigationCards() {<div className="space-y-4"><div className="flex items-center justify-between"><div className="flex items-center gap-2">- <FolderOpen className="h-6 w-6 text-muted-foreground" />+ <Search className="h-6 w-6 text-muted-foreground" /><h2 className="text-xl font-semibold">Investigations</h2><span className="text-sm text-muted-foreground">{investigations.length} investigations@@ -176,7 +177,7 @@ export function InvestigationCards() {</NewInvestigation></div></div>-+<div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">{investigations.slice(0, 8).map((investigation: any) => (<InvestigationCard key={investigation.id} investigation={investigation} />diff --git a/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx b/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsxindex a951851e..97eaa6da 100644--- a/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx+++ b/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx@@ -131,7 +131,7 @@ export function InvestigationSketches({ investigationId, title }: InvestigationS<BarChart3 className="h-6 w-6 text-muted-foreground" /><h2 className="text-xl font-semibold">Sketches</h2></div>- <NewSketch noDropDown>+ <NewSketch><Button size="sm"><Plus className="w-4 h-4 mr-2" />New Sketch@@ -144,7 +144,7 @@ export function InvestigationSketches({ investigationId, title }: InvestigationS<p className="text-muted-foreground mb-4">Create your first sketch to start visualizing your investigation data.</p>- <NewSketch noDropDown>+ <NewSketch><Button><Plus className="w-4 h-4 mr-2" />Create Sketch@@ -166,7 +166,7 @@ export function InvestigationSketches({ investigationId, title }: InvestigationS</span></div><div className="flex items-center gap-2">- <NewSketch noDropDown>+ <NewSketch><Button size="sm"><Plus className="w-4 h-4 mr-2" />New Sketchdiff --git a/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsx b/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsxnew file mode 100644index 00000000..bd27a881--- /dev/null+++ b/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsx@@ -0,0 +1,289 @@+import * as React from "react"+import { Area, AreaChart, CartesianGrid, XAxis } from "recharts"++import { useIsMobile } from "@/hooks/use-mobile"+import {+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card"+import {+ ChartConfig,+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@/components/ui/chart"+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select"+import {+ ToggleGroup,+ ToggleGroupItem,+} from "@/components/ui/toggle-group"++export const description = "An interactive area chart"++const chartData = [+ { date: "2024-04-01", desktop: 222, mobile: 150 },+ { date: "2024-04-02", desktop: 97, mobile: 180 },+ { date: "2024-04-03", desktop: 167, mobile: 120 },+ { date: "2024-04-04", desktop: 242, mobile: 260 },+ { date: "2024-04-05", desktop: 373, mobile: 290 },+ { date: "2024-04-06", desktop: 301, mobile: 340 },+ { date: "2024-04-07", desktop: 245, mobile: 180 },+ { date: "2024-04-08", desktop: 409, mobile: 320 },+ { date: "2024-04-09", desktop: 59, mobile: 110 },+ { date: "2024-04-10", desktop: 261, mobile: 190 },+ { date: "2024-04-11", desktop: 327, mobile: 350 },+ { date: "2024-04-12", desktop: 292, mobile: 210 },+ { date: "2024-04-13", desktop: 342, mobile: 380 },+ { date: "2024-04-14", desktop: 137, mobile: 220 },+ { date: "2024-04-15", desktop: 120, mobile: 170 },+ { date: "2024-04-16", desktop: 138, mobile: 190 },+ { date: "2024-04-17", desktop: 446, mobile: 360 },+ { date: "2024-04-18", desktop: 364, mobile: 410 },+ { date: "2024-04-19", desktop: 243, mobile: 180 },+ { date: "2024-04-20", desktop: 89, mobile: 150 },+ { date: "2024-04-21", desktop: 137, mobile: 200 },+ { date: "2024-04-22", desktop: 224, mobile: 170 },+ { date: "2024-04-23", desktop: 138, mobile: 230 },+ { date: "2024-04-24", desktop: 387, mobile: 290 },+ { date: "2024-04-25", desktop: 215, mobile: 250 },+ { date: "2024-04-26", desktop: 75, mobile: 130 },+ { date: "2024-04-27", desktop: 383, mobile: 420 },+ { date: "2024-04-28", desktop: 122, mobile: 180 },+ { date: "2024-04-29", desktop: 315, mobile: 240 },+ { date: "2024-04-30", desktop: 454, mobile: 380 },+ { date: "2024-05-01", desktop: 165, mobile: 220 },+ { date: "2024-05-02", desktop: 293, mobile: 310 },+ { date: "2024-05-03", desktop: 247, mobile: 190 },+ { date: "2024-05-04", desktop: 385, mobile: 420 },+ { date: "2024-05-05", desktop: 481, mobile: 390 },+ { date: "2024-05-06", desktop: 498, mobile: 520 },+ { date: "2024-05-07", desktop: 388, mobile: 300 },+ { date: "2024-05-08", desktop: 149, mobile: 210 },+ { date: "2024-05-09", desktop: 227, mobile: 180 },+ { date: "2024-05-10", desktop: 293, mobile: 330 },+ { date: "2024-05-11", desktop: 335, mobile: 270 },+ { date: "2024-05-12", desktop: 197, mobile: 240 },+ { date: "2024-05-13", desktop: 197, mobile: 160 },+ { date: "2024-05-14", desktop: 448, mobile: 490 },+ { date: "2024-05-15", desktop: 473, mobile: 380 },+ { date: "2024-05-16", desktop: 338, mobile: 400 },+ { date: "2024-05-17", desktop: 499, mobile: 420 },+ { date: "2024-05-18", desktop: 315, mobile: 350 },+ { date: "2024-05-19", desktop: 235, mobile: 180 },+ { date: "2024-05-20", desktop: 177, mobile: 230 },+ { date: "2024-05-21", desktop: 82, mobile: 140 },+ { date: "2024-05-22", desktop: 81, mobile: 120 },+ { date: "2024-05-23", desktop: 252, mobile: 290 },+ { date: "2024-05-24", desktop: 294, mobile: 220 },+ { date: "2024-05-25", desktop: 201, mobile: 250 },+ { date: "2024-05-26", desktop: 213, mobile: 170 },+ { date: "2024-05-27", desktop: 420, mobile: 460 },+ { date: "2024-05-28", desktop: 233, mobile: 190 },+ { date: "2024-05-29", desktop: 78, mobile: 130 },+ { date: "2024-05-30", desktop: 340, mobile: 280 },+ { date: "2024-05-31", desktop: 178, mobile: 230 },+ { date: "2024-06-01", desktop: 178, mobile: 200 },+ { date: "2024-06-02", desktop: 470, mobile: 410 },+ { date: "2024-06-03", desktop: 103, mobile: 160 },+ { date: "2024-06-04", desktop: 439, mobile: 380 },+ { date: "2024-06-05", desktop: 88, mobile: 140 },+ { date: "2024-06-06", desktop: 294, mobile: 250 },+ { date: "2024-06-07", desktop: 323, mobile: 370 },+ { date: "2024-06-08", desktop: 385, mobile: 320 },+ { date: "2024-06-09", desktop: 438, mobile: 480 },+ { date: "2024-06-10", desktop: 155, mobile: 200 },+ { date: "2024-06-11", desktop: 92, mobile: 150 },+ { date: "2024-06-12", desktop: 492, mobile: 420 },+ { date: "2024-06-13", desktop: 81, mobile: 130 },+ { date: "2024-06-14", desktop: 426, mobile: 380 },+ { date: "2024-06-15", desktop: 307, mobile: 350 },+ { date: "2024-06-16", desktop: 371, mobile: 310 },+ { date: "2024-06-17", desktop: 475, mobile: 520 },+ { date: "2024-06-18", desktop: 107, mobile: 170 },+ { date: "2024-06-19", desktop: 341, mobile: 290 },+ { date: "2024-06-20", desktop: 408, mobile: 450 },+ { date: "2024-06-21", desktop: 169, mobile: 210 },+ { date: "2024-06-22", desktop: 317, mobile: 270 },+ { date: "2024-06-23", desktop: 480, mobile: 530 },+ { date: "2024-06-24", desktop: 132, mobile: 180 },+ { date: "2024-06-25", desktop: 141, mobile: 190 },+ { date: "2024-06-26", desktop: 434, mobile: 380 },+ { date: "2024-06-27", desktop: 448, mobile: 490 },+ { date: "2024-06-28", desktop: 149, mobile: 200 },+ { date: "2024-06-29", desktop: 103, mobile: 160 },+ { date: "2024-06-30", desktop: 446, mobile: 400 },+]++const chartConfig = {+ visitors: {+ label: "Visitors",+ },+ desktop: {+ label: "Desktop",+ color: "var(--primary)",+ },+ mobile: {+ label: "Mobile",+ color: "var(--primary)",+ },+} satisfies ChartConfig++export function ChartAreaInteractive() {+ const isMobile = useIsMobile()+ const [timeRange, setTimeRange] = React.useState("90d")++ React.useEffect(() => {+ if (isMobile) {+ setTimeRange("7d")+ }+ }, [isMobile])++ const filteredData = chartData.filter((item) => {+ const date = new Date(item.date)+ const referenceDate = new Date("2024-06-30")+ let daysToSubtract = 90+ if (timeRange === "30d") {+ daysToSubtract = 30+ } else if (timeRange === "7d") {+ daysToSubtract = 7+ }+ const startDate = new Date(referenceDate)+ startDate.setDate(startDate.getDate() - daysToSubtract)+ return date >= startDate+ })++ return (+ <Card className="@container/card">+ <CardHeader>+ <CardTitle>Total Visitors</CardTitle>+ <CardDescription>+ <span className="hidden @[540px]/card:block">+ Total for the last 3 months+ </span>+ <span className="@[540px]/card:hidden">Last 3 months</span>+ </CardDescription>+ <CardAction>+ <ToggleGroup+ type="single"+ value={timeRange}+ onValueChange={setTimeRange}+ variant="outline"+ className="hidden *:data-[slot=toggle-group-item]:!px-4 @[767px]/card:flex"+ >+ <ToggleGroupItem value="90d">Last 3 months</ToggleGroupItem>+ <ToggleGroupItem value="30d">Last 30 days</ToggleGroupItem>+ <ToggleGroupItem value="7d">Last 7 days</ToggleGroupItem>+ </ToggleGroup>+ <Select value={timeRange} onValueChange={setTimeRange}>+ <SelectTrigger+ className="flex w-40 **:data-[slot=select-value]:block **:data-[slot=select-value]:truncate @[767px]/card:hidden"+ size="sm"+ aria-label="Select a value"+ >+ <SelectValue placeholder="Last 3 months" />+ </SelectTrigger>+ <SelectContent className="rounded-xl">+ <SelectItem value="90d" className="rounded-lg">+ Last 3 months+ </SelectItem>+ <SelectItem value="30d" className="rounded-lg">+ Last 30 days+ </SelectItem>+ <SelectItem value="7d" className="rounded-lg">+ Last 7 days+ </SelectItem>+ </SelectContent>+ </Select>+ </CardAction>+ </CardHeader>+ <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">+ <ChartContainer+ config={chartConfig}+ className="aspect-auto h-[250px] w-full"+ >+ <AreaChart data={filteredData}>+ <defs>+ <linearGradient id="fillDesktop" x1="0" y1="0" x2="0" y2="1">+ <stop+ offset="5%"+ stopColor="var(--color-desktop)"+ stopOpacity={1.0}+ />+ <stop+ offset="95%"+ stopColor="var(--color-desktop)"+ stopOpacity={0.1}+ />+ </linearGradient>+ <linearGradient id="fillMobile" x1="0" y1="0" x2="0" y2="1">+ <stop+ offset="5%"+ stopColor="var(--color-mobile)"+ stopOpacity={0.8}+ />+ <stop+ offset="95%"+ stopColor="var(--color-mobile)"+ stopOpacity={0.1}+ />+ </linearGradient>+ </defs>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="date"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ minTickGap={32}+ tickFormatter={(value) => {+ const date = new Date(value)+ return date.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ })+ }}+ />+ <ChartTooltip+ cursor={false}+ content={+ <ChartTooltipContent+ labelFormatter={(value) => {+ return new Date(value).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ })+ }}+ indicator="dot"+ />+ }+ />+ <Area+ dataKey="mobile"+ type="natural"+ fill="url(#fillMobile)"+ stroke="var(--color-mobile)"+ stackId="a"+ />+ <Area+ dataKey="desktop"+ type="natural"+ fill="url(#fillDesktop)"+ stroke="var(--color-desktop)"+ stackId="a"+ />+ </AreaChart>+ </ChartContainer>+ </CardContent>+ </Card>+ )+}diff --git a/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsx b/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsxnew file mode 100644index 00000000..93996d66--- /dev/null+++ b/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsx@@ -0,0 +1,101 @@+import { TrendingUp, TrendingDown } from "lucide-react"+import { Badge } from "@/components/ui/badge"+import {+ Card,+ CardAction,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/components/ui/card"++export function SectionCards() {+ return (+ <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:shadow-xs @xl/main:grid-cols-2 @2xl/main:grid-cols-4 @5xl/main:grid-cols-4">+ <Card className="@container/card">+ <CardHeader>+ <CardDescription>Total items</CardDescription>+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">+ 127981+ </CardTitle>+ <CardAction>+ <Badge variant="outline">+ <TrendingUp />+ +12.5%+ </Badge>+ </CardAction>+ </CardHeader>+ <CardFooter className="flex-col items-start gap-1.5 text-sm">+ <div className="line-clamp-1 flex gap-2 font-medium">+ Trending up this month <TrendingUp className="size-4" />+ </div>+ <div className="text-muted-foreground">+ Discovered assets for the last 6 months+ </div>+ </CardFooter>+ </Card>+ <Card className="@container/card">+ <CardHeader>+ <CardDescription>New assets</CardDescription>+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">+ 1234+ </CardTitle>+ <CardAction>+ <Badge variant="outline">+ <TrendingDown />+ -20%+ </Badge>+ </CardAction>+ </CardHeader>+ <CardFooter className="flex-col items-start gap-1.5 text-sm">+ <div className="line-clamp-1 flex gap-2 font-medium">+ Down 20% this period <TrendingDown className="size-4" />+ </div>+ <div className="text-muted-foreground">+ Newly discovered assets+ </div>+ </CardFooter>+ </Card>+ <Card className="@container/card">+ <CardHeader>+ <CardDescription>Active Accounts</CardDescription>+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">+ 45,678+ </CardTitle>+ <CardAction>+ <Badge variant="outline">+ <TrendingUp />+ +12.5%+ </Badge>+ </CardAction>+ </CardHeader>+ <CardFooter className="flex-col items-start gap-1.5 text-sm">+ <div className="line-clamp-1 flex gap-2 font-medium">+ Strong user retention <TrendingUp className="size-4" />+ </div>+ <div className="text-muted-foreground">Engagement exceed targets</div>+ </CardFooter>+ </Card>+ <Card className="@container/card">+ <CardHeader>+ <CardDescription>Growth Rate</CardDescription>+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">+ 4.5%+ </CardTitle>+ <CardAction>+ <Badge variant="outline">+ <TrendingUp />+ +4.5%+ </Badge>+ </CardAction>+ </CardHeader>+ <CardFooter className="flex-col items-start gap-1.5 text-sm">+ <div className="line-clamp-1 flex gap-2 font-medium">+ Steady performance increase <TrendingUp className="size-4" />+ </div>+ <div className="text-muted-foreground">Meets growth projections</div>+ </CardFooter>+ </Card>+ </div>+ )+}diff --git a/flowsint-app/src/renderer/src/components/flows/controls.tsx b/flowsint-app/src/renderer/src/components/flows/controls.tsxindex 494feddc..1306a83e 100644--- a/flowsint-app/src/renderer/src/components/flows/controls.tsx+++ b/flowsint-app/src/renderer/src/components/flows/controls.tsx@@ -3,7 +3,7 @@ import { Button } from "@/components/ui/button"import { Panel } from "@xyflow/react"import { Save, Trash2, ZoomIn, ZoomOut, Maximize, LayoutGrid } from "lucide-react"import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"-import { FlowDetailsPanel } from "./flow-name-panel"+import { FlowNamePanel } from "./flow-name-panel"interface FlowControlsProps {loading: boolean@@ -30,7 +30,7 @@ export function FlowControls({}: FlowControlsProps) {return (<TooltipProvider>- <FlowDetailsPanel flow={flow} />+ <FlowNamePanel flow={flow} /><Panel position="bottom-right" className="flex gap-2 mt-28 mr-2 z-40"><Tooltip><TooltipTrigger asChild>diff --git a/flowsint-app/src/renderer/src/components/flows/editor.tsx b/flowsint-app/src/renderer/src/components/flows/editor.tsxindex 973457b2..52ffc4ff 100644--- a/flowsint-app/src/renderer/src/components/flows/editor.tsx+++ b/flowsint-app/src/renderer/src/components/flows/editor.tsx@@ -21,7 +21,6 @@ import { Button } from "@/components/ui/button"import ScannerNode from "./scanner-node"import TypeNode from "./type-node"import { type ScannerNodeData } from "@/types/transform"-import { categoryColors } from "./scanner-data"import { FlowControls } from "./controls"import { getDagreLayoutedElements } from "@/lib/utils"import { toast } from "sonner"@@ -42,6 +41,9 @@ import { useTheme } from "../theme-provider"import ParamsDialog from "./params-dialog"import FlowSheet from "./flow-sheet"import ContextMenu from "./context-menu"+import { useNodesDisplaySettings } from "@/stores/node-display-settings"+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"const nodeTypes: NodeTypes = {scanner: ScannerNode,@@ -73,6 +75,7 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditorconst { flowId } = useParams({ strict: false })const [showModal, setShowModal] = useState(false)const hasInitialized = useRef(false)+ const queryClient = useQueryClient()// #### Simulation State ####const [isSimulating, setIsSimulating] = useState(false)@@ -91,6 +94,67 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditorconst onConnect = useFlowStore(state => state.onConnect)const setSelectedNode = useFlowStore(state => state.setSelectedNode)const setLoading = useFlowStore(state => state.setLoading)+ const colors = useNodesDisplaySettings(s => s.colors)++ // #### TanStack Query Mutations ####+ // Create flow mutation+ const createFlowMutation = useMutation({+ mutationFn: flowService.create,+ onSuccess: (data) => {+ toast.success("Transform saved successfully.")+ router.navigate({ to: `/dashboard/flows/${data.id}` })+ },+ onError: (error) => {+ toast.error("Error creating transform: " + (error instanceof Error ? error.message : "Unknown error"))+ },+ })++ // Update flow mutation+ const updateFlowMutation = useMutation({+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>+ flowService.update(flowId, body),+ onSuccess: () => {+ toast.success("Transform saved successfully.")+ // Invalidate the flow detail query+ if (flowId) {+ queryClient.invalidateQueries({+ queryKey: queryKeys.flows.detail(flowId)+ })+ }+ },+ onError: (error) => {+ toast.error("Error saving transform: " + (error instanceof Error ? error.message : "Unknown error"))+ },+ })++ // Delete flow mutation+ const deleteFlowMutation = useMutation({+ mutationFn: flowService.delete,+ onSuccess: () => {+ router.navigate({ to: "/dashboard/flows" })+ toast.success("Flow deleted successfully.")+ // Invalidate flows list+ queryClient.invalidateQueries({+ queryKey: queryKeys.flows.list+ })+ },+ onError: (error) => {+ toast.error("Error deleting flow: " + (error instanceof Error ? error.message : "Unknown error"))+ },+ })++ // Compute flow mutation+ const computeFlowMutation = useMutation({+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>+ flowService.compute(flowId, body),+ onSuccess: (response) => {+ setFlowBranches(response.flowBranches)+ startSimulation()+ },+ onError: (error) => {+ toast.error("Error computing flow: " + (error instanceof Error ? error.message : "Unknown error"))+ },+ })const [menu, setMenu] = useState<{node: FlowNode;@@ -188,7 +252,7 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditorclass_name: scannerData.class_name,module: scannerData.module || "",key: scannerData.name,- color: categoryColors[scannerData.category] || "#94a3b8",+ color: colors[scannerData.category.toLowerCase()] || "#94a3b8",name: scannerData.name,category: scannerData.category,type: scannerData.type,@@ -271,7 +335,7 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditortoast.error("Make sure your transform contains an input type.")return}- let newTransform+const body = JSON.stringify({name: name,description: description,@@ -281,25 +345,20 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditoredges,},})+if (flowId) {- newTransform = await flowService.update(flowId, body)+ await updateFlowMutation.mutateAsync({ flowId, body })} else {- newTransform = await flowService.create(body)- if (!newTransform) {- toast.error("Error creating transform")- return- }+ await createFlowMutation.mutateAsync(body)}- toast.success("Transform saved successfully.")- newTransform && !flowId && router.navigate({ to: `/dashboard/flows/${newTransform.id}` })} catch (error) {- toast.error("Error saving transform" + JSON.stringify(error))+ console.error("Error saving flow:", error)} finally {setLoading(false)setShowModal(false)}},- [nodes, edges, flowId, router, setLoading],+ [nodes, edges, flowId, createFlowMutation, updateFlowMutation, setLoading],)const handleSaveFlow = useCallback(async () => {@@ -319,12 +378,10 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditor})) {setLoading(true)- await flowService.delete(flowId)- router.navigate({ to: "/dashboard/flows" })- toast.success("Flow deleted successfully.")+ await deleteFlowMutation.mutateAsync(flowId)setLoading(false)}- }, [flowId, confirm, setLoading])+ }, [flowId, confirm, deleteFlowMutation, setLoading])// #### Flow Computation ####const handleComputeFlow = useCallback(async () => {@@ -340,15 +397,13 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditoredges,initialValue: "domain"}- const response = await flowService.compute(flowId, JSON.stringify(body))- setFlowBranches(response.flowBranches)- startSimulation()+ await computeFlowMutation.mutateAsync({ flowId, body: JSON.stringify(body) })} catch (error) {- toast.error("Error computing flow")+ console.error("Error computing flow:", error)} finally {setLoading(false)}- }, [flowId, nodes, edges])+ }, [flowId, nodes, edges, computeFlowMutation, setLoading])// #### Simulation State Management ####// Update the updateNodeState function with proper typesdiff --git a/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx b/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsxindex 78197aac..a670e12f 100644--- a/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx+++ b/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx@@ -1,37 +1,54 @@-import { useState, useEffect, type KeyboardEvent, useRef } from "react"+import { useEffect, useRef, useState, type KeyboardEvent } from "react"import { Panel } from "@xyflow/react"-import { toast } from "sonner"import { Card } from "@/components/ui/card"+import { toast } from "sonner"import { flowService } from "@/api/flow-service"+import { useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"+import type { Flow } from "@/types/flow"-interface FlowDetailsPanelProps {- flow?: {- id: string- name: string- description?: string- }- onUpdate?: (updates: { name?: string; description?: string }) => void+interface FlowNamePanelProps {+ flow?: Flow+ onUpdate?: (updates: Partial<Flow>) => voiddisabled?: boolean}-export function FlowDetailsPanel({ flow, onUpdate, disabled = false }: FlowDetailsPanelProps) {- const [name, setName] = useState<string>(flow?.name || "My Flow")- const [description, setDescription] = useState<string>(flow?.description || "")- const [isEditingName, setIsEditingName] = useState<boolean>(false)- const [isEditingDesc, setIsEditingDesc] = useState<boolean>(false)- const [isSaving, setIsSaving] = useState<boolean>(false)+export const FlowNamePanel = ({ flow, onUpdate, disabled = false }: FlowNamePanelProps) => {+ const [isEditingName, setIsEditingName] = useState(false)+ const [isEditingDesc, setIsEditingDesc] = useState(false)+ const [name, setName] = useState(flow?.name || "My flow")+ const [description, setDescription] = useState(flow?.description || "")+ const [isSaving, setIsSaving] = useState(false)const nameInputRef = useRef<HTMLInputElement>(null)const descInputRef = useRef<HTMLInputElement>(null)+ const queryClient = useQueryClient()++ // Update flow mutation+ const updateFlowMutation = useMutation({+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>+ flowService.update(flowId, body),+ onSuccess: (data, variables) => {+ if (onUpdate) {+ onUpdate(variables.body as Partial<Flow>)+ }+ // Invalidate the flow detail query+ queryClient.invalidateQueries({+ queryKey: queryKeys.flows.detail(variables.flowId)+ })+ toast.success("Flow updated successfully.")+ },+ onError: (error) => {+ toast.error("Failed to update flow: " + (error instanceof Error ? error.message : "Unknown error"))+ },+ })useEffect(() => {- if (flow?.name) {- setName(flow.name)- }- if (flow?.description !== undefined) {- setDescription(flow.description)+ if (flow) {+ setName(flow.name || "My flow")+ setDescription(flow.description || "")}- }, [flow?.name, flow?.description])+ }, [flow])useEffect(() => {if (isEditingName && nameInputRef.current) {@@ -58,16 +75,16 @@ export function FlowDetailsPanel({ flow, onUpdate, disabled = false }: FlowDetaifield === "name" ? setIsEditingName(false) : setIsEditingDesc(false)return}+setIsSaving(true)try {const updates = { [field]: trimmedValue }- await flowService.update(flow.id, JSON.stringify(updates))- if (onUpdate) {- onUpdate(updates)- }- toast.success(`${field === "name" ? "Name" : "Description"} updated.`)+ await updateFlowMutation.mutateAsync({+ flowId: flow.id,+ body: JSON.stringify(updates)+ })} catch (error) {- toast.error(`Failed to update flow ${field}`)+ // Revert local state on errorif (field === "name") {setName(flow.name)} else {diff --git a/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx b/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsxindex 0a9f1511..5b204b4d 100644--- a/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx+++ b/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx@@ -15,7 +15,6 @@ import { Scanner } from "@/types/transform"import { useQuery } from "@tanstack/react-query"import { Input } from "../ui/input"import { Alert, AlertDescription } from "../ui/alert"-import { categoryColors } from "./scanner-data"import { useIcon } from "@/hooks/use-icon"import { flowService } from "@/api/flow-service"@@ -25,6 +24,7 @@ const FlowSheet = ({ onLayout }: { onLayout: () => void }) => {const selectedNode = useFlowStore(state => state.selectedNode)const setNodes = useFlowStore(state => state.setNodes)const setEdges = useFlowStore(state => state.setEdges)+ const colors = useNodesDisplaySettings(s => s.colors)const { data: materials, isLoading, error } = useQuery({queryKey: ["raw_material", selectedNode?.data.outputs.type],@@ -63,7 +63,7 @@ const FlowSheet = ({ onLayout }: { onLayout: () => void }) => {class_name: scanner.class_name,module: scanner.module || "",key: scanner.name,- color: categoryColors[scanner.category] || "#94a3b8",+ color: colors[scanner.category.toLowerCase()] || "#94a3b8",name: scanner.name,category: scanner.category,type: scanner.type,diff --git a/flowsint-app/src/renderer/src/components/flows/new-flow.tsx b/flowsint-app/src/renderer/src/components/flows/new-flow.tsxindex 96d10148..dbb248b7 100644--- a/flowsint-app/src/renderer/src/components/flows/new-flow.tsx+++ b/flowsint-app/src/renderer/src/components/flows/new-flow.tsx@@ -3,35 +3,47 @@ import { toast } from 'sonner'import { useNavigate } from '@tanstack/react-router'import { useFlowStore } from '@/stores/flow-store'import { flowService } from '@/api/flow-service'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { queryKeys } from '@/api/query-keys'const NewFlow = ({ children }: { children: ReactNode }) => {const navigate = useNavigate()+ const queryClient = useQueryClient()const setNodes = useFlowStore(state => state.setNodes)const setEdges = useFlowStore(state => state.setEdges)+ const createFlowMutation = useMutation({+ mutationFn: flowService.create,+ onSuccess: (response) => {+ // Reset nodes and edges+ setNodes([])+ setEdges([])+ navigate({ to: `/dashboard/flows/${response.id}` })+ // Invalidate flows list+ queryClient.invalidateQueries({+ queryKey: queryKeys.flows.list+ })+ },+ onError: (error) => {+ toast.error('Failed to create flow: ' + (error instanceof Error ? error.message : "Unknown error"))+ }+ })+const handleCreateTransform = useCallback(async () => {toast.promise(- (async () => {- // Reset nodes and edges- setNodes([])- setEdges([])- const response = await flowService.create(JSON.stringify({- name: "New flow",- description: "A new example flow.",- category: [],- flow_schema: {}- }))- navigate({ to: `/dashboard/flows/${response.id}` })- return response- })(),+ createFlowMutation.mutateAsync(JSON.stringify({+ name: "New flow",+ description: "A new example flow.",+ category: [],+ flow_schema: {}+ })),{loading: 'Creating transform...',success: 'Transform created successfully.',error: 'Failed to create flow.'})-- }, [setNodes, setEdges, navigate])+ }, [createFlowMutation])if (!isValidElement(children)) {return nulldiff --git a/flowsint-app/src/renderer/src/components/flows/scanner-data.tsx b/flowsint-app/src/renderer/src/components/flows/scanner-data.tsxdeleted file mode 100644index 5ab64be0..00000000--- a/flowsint-app/src/renderer/src/components/flows/scanner-data.tsx+++ /dev/null@@ -1,57 +0,0 @@-// Default color for fallback cases-export const DEFAULT_COLOR = "#94a3b8"--// Colors for each category/type-export const categoryColors: Record<string, string> = {- // Categories- social: "#3b82f6",- email: "#10b981",- website: "#f59e0b",- phone: "#8b5cf6",- ips: "#ef4444",- domains: "#10b981",- type: "#f59e0b",- cidr: "#A2D4BF",- asn: "#F7D154",- organization: "#9C27B0",-}--// Graph viewer specific colors-export const GRAPH_COLORS = {- // Link colors- LINK_DEFAULT: 'rgba(128, 128, 128, 0.6)',- LINK_HIGHLIGHTED: 'rgba(255, 115, 0, 0.68)',- LINK_DIMMED: 'rgba(133, 133, 133, 0.23)',- LINK_LABEL_HIGHLIGHTED: 'rgba(255, 115, 0, 0.9)',- LINK_LABEL_DEFAULT: 'rgba(180, 180, 180, 0.75)',-- // Node highlight colors- NODE_HIGHLIGHT_HOVER: 'rgba(255, 0, 0, 0.3)',- NODE_HIGHLIGHT_DEFAULT: 'rgba(255, 165, 0, 0.3)',-- // Text colors- TEXT_LIGHT: '#161616',- TEXT_DARK: '#FFFFFF',-- // Background colors- BACKGROUND_LIGHT: "#FFFFFF",- BACKGROUND_DARK: '#161616',-- // Transparent colors- TRANSPARENT: "#00000000",-- // Default node color- NODE_DEFAULT: '#0074D9',-} as const--/**- * Get the color for a scanner based on its type or category- * @param type The scanner type- * @param category The scanner category- * @returns The color to use- */-export const getScannerColor = (type?: string, category?: string): string => {- if (type && categoryColors[type]) return categoryColors[type]- if (category && categoryColors[category]) return categoryColors[category]- return DEFAULT_COLOR-}\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx b/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsxindex e487b54d..82845dde 100644--- a/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx@@ -9,12 +9,13 @@ import { Card, CardContent } from "@/components/ui/card"import { AnimatePresence, motion } from "framer-motion"import { DynamicForm } from "@/components/graphs/dynamic-form"import { Badge } from "@/components/ui/badge"-import { GraphNode, useGraphStore } from "@/stores/graph-store"+import { useGraphStore } from "@/stores/graph-store"import { sketchService } from "@/api/sketch-service"import { useParams } from "@tanstack/react-router"import { useIcon } from "@/hooks/use-icon"import { useLayoutStore } from "@/stores/layout-store"import { useActionItems } from "@/hooks/use-action-items"+import { GraphNode } from "@/types"export default function AddItemDialog() {const handleOpenFormModal = useGraphStore(state => state.handleOpenFormModal)diff --git a/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx b/flowsint-app/src/renderer/src/components/graphs/context-menu.tsxindex d390116a..9a0f73b5 100644--- a/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx@@ -1,5 +1,5 @@import React, { useState } from 'react';-import { transformService } from '@/api/transfrom-service';+import { transformService } from '@/api/transform-service';import { flowService } from '@/api/flow-service';import { useQuery } from '@tanstack/react-query';import { Skeleton } from '@/components/ui/skeleton';diff --git a/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx b/flowsint-app/src/renderer/src/components/graphs/create-relation.tsxindex ee4debb6..fb9601dc 100644--- a/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx@@ -3,12 +3,13 @@ import { useGraphStore } from "@/stores/graph-store"import { Button } from "@/components/ui/button"import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"import { Input } from "@/components/ui/input"-import { ArrowRight, ArrowLeftRight } from "lucide-react"-import { Badge } from "@/components/ui/badge"-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"+import { ArrowRight, ArrowLeftRight, GitPullRequestArrow } from "lucide-react"+import { Label } from "@/components/ui/label"import { toast } from "sonner"import { sketchService } from "@/api/sketch-service"import { useParams } from "@tanstack/react-router"+import { useIcon } from "@/hooks/use-icon"+import { RadioGroupItem } from "@/components/ui/radio-group"export function CreateRelationDialog() {@@ -18,24 +19,29 @@ export function CreateRelationDialog() {const openAddRelationDialog = useGraphStore((state) => state.openAddRelationDialog)const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)const [relationType, setRelationType] = useState("IS_RELATED_TO")- const [direction, setDirection] = useState<"one-way" | "two-way">("one-way")+ const [isReversed, setIsReversed] = useState(false)const handleSubmit = async (e: { preventDefault: () => void }) => {e.preventDefault()++ // Determine source/target based on switch state. If multiple nodes are selected,+ // relate all left-side nodes to the single right-side node.+ const sourceIndex = isReversed ? selectedNodes.length - 1 : 0+ const targetIndex = isReversed ? 0 : selectedNodes.length - 1+const newEdge = {- source: selectedNodes[0],- target: selectedNodes[1],- type: "custom",+ source: selectedNodes[sourceIndex],+ target: selectedNodes[targetIndex],label: relationType,sketch_id: sketchId}- const newEdgeObject = { type: newEdge.type, label: relationType, source: newEdge.source.id, target: newEdge.target.id } as any+ const newEdgeObject = { label: relationType, type: "one-way", source: newEdge.source.id, target: newEdge.target.id } as anytoast.promise((async () => {if (addEdge) addEdge(newEdgeObject)setOpenAddRelationDialog(false)- return sketchService.addEdge(sketchId as string, JSON.stringify(newEdge))+ return sketchService.addEdge(sketchId as string, JSON.stringify(newEdgeObject))})(),{loading: 'Creating relation...',@@ -45,96 +51,93 @@ export function CreateRelationDialog() {)}- const getNodeDisplayName = (node: any) => {- return node.data?.label || node.data?.username || node.id- }-return (<Dialog open={openAddRelationDialog} onOpenChange={setOpenAddRelationDialog}>- <DialogContent className="!w-full !max-w-[730px]">+ <DialogContent className="!w-full !max-w-[600px]"><DialogHeader>- <DialogTitle>New relationship</DialogTitle>+ <DialogTitle className="flex items-center gap-2">+ <GitPullRequestArrow className="h-4 w-4" />+ New relationship+ </DialogTitle></DialogHeader>- <form onSubmit={handleSubmit} className="space-y-6">- <Tabs- defaultValue="one-way"- className="w-full"- onValueChange={(value) => setDirection(value as "one-way" | "two-way")}- >- <TabsList className="grid w-full grid-cols-2">- <TabsTrigger value="one-way" className="flex items-center justify-center gap-2">- <ArrowRight className="h-4 w-4" />- <span>One-way</span>- </TabsTrigger>- <TabsTrigger value="two-way" className="flex items-center justify-center gap-2">- <ArrowLeftRight className="h-4 w-4" />- <span>Two-way</span>- </TabsTrigger>- </TabsList>- <TabsContent value="one-way" className="mt-4">- <div className="flex items-center gap-2 p-4 border justify-between rounded-lg bg-background">- <div className="flex-col min-w-0 items-start">- <div className="text-xs font-medium mb-2">From</div>- <div className="flex flex-wrap gap-1">- {selectedNodes.slice(0, selectedNodes.length - 1).map((node) => (- <Badge key={node.id} variant="outline" className="max-w-full truncate">- {getNodeDisplayName(node)}- </Badge>- ))}- </div>- </div>- <div className="flex flex-col w-full items-center justify-center px-2">- <ArrowRight className="h-5 w-5 text-muted-foreground my-1" />- <Input- placeholder="IS_RELATED_TO"- className="w-2/3 mx-auto text-center text-sm"- value={relationType}- onChange={(e) => setRelationType(e.target.value)}- required- />- </div>- <div className="flex-col min-w-0 items-end">- <div className="text-xs font-medium mb-2">To</div>- <div className="flex flex-wrap gap-1">- {selectedNodes.slice(-1).map((node) => (- <Badge key={node.id} variant="outline" className="max-w-full truncate">- {getNodeDisplayName(node)}- </Badge>- ))}- </div>+ <form onSubmit={handleSubmit} className="space-y-4">+ {/* Selected Nodes Display */}+ <div className="space-y-2">+ <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ Selected Nodes ({selectedNodes.length})+ </Label>+ <div className="flex flex-wrap w-full gap-2">+ {selectedNodes.map((node) => (+ <NodeDisplayCard key={node.id} node={node} />+ ))}+ </div>+ </div>++ {/* Relationship Type */}+ <div className="space-y-2">+ <Label htmlFor="relation-type" className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ Relationship Type+ </Label>+ <Input+ id="relation-type"+ placeholder="e.g., IS_RELATED_TO, WORKS_FOR, OWNS"+ value={relationType}+ onChange={(e) => setRelationType(e.target.value)}+ className="w-full h-9 text-sm"+ required+ />+ </div>++ {/* Visual Preview (one-way with switch) */}+ <div className="space-y-2">+ <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Preview</Label>+ {/* Switch control outside of the preview box */}+ <div className="flex justify-end">+ <Button+ type="button"+ variant="secondary"+ size="sm"+ className="shadow-sm"+ onClick={() => setIsReversed((v) => !v)}+ aria-label="Switch direction"+ title="Switch direction"+ >+ <ArrowLeftRight className="h-4 w-4 mr-1" />+ <span>Switch direction</span>+ </Button>+ </div>+ <div className="p-3 border rounded-md bg-muted/20">+ <div className="flex items-center justify-between">+ {/* Left side nodes */}+ <div className="flex items-center gap-2">+ {(isReversed ? selectedNodes.slice(1) : selectedNodes.slice(0, -1)).map((node) => (+ <NodeDisplayCard key={node.id} node={node} variant="preview" />+ ))}</div>- </div>- </TabsContent>- <TabsContent value="two-way" className="mt-4">- <div className="flex items-center gap-2 p-4 border rounded-lg bg-background">- <div className="flex-1 min-w-0">- <div className="text-xs font-medium mb-2">Nodes</div>- <div className="flex flex-wrap gap-1">- {selectedNodes.map((node) => (- <Badge key={node.id} variant="outline" className="max-w-full truncate">- {getNodeDisplayName(node)}- </Badge>- ))}+ <div className="flex items-center truncate justify-center px-2 flex-shrink-0 min-w-0 grow">+ <div className="flex items-center gap-1 text-xs text-muted-foreground">+ <div className="h-px bg-muted-foreground/30 flex-1"></div>+ <span className="px-2 py-1 bg-muted/50 rounded-sm truncate">+ {relationType || "IS_RELATED"}+ </span>+ <ArrowRight className="h-3 w-3 text-muted-foreground/50" /></div></div>- <div className="flex flex-col items-center px-2">- <ArrowLeftRight className="h-5 w-5 text-muted-foreground my-1" />- <Input- placeholder="Type de relation"- className="w-32 text-center text-sm"- value={relationType}- onChange={(e) => setRelationType(e.target.value)}- required- />+ {/* Right side node */}+ <div className="flex items-center gap-2">+ {(isReversed ? selectedNodes.slice(0, 1) : selectedNodes.slice(-1)).map((node) => (+ <NodeDisplayCard key={node.id} node={node} variant="preview" />+ ))}</div></div>- </TabsContent>- </Tabs>+ </div>+ </div>+<DialogFooter>- <Button type="button" variant="outline" onClick={() => setOpenAddRelationDialog(false)}>+ <Button type="button" variant="outline" size="sm" onClick={() => setOpenAddRelationDialog(false)}>Cancel</Button>- <Button type="submit" disabled={!relationType.trim()}>+ <Button type="submit" size="sm" disabled={!relationType.trim()}>Create</Button></DialogFooter>@@ -143,3 +146,59 @@ export function CreateRelationDialog() {</Dialog>)}++interface NodeDisplayCardProps {+ node: any+ variant?: "default" | "preview"+ asRadio?: boolean+ radioValue?: string+ id?: string+}++export function NodeDisplayCard({ node, variant = "default", asRadio = false, radioValue, id }: NodeDisplayCardProps) {+ const NodeIcon = useIcon(node.data?.type, node.data?.src)++ const getNodeDisplayName = (node: any) => {+ return node.data?.label || node.data?.username || node.id+ }++ if (variant === "preview") {+ return (+ <div className="flex items-center gap-2">+ <div className="flex items-center justify-center w-6 h-6 rounded-full bg-muted">+ <NodeIcon size={20} />+ </div>+ <span className="text-xs text-muted-foreground truncate">+ {getNodeDisplayName(node)}+ </span>+ </div>+ )+ }++ if (asRadio) {+ return (+ <label htmlFor={id} className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors cursor-pointer data-[state=checked]:border-primary data-[state=checked]:bg-primary/5">+ <RadioGroupItem id={id} value={radioValue || ""} className="mt-0.5" />+ <div className="flex items-center gap-2">+ <div className="flex items-center justify-center w-5 h-5 rounded-full bg-muted">+ <NodeIcon size={16} />+ </div>+ <span className="text-sm truncate">+ {getNodeDisplayName(node)}+ </span>+ </div>+ </label>+ )+ }++ return (+ <div className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors">+ <div className="flex items-center justify-center w-5 h-5 rounded-full bg-muted">+ <NodeIcon size={16} />+ </div>+ <span className="text-sm truncate">+ {getNodeDisplayName(node)}+ </span>+ </div>+ )+}diff --git a/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx b/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsxindex 693316fe..996241e9 100644--- a/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx@@ -14,6 +14,8 @@ import { useParams } from "@tanstack/react-router"import { toast } from "sonner"import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"import { useIcon } from "@/hooks/use-icon"+import { useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"export const NodeEditorModal: React.FC = () => {const currentNode = useGraphStore(state => state.currentNode)@@ -44,42 +46,71 @@ export const NodeEditorModal: React.FC = () => {}}, [currentNode]);- const handleSave = async () => {- if (!currentNode || !sketchId) return;-- setIsSaving(true);-- try {- // Prepare the data for the API- const updateData = {- nodeId: currentNode.id,- data: formData- };+ const queryClient = useQueryClient()- // Call the API to update the node- const result = await sketchService.updateNode(sketchId, JSON.stringify(updateData));-- if (result.status === "node updated") {+ // Update node mutation+ const updateNodeMutation = useMutation({+ mutationFn: async ({ sketchId, updateData }: { sketchId: string, updateData: any }) => {+ return sketchService.updateNode(sketchId, JSON.stringify(updateData))+ },+ onSuccess: (result, variables) => {+ if (result.status === "node updated" && currentNode) {// Update the local store- updateNode(currentNode.id, formData);+ updateNode(currentNode.id, formData)setCurrentNode({...currentNode,data: {...currentNode.data,...formData}- });+ })++ // Invalidate related queries+ if (sketchId) {+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.detail(sketchId)+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.graph(sketchId, sketchId)+ })+ // Also invalidate investigation queries that might show sketch data+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.list+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.dashboard+ })+ }- toast.success("Node updated successfully");- setOpenNodeEditorModal(false);+ toast.success("Node updated successfully")+ setOpenNodeEditorModal(false)} else {- toast.error("Failed to update node");+ toast.error("Failed to update node")}+ },+ onError: (error) => {+ console.error("Error updating node:", error)+ toast.error("Failed to update node. Please try again.")+ }+ });++ const handleSave = async () => {+ if (!currentNode || !sketchId) return+ setIsSaving(true)++ try {+ // Prepare the data for the API+ const updateData = {+ nodeId: currentNode.id,+ data: formData+ };++ // Call the mutation+ await updateNodeMutation.mutateAsync({ sketchId, updateData })} catch (error) {- console.error("Error updating node:", error);- toast.error("Failed to update node. Please try again.");+ console.error("Error updating node:", error)} finally {- setIsSaving(false);+ setIsSaving(false)}};diff --git a/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx b/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsxindex 91e1c5f6..ad0dd825 100644--- a/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx@@ -104,7 +104,7 @@ const RelationshipItem = memo(({ node }: { node: GraphNode }) => {className='w-full h-full text-left hover:underline cursor-pointer flex items-center'onClick={handleClick}>- <TypeBadge className='w-full truncate block' type={node.data.type}>+ <TypeBadge className='w-full truncate block text-center' type={node.data.type}>{node.data.label}</TypeBadge></button>diff --git a/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx b/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsxindex 59c66c4a..ea18abb2 100644--- a/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx@@ -69,7 +69,7 @@ export const DraggableItem = memo(function DraggableItem({style={{ borderLeftColor: colorStr }}><div>- <IconComponent showBorder size={16} type={type} />+ <IconComponent size={16} type={type} /></div><div className="w-full p-1 text-left flex-1 min-w-0"><h3 className="text-sm font-medium truncate w-full">{label}</h3>diff --git a/flowsint-app/src/renderer/src/components/graphs/force-controls.tsx b/flowsint-app/src/renderer/src/components/graphs/force-controls.tsxdeleted file mode 100644index 9e645637..00000000--- a/flowsint-app/src/renderer/src/components/graphs/force-controls.tsx+++ /dev/null@@ -1,100 +0,0 @@-import { useGraphSettingsStore } from '@/stores/graph-settings-store';-import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';-import { Slider } from '../ui/slider';-import { Label } from '../ui/label';-import { Zap, Move, Target } from 'lucide-react';-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';-import { useCallback } from 'react';--const ForceControls = ({ children }: { children: React.ReactNode }) => {- const settings = useGraphSettingsStore(s => s.settings);- const currentPreset = useGraphSettingsStore(s => s.currentPreset);- const updateSetting = useGraphSettingsStore(s => s.updateSetting);- const applyPreset = useGraphSettingsStore(s => s.applyPreset);- const getPresets = useGraphSettingsStore(s => s.getPresets);- const setSettingsModalOpen = useGraphSettingsStore(s => s.setSettingsModalOpen)-- const handleOpenSettingsModal = useCallback(() => {- setSettingsModalOpen(true)- }, [setSettingsModalOpen])-- const quickControls = [- {- key: 'd3AlphaDecay',- label: 'Convergence',- icon: <Zap className="w-3 h-3" />,- },- {- key: 'd3VelocityDecay',- label: 'Friction',- icon: <Move className="w-3 h-3" />,- },- {- key: 'cooldownTicks',- label: 'Simulation',- icon: <Target className="w-3 h-3" />,- }- ];-- const presets = getPresets();-- return (- <Popover>- <PopoverTrigger asChild>- <div>- {children}- </div>- </PopoverTrigger>- <PopoverContent className="w-72" align="start">- <div className="space-y-4">- <div className="text-sm font-medium text-foreground">Force Presets</div>- <Select value={currentPreset || ""} onValueChange={applyPreset}>- <SelectTrigger className="w-full">- <SelectValue placeholder="Choose a preset..." />- </SelectTrigger>- <SelectContent>- {Object.keys(presets).map((presetName) => (- <SelectItem key={presetName} value={presetName}>- {presetName}- </SelectItem>- ))}- </SelectContent>- </Select>-- <div className="border-t pt-4">- <div className="text-sm font-medium text-foreground mb-3">Quick Controls</div>- {quickControls.map(({ key, label, icon }) => {- const setting = settings[key];- if (!setting) return null;-- return (- <div key={key} className="space-y-2 mb-4">- <div className="flex items-center gap-2">- {icon}- <Label className="text-xs font-medium flex-1">- {label} ({setting.value})- </Label>- </div>- <Slider- value={[setting.value]}- onValueChange={(values) => updateSetting(key, values[0])}- min={setting.min}- max={setting.max}- step={setting.step}- className="w-full"- />- </div>- );- })}- </div>-- <div className="text-right pt-3 border-t">- <button className='text-primary text-sm underline' onClick={handleOpenSettingsModal}> More settings</button>- </div>- </div>- </PopoverContent>- </Popover>- );-};--export default ForceControls;\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/graphs/global-settings.tsx b/flowsint-app/src/renderer/src/components/graphs/global-settings.tsxdeleted file mode 100644index 52555a87..00000000--- a/flowsint-app/src/renderer/src/components/graphs/global-settings.tsx+++ /dev/null@@ -1,113 +0,0 @@-import { Button } from "@/components/ui/button"-import {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog"--import { useGraphGeneralSettingsStore } from "@/stores/graph-general-store"-import { isMacOS } from "@/components/analyses/editor/utils"--export default function GlobalSettings() {- const settingsModalOpen = useGraphGeneralSettingsStore(s => s.settingsModalOpen)- const setSettingsModalOpen = useGraphGeneralSettingsStore(s => s.setSettingsModalOpen)-- return (- <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle>General settings</DialogTitle>- <DialogDescription>- Make changes to your general settings here. Click save when you're- done.- </DialogDescription>- </DialogHeader>- <div className="grid gap-4">- Comming soon.- </div>- <DialogFooter>- <DialogClose asChild>- <Button variant="outline">Cancel</Button>- </DialogClose>- <Button type="submit">Save changes</Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}--export function KeyboardShortcuts() {- const keyboardShortcutsOpen = useGraphGeneralSettingsStore(s => s.keyboardShortcutsOpen)- const setKeyboardShortcutsOpen = useGraphGeneralSettingsStore(s => s.setKeyboardShortcutsOpen)-- const isMac = isMacOS()- const modKey = isMac ? "⌘" : "Ctrl"-- const shortcuts = [- {- category: "Navigation & Panels",- items: [- { key: `${modKey}+L`, description: "Toggle Analysis Panel" },- { key: `${modKey}+B`, description: "Toggle Panel" },- { key: `${modKey}+D`, description: "Toggle Console" },- { key: `${modKey}+J`, description: "Open Command Palette" },- ]- },- {- category: "Chat & Assistant",- items: [- { key: `${modKey}+E`, description: "Toggle Chat Assistant" },- { key: "Escape", description: "Close Chat Assistant" },- ]- },- {- category: "File Operations",- items: [- { key: `${modKey}+S`, description: "Save (Analysis/Flow)" },- ]- }- ]-- return (- <Dialog open={keyboardShortcutsOpen} onOpenChange={setKeyboardShortcutsOpen}>- <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">- <DialogHeader>- <DialogTitle>Keyboard Shortcuts</DialogTitle>- <DialogDescription>- Here is the list of all available keyboard shortcuts.- </DialogDescription>- </DialogHeader>- <div className="space-y-6">- {shortcuts.map((category) => (- <div key={category.category} className="space-y-3">- <h3 className="text-sm font-semibold text-foreground/80 uppercase tracking-wide">- {category.category}- </h3>- <div className="space-y-2">- {category.items.map((item) => (- <div key={item.key} className="flex items-center justify-between py-2 px-3 rounded-md bg-muted/50">- <span className="text-sm text-muted-foreground">- {item.description}- </span>- <kbd className="inline-flex items-center gap-1 rounded border bg-background px-2 py-1 text-xs font-mono font-medium text-foreground shadow-sm">- {item.key}- </kbd>- </div>- ))}- </div>- </div>- ))}- </div>- <DialogFooter>- <DialogClose asChild>- <Button variant="outline">Close</Button>- </DialogClose>- </DialogFooter>- </DialogContent>- </Dialog>- )-}\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-main.tsxindex 18f3e6dc..c4e68f4c 100644--- a/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx@@ -2,13 +2,14 @@ import { useGraphStore } from '@/stores/graph-store'import React, { useRef, useCallback } from 'react'import GraphViewer from './graph-viewer'import ContextMenu from './context-menu'+import { useGraphSettingsStore } from '@/stores/graph-settings-store'const GraphMain = () => {const filteredNodes = useGraphStore(s => s.filteredNodes)const filteredEdges = useGraphStore(s => s.filteredEdges)- // const currentNode = useGraphStore(s => s.currentNode)const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection)const clearSelectedNodes = useGraphStore(s => s.clearSelectedNodes)+ const settings = useGraphSettingsStore(s => s.settings)const graphRef = useRef<any>()const containerRef = useRef<HTMLDivElement>(null)@@ -61,6 +62,7 @@ const GraphMain = () => {showIcons={true}onGraphRef={handleGraphRef}allowLasso+ minimap={settings.general.showMinimap.value}/>{menu && <ContextMenu onClick={handleBackgroundClick} {...menu} />}</div>diff --git a/flowsint-app/src/renderer/src/components/graphs/graph-settings.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-settings.tsxdeleted file mode 100644index c8527936..00000000--- a/flowsint-app/src/renderer/src/components/graphs/graph-settings.tsx+++ /dev/null@@ -1,117 +0,0 @@-import { useGraphSettingsStore } from '@/stores/graph-settings-store'-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog"-import { Slider } from "@/components/ui/slider"-import { Label } from '../ui/label'-import { memo, useCallback } from 'react'-import { Button } from '../ui/button'-import { type ForceGraphSetting } from '@/types'-import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '../ui/accordion'--const GraphSettings = () => {- const settings = useGraphSettingsStore(s => s.settings)- const settingsModalOpen = useGraphSettingsStore(s => s.settingsModalOpen)- const setSettingsModalOpen = useGraphSettingsStore(s => s.setSettingsModalOpen)- const updateSetting = useGraphSettingsStore(s => s.updateSetting)- const resetSettings = useGraphSettingsStore(s => s.resetSettings)-- // Categorize settings- const categories = {- 'Simulation Control': [- 'd3AlphaDecay',- 'd3AlphaMin',- 'd3VelocityDecay',- 'cooldownTicks',- 'cooldownTime',- 'warmupTicks'- ],- 'Visual Appearance': [- 'nodeSize',- 'linkWidth',- 'linkDirectionalArrowLength',- 'linkDirectionalArrowRelPos',- 'linkDirectionalParticleSpeed'- ],- 'Layout': [- 'dagLevelDistance'- ]- }-- return (- <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>- <DialogContent className='max-h-[90vh] !w-[90vw] !max-w-[700px] overflow-y-auto'>- <DialogHeader>- <DialogTitle>Graph settings</DialogTitle>- <DialogDescription>- Update the settings of your graph. Changes apply in real-time.- </DialogDescription>- </DialogHeader>-- <Accordion type="multiple" defaultValue={['Force Physics', 'Simulation Control']} className="w-full">- {Object.entries(categories).map(([categoryName, settingKeys]) => (- <AccordionItem key={categoryName} value={categoryName}>- <AccordionTrigger className="text-sm font-medium">- {categoryName}- </AccordionTrigger>- <AccordionContent className="space-y-4">- {settingKeys.map((key) => {- const setting = settings[key];- if (!setting) return null;- return (- <SettingItem- key={key}- label={key}- updateSetting={updateSetting}- setting={setting}- />- );- })}- </AccordionContent>- </AccordionItem>- ))}- </Accordion>-- <div className='text-right border-t pt-4'>- <Button onClick={resetSettings}>- Reset to defaults- </Button>- </div>- </DialogContent>- </Dialog>- )-}--export default GraphSettings--type SettingItemProps = {- setting: ForceGraphSetting- label: string- updateSetting: (key: string, value: number) => void-}-const SettingItem = memo(({ setting, label, updateSetting }: SettingItemProps) => {-- const handleUpdateSetting = useCallback((newValues: number[]) => {- updateSetting(label, newValues[0])- }, [setting, updateSetting])-- return (- <div className='grid grid-cols-1 gap-1'>- <Label htmlFor={label}>{label} ({setting.value})</Label>- <p className='opacity-60 text-sm'>{setting.description}</p>- <Slider- className='mt-2'- id={label}- onValueChange={handleUpdateSetting}- value={[setting.value]}- min={setting.min}- max={setting.max}- step={setting.step}- />- </div>- )-})\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsxindex 3c5a9324..015fdbeb 100644--- a/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx@@ -7,10 +7,10 @@ import React, { useCallback, useMemo, useEffect, useState, useRef } from 'react'import ForceGraph2D from 'react-force-graph-2d';import { Button } from '../ui/button';import { useTheme } from '@/components/theme-provider'-import { GRAPH_COLORS } from '../flows/scanner-data';import { Share2, Type } from 'lucide-react';import Lasso from './lasso';import { GraphNode, GraphEdge } from '@/types';+import MiniMap from './minimap';function truncateText(text: string, limit: number = 16) {if (text.length <= limit)@@ -35,8 +35,40 @@ interface GraphViewerProps {onGraphRef?: (ref: any) => void;instanceId?: string; // Add instanceId prop for instance-specific actionsallowLasso?: boolean+ minimap?: boolean}+// Graph viewer specific colors+export const GRAPH_COLORS = {+ // Link colors+ LINK_DEFAULT: 'rgba(128, 128, 128, 0.6)',+ LINK_HIGHLIGHTED: 'rgba(255, 115, 0, 0.68)',+ LINK_DIMMED: 'rgba(133, 133, 133, 0.23)',+ LINK_LABEL_HIGHLIGHTED: 'rgba(255, 115, 0, 0.9)',+ LINK_LABEL_DEFAULT: 'rgba(180, 180, 180, 0.75)',++ // Node highlight colors+ NODE_HIGHLIGHT_HOVER: 'rgba(255, 0, 0, 0.3)',+ NODE_HIGHLIGHT_DEFAULT: 'rgba(255, 165, 0, 0.3)',++ LASSO_FILL: 'rgba(255, 115, 0, 0.07)',+ LASSO_STROKE: 'rgba(255, 115, 0, 0.56)',++ // Text colors+ TEXT_LIGHT: '#161616',+ TEXT_DARK: '#FFFFFF',++ // Background colors+ BACKGROUND_LIGHT: "#FFFFFF",+ BACKGROUND_DARK: '#161616',++ // Transparent colors+ TRANSPARENT: "#00000000",++ // Default node color+ NODE_DEFAULT: '#0074D9',+} as const+const CONSTANTS = {NODE_COUNT_THRESHOLD: 500,NODE_DEFAULT_SIZE: 10,@@ -116,9 +148,14 @@ const GraphViewer: React.FC<GraphViewerProps> = ({style,onGraphRef,instanceId,- allowLasso = false+ allowLasso = false,+ minimap = false}) => {- const [currentZoom, setCurrentZoom] = useState(1);+ const [currentZoom, setCurrentZoom] = useState({+ k: 1,+ x: 1,+ y: 1+ });const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });const isLassoActive = useGraphControls(s => s.isLassoActive)// Hover highlighting state@@ -136,8 +173,10 @@ const GraphViewer: React.FC<GraphViewerProps> = ({// Store selectorsconst nodeColors = useNodesDisplaySettings(s => s.colors);const getSize = useNodesDisplaySettings(s => s.getSize);- const settings = useGraphSettingsStore(s => s.settings);const view = useGraphControls(s => s.view);++ // Get settings by categories to avoid re-renders+ const forceSettings = useGraphSettingsStore(s => s.forceSettings);const setActions = useGraphControls(s => s.setActions);const currentNode = useGraphStore(s => s.currentNode)const selectedNodes = useGraphStore(s => s.selectedNodes)@@ -276,7 +315,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({// Memoized rendering checkconst shouldUseSimpleRendering = useMemo(() =>- nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || currentZoom < 1.5+ nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || currentZoom.k < 1.5, [nodes.length, currentZoom]);// Memoized graph data transformation with proper memoization dependencies@@ -382,7 +421,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({if (!showLabels) return new Set<string>();// Find the appropriate layer for current zoom- const currentLayer = CONSTANTS.LABEL_LAYERS.find(layer => currentZoom >= layer.minZoom);+ const currentLayer = CONSTANTS.LABEL_LAYERS.find(layer => currentZoom.k >= layer.minZoom);if (!currentLayer) return new Set<string>();// Sort nodes by weight (number of connections) in descending order@@ -556,7 +595,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({// Optimized node rendering with proper icon cachingconst renderNode = useCallback((node: any, ctx: CanvasRenderingContext2D, globalScale: number) => {- const size = Math.min((node.nodeSize + node.neighbors.length / 5), 20) * (settings.nodeSize.value / 100 + .4);+ const size = Math.min((node.nodeSize + node.neighbors.length / 5), 20) * (forceSettings.nodeSize.value / 100 + .4);node.val = size / 5const isHighlighted = highlightNodes.has(node.id) || isSelected(node.id);const hasAnyHighlight = highlightNodes.size > 0 || highlightLinks.size > 0;@@ -622,7 +661,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({ctx.fillText(label, node.x, bgY + bgHeight / 2);}}- }, [shouldUseSimpleRendering, showLabels, showIcons, isCurrent, isSelected, settings.nodeSize.value, theme, highlightNodes, highlightLinks, hoverNode, getVisibleLabels]);+ }, [shouldUseSimpleRendering, forceSettings, showLabels, showIcons, isCurrent, isSelected, theme, highlightNodes, highlightLinks, hoverNode, getVisibleLabels]);const renderLink = useCallback((link: any, ctx: CanvasRenderingContext2D) => {const { source: start, target: end } = link;@@ -633,18 +672,19 @@ const GraphViewer: React.FC<GraphViewerProps> = ({let strokeStyle: string;let lineWidth: number;let fillStyle: string;+if (isHighlighted) {strokeStyle = GRAPH_COLORS.LINK_HIGHLIGHTED;fillStyle = GRAPH_COLORS.LINK_HIGHLIGHTED;- lineWidth = CONSTANTS.LINK_WIDTH * (settings.linkWidth.value / 3);+ lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 3);} else if (hasAnyHighlight) {strokeStyle = GRAPH_COLORS.LINK_DIMMED;fillStyle = GRAPH_COLORS.LINK_DIMMED;- lineWidth = CONSTANTS.LINK_WIDTH * (settings.linkWidth.value / 5);+ lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 5);} else {strokeStyle = GRAPH_COLORS.LINK_DEFAULT;fillStyle = GRAPH_COLORS.LINK_DEFAULT;- lineWidth = CONSTANTS.LINK_WIDTH * (settings.linkWidth.value / 5);+ lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 5);}// Draw connection linectx.beginPath();@@ -654,9 +694,9 @@ const GraphViewer: React.FC<GraphViewerProps> = ({ctx.lineWidth = lineWidth;ctx.stroke();// Draw directional arrow- const arrowLength = settings.linkDirectionalArrowLength?.value;+ const arrowLength = forceSettings.linkDirectionalArrowLength.value;if (arrowLength && arrowLength > 0) {- const arrowRelPos = settings.linkDirectionalArrowRelPos?.value || 1;+ const arrowRelPos = forceSettings.linkDirectionalArrowRelPos.value || 1;// Calculate arrow position along the linklet arrowX = start.x + (end.x - start.x) * arrowRelPos;let arrowY = start.y + (end.y - start.y) * arrowRelPos;@@ -667,7 +707,7 @@ const GraphViewer: React.FC<GraphViewerProps> = ({const distance = Math.sqrt(dx * dx + dy * dy);if (distance > 0) {// Calculate target node size (same as in renderNode function)- const targetNodeSize = (end.nodeSize || CONSTANTS.NODE_DEFAULT_SIZE) * (settings.nodeSize.value / 100 + 0.4);+ const targetNodeSize = (end.nodeSize || CONSTANTS.NODE_DEFAULT_SIZE) * (forceSettings.nodeSize.value / 100 + 0.4);// Calculate offset to place arrow at node edgeconst offset = targetNodeSize / distance;arrowX = end.x - dx * offset;@@ -727,21 +767,28 @@ const GraphViewer: React.FC<GraphViewerProps> = ({ctx.fillText(link.label, 0, 0);ctx.restore();}- }, [shouldUseSimpleRendering, settings.linkWidth.value, settings.linkDirectionalArrowLength?.value, settings.linkDirectionalArrowRelPos?.value, settings.nodeSize.value, theme, highlightLinks, highlightNodes]);+ }, [shouldUseSimpleRendering, forceSettings, theme, highlightLinks, highlightNodes]);// Restart simulation when settings change (debounced)useEffect(() => {let settingsTimeout: number | undefined;- if (graphRef.current && isGraphReadyRef.current) {- if (settingsTimeout) clearTimeout(settingsTimeout);- settingsTimeout = setTimeout(() => {- graphRef.current?.d3ReheatSimulation();- }, 100) as any; // Debounce settings changes- }++ const restartSimulation = () => {+ if (graphRef.current && isGraphReadyRef.current) {+ if (settingsTimeout) clearTimeout(settingsTimeout);+ settingsTimeout = setTimeout(() => {+ graphRef.current?.d3ReheatSimulation();+ }, 100) as any; // Debounce settings changes+ }+ };++ // Restart simulation when force settings change+ restartSimulation();+return () => {if (settingsTimeout) clearTimeout(settingsTimeout);};- }, [settings]);+ }, [forceSettings]);// Clear highlights when graph data changesuseEffect(() => {@@ -851,15 +898,16 @@ const GraphViewer: React.FC<GraphViewerProps> = ({node.fx = node.x;node.fy = node.y;})}- cooldownTicks={view === "hierarchy" ? 0 : settings.cooldownTicks?.value}- cooldownTime={settings.cooldownTime?.value}- d3AlphaDecay={settings.d3AlphaDecay?.value}- d3AlphaMin={settings.d3AlphaMin?.value}- d3VelocityDecay={settings.d3VelocityDecay?.value}- warmupTicks={settings.warmupTicks?.value}- dagLevelDistance={settings.dagLevelDistance?.value}+ cooldownTicks={view === "hierarchy" ? 0 : forceSettings.cooldownTicks.value}+ cooldownTime={forceSettings.cooldownTime.value}+ d3AlphaDecay={forceSettings.d3AlphaDecay.value}+ d3AlphaMin={forceSettings.d3AlphaMin.value}+ d3VelocityDecay={forceSettings.d3VelocityDecay.value}+ warmupTicks={forceSettings.warmupTicks.value}+ dagLevelDistance={forceSettings.dagLevelDistance.value}backgroundColor={backgroundColor}- onZoom={(zoom) => setCurrentZoom(zoom.k)}+ onZoom={(zoom) => setCurrentZoom(zoom)}+ onZoomEnd={(zoom) => setCurrentZoom(zoom)}linkCanvasObject={renderLink}enableNodeDrag={!shouldUseSimpleRendering}autoPauseRedraw={true}@@ -868,6 +916,11 @@ const GraphViewer: React.FC<GraphViewerProps> = ({/>{allowLasso && isLassoActive && <Lasso nodes={graphData.nodes} graph2ScreenCoords={graph2ScreenCoords} partial={true} width={containerSize.width}height={containerSize.height} />}+ {minimap && graphData.nodes &&+ <MiniMap zoomTransform={currentZoom}+ canvasWidth={containerSize.width}+ canvasHeight={containerSize.height}+ nodes={graphData.nodes as GraphNode[]} />}</div >);};diff --git a/flowsint-app/src/renderer/src/components/graphs/index.tsx b/flowsint-app/src/renderer/src/components/graphs/index.tsxindex 34008523..b28490de 100644--- a/flowsint-app/src/renderer/src/components/graphs/index.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/index.tsx@@ -15,16 +15,15 @@ import { useActionItems } from '@/hooks/use-action-items'import { toast } from 'sonner'import MapPanel from '../map/map-panel'import NewActions from './add-item-dialog'-import GraphSettings from './graph-settings'import GraphMain from './graph-main'-import GlobalSettings, { KeyboardShortcuts } from './global-settings'+import Settings, { KeyboardShortcuts } from './settings'import { type GraphNode, type GraphEdge } from '@/types'+import { MergeDialog } from './merge-nodes'+import { useGraphSettingsStore } from '@/stores/graph-settings-store'const RelationshipsTable = lazy(() => import('@/components/table/relationships-view'))const Graph = lazy(() => import('./graph'))// const Wall = lazy(() => import('./wall/wall'))-const NODE_COUNT_THRESHOLD = 1500;-// Separate component for the drag overlayconst DragOverlay = memo(({ isDragging }: { isDragging: boolean }) => (<div@@ -50,10 +49,13 @@ const GraphPanel = ({ graphData, isLoading }: GraphPanelProps) => {const handleOpenFormModal = useGraphStore(s => s.handleOpenFormModal)const nodes = useGraphStore(s => s.nodes)const view = useGraphControls((s) => s.view)+ const settings = useGraphSettingsStore(s => s.settings)const updateGraphData = useGraphStore(s => s.updateGraphData)const setFilters = useGraphStore(s => s.setFilters)const filters = useGraphStore(s => s.filters)const { actionItems, isLoading: isLoadingActionItems } = useActionItems()+ const NODE_COUNT_THRESHOLD = settings.general.graphViewerThreshold.value+const { sketch } = useLoaderData({from: '/_auth/dashboard/investigations/$investigationId/$type/$id',})@@ -162,9 +164,9 @@ const GraphPanel = ({ graphData, isLoading }: GraphPanelProps) => {</div><NewActions /><CreateRelationDialog />+ <MergeDialog /><NodeEditorModal />- <GraphSettings />- <GlobalSettings />+ <Settings /><KeyboardShortcuts /></div>)diff --git a/flowsint-app/src/renderer/src/components/graphs/lasso.tsx b/flowsint-app/src/renderer/src/components/graphs/lasso.tsxindex 80527c28..ce4e4f41 100644--- a/flowsint-app/src/renderer/src/components/graphs/lasso.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/lasso.tsx@@ -1,6 +1,7 @@import { memo, useRef, type PointerEvent } from 'react';import { useGraphStore } from '@/stores/graph-store';import { GraphNode } from '@/types';+import { GRAPH_COLORS } from './graph-viewer';type NodePoints = ([number, number] | [number, number, number])[];type NodePointObject = Record<string, NodePoints>;@@ -46,7 +47,6 @@ export function Lasso({ partial, width, height, graph2ScreenCoords, nodes }: { pcanvas.setPointerCapture(e.pointerId);pointRef.current = [getRelativeCoordinates(e, canvas)];- // Enregistre les coins de chaque node pour la détectionnodePointsRef.current = {};for (const node of nodes) {const { x, y } = graph2ScreenCoords(node);@@ -64,8 +64,8 @@ export function Lasso({ partial, width, height, graph2ScreenCoords, nodes }: { pctxRef.current = ctx;ctx.lineWidth = 1;- ctx.fillStyle = 'rgba(0, 89, 220, 0.08)';- ctx.strokeStyle = 'rgba(0, 89, 220, 0.8)';+ ctx.fillStyle = `${GRAPH_COLORS.LASSO_FILL}`;+ ctx.strokeStyle = GRAPH_COLORS.LASSO_STROKE;}function handlePointerMove(e: PointerEvent) {diff --git a/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx b/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsxindex 42a45b63..abc7905b 100644--- a/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx@@ -18,7 +18,7 @@ import { useLaunchTransform } from "@/hooks/use-launch-transform"import { useLaunchFlow } from "@/hooks/use-launch-flow"import { formatDistanceToNow } from "date-fns"import { useQuery } from "@tanstack/react-query"-import { transformService } from "@/api/transfrom-service"+import { transformService } from "@/api/transform-service"import { flowService } from '@/api/flow-service';import { Link, useParams } from "@tanstack/react-router"import { capitalizeFirstLetter } from "@/lib/utils"diff --git a/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsx b/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsxnew file mode 100644index 00000000..da7cb3ea--- /dev/null+++ b/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsx@@ -0,0 +1,176 @@+import { useEffect, useState } from "react"+import { useGraphStore } from "@/stores/graph-store"+import { Button } from "@/components/ui/button"+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"+import { Info, Merge, MinusCircleIcon, PlusCircleIcon, X } from "lucide-react"+import { Label } from "@/components/ui/label"+import { toast } from "sonner"+import { GraphNode } from "@/types"+import { NodeDisplayCard } from "./create-relation"+import { RadioGroup } from "@/components/ui/radio-group"+import { Alert, AlertDescription, AlertTitle } from "../ui/alert"+import { cn, deepObjectDiff } from "@/lib/utils"+import { sketchService } from "@/api/sketch-service"+import { useParams } from "@tanstack/react-router"++export function MergeDialog() {+ const { id: sketchId } = useParams({ strict: false })+ const selectedNodes = useGraphStore((state) => state.selectedNodes || [])+ const openMergeDialog = useGraphStore((state) => state.openMergeDialog)+ const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)+ const [priorityIndex, setPriorityIndex] = useState(0)+ const [preview, setPreview] = useState<GraphNode | null>(null)+ const [old, setOld] = useState<GraphNode | null>(null)++ useEffect(() => {+ if (selectedNodes.length === 0) return+ const priorityEntity = selectedNodes[priorityIndex]+ if (!priorityEntity) return+ const otherEntitiesToMerge = selectedNodes.filter((node) => node?.id != priorityEntity?.id)+ const old = {+ ...otherEntitiesToMerge.reduce((acc, entity) => ({+ ...acc,+ ...entity,+ }), {} as GraphNode)+ }+ const merge = {+ ...old,+ ...priorityEntity,+ }+ setOld(old)+ setPreview(merge)+ }, [selectedNodes, priorityIndex, setPreview])++ const handleSubmit = async (e: { preventDefault: () => void }) => {+ e.preventDefault()+ if (!preview)+ return toast.error("No preview available.")+ if (!selectedNodes.every((n) => n.data.type === selectedNodes[0].data.type))+ return toast.error("Cannot merge entities of different types.")+ const entitiesToMerge = selectedNodes.map((node) => node.id)+ const body = JSON.stringify({ oldNodes: entitiesToMerge, newNode: preview })+ return toast.promise(+ (async () => {+ await sketchService.mergeNodes(sketchId as string, body)+ setOpenMergeDialog(false)+ })(),+ {+ loading: 'Merging entities...',+ success: 'Entities successfully merged.',+ error: (error) => {+ console.log(error)+ return 'Unexpected error during merging.'+ }+ }+ )+ }++ return (+ <Dialog open={openMergeDialog} onOpenChange={setOpenMergeDialog}>+ <DialogContent className="!w-full !max-w-[700px] max-h-[90vh] overflow-y-auto overflow-x-hidden">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <Merge className="h-4 w-4" />+ Merging {selectedNodes.length} entities+ </DialogTitle>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-4 w-full overflow-hidden">+ {/* Selected Nodes Display */}+ <div className="space-y-2 w-full">+ <Alert className="">+ <Info />+ <AlertTitle>Heads up!</AlertTitle>+ <AlertDescription>+ When merging, you can choose which entity is prioritary, simply click it in the list below.+ Also keep in mind:+ <div>+ <ul className="ml-2 !list-disc">+ <li>All <span className="font-semibold">attributes</span> will be merged, and the matching ones values will be based on the prioritary entity</li>+ <li>Only one node will be kept, and all <span className="font-semibold">relationships</span> will be merged</li>+ </ul>+ </div>+ </AlertDescription>+ </Alert>+ <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ Selected Nodes ({selectedNodes.length})+ </Label>+ <RadioGroup+ className="flex overflow-x-auto w-full gap-2"+ value={String(priorityIndex)}+ onValueChange={(value) => setPriorityIndex(parseInt(value, 10))}+ >+ {selectedNodes.map((node, index) => (+ <NodeDisplayCard+ key={node.id}+ id={`priority-${node.id}`}+ node={node}+ asRadio+ radioValue={String(index)}+ />+ )+ )}+ </RadioGroup>+ </div>+ {preview && old && <div className="space-y-2 text-sm">+ <p>Merged attributes</p>+ <div className="rounded-md border overflow-hidden">+ <KeyValueDisplayDiff oldRecord={old.data} newRecord={preview.data} />+ </div>+ </div>}+ <DialogFooter>+ <Button type="button" variant="outline" size="sm" onClick={() => setOpenMergeDialog(false)}>+ Cancel+ </Button>+ <Button type="submit" size="sm">+ Merge ({selectedNodes.length})+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog >+ )+}++interface KeyValueDisplayDiffProps {+ oldRecord: Record<string, any>+ newRecord: Record<string, any>+}+function KeyValueDisplayDiff({ oldRecord, newRecord }: KeyValueDisplayDiffProps) {+ const diffObject = deepObjectDiff(oldRecord, newRecord)+ return (+ <div className={"w-full border-collapse divide-y divide-border"}>+ {diffObject && Object.entries(diffObject)+ .filter(([key]) => !["sketch_id", "caption", "size", "color", "description"].includes(key))+ .map(([key, value], index) => {+ const isNewKey = value.new+ const hasChanged = !value.identical+ const isOldKey = value.removed+ return (+ <div+ key={index}+ className={cn("flex w-full bg-card items-center divide-x divide-border p-0",+ hasChanged && "bg-orange-300/10",+ isNewKey && "bg-green-400/10",+ isOldKey && "bg-red-400/10",+ )}+ >+ <div className={cn("w-1/2 px-4 p-2 text-sm text-muted-foreground flex items-center gap-1 font-normal truncate")}>+ {isNewKey && <PlusCircleIcon className="h-4 w-4 text-green-400" />}+ {isOldKey && <MinusCircleIcon className="h-4 w-4 text-red-400" />}+ <span className={cn(+ hasChanged && "text-orange-300",+ isNewKey && "text-green-400",+ isOldKey && "text-red-400",+ )}>{key}</span>+ </div>+ <div className="w-1/2 px-4 p-2 text-sm font-medium flex items-center justify-between min-w-0">+ {!hasChanged ? <div className="truncate font-normal">{JSON.stringify(value.value ?? "")}</div> :+ <div className="truncate flex flex-wrap gap-2 font-semibold">+ <span className="line-through text-red-300">{JSON.stringify(value.oldValue)}</span><span className={cn(isOldKey ? "text-red-500" : "text-green-500")}>{JSON.stringify(value.newValue ?? "")}</span></div>}+ </div>+ </div>+ )+ })}+ </div >+ )+}diff --git a/flowsint-app/src/renderer/src/components/graphs/minimap.tsx b/flowsint-app/src/renderer/src/components/graphs/minimap.tsxnew file mode 100644index 00000000..a1f35c9e--- /dev/null+++ b/flowsint-app/src/renderer/src/components/graphs/minimap.tsx@@ -0,0 +1,147 @@+import { GraphNode } from '@/types';+import { useMemo } from 'react';+import { GRAPH_COLORS } from './graph-viewer';++interface zoomTransform {+ x: number,+ y: number,+ k: number,+}+interface MinimapProps {+ nodes: GraphNode[]+ zoomTransform: zoomTransform+ width?: number,+ height?: number+ canvasWidth: number+ canvasHeight: number+}+const Minimap = ({+ nodes,+ zoomTransform,+ width = 160,+ height = 120,+ canvasWidth = 800,+ canvasHeight = 600,+}: MinimapProps) => {+ // Calculate the visible viewport in world coordinates+ const invScale = 1 / zoomTransform.k;++ // The viewport center in world coordinates+ // zoomTransform.x and zoomTransform.y are screen offsets, so we need to convert them+ const viewportCenterX = zoomTransform.x * invScale;+ const viewportCenterY = zoomTransform.y * invScale;++ // Viewport dimensions in world coordinates+ const viewportWidth = canvasWidth * invScale;+ const viewportHeight = canvasHeight * invScale;++ // Viewport bounds in world coordinates+ const viewportX1 = viewportCenterX - viewportWidth / 2;+ const viewportY1 = viewportCenterY - viewportHeight / 2;+ const viewportX2 = viewportCenterX + viewportWidth / 2;+ const viewportY2 = viewportCenterY + viewportHeight / 2;++ // Calculate global bounding box including nodes and viewport+ const [minX, minY, maxX, maxY] = useMemo(() => {+ const validNodes = nodes.filter(n =>+ typeof n.x === 'number' &&+ typeof n.y === 'number'+ );++ if (validNodes.length === 0) {+ // If no nodes, just show the viewport+ return [viewportX1, viewportY1, viewportX2, viewportY2];+ }++ const nodeXs = validNodes.map(n => n.x);+ const nodeYs = validNodes.map(n => n.y);++ const allX = [...nodeXs, viewportX1, viewportX2];+ const allY = [...nodeYs, viewportY1, viewportY2];++ return [+ Math.min(...allX.filter((x): x is number => x !== undefined)),+ Math.min(...allY.filter((y): y is number => y !== undefined)),+ Math.max(...allX.filter((x): x is number => x !== undefined)),+ Math.max(...allY.filter((y): y is number => y !== undefined)),+ ];+ }, [nodes, viewportX1, viewportY1, viewportX2, viewportY2]);++ const worldWidth = maxX - minX || 1;+ const worldHeight = maxY - minY || 1;++ // Scale to fit everything in the minimap+ const scaleX = width / worldWidth;+ const scaleY = height / worldHeight;+ const scale = Math.min(scaleX, scaleY);++ // Center the minimap content+ const offsetX = (width - worldWidth * scale) / 2;+ const offsetY = (height - worldHeight * scale) / 2;++ // Project world coordinates to minimap coordinates+ const project = (x, y) => [+ (x - minX) * scale + offsetX,+ (y - minY) * scale + offsetY+ ];++ // Project viewport bounds to minimap coordinates+ const [vx1, vy1] = project(viewportX1, viewportY1);+ const [vx2, vy2] = project(viewportX2, viewportY2);++ // Calculate viewBox dimensions with padding+ const viewBoxWidth = Math.abs(vx2 - vx1) + 6;+ const viewBoxHeight = Math.abs(vy2 - vy1) + 6;++ // Position the viewBox to show the current viewport+ const viewBoxX = Math.min(vx1, vx2) - 3;+ const viewBoxY = Math.min(vy1, vy2) - 3;++ // Fixed node radius for consistent sizing+ const nodeRadius = 2;++ return (+ <div style={{ width: width, height: height }} className='absolute bottom-3 right-3 bg-background/90 backdrop-blur-sm overflow-hidden border border-border rounded-lg'>+ <svg+ width={width}+ height={height}+ className="bg-transparent"+ style={{ backgroundColor: "transparent" }}+ >+ {nodes+ .filter((n: GraphNode) =>+ typeof n.x === 'number' && typeof n.y === 'number'+ )+ .map((n: GraphNode, i: number) => {+ const [cx, cy] = project(n.x, n.y);+ return (+ <circle+ key={i}+ cx={cx}+ cy={cy}+ r={nodeRadius}+ fill={n.nodeColor || 'currentColor'}+ className="text-foreground"+ />+ );+ })}++ {/* Viewport rectangle - shows current visible area */}+ <rect+ x={viewBoxX}+ y={viewBoxY}+ rx={4}+ ry={4}+ width={viewBoxWidth}+ height={viewBoxHeight}+ fill={GRAPH_COLORS.LASSO_FILL}+ stroke={GRAPH_COLORS.LASSO_STROKE}++ strokeWidth={1}+ />+ </svg>+ </div>+ );+};++export default Minimap;diff --git a/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx b/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsxindex ac7a1773..7840ec71 100644--- a/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx@@ -1,6 +1,11 @@-import React, { useState } from "react"+import { useState, type ReactNode } from "react"import { useForm } from "react-hook-form"+import { useRouter, useParams } from "@tanstack/react-router"+import { toast } from "sonner"+import { sketchService } from "@/api/sketch-service"+import { useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"import { Button } from "@/components/ui/button"import {Dialog,@@ -11,33 +16,23 @@ import {DialogTitle,DialogTrigger,} from "@/components/ui/dialog"-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu"import { Input } from "@/components/ui/input"import { Label } from "@/components/ui/label"-import { toast } from "sonner"-import { useParams, useRouter } from "@tanstack/react-router"-import { sketchService } from "@/api/sketch-service"-type FormValues = {+interface FormValues {title: stringdescription?: string}-export default function NewSketch({- children,- noDropDown = false,-}: {- children: React.ReactNode- noDropDown?: boolean-}) {+interface NewSketchProps {+ children: ReactNode+}++export default function NewSketch({ children }: NewSketchProps) {const [open, setOpen] = useState(false)const router = useRouter()const { investigationId } = useParams({ strict: false })+ const queryClient = useQueryClient()const {register,@@ -46,19 +41,10 @@ export default function NewSketch({reset,} = useForm<FormValues>()- async function onSubmit(data: FormValues) {- if (!investigationId) {- toast.error("A sketch must be related to an investigation.")- return- }-- try {- const payload = {- ...data,- investigation_id: investigationId,- }- const result = await sketchService.create(JSON.stringify(payload))-+ // Create sketch mutation+ const createSketchMutation = useMutation({+ mutationFn: sketchService.create,+ onSuccess: (result) => {if (result.id) {setOpen(false)toast.success("New sketch created.")@@ -66,13 +52,40 @@ export default function NewSketch({to: `/dashboard/investigations/${investigationId}/graph/${result.id}`,})reset()+ // Invalidate sketches list and investigation sketches+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.list+ })+ if (investigationId) {+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.sketches(investigationId)+ })+ }} else {toast.error(result.error || "Failed to create sketch.")}- } catch (error) {+ },+ onError: (error) => {toast.error("Unexpected error occurred.")console.error(error)}+ })++ async function onSubmit(data: FormValues) {+ if (!investigationId) {+ toast.error("A sketch must be related to an investigation.")+ return+ }++ try {+ const payload = {+ ...data,+ investigation_id: investigationId,+ }+ await createSketchMutation.mutateAsync(JSON.stringify(payload))+ } catch (error) {+ console.error('Error creating sketch:', error)+ }}const formContent = (@@ -121,48 +134,19 @@ export default function NewSketch({</form>)- if (noDropDown) {- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <div>{children}</div>- </DialogTrigger>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle>New sketch</DialogTitle>- <DialogDescription>Create a new blank sketch.</DialogDescription>- </DialogHeader>- {formContent}- </DialogContent>- </Dialog>- )- }-return (- <>- <DropdownMenu>- <DropdownMenuTrigger asChild><div>{children}</div></DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onSelect={() => setOpen(true)}>- New sketch- {/* <span className="ml-auto text-xs text-muted-foreground">⌘ E</span> */}- </DropdownMenuItem>- <DropdownMenuItem disabled>- New wall- {/* <span className="ml-auto text-xs text-muted-foreground">⌘ E</span> */}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>-- <Dialog open={open} onOpenChange={setOpen}>- <DialogContent className="sm:max-w-[425px]">- <DialogHeader>- <DialogTitle>New sketch</DialogTitle>- <DialogDescription>Create a new blank sketch.</DialogDescription>- </DialogHeader>- {formContent}- </DialogContent>- </Dialog>- </>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <div>{children}</div>+ </DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>New sketch</DialogTitle>+ <DialogDescription>Create a new blank sketch.</DialogDescription>+ </DialogHeader>+ {formContent}+ </DialogContent>+ </Dialog>)}+diff --git a/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx b/flowsint-app/src/renderer/src/components/graphs/node-actions.tsxindex a17fb3e6..299c1917 100644--- a/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx@@ -1,7 +1,7 @@import React, { memo, useCallback } from 'react';import { Button } from '@/components/ui/button';import { Pencil, Trash2, Sparkles, Plus } from 'lucide-react';-import { GraphNode, useGraphStore } from '@/stores/graph-store';+import { useGraphStore } from '@/stores/graph-store';import { useParams } from '@tanstack/react-router';import { useConfirm } from '@/components/use-confirm-dialog';import { toast } from 'sonner';@@ -13,6 +13,7 @@ import {TooltipTrigger,} from '@/components/ui/tooltip';import { useLayoutStore } from '@/stores/layout-store';+import { GraphNode } from '@/types';const NodeActions = memo(({ node, setMenu }: { node: GraphNode, setMenu?: (menu: any | null) => void }) => {diff --git a/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsxindex a68a57a3..e8fdabb6 100644--- a/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx@@ -2,7 +2,6 @@ import React, { memo, useCallback } from 'react';import { Button } from '@/components/ui/button';import { Trash2, Sparkles, XIcon, Rocket } from 'lucide-react';import { useGraphStore } from '@/stores/graph-store';-import { useParams } from '@tanstack/react-router';import { useConfirm } from '@/components/use-confirm-dialog';import { toast } from 'sonner';import { sketchService } from '@/api/sketch-service';@@ -18,6 +17,7 @@ import { useNodesDisplaySettings } from '@/stores/node-display-settings';import { Badge } from '../ui/badge';import LaunchFlow from './launch-transform';import { TypeBadge } from '../type-badge';+import { useParams } from '@tanstack/react-router';const SelectedItemsPanel = () => {const selectedNodes = useGraphStore(s => s.selectedNodes)diff --git a/flowsint-app/src/renderer/src/components/graphs/settings.tsx b/flowsint-app/src/renderer/src/components/graphs/settings.tsxnew file mode 100644index 00000000..528d77a0--- /dev/null+++ b/flowsint-app/src/renderer/src/components/graphs/settings.tsx@@ -0,0 +1,702 @@+import { Button } from "@/components/ui/button"+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog"+import { Input } from "@/components/ui/input"+import { Label } from "@/components/ui/label"+import { Textarea } from "@/components/ui/textarea"+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"+import { Skeleton } from "@/components/ui/skeleton"+import { Switch } from "@/components/ui/switch"+import { Slider } from "@/components/ui/slider"+import { toast } from "sonner"++import { useGraphSettingsStore } from "@/stores/graph-settings-store"+import { isMacOS } from "@/components/analyses/editor/utils"+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"+import { Sketch } from "@/types"+import { useParams } from "@tanstack/react-router"+import { sketchService } from "@/api/sketch-service"+import { useState, useEffect } from "react"+import { queryKeys } from "@/api/query-keys"+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"++// SettingItem Components+interface SettingItemProps {+ label: string+ description?: string+ children: React.ReactNode+ inline?: boolean+}++function SettingItem({ label, description, children, inline = false }: SettingItemProps) {+ if (inline) {+ return (+ <div className="flex items-center justify-between py-3">+ <div className="space-y-1 flex-1">+ <Label className="text-sm font-medium text-foreground">{label}</Label>+ {description && (+ <p className="text-xs text-muted-foreground">{description}</p>+ )}+ </div>+ <div className="ml-4">+ {children}+ </div>+ </div>+ )+ }++ return (+ <div className="space-y-2">+ <div className="space-y-1">+ <Label className="text-sm font-medium text-foreground">{label}</Label>+ {description && (+ <p className="text-xs text-muted-foreground">{description}</p>+ )}+ </div>+ {children}+ </div>+ )+}++// Dynamic Setting Components+interface DynamicSettingProps {+ categoryId: string+ settingKey: string+ setting: any+ onValueChange: (value: any) => void+}++function DynamicSetting({ categoryId, settingKey, setting, onValueChange }: DynamicSettingProps) {++ // For force settings, always use slider regardless of type+ const shouldUseSlider = categoryId === "graph" || setting.type === "slider"++ if (shouldUseSlider && (setting.type === "number" || setting.type === "slider")) {+ return (+ <SettingItem label={settingKey} description={setting.description} inline={true}>+ <div className="flex items-center space-x-3 w-64">+ <Slider+ value={[setting.value]}+ onValueChange={([value]) => onValueChange(value)}+ min={setting.min || 0}+ max={setting.max || 100}+ step={setting.step || 1}+ className="flex-1"+ />+ <Input+ type="number"+ value={setting.value}+ onChange={(e) => onValueChange(Number(e.target.value))}+ min={setting.min}+ max={setting.max}+ step={setting.step}+ className="h-9 w-20"+ />+ </div>+ </SettingItem>+ )+ }++ switch (setting.type) {+ case "boolean":+ return (+ <SettingItem label={settingKey} description={setting.description} inline={true}>+ <div className="flex items-center space-x-2">+ <Switch+ checked={setting.value}+ onCheckedChange={onValueChange}+ />+ <span className="text-sm text-muted-foreground">+ {setting.value ? "Enabled" : "Disabled"}+ </span>+ </div>+ </SettingItem>+ )++ case "select":+ return (+ <SettingItem label={settingKey} description={setting.description} inline={true}>+ <Select value={setting.value} onValueChange={onValueChange}>+ <SelectTrigger className="h-9 w-48">+ <SelectValue placeholder="Select option" />+ </SelectTrigger>+ <SelectContent>+ {setting.options?.map((option: any) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingItem>+ )++ case "text":+ return (+ <SettingItem label={settingKey} description={setting.description} inline={false}>+ <Input+ type="text"+ value={setting.value}+ onChange={(e) => onValueChange(e.target.value)}+ placeholder="Enter value"+ className="h-10"+ />+ </SettingItem>+ )++ case "textarea":+ return (+ <SettingItem label={settingKey} description={setting.description} inline={false}>+ <Textarea+ value={setting.value}+ onChange={(e) => onValueChange(e.target.value)}+ placeholder="Enter value"+ rows={4}+ className="resize-none"+ />+ </SettingItem>+ )++ case "color":+ return (+ <SettingItem label={settingKey} description={setting.description} inline={true}>+ <div className="flex items-center space-x-2">+ <Input+ type="color"+ value={setting.value}+ onChange={(e) => onValueChange(e.target.value)}+ className="h-9 w-12 p-1"+ />+ <Input+ type="text"+ value={setting.value}+ onChange={(e) => onValueChange(e.target.value)}+ placeholder="#000000"+ className="h-9 w-24"+ />+ </div>+ </SettingItem>+ )++ case "number":+ return (+ <SettingItem label={settingKey} description={setting.description} inline={true}>+ <Input+ type="number"+ value={setting.value}+ onChange={(e) => onValueChange(Number(e.target.value))}+ placeholder="Enter number"+ min={setting.min}+ max={setting.max}+ step={setting.step}+ className="h-9 w-32"+ />+ </SettingItem>+ )++ default:+ return (+ <SettingItem label={settingKey} description={setting.description} inline={false}>+ <div className="text-sm text-muted-foreground">+ Unknown setting type: {setting.type}+ </div>+ </SettingItem>+ )+ }+}++// Dynamic Section Renderer+interface DynamicSectionProps {+ categoryId: string+ category: any+ title: string+ description: string+}++function DynamicSection({ categoryId, category, title, description }: DynamicSectionProps) {+ const getPresets = useGraphSettingsStore(s => s.getPresets)+ const applyPreset = useGraphSettingsStore(s => s.applyPreset)+ const resetSettings = useGraphSettingsStore(s => s.resetSettings)+ const updateSetting = useGraphSettingsStore(s => s.updateSetting)++ if (!category) {+ return (+ <div className="space-y-6 flex flex-col h-full">+ <div className="space-y-1">+ <h3 className="text-lg font-semibold text-foreground">{title}</h3>+ <p className="text-sm text-muted-foreground">{description}</p>+ </div>+ <div className="text-sm text-muted-foreground">+ No settings available for category: {category}+ <br />+ Available categories: {Object.keys(category || {}).join(', ')}+ </div>+ </div>+ )+ }++ const handleSettingChange = (settingKey: string, value: any) => {+ updateSetting(categoryId, settingKey, value)+ }++ return (+ <div className="space-y-6 flex flex-col h-full">+ <div className="space-y-1">+ <h3 className="text-lg font-semibold text-foreground">{title}</h3>+ <p className="text-sm text-muted-foreground">{description}</p>+ </div>++ {/* Special handling for force section */}+ {categoryId === "graph" && (+ <div className="border-b pb-6">+ <div className="space-y-1">+ <h4 className="text-md font-semibold text-foreground">Force graph presets</h4>+ <p className="text-sm text-muted-foreground">+ Apply predefined configurations for different graph layouts.+ </p>+ </div>+ <div className="grid grid-cols-2 gap-2 mt-4">+ {Object.keys(getPresets()).map((presetName) => (+ <Button+ key={presetName}+ variant="outline"+ size="sm"+ onClick={() => applyPreset(presetName)}+ className="justify-start"+ >+ {presetName}+ </Button>+ ))}+ </div>+ <div className="mt-4">+ <Button+ variant="outline"+ size="sm"+ onClick={() => resetSettings()}+ className="w-full"+ >+ Reset to Defaults+ </Button>+ </div>+ </div>+ )}++ <div className="space-y-5">+ {Object.entries(category).map(([settingKey, setting]) => (+ <DynamicSetting+ key={settingKey}+ categoryId={categoryId}+ settingKey={settingKey}+ setting={setting}+ onValueChange={(value) => handleSettingChange(settingKey, value)}+ />+ ))}+ </div>+ <div className="grow" />+ </div>+ )+}++export default function GlobalSettings() {+ const settingsModalOpen = useGraphSettingsStore(s => s.settingsModalOpen)+ const setSettingsModalOpen = useGraphSettingsStore(s => s.setSettingsModalOpen)+ let settings = useGraphSettingsStore(s => s.settings)+ const queryClient = useQueryClient()++ const [activeSection, setActiveSection] = useState("information")++ const { id, investigationId } = useParams({ strict: false })+ const { data: sketch, isLoading, isError, refetch } = useQuery({+ queryKey: ["investigations", investigationId, "graph", id],+ queryFn: () => sketchService.getById(id as string),+ refetchOnWindowFocus: false,+ enabled: Boolean(id)+ })++ // Form state+ const [formData, setFormData] = useState({+ title: "",+ description: "",+ status: "active"+ })++ // Update form data when sketch data changes+ useEffect(() => {+ if (sketch) {+ setFormData({+ title: sketch.title || "",+ description: sketch.description || "",+ status: sketch.status || "active"+ })+ }+ }, [sketch])++ const updateMutation = useMutation({+ mutationFn: async (updated: Partial<Sketch>) => {+ if (!id) return+ return sketchService.update(id, JSON.stringify(updated))+ },+ onSuccess: async (data) => {+ if (!id || !investigationId) return++ // Update the query cache using query key factory+ queryClient.setQueryData(queryKeys.sketches.graph(investigationId, id), data)+ // Also update the sketches list if it exists+ queryClient.setQueryData(queryKeys.investigations.sketches(investigationId), (oldData: any) => {+ if (!oldData?.sketches) return oldData+ return {+ ...oldData,+ sketches: oldData.sketches.map((s: Sketch) => s.id === id ? data : s)+ }+ })+ // Invalidate related queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.detail(id)+ })+ toast.success("Sketch updated successfully")+ setSettingsModalOpen(false)+ },+ onError: (error) => {+ toast.error("Failed to update sketch: " + (error instanceof Error ? error.message : "Unknown error"))+ }+ })++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault()+ updateMutation.mutate(formData)+ }++ const handleInputChange = (field: string, value: string) => {+ setFormData(prev => ({+ ...prev,+ [field]: value+ }))+ }++ if (isLoading) {+ return (+ <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>General settings</DialogTitle>+ <DialogDescription>+ Make changes to your sketch settings here. Click save when you're done.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4">+ <div className="grid gap-2">+ <Skeleton className="h-4 w-16" />+ <Skeleton className="h-10 w-full" />+ </div>+ <div className="grid gap-2">+ <Skeleton className="h-4 w-24" />+ <Skeleton className="h-20 w-full" />+ </div>+ <div className="grid gap-2">+ <Skeleton className="h-4 w-16" />+ <Skeleton className="h-10 w-full" />+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" disabled>Cancel</Button>+ <Button disabled>Saving...</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+ }++ if (isError) {+ return (+ <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>General settings</DialogTitle>+ <DialogDescription>+ Error loading sketch data. Please try again.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4">+ <Button onClick={() => refetch()}>Retry</Button>+ </div>+ </DialogContent>+ </Dialog>+ )+ }++ const getSelectedSectionPanel = (sectionId: string) => {+ if (sectionId === "information") {+ return (+ <div className="space-y-6 flex flex-col h-full">+ <div className="space-y-1">+ <h3 className="text-lg font-semibold text-foreground">General Information</h3>+ <p className="text-sm text-muted-foreground">+ Configure the basic details and metadata for your sketch.+ </p>+ </div>++ <div className="space-y-5">+ <TextSetting+ label="Title"+ description="The name of your sketch"+ value={formData.title}+ onValueChange={(value) => handleInputChange("title", value)}+ placeholder="Enter sketch title"+ />++ <TextareaSetting+ label="Description"+ description="A brief description of what this sketch represents"+ value={formData.description}+ onValueChange={(value) => handleInputChange("description", value)}+ placeholder="Enter sketch description"+ rows={4}+ />++ <SelectSetting+ label="Status"+ description="The current status of this sketch"+ value={formData.status}+ onValueChange={(value) => handleInputChange("status", value)}+ options={[+ { value: "active", label: "Active" },+ { value: "inactive", label: "Inactive" },+ { value: "archived", label: "Archived" }+ ]}+ placeholder="Select status"+ />+ </div>++ <div className="grow" />++ <div className="border-t pt-6">+ <DialogFooter className="gap-3">+ <DialogClose asChild>+ <Button variant="outline" type="button" className="h-10 px-6">+ Cancel+ </Button>+ </DialogClose>+ <Button+ type="submit"+ disabled={updateMutation.isPending}+ onClick={handleSubmit}+ className="h-10 px-6"+ >+ {updateMutation.isPending ? "Saving..." : "Save Changes"}+ </Button>+ </DialogFooter>+ </div>+ </div>+ )+ }++ // For all other sections, use the dynamic renderer+ const category = settings[sectionId]+ if (category) {+ return (+ <DynamicSection+ categoryId={sectionId}+ category={category}+ title={category.title}+ description={category.description}+ />+ )+ }++ return <div>Section not found.</div>+ }++ return (+ <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>+ <DialogContent className="sm:max-w-[800px] h-[80vh] flex flex-col items-start overflow-hidden">+ <DialogHeader>+ <DialogTitle>Sketch settings</DialogTitle>+ <DialogDescription>+ Configure your sketch settings and preferences.+ </DialogDescription>+ </DialogHeader>+ <Tabs value={activeSection} onValueChange={setActiveSection} className="w-full h-full overflow-hidden">+ <div className="grid grid-cols-4 gap-6 h-full divide-x overflow-hidden">+ {/* Left sidebar with tabs */}+ <div className="col-span-1 pr-3">+ <TabsList className="flex bg-transparent flex-col gap-2 w-full h-auto">+ {Object.keys(settings).map((category: string) => (+ <TabsTrigger+ key={category}+ value={category}+ className="w-full justify-start capitalize h-10"+ >+ {category}+ </TabsTrigger>+ ))}+ </TabsList>+ </div>++ {/* Right content panel */}+ <div className="col-span-3 h-full w-full overflow-auto p-1">+ {Object.keys(settings).map((category: string) => (+ <TabsContent key={category} value={category} className="mt-0 h-full w-full flex flex-col justify-center">+ {getSelectedSectionPanel(category)}+ </TabsContent>+ ))}+ </div>+ </div>+ </Tabs>+ </DialogContent>+ </Dialog>+ )+}++// Legacy components for backward compatibility (keeping the general section working)+interface TextSettingProps {+ label: string+ description?: string+ value: string+ onValueChange: (value: string) => void+ placeholder?: string+ type?: "text" | "email" | "url" | "number"+}++function TextSetting({ label, description, value, onValueChange, placeholder, type = "text" }: TextSettingProps) {+ return (+ <SettingItem label={label} description={description} inline={false}>+ <Input+ type={type}+ value={value}+ onChange={(e) => onValueChange(e.target.value)}+ placeholder={placeholder}+ className="h-10"+ />+ </SettingItem>+ )+}++interface TextareaSettingProps {+ label: string+ description?: string+ value: string+ onValueChange: (value: string) => void+ placeholder?: string+ rows?: number+}++function TextareaSetting({ label, description, value, onValueChange, placeholder, rows = 4 }: TextareaSettingProps) {+ return (+ <SettingItem label={label} description={description} inline={false}>+ <Textarea+ value={value}+ onChange={(e) => onValueChange(e.target.value)}+ placeholder={placeholder}+ rows={rows}+ className="resize-none"+ />+ </SettingItem>+ )+}++interface SelectSettingProps {+ label: string+ description?: string+ value: string+ onValueChange: (value: string) => void+ options: { value: string; label: string }[]+ placeholder?: string+}++function SelectSetting({ label, description, value, onValueChange, options, placeholder }: SelectSettingProps) {+ return (+ <SettingItem label={label} description={description} inline={true}>+ <Select value={value} onValueChange={onValueChange}>+ <SelectTrigger className="h-9 w-48">+ <SelectValue placeholder={placeholder} />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingItem>+ )+}++export function KeyboardShortcuts() {+ const keyboardShortcutsOpen = useGraphSettingsStore(s => s.keyboardShortcutsOpen)+ const setKeyboardShortcutsOpen = useGraphSettingsStore(s => s.setKeyboardShortcutsOpen)++ const isMac = isMacOS()+ const modKey = isMac ? "⌘" : "Ctrl"++ const shortcuts = [+ {+ category: "Navigation & Panels",+ items: [+ { key: `${modKey}+L`, description: "Toggle Analysis Panel" },+ { key: `${modKey}+B`, description: "Toggle Panel" },+ { key: `${modKey}+D`, description: "Toggle Console" },+ { key: `${modKey}+J`, description: "Open Command Palette" },+ ]+ },+ {+ category: "Chat & Assistant",+ items: [+ { key: `${modKey}+E`, description: "Toggle Chat Assistant" },+ { key: "Escape", description: "Close Chat Assistant" },+ ]+ },+ {+ category: "File Operations",+ items: [+ { key: `${modKey}+S`, description: "Save (Analysis/Flow)" },+ ]+ }+ ]++ return (+ <Dialog open={keyboardShortcutsOpen} onOpenChange={setKeyboardShortcutsOpen}>+ <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>Keyboard Shortcuts</DialogTitle>+ <DialogDescription>+ Here is the list of all available keyboard shortcuts.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-6">+ {shortcuts.map((category) => (+ <div key={category.category} className="space-y-3">+ <h3 className="text-sm font-semibold text-foreground/80 uppercase tracking-wide">+ {category.category}+ </h3>+ <div className="space-y-2">+ {category.items.map((item) => (+ <div key={item.key} className="flex items-center justify-between py-2 px-3 rounded-md bg-muted/50">+ <span className="text-sm text-muted-foreground">+ {item.description}+ </span>+ <kbd className="inline-flex items-center gap-1 rounded border bg-background px-2 py-1 text-xs font-mono font-medium text-foreground shadow-sm">+ {item.key}+ </kbd>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ <DialogFooter>+ <DialogClose asChild>+ <Button variant="outline">Close</Button>+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx b/flowsint-app/src/renderer/src/components/graphs/toolbar.tsxindex 8733d1ce..3d2298a3 100644--- a/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx@@ -10,17 +10,16 @@ import {Waypoints,MapPin,List,- SlidersHorizontal,GitFork,ArrowRightLeft,FunnelPlus,GitPullRequestArrow,- LassoSelect+ LassoSelect,+ Merge} from "lucide-react"import { memo, useCallback } from "react"import { toast } from "sonner"import { cn } from "@/lib/utils"-import ForceControls from './force-controls'import Filters from "./filters"import { useGraphStore } from "@/stores/graph-store"@@ -49,7 +48,7 @@ export const ToolbarButton = memo(function ToolbarButton({disabled={disabled}variant="outline"size="icon"- className={cn("h-8 w-8 relative shadow-none", toggled && "bg-muted hover:bg-muted")}+ className={cn("h-8 w-8 relative shadow-none", toggled && "bg-primary/30 border-primary text-primary hover:bg-primary/40 hover:text-primary")}>{icon}{badge && <span className="absolute -top-2 -right-2 z-50 bg-primary text-white text-[10px] rounded-full w-auto min-w-4.5 h-4.5 p-1 flex items-center justify-center">{badge}</span>}@@ -72,11 +71,12 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: booleanconst setIsLassoActive = useGraphControls((s) => s.setIsLassoActive)const selectedNodes = useGraphStore(s => s.selectedNodes)const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)+ const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)+ const filters = useGraphStore(s => s.filters)const handleRefresh = useCallback(() => {try {refetchGraph()- onLayout("dagre")} catch (error) {toast.error("Failed to refresh graph data");}@@ -84,7 +84,8 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: booleanconst handleForceLayout = useCallback(() => {setView("force")- }, [setView])+ setTimeout(() => zoomToFit(), 500)+ }, [setView, zoomToFit])const handleTableLayout = useCallback(() => {setView("table")@@ -101,17 +102,24 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: booleanconst handleDagreLayoutTB = useCallback(() => {setView("hierarchy")onLayout && onLayout("dagre-tb")- }, [onLayout, setView])+ setTimeout(() => zoomToFit(), 200)+ }, [onLayout, setView, zoomToFit])const handleOpenAddRelationDialog = useCallback(() => {setOpenAddRelationDialog(true)}, [setOpenAddRelationDialog])+ const handleOpenMergeDialog = useCallback(() => {+ setOpenMergeDialog(true)+ }, [setOpenMergeDialog])+const handleLassoSelect = useCallback(() => {setIsLassoActive(!isLassoActive)}, [setIsLassoActive, isLassoActive])const areExactlyTwoSelected = selectedNodes.length === 2+ const areMergeable = selectedNodes.length > 1 && selectedNodes.every((n) => n.data.type === selectedNodes[0].data.type)+ const hasFilters = !(filters.types.every(t => t.checked) || filters.types.every(t => !t.checked))return (<div className="flex w-full justify-between gap-2 items-center">@@ -123,6 +131,13 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: booleanonClick={handleOpenAddRelationDialog}disabled={!areExactlyTwoSelected}badge={areExactlyTwoSelected ? 2 : null}+ />+ <ToolbarButton+ icon={<Merge className="h-4 w-4 opacity-70" />}+ tooltip="Merge"+ onClick={handleOpenMergeDialog}+ disabled={!areMergeable}+ badge={areMergeable ? selectedNodes.length : null}/><ToolbarButton@@ -150,18 +165,12 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: booleantoggled={isLassoActive}disabled={!["force", "hierarchy"].includes(view)}/>- <ForceControls>- <ToolbarButton- disabled={isLoading || !["force", "hierarchy"].includes(view)}- icon={<SlidersHorizontal className={cn("h-4 w-4 opacity-70")} />}- tooltip="Settings"- />- </ForceControls><Filters><ToolbarButtondisabled={isLoading}icon={<FunnelPlus className={cn("h-4 w-4 opacity-70")} />}tooltip="Filters"+ toggled={hasFilters}/></Filters><ToolbarButton@@ -178,12 +187,10 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: booleanicon={<GitFork className="h-4 w-4 opacity-70 rotate-180" />}tooltip={`Hierarchy`}toggled={["hierarchy"].includes(view)}- disabled={["hierarchy"].includes(view)}onClick={handleDagreLayoutTB}/><ToolbarButtonicon={<Waypoints className="h-4 w-4 opacity-70" />}- disabled={["force"].includes(view)}tooltip={"Graph view"}toggled={["force"].includes(view)}onClick={handleForceLayout}@@ -191,21 +198,18 @@ export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean<ToolbarButtonicon={<List className="h-4 w-4 opacity-70" />}tooltip={"Table view"}- disabled={["table"].includes(view)}toggled={["table"].includes(view)}onClick={handleTableLayout}/><ToolbarButtonicon={<ArrowRightLeft className="h-4 w-4 opacity-70" />}tooltip={"Relationships view"}- disabled={["relationships"].includes(view)}toggled={["relationships"].includes(view)}onClick={handleRelationshipsLayout}/><ToolbarButtonicon={<MapPin className="h-4 w-4 opacity-70" />}tooltip={"Map view"}- disabled={["map"].includes(view)}toggled={["map"].includes(view)}onClick={handleMapLayout}/>diff --git a/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx b/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsxindex 62bba4b0..d5f76110 100644--- a/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx+++ b/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx@@ -1,10 +1,10 @@import { investigationService } from "@/api/investigation-service"import type { Investigation } from "@/types/investigation"-import { useQuery } from "@tanstack/react-query"+import { useQuery, useQueryClient } from "@tanstack/react-query"import type { Sketch } from "@/types/sketch"import NewInvestigation from "./new-investigation"import { Button } from "../ui/button"-import { MoreVertical, PlusIcon, Trash2, Waypoints } from "lucide-react"+import { MoreVertical, PlusIcon, Trash2, Waypoints, ChevronRight, ChevronDown, Folder, FileText, Search } from "lucide-react"import { Input } from "../ui/input"import { cn } from "@/lib/utils"import { Link, useParams } from "@tanstack/react-router"@@ -14,10 +14,158 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { toast } from "sonner"import { sketchService } from "@/api/sketch-service"import { useState, useMemo } from "react"+import { queryKeys } from "@/api/query-keys"+import { useMutation } from "@tanstack/react-query"++// Tree node component for investigations and sketches+const TreeNode = ({+ item,+ level = 0,+ isExpanded,+ onToggle,+ isActive,+ onDelete,+ children,+ isClickable = true+}: {+ item: { id: string, name: string, type: 'investigation' | 'sketch' },+ level?: number,+ isExpanded?: boolean,+ onToggle?: () => void,+ isActive?: boolean,+ onDelete?: (e: React.MouseEvent) => void,+ children?: React.ReactNode,+ isClickable?: boolean+}) => {+ const isInvestigation = item.type === 'investigation'+ const hasChildren = isInvestigation && children+ const canExpand = isInvestigation && hasChildren++ const handleToggle = (e: React.MouseEvent) => {+ e.preventDefault()+ e.stopPropagation()+ onToggle?.()+ }++ const handleDelete = (e: React.MouseEvent) => {+ e.preventDefault()+ e.stopPropagation()+ onDelete?.(e)+ }++ const handleDropdownClick = (e: React.MouseEvent) => {+ e.preventDefault()+ e.stopPropagation()+ }++ return (+ <div className="w-full">+ <div+ className={cn(+ "flex items-center group gap-2 px-3 py-2 hover:bg-muted/50 transition-colors",+ isActive && "bg-muted",+ level > 0 && "ml-4",+ !isClickable && "cursor-default"+ )}+ style={{ paddingLeft: `${12 + (level * 16)}px` }}+ >+ {/* Expand/collapse button for investigations */}+ {canExpand && (+ <Button+ variant="ghost"+ size="icon"+ className="h-4 w-4 p-0 hover:bg-transparent"+ onClick={handleToggle}+ >+ {isExpanded ? (+ <ChevronDown className="h-3 w-3" />+ ) : (+ <ChevronRight className="h-3 w-3" />+ )}+ </Button>+ )}++ {/* Icon */}+ {isInvestigation ? (+ <Search className="h-4 w-4 text-muted-foreground" />+ ) : (+ <Waypoints className="h-4 w-4 text-muted-foreground" />+ )}++ {/* Name */}+ <span className="flex-1 text-sm truncate font-medium">+ {item.name}+ </span>++ {/* Actions */}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <div>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 group-hover:opacity-100 opacity-0 transition-all duration-100"+ onClick={handleDropdownClick}+ >+ <MoreVertical className="h-4 w-4" />+ </Button>+ </div>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem variant="destructive" onClick={handleDelete}>+ <Trash2 className="h-4 w-4 mr-2" />+ Delete {isInvestigation ? 'Investigation' : 'Sketch'}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ {/* Children */}+ {canExpand && isExpanded && (+ <div className="w-full">+ {children}+ </div>+ )}+ </div>+ )+}export const SketchListItem = ({ sketch, investigationId, refetch }: { sketch: Sketch, investigationId: string, refetch: () => void }) => {const { confirm } = useConfirm();+ const queryClient = useQueryClient();+ // Delete sketch mutation+ const deleteSketchMutation = useMutation({+ mutationFn: sketchService.delete,+ onSuccess: () => {+ // Invalidate all related queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.list+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.detail(investigationId)+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.sketches(investigationId)+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.list+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.detail(sketch.id)+ })+ queryClient.invalidateQueries({+ queryKey: queryKeys.sketches.graph(investigationId, sketch.id)+ })+ // Also invalidate dashboard queries+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.dashboard+ })+ },+ onError: (error) => {+ console.error("Error deleting sketch:", error)+ }+ });const handleDelete = async (e: React.MouseEvent) => {e.preventDefault();@@ -29,9 +177,7 @@ export const SketchListItem = ({ sketch, investigationId, refetch }: { sketch: S});if (confirmed) {- const deletePromise = () => sketchService.delete(sketch.id).then(() => refetch());-- toast.promise(deletePromise, {+ toast.promise(deleteSketchMutation.mutateAsync(sketch.id), {loading: 'Deleting sketch...',success: () => `Sketch "${sketch.title}" has been deleted`,error: 'Failed to delete sketch'@@ -50,28 +196,13 @@ export const SketchListItem = ({ sketch, investigationId, refetch }: { sketch: Sid={sketch.id}>{({ isActive }) => (- <div className={cn(- "flex items-center group gap-2 px-3 py-2",- isActive ? "bg-muted" : "hover:bg-muted/50"- )}>- <Waypoints className="h-4 w-4 text-primary opacity-70" strokeWidth={1.5} />- <span className="flex-1 text-sm truncate">{sketch.title}</span>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <div>- <Button variant="ghost" size="icon" className="h-6 w-6 group-hover:opacity-100 opacity-0 transition-all duration-100">- <MoreVertical className="h-4 w-4" />- </Button>- </div>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem variant="destructive" onClick={handleDelete}>- <Trash2 className="h-4 w-4 mr-2" />- Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>+ <TreeNode+ item={{ id: sketch.id, name: sketch.title, type: 'sketch' }}+ level={1}+ isActive={isActive}+ onDelete={handleDelete}+ isClickable={false}+ />)}</Link>);@@ -79,19 +210,20 @@ export const SketchListItem = ({ sketch, investigationId, refetch }: { sketch: Sconst InvestigationList = () => {const { data, isLoading, error, refetch } = useQuery({- queryKey: ["investigations", "list"],+ queryKey: queryKeys.investigations.list,queryFn: investigationService.get,})- const { investigationId } = useParams({ strict: false })const { confirm } = useConfirm();const [searchQuery, setSearchQuery] = useState("")+ const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set())+ const queryClient = useQueryClient()const filteredInvestigations = useMemo(() => {if (!data) return []if (!searchQuery.trim()) return dataconst query = searchQuery.toLowerCase().trim()- return data.filter((investigation) => {+ return data.filter((investigation: Investigation) => {const matchesInvestigation = investigation.name.toLowerCase().includes(query)const matchesSketches = investigation.sketches?.some(sketch =>sketch.title.toLowerCase().includes(query)@@ -100,6 +232,18 @@ const InvestigationList = () => {})}, [data, searchQuery])+ const toggleNode = (nodeId: string) => {+ setExpandedNodes(prev => {+ const newSet = new Set(prev)+ if (newSet.has(nodeId)) {+ newSet.delete(nodeId)+ } else {+ newSet.add(nodeId)+ }+ return newSet+ })+ }+const handleDeleteInvestigation = async (investigation: Investigation, e: React.MouseEvent) => {e.preventDefault();e.stopPropagation();@@ -110,7 +254,27 @@ const InvestigationList = () => {});if (confirmed) {- const deletePromise = () => investigationService.delete(investigation.id).then(() => refetch());+ const deletePromise = () => investigationService.delete(investigation.id).then(() => {+ // Invalidate the investigations list+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.list+ })++ // Also remove related data from cache+ queryClient.removeQueries({+ queryKey: queryKeys.investigations.detail(investigation.id)+ })+ queryClient.removeQueries({+ queryKey: queryKeys.investigations.sketches(investigation.id)+ })+ queryClient.removeQueries({+ queryKey: queryKeys.investigations.analyses(investigation.id)+ })+ queryClient.removeQueries({+ queryKey: queryKeys.investigations.flows(investigation.id)+ })+ });+toast.promise(deletePromise, {loading: 'Deleting investigation...',success: () => `Investigation "${investigation.name}" has been deleted`,@@ -143,56 +307,47 @@ const InvestigationList = () => {</div>) : filteredInvestigations.length > 0 ? (<div className="overflow-auto">- {filteredInvestigations.map((investigation: Investigation) => (- <div key={investigation.id}>- <div className="flex items-center group gap-2 px-3 py-2 border-b">+ {filteredInvestigations.map((investigation: Investigation) => {+ const isExpanded = expandedNodes.has(investigation.id)+ const hasSketches = investigation.sketches && investigation.sketches.length > 0++ return (+ <div key={investigation.id} className="w-full"><Linkto="/dashboard/investigations/$investigationId"params={{investigationId: investigation.id,}}- className={cn(- "flex-1 text-sm font-medium hover:underline",- investigationId === investigation.id && "text-primary"- )}>- {investigation.name}+ {({ isActive }) => (+ <TreeNode+ item={{ id: investigation.id, name: investigation.name, type: 'investigation' }}+ isExpanded={isExpanded}+ onToggle={() => toggleNode(investigation.id)}+ isActive={isActive}+ onDelete={(e) => handleDeleteInvestigation(investigation, e)}+ isClickable={false}+ >+ {hasSketches ? (+ investigation.sketches!.map((sketch: Sketch) => (+ <SketchListItem+ refetch={refetch}+ key={sketch.id}+ sketch={sketch}+ investigationId={investigation.id}+ />+ ))+ ) : (+ <div className="ml-8 px-3 py-2 text-sm text-muted-foreground">+ No sketches+ </div>+ )}+ </TreeNode>+ )}</Link>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <div>- <Button variant="ghost" size="icon" className="h-6 w-6 group-hover:opacity-100 opacity-0 transition-all duration-100">- <MoreVertical className="h-4 w-4" />- </Button>- </div>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem variant="destructive" onClick={(e) => handleDeleteInvestigation(investigation, e)}>- <Trash2 className="h-4 w-4 mr-2" />- Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu></div>-- {investigation.sketches && investigation.sketches.length > 0 ? (- <div className="pl-4">- {investigation.sketches.map((sketch: Sketch) => (- <SketchListItem- refetch={refetch}- key={sketch.id}- sketch={sketch}- investigationId={investigation.id}- />- ))}- </div>- ) : (- <p className="px-7 py-2 text-sm text-muted-foreground">- Empty- </p>- )}- </div>- ))}+ )+ })}</div>) : (<div className="flex-1 flex flex-col items-center justify-center text-center gap-2 p-4">diff --git a/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx b/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsxindex 9d85adb4..ceb36f5c 100644--- a/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx+++ b/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx@@ -1,32 +1,18 @@-import type React from "react"-import { useState } from "react"+import { useState, type ReactNode } from "react"import { useForm } from "react-hook-form"import { zodResolver } from "@hookform/resolvers/zod"-import * as z from "zod"+import { useRouter } from "@tanstack/react-router"+import { toast } from "sonner"import { investigationService } from "@/api/investigation-service"+import { useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"import { Button } from "@/components/ui/button"-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog"+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"import { Input } from "@/components/ui/input"-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/components/ui/form"-import { toast } from "sonner"-import { useRouter } from "@tanstack/react-router"-import { DialogTrigger } from "@radix-ui/react-dialog"+import * as z from "zod"// Schema de validation Zodconst investigationSchema = z.object({@@ -42,13 +28,14 @@ const investigationSchema = z.object({type InvestigationFormData = z.infer<typeof investigationSchema>interface NewInvestigationProps {- children: React.ReactNode+ children: ReactNodenoDropDown?: boolean}-export default function NewInvestigation({ children, noDropDown }: NewInvestigationProps) {+export default function NewInvestigation({ children, noDropDown = false }: NewInvestigationProps) {const [open, setOpen] = useState(false)const router = useRouter()+ const queryClient = useQueryClient()const form = useForm<InvestigationFormData>({resolver: zodResolver(investigationSchema),@@ -60,20 +47,34 @@ export default function NewInvestigation({ children, noDropDown }: NewInvestigatconst { handleSubmit, formState: { isSubmitting }, reset } = form- const onSubmit = async (data: InvestigationFormData) => {- try {- const result = await investigationService.create(JSON.stringify(data))+ // Create investigation mutation+ const createInvestigationMutation = useMutation({+ mutationFn: investigationService.create,+ onSuccess: (result) => {if (result.id) {handleClose()toast.success("New investigation created.")router.navigate({ to: `/dashboard/investigations/${result.id}` })+ // Invalidate investigations list+ queryClient.invalidateQueries({+ queryKey: queryKeys.investigations.list+ })} else {toast.error(result.error || "Failed to create investigation")}- } catch (error) {+ },+ onError: (error) => {console.error('Error creating investigation:', error)toast.error("An unexpected error occurred")}+ })++ const onSubmit = async (data: InvestigationFormData) => {+ try {+ await createInvestigationMutation.mutateAsync(JSON.stringify(data))+ } catch (error) {+ console.error('Error creating investigation:', error)+ }}const handleClose = () => {diff --git a/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx b/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsxindex e9c4c18d..a35af897 100644--- a/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx+++ b/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx@@ -9,11 +9,12 @@ import { SkeletonList } from "../shared/skeleton-list"import NewSketch from "../graphs/new-sketch"import { SketchListItem } from "./investigation-list"import { useState, useMemo } from "react"+import { queryKeys } from "@/api/query-keys"const SketchList = () => {const { investigationId } = useParams({ strict: false })const { data: investigation, isLoading, refetch, error } = useQuery({- queryKey: ["investigations", "sketches", investigationId],+ queryKey: queryKeys.investigations.detail(investigationId as string),queryFn: () => investigationService.getById(investigationId as string),})const [searchQuery, setSearchQuery] = useState("")diff --git a/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx b/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsxindex 06d4d869..357abafb 100644--- a/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx+++ b/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx@@ -14,6 +14,7 @@ import { investigationService } from "@/api/investigation-service";import { useNavigate, useParams } from "@tanstack/react-router";import { Search, ChevronDown, Plus, FolderOpen } from "lucide-react";import NewInvestigation from "@/components/investigations/new-investigation";+import { queryKeys } from "@/api/query-keys";export default function InvestigationSelector() {const navigate = useNavigate()@@ -22,7 +23,7 @@ export default function InvestigationSelector() {const [searchQuery, setSearchQuery] = useState("")const { data: investigations, isLoading } = useQuery({- queryKey: ["dashboard", "selector", investigationId],+ queryKey: queryKeys.investigations.selector(investigationId as string),queryFn: investigationService.get,refetchOnWindowFocus: true,})diff --git a/flowsint-app/src/renderer/src/components/layout/log-panel.tsx b/flowsint-app/src/renderer/src/components/layout/log-panel.tsxindex 63685263..6f5d56d3 100644--- a/flowsint-app/src/renderer/src/components/layout/log-panel.tsx+++ b/flowsint-app/src/renderer/src/components/layout/log-panel.tsx@@ -22,6 +22,8 @@ import { EventLevel } from "@/types"import { cn } from "@/lib/utils"import { Button } from "../ui/button"import { useEvents } from "@/hooks/use-events"+import { useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"const logLevelConfig = {[EventLevel.INFO]: {@@ -103,7 +105,24 @@ export const LogPanel = memo(() => {const bottomRef = useRef<HTMLDivElement | null>(null)const scrollAreaRef = useRef<HTMLDivElement>(null)const { logs, refetch } = useEvents(sketch_id as string)+ const queryClient = useQueryClient()+ // Delete logs mutation+ const deleteLogsMutation = useMutation({+ mutationFn: logService.delete,+ onSuccess: () => {+ // Invalidate logs for this sketch+ if (sketch_id) {+ queryClient.invalidateQueries({+ queryKey: queryKeys.logs.bySketch(sketch_id)+ })+ }+ refetch()+ },+ onError: (error) => {+ console.error("Error deleting logs:", error)+ }+ })useEffect(() => {if (bottomRef.current) {@@ -120,8 +139,7 @@ export const LogPanel = memo(() => {})))return- await logService.delete(sketch_id)- refetch()+ await deleteLogsMutation.mutateAsync(sketch_id)}const formatTime = (date: string) => {diff --git a/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx b/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsxindex 90e9e495..a320e194 100644--- a/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx+++ b/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx@@ -16,6 +16,7 @@ import { investigationService } from "@/api/investigation-service";import { analysisService } from "@/api/analysis-service";import { Waypoints, FileText, Search, ChevronDown, Plus, ArrowLeft, Home } from "lucide-react";import NewSketch from "@/components/graphs/new-sketch";+import { queryKeys } from "@/api/query-keys";export default function CaseSelector() {const navigate = useNavigate()@@ -24,13 +25,13 @@ export default function CaseSelector() {const [searchQuery, setSearchQuery] = useState("")const { data: investigation, isLoading: isLoadingInvestigation } = useQuery({- queryKey: ["dashboard", "investigation", investigationId],+ queryKey: queryKeys.sketches.dashboard(investigationId as string),queryFn: () => investigationService.getById(investigationId as string),refetchOnWindowFocus: true,})const { data: analyses, isLoading: isLoadingAnalyses } = useQuery({- queryKey: ["analyses", investigationId],+ queryKey: queryKeys.analyses.dashboard(investigationId as string),queryFn: () => analysisService.getByInvestigationId(investigationId as string),enabled: !!investigationId,refetchOnWindowFocus: true,@@ -158,7 +159,7 @@ export default function CaseSelector() {</div><Separator className="my-0.5" /><div className="py-0.5">- <NewSketch noDropDown={true}>+ <NewSketch><Buttonvariant="ghost"size="sm"diff --git a/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx b/flowsint-app/src/renderer/src/components/layout/top-navbar.tsxindex 21d8b0ba..4594acb1 100644--- a/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx+++ b/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx@@ -19,7 +19,7 @@ import {} from "@/components/ui/dropdown-menu"import { Ellipsis } from "lucide-react"import { isMac } from "@/lib/utils"-import { useGraphGeneralSettingsStore } from "@/stores/graph-general-store"+import { useGraphSettingsStore } from "@/stores/graph-settings-store"export const TopNavbar = memo(() => {const { investigationId, id, type } = useParams({ strict: false })@@ -33,9 +33,8 @@ export const TopNavbar = memo(() => {const checkWindowState = async () => {try {const windowState = await window.api.getWindowState()- setIsFullscreen(windowState.isFullscreen)+ setIsFullscreen(windowState?.isFullscreen)} catch (error) {- console.error('Failed to get window state:', error)setIsFullscreen(true)}}@@ -49,9 +48,10 @@ export const TopNavbar = memo(() => {}}, [])+return (<header className={`flex items-center bg-card h-12 border-b shrink-0 ${isFullscreen ? 'px-4' : 'pl-20 pr-4'} -webkit-app-region-drag`}>- <div className="flex items-center gap-4">+ <div className="flex items-center gap-4 -webkit-app-region-no-drag"><Link to="/dashboard" className="flex items-center gap-2"><img src="/icon.png" alt="Flowsint" className="h-8 w-8" /><span className="text-lg font-semibold">Flowsint</span>@@ -65,7 +65,7 @@ export const TopNavbar = memo(() => {</div></div><div className="grow flex items-center justify-center">- <Command />+ <div className="-webkit-app-region-no-drag"><Command /></div></div><div className="flex items-center gap-4 -webkit-app-region-no-drag"><div className="flex items-center space-x-2">@@ -85,8 +85,8 @@ export const TopNavbar = memo(() => {export function InvestigationMenu() {- const setSettingsModalOpen = useGraphGeneralSettingsStore(s => s.setSettingsModalOpen)- const setKeyboardShortcutsOpen = useGraphGeneralSettingsStore(s => s.setKeyboardShortcutsOpen)+ const setSettingsModalOpen = useGraphSettingsStore(s => s.setSettingsModalOpen)+ const setKeyboardShortcutsOpen = useGraphSettingsStore(s => s.setKeyboardShortcutsOpen)return (<DropdownMenu>@@ -99,7 +99,7 @@ export function InvestigationMenu() {<DropdownMenuLabel>Settings</DropdownMenuLabel><DropdownMenuGroup><DropdownMenuItem onClick={() => setSettingsModalOpen(true)}>- Preferences+ General<DropdownMenuShortcut>⌘G</DropdownMenuShortcut></DropdownMenuItem><DropdownMenuItem onClick={() => setKeyboardShortcutsOpen(true)}>@@ -107,25 +107,6 @@ export function InvestigationMenu() {<DropdownMenuShortcut>⌘K</DropdownMenuShortcut></DropdownMenuItem></DropdownMenuGroup>- {/* <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem>Team</DropdownMenuItem>- <DropdownMenuSub>- <DropdownMenuSubTrigger>Invite users</DropdownMenuSubTrigger>- <DropdownMenuPortal>- <DropdownMenuSubContent>- <DropdownMenuItem>Email</DropdownMenuItem>- <DropdownMenuItem>Message</DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem>More...</DropdownMenuItem>- </DropdownMenuSubContent>- </DropdownMenuPortal>- </DropdownMenuSub>- <DropdownMenuItem>- New Team- <DropdownMenuShortcut>⌘T</DropdownMenuShortcut>- </DropdownMenuItem>- </DropdownMenuGroup> */}<DropdownMenuSeparator /><DropdownMenuItem><a href="https://github.com/reconurge">GitHub</a></DropdownMenuItem><DropdownMenuItem><a href="https://github.com/reconurge">Support</a></DropdownMenuItem>diff --git a/flowsint-app/src/renderer/src/components/table/nodes-view.tsx b/flowsint-app/src/renderer/src/components/table/nodes-view.tsxindex 33a82640..be032cfa 100644--- a/flowsint-app/src/renderer/src/components/table/nodes-view.tsx+++ b/flowsint-app/src/renderer/src/components/table/nodes-view.tsx@@ -1,10 +1,9 @@import { useGraphStore } from "@/stores/graph-store";import { useVirtualizer } from "@tanstack/react-virtual";-import { useRef, useState, useMemo, useCallback } from "react";+import { useRef, useState, useMemo, useCallback, memo } from "react";import { Input } from "@/components/ui/input";import { Badge } from "@/components/ui/badge";-import { Card, CardContent } from "@/components/ui/card";-import { Search, Users, Link, Filter } from "lucide-react";+import { Search, Users, Link, Filter, Calendar } from "lucide-react";import { useIcon } from "@/hooks/use-icon";import {Select,@@ -13,9 +12,10 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";+import { Checkbox } from "@/components/ui/checkbox";import { CopyButton } from "../copy";import { GraphNode } from '@/types';-+import { formatDistanceToNow } from "date-fns";export type RelationshipType = {source: GraphNode@@ -23,45 +23,92 @@ export type RelationshipType = {edge: { label: string }}-const ITEM_HEIGHT = 67; // Balanced spacing between items (55px card + 12px padding)+const ITEM_HEIGHT = 56; // Row height used by virtualizer// Separate component for node item to avoid hook order issuesinterface NodeItemProps {node: GraphNode;- style: React.CSSProperties;- onNodeClick: (node: GraphNode) => void+ onNodeClick: (node: GraphNode) => void;+ isSelected: boolean;+ onSelectionChange: (node: GraphNode, checked: boolean) => void;}-function NodeItem({ node, style, onNodeClick }: NodeItemProps) {+const NodeItem = memo(function NodeItem({ node, onNodeClick, isSelected, onSelectionChange }: NodeItemProps) {const SourceIcon = useIcon(node.data?.type, node.data?.src);- const handleNodeClik = useCallback(() => {+ const handleNodeClick = useCallback(() => {onNodeClick(node)- }, [])+ }, [onNodeClick, node])+ const handleCheckboxChange = useCallback((checked: boolean) => {+ onSelectionChange(node, checked)+ }, [onSelectionChange, node])++ const formatCreatedAt = useCallback((dateString: string) => {+ try {+ return formatDistanceToNow(new Date(dateString), { addSuffix: true })+ } catch {+ return 'Unknown'+ }+ }, [])return (- <div style={style} className="px-4 pb-2">- <Card className="h-[55px] hover:shadow-md transition-shadow duration-200 p-0">- <CardContent className="p-3 h-[55px] flex items-center gap-2 min-w-0">- {/* Source Node */}- <div className="flex items-center gap-2 flex-1 min-w-0">- <div className="flex items-center justify-center w-8 h-8 rounded-full bg-muted flex-shrink-0">- <SourceIcon className="h-4 w-4" />- </div>- <button onClick={handleNodeClik} className="font-medium text-sm hover:text-primary hover:underline cursor-pointer text-left max-w-full">- <span className="block truncate">- {node.data?.label ?? node.id}- </span>- </button>- <CopyButton content={node.data?.label ?? node.id} />+ <div className="px-4">+ <div className="grid items-center h-[56px] gap-3 text-sm border-b last:border-b-0"+ style={{+ gridTemplateColumns: "24px 32px 1fr 140px 160px 32px"+ }}+ >+ {/* Checkbox */}+ <div className="flex items-center">+ <Checkbox+ checked={isSelected}+ onCheckedChange={handleCheckboxChange}+ />+ </div>++ {/* Icon */}+ <div className="flex items-center justify-center">+ <div className="flex items-center justify-center w-6 h-6 rounded bg-muted">+ <SourceIcon className="h-4 w-4" /></div>- <div><Badge variant={"outline"}>{node.data.type}</Badge></div>- </CardContent>- </Card>+ </div>++ {/* Label */}+ <div className="min-w-0 flex justify-start grow">+ <button+ onClick={handleNodeClick}+ className="font-medium hover:text-primary hover:underline cursor-pointer p-0"+ >+ <span className="block truncate">+ {node.data?.label ?? node.id}+ </span>+ </button>+ </div>++ {/* Type */}+ <div>+ <Badge variant="outline" className="text-xs">+ {node.data?.type || 'Unknown'}+ </Badge>+ </div>++ {/* Created At */}+ <div className="flex items-center gap-1 text-xs text-muted-foreground min-w-0">+ <Calendar className="h-3 w-3" />+ <span className="truncate">+ {node.data?.created_at ? formatCreatedAt(node.data.created_at) : 'Unknown'}+ </span>+ </div>++ {/* Copy Button */}+ <div className="flex justify-end">+ <CopyButton content={node.data?.label ?? node.id} />+ </div>+ </div></div>);-}+})type NodesTableProps = {nodes: GraphNode[]@@ -71,40 +118,61 @@ export default function NodesTable({ nodes }: NodesTableProps) {const [selectedType, setSelectedType] = useState<string>("all");const parentRef = useRef<HTMLDivElement>(null);const setCurrentNode = useGraphStore(s => s.setCurrentNode)- // const setOpenNodeEditorModal = useGraphStore(s => s.setOpenNodeEditorModal)+ const selectedNodes = useGraphStore(s => s.selectedNodes)+ const setSelectedNodes = useGraphStore(s => s.setSelectedNodes)+ const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection)const onNodeClick = useCallback((node: GraphNode) => {setCurrentNode(node)- // setOpenNodeEditorModal(true)- }, [setCurrentNode,- // setOpenNodeEditorModal- ])-+ }, [setCurrentNode])// Filter nodes based on search and typeconst filteredNodes = useMemo(() => {if (!nodes) return [];return nodes.filter((node: GraphNode) => {- const matchesSearch = searchQuery === "" ||- node.data?.label?.toLowerCase().includes(searchQuery.toLowerCase()) ||- node.data?.label?.toLowerCase().includes(searchQuery.toLowerCase())+ const lower = searchQuery.toLowerCase();+ const label = node.data?.label?.toLowerCase() ?? "";+ const type = node.data?.type?.toLowerCase() ?? "";+ const matchesSearch = lower === "" || label.includes(lower) || type.includes(lower);- const matchesType = selectedType === "all" ||- node.data?.type === selectedType ||- node.data?.type === selectedType;+ const matchesType = selectedType === "all" || node.data?.type === selectedType;return matchesSearch && matchesType;});}, [nodes, searchQuery, selectedType]);+ const handleSelectAll = useCallback((checked: boolean) => {+ if (checked) {+ setSelectedNodes(filteredNodes)+ } else {+ setSelectedNodes([])+ }+ }, [setSelectedNodes, filteredNodes])++ const handleNodeSelectionChange = useCallback((node: GraphNode, checked: boolean) => {+ toggleNodeSelection(node, checked)+ }, [toggleNodeSelection])++ const isNodeSelected = useCallback((nodeId: string) => {+ return selectedNodes.some(node => node.id === nodeId)+ }, [selectedNodes])++ const isAllSelected = useMemo(() => {+ return filteredNodes.length > 0 && filteredNodes.every(node => isNodeSelected(node.id))+ }, [filteredNodes, isNodeSelected])++ const isIndeterminate = useMemo(() => {+ const selectedCount = filteredNodes.filter(node => isNodeSelected(node.id)).length+ return selectedCount > 0 && selectedCount < filteredNodes.length+ }, [filteredNodes, isNodeSelected])+// Get unique node types for filterconst nodeTypes = useMemo(() => {if (!nodes) return [];const types = new Set<string>();nodes.forEach((node: GraphNode) => {if (node.data?.type) types.add(node.data.type);- if (node.data?.type) types.add(node.data.type);});return Array.from(types).sort();}, [nodes]);@@ -131,7 +199,7 @@ export default function NodesTable({ nodes }: NodesTableProps) {}return (- <div className="w-full grow flex flex-col pt-18 space-y-4 p-4 px-6">+ <div className="w-full grow flex flex-col pt-18 p-4 px-6">{/* Header with stats */}<div className="flex items-center justify-between"><div className="space-y-1">@@ -147,7 +215,7 @@ export default function NodesTable({ nodes }: NodesTableProps) {</div>{/* Search and Filter */}- <div className="flex gap-4">+ <div className="flex gap-4 my-4"><div className="relative flex-1"><Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input@@ -172,11 +240,32 @@ export default function NodesTable({ nodes }: NodesTableProps) {</SelectContent></Select></div>+ {/* Table Header */}+ <div className="grid items-center h-[44px] px-4 bg-muted/50 p-2 rounded-t-lg border text-sm font-medium text-muted-foreground"+ style={{ gridTemplateColumns: "24px 32px 1fr 140px 160px 32px" }}+ >+ <div className="flex items-center">+ <Checkbox+ checked={isAllSelected}+ ref={(el) => {+ if (el && 'indeterminate' in el) {+ (el as HTMLInputElement).indeterminate = isIndeterminate+ }+ }}+ onCheckedChange={handleSelectAll}+ />+ </div>+ <div></div> {/* Icon */}+ <div className="text-center">Label</div>+ <div>Type</div>+ <div>Created</div>+ <div></div> {/* Actions */}+ </div>{/* Virtualized List */}<divref={parentRef}- className="grow overflow-auto py-4 rounded-lg border"+ className="grow overflow-auto rounded-b-lg border border-t-0"><divstyle={{@@ -184,16 +273,14 @@ export default function NodesTable({ nodes }: NodesTableProps) {width: '100%',position: 'relative',}}- className="space-y-2"+ className="">{virtualizer.getVirtualItems().map((virtualRow) => {const node = filteredNodes[virtualRow.index];return (- <NodeItem- key={virtualRow.index}- node={node}- onNodeClick={onNodeClick}+ <div+ key={node.id}style={{position: 'absolute',top: 0,@@ -202,7 +289,15 @@ export default function NodesTable({ nodes }: NodesTableProps) {height: `${virtualRow.size}px`,transform: `translateY(${virtualRow.start}px)`,}}- />+ className="hover:bg-muted/40"+ >+ <NodeItem+ node={node}+ onNodeClick={onNodeClick}+ isSelected={isNodeSelected(node.id)}+ onSelectionChange={handleNodeSelectionChange}+ />+ </div>);})}</div>diff --git a/flowsint-app/src/renderer/src/hooks/use-chat.ts b/flowsint-app/src/renderer/src/hooks/use-chat.tsindex fb4b496c..7c0b2423 100644--- a/flowsint-app/src/renderer/src/hooks/use-chat.ts+++ b/flowsint-app/src/renderer/src/hooks/use-chat.ts@@ -18,6 +18,7 @@ import type { Editor } from '@tiptap/react'import { useGraphStore } from '@/stores/graph-store';import { useChatState } from '@/stores/use-chat-store';import { useParams } from '@tanstack/react-router'+import { queryKeys } from '@/api/query-keys';const markdownToHtml = (markdown: string) => {return marked(markdown, {@@ -46,7 +47,7 @@ export const useChat = ({ onContentUpdate, onSuccess, editor }: UseChatOptions)// Fetch current chat data with messagesconst { data: currentChat, isLoading: isLoadingChat } = useQuery({- queryKey: ['chat', currentChatId],+ queryKey: queryKeys.chats.detail(currentChatId!),queryFn: () => chatCRUDService.getById(currentChatId!),enabled: !!currentChatId,refetchOnWindowFocus: false,@@ -65,7 +66,7 @@ export const useChat = ({ onContentUpdate, onSuccess, editor }: UseChatOptions)onSuccess: (data) => {// Add the new chat to the store// Invalidate chats query to refresh the list- queryClient.invalidateQueries({ queryKey: ['chat', currentChatId] })+ queryClient.invalidateQueries({ queryKey: queryKeys.chats.detail(currentChatId!) })setCurrentChatId(data.id)toast.success("New chat created successfully!")},@@ -84,7 +85,7 @@ export const useChat = ({ onContentUpdate, onSuccess, editor }: UseChatOptions)onSuccess: () => {// Remove the chat from the store// Invalidate chats query to refresh the list- queryClient.invalidateQueries({ queryKey: ['chats'] })+ queryClient.invalidateQueries({ queryKey: queryKeys.chats.list })toast.success("Chat deleted successfully!")},onError: (error) => {@@ -144,7 +145,7 @@ export const useChat = ({ onContentUpdate, onSuccess, editor }: UseChatOptions)// Invalidate the current chat query to refresh messagesif (currentChatId) {onContentUpdate("")- queryClient.invalidateQueries({ queryKey: ['chat', currentChatId] })+ queryClient.invalidateQueries({ queryKey: queryKeys.chats.detail(currentChatId) })}},onError: (error) => {diff --git a/flowsint-app/src/renderer/src/hooks/use-events.ts b/flowsint-app/src/renderer/src/hooks/use-events.tsindex d1d9d8e0..7c69a17d 100644--- a/flowsint-app/src/renderer/src/hooks/use-events.ts+++ b/flowsint-app/src/renderer/src/hooks/use-events.ts@@ -3,6 +3,7 @@ import { useQuery } from "@tanstack/react-query"import { logService } from "@/api/log-service"import { EventLevel } from "@/types"import { useGraphControls } from "@/stores/graph-controls-store"+import { queryKeys } from "@/api/query-keys"export function useEvents(sketch_id: string | undefined) {const [liveLogs, setLiveLogs] = useState<Event[]>([])@@ -10,7 +11,7 @@ export function useEvents(sketch_id: string | undefined) {const refetchGraph = useGraphControls((s) => s.refetchGraph)const { data: previousLogs = [], refetch } = useQuery({- queryKey: ["logs", sketch_id],+ queryKey: queryKeys.logs.bySketch(sketch_id as string),queryFn: () => logService.get(sketch_id as string),refetchOnWindowFocus: false,enabled: !!sketch_id,diff --git a/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts b/flowsint-app/src/renderer/src/hooks/use-launch-flow.tsindex 05649b03..196a6ece 100644--- a/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts+++ b/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts@@ -1,9 +1,27 @@import { toast } from "sonner"import { useConfirm } from "@/components/use-confirm-dialog"import { flowService } from "@/api/flow-service"+import { useMutation, useQueryClient } from "@tanstack/react-query"+import { queryKeys } from "@/api/query-keys"export function useLaunchFlow(askUser: boolean = false) {const { confirm } = useConfirm()+ const queryClient = useQueryClient()++ // Launch flow mutation+ const launchFlowMutation = useMutation({+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>+ flowService.launch(flowId, body),+ onSuccess: (data, variables) => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.flows.detail(variables.flowId)+ })+ },+ onError: (error) => {+ console.error("Error launching flow:", error)+ }+ })+const launchFlow = async (values: string[], flow_id: string, sketch_id: string | null | undefined) => {if (!sketch_id) return toast.error("Could not find the graph.")if (askUser) {@@ -16,13 +34,15 @@ export function useLaunchFlow(askUser: boolean = false) {const body = JSON.stringify({ values, sketch_id })const sliced = values.slice(0, 2)const left = values.length - sliced.length- toast.promise(flowService.launch(flow_id, body), {++ toast.promise(launchFlowMutation.mutateAsync({ flowId: flow_id, body }), {loading: "Loading...",success: () => `Flow ${flow_id} has been launched on "${sliced.join(",")}" ${left > 0 && ` and ${left} others`}.`,error: () => `An error occurred launching flow.`,})return}+return {launchFlow,}diff --git a/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts b/flowsint-app/src/renderer/src/hooks/use-launch-transform.tsindex 6152867c..1516058b 100644--- a/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts+++ b/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts@@ -1,6 +1,6 @@import { toast } from "sonner"import { useConfirm } from "@/components/use-confirm-dialog"-import { transformService } from "@/api/transfrom-service"+import { transformService } from "@/api/transform-service"export function useLaunchTransform(askUser: boolean = false) {const { confirm } = useConfirm()diff --git a/flowsint-app/src/renderer/src/lib/utils.ts b/flowsint-app/src/renderer/src/lib/utils.tsindex 8b2efbdd..f5c5644a 100644--- a/flowsint-app/src/renderer/src/lib/utils.ts+++ b/flowsint-app/src/renderer/src/lib/utils.ts@@ -197,8 +197,8 @@ export const getForceLayoutedElements = (}}-export const getDagreLayoutedElements = (nodes: GraphNode[],- edges: GraphEdge[],+export const getDagreLayoutedElements = (nodes: GraphNode[] | any,+ edges: GraphEdge[] | any,options: LayoutOptions = {direction: "TB",strength: -300,@@ -345,3 +345,30 @@ export const getAllNodeTypes = (actionItems: any[]) => {}export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0+++interface Dictionary {+ [Key: string]: any;+}++export function deepObjectDiff(obj1: Dictionary, obj2: Dictionary): Dictionary {+ let diffObject = {}+ // We want object 2 to be compared against object 1+ if (typeof obj1 != "object" || typeof obj2 != "object") throw Error("Items to compare mustr be objects.")+ // We map over the obj2 key:value duos to retrieve new keys that obj2 might have+ Object.entries(obj2).forEach(([key, value]) => {+ // We check for additional keys+ if (!obj1.hasOwnProperty(key))+ diffObject = { ...diffObject, [key]: { value, new: true } }+ else {+ diffObject = { ...diffObject, [key]: { value, new: false, oldValue: obj1[key] ?? null, newValue: obj2[key] ?? null, identical: obj2[key] === obj1[key] } }+ }+ })+ // We map over the obj1 key:value duos to retrieve new keys that might have disapeared+ Object.entries(obj1).forEach(([key, value]) => {+ // We check for additional keys+ if (!obj2.hasOwnProperty(key))+ diffObject = { ...diffObject, [key]: { value, removed: true } }+ })+ return diffObject+}\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsxindex 92a5bdf3..98703c05 100644--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx@@ -47,7 +47,7 @@ function FlowPage() {return (<div className="h-full w-full overflow-y-auto bg-background">- <div className="bg-gradient-to-r from-secondary/10 to-primary/10 border-b border-border z-10">+ <div className="border-b border-border z-10"><div className="max-w-7xl mx-auto p-8"><div className="flex items-center justify-between"><div className="space-y-1">diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsxindex 99d5fe56..5f86bd86 100644--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx@@ -1,6 +1,11 @@import { createFileRoute } from '@tanstack/react-router';import { InvestigationSkeleton } from '@/components/dashboard/investigation-skeleton';import { InvestigationCards } from '@/components/dashboard/investigation-cards';+import { SectionCards } from '@/components/dashboard/section-cards';+import { ChartAreaInteractive } from '@/components/dashboard/main-chart';+import NewInvestigation from '@/components/investigations/new-investigation';+import { Button } from '@/components/ui/button';+import { Plus } from 'lucide-react';// import { AnalysisCards } from '@/components/dashboard/analysis-cards';export const Route = createFileRoute('/_auth/dashboard/')({@@ -16,8 +21,29 @@ function DashboardPage() {{/* Main Content */}<div className="max-w-7xl mx-auto p-8 space-y-12" style={{ containerType: 'inline-size' }}>{/* Investigation Cards */}+ {/* <div className="flex flex-1 flex-col">+ <div className="@container/main px-6 flex flex-1 flex-col gap-2">+ <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <h2 className="text-2xl font-semibold">Welcome back</h2>+ </div>+ <NewInvestigation noDropDown>+ <Button size="sm">+ <Plus className="w-4 h-4 mr-2" />+ New Investigation+ </Button>+ </NewInvestigation>+ </div>+ <SectionCards />+ <div>+ <ChartAreaInteractive />+ </div>+ </div>+ </div>+ </div> */}<InvestigationCards />-+{/* Analysis Cards */}{/* <AnalysisCards /> */}</div>diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsxindex 3b3fb245..bfbed119 100644--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx@@ -1,4 +1,4 @@-import { createFileRoute, useLoaderData } from '@tanstack/react-router'+import { createFileRoute, Link, useLoaderData } from '@tanstack/react-router'import GraphPanel from '@/components/graphs'import { sketchService } from '@/api/sketch-service'import { useQuery } from '@tanstack/react-query'@@ -124,14 +124,14 @@ export const Route = createFileRoute('/_auth/dashboard/investigations/$investiga</svg>Reload Page</button>-- <button- onClick={() => window.history.back()}- className="w-full bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground- px-4 py-2 rounded-md font-medium transition-colors"+ <Link+ to="/dashboard">- Go Back- </button>+ <button className="w-full bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground px-4 py-2 rounded-md font-medium transition-colors"+ >+ Go home+ </button>+ </Link></div><div className="mt-6 pt-4 border-t">diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsxindex fafefb66..0b3ba383 100644--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx@@ -5,10 +5,17 @@ import { Button } from '@/components/ui/button'import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'import { Badge } from '@/components/ui/badge'import { Separator } from '@/components/ui/separator'-import { Plus, Calendar, User, FileText, BarChart3, Clock, ArrowRight } from 'lucide-react'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import { Plus, Calendar, User, FileText, BarChart3, Clock, ChevronDown } from 'lucide-react'import { useMutation, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'import { formatDistanceToNow } from 'date-fns'+import NewSketch from '@/components/graphs/new-sketch'function InvestigationSkeleton() {return (@@ -80,10 +87,10 @@ function InvestigationPage() {// Navigate to the new analysis pagenavigate({to: "/dashboard/investigations/$investigationId/$type/$id",- params: {- investigationId: investigation.id,- type: "analysis",- id: data.id+ params: {+ investigationId: investigation.id,+ type: "analysis",+ id: data.id}})},@@ -109,17 +116,37 @@ function InvestigationPage() {</p></div><div className="flex items-center gap-3">- <Button- onClick={() => createAnalysisMutation.mutate()}- disabled={createAnalysisMutation.isPending}- className="gap-2"- >- <Plus className="h-4 w-4" />- New Analysis- </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <div>+ <Button className="gap-2" disabled={createAnalysisMutation.isPending}>+ New+ <ChevronDown className="h-4 w-4" />+ </Button>+ </div>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onClick={() => createAnalysisMutation.mutate()}+ disabled={createAnalysisMutation.isPending}+ >+ <FileText className="h-4 w-4 mr-2" />+ New Analysis+ {createAnalysisMutation.isPending && (+ <span className="ml-2 text-xs text-muted-foreground">Creating...</span>+ )}+ </DropdownMenuItem>+ <NewSketch>+ <DropdownMenuItem onSelect={(e) => e.preventDefault()}>+ <BarChart3 className="h-4 w-4 mr-2" />+ New Sketch+ </DropdownMenuItem>+ </NewSketch>+ </DropdownMenuContent>+ </DropdownMenu></div></div>-+<div className="flex items-center gap-6 text-sm text-muted-foreground"><div className="flex items-center gap-2"><Calendar className="h-4 w-4" />@@ -153,7 +180,7 @@ function InvestigationPage() {</p></CardContent></Card>-+<Card><CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"><CardTitle className="text-sm font-medium">Total Analyses</CardTitle>@@ -166,7 +193,7 @@ function InvestigationPage() {</p></CardContent></Card>-+<Card><CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"><CardTitle className="text-sm font-medium">Last Activity</CardTitle>@@ -193,20 +220,8 @@ function InvestigationPage() {<h2 className="text-xl font-semibold">Sketches</h2><Badge variant="outline" className="ml-2">{sketchCount}</Badge></div>- <Button- variant="outline"- size="sm"- onClick={() => navigate({- to: "/dashboard/investigations/$investigationId",- params: { investigationId: investigation.id }- })}- className="gap-2"- >- View All- <ArrowRight className="h-4 w-4" />- </Button></div>-+{sketchCount === 0 ? (<Card className="border-dashed"><CardContent className="flex flex-col items-center justify-center py-8">@@ -215,54 +230,33 @@ function InvestigationPage() {<p className="text-muted-foreground mb-4 text-center max-w-md">Create your first sketch to start visualizing your investigation data and building relationships between entities.</p>- <Button- variant="outline"- onClick={() => navigate({- to: "/dashboard/investigations/$investigationId",- params: { investigationId: investigation.id }- })}- className="gap-2"- >- <Plus className="h-4 w-4" />- Create Sketch- </Button>+</CardContent></Card>) : (<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">{investigation.sketches?.slice(0, 8).map((sketch: any) => (- <Card- key={sketch.id}- className="group py-2 relative overflow-hidden cursor-pointer transition-all duration-300 hover:scale-[1.02] hover:shadow-xl border-0 bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/30 dark:to-indigo-950/20 hover:from-blue-100 hover:to-indigo-200 dark:hover:from-blue-900/40 dark:hover:to-indigo-900/30"+ <Card+ key={sketch.id}+ className="group py-2 relative overflow-hidden cursor-pointer border-2 border-border hover:border-primary bg-primary/10"onClick={() => navigate({to: "/dashboard/investigations/$investigationId/$type/$id",- params: {- investigationId: investigation.id,+ params: {+ investigationId: investigation.id,type: "graph",- id: sketch.id+ id: sketch.id}})}>- <div className="absolute inset-0 bg-gradient-to-r from-blue-500/10 to-indigo-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300" /><CardContent className="p-6 relative">- <div className="flex items-start justify-between mb-4">- <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg">- <BarChart3 className="h-5 w-5 text-white" />- </div>- <Badge variant="secondary" className="text-xs font-medium bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm">- {sketch.status || "active"}- </Badge>- </div>-<div className="space-y-3">- <h4 className="font-semibold text-gray-900 dark:text-gray-100 line-clamp-1 group-hover:text-blue-700 dark:group-hover:text-blue-300 transition-colors">+ <h4 className="font-semibold line-clamp-1 group-hover:text-primary transition-colors">{sketch.title}</h4>- <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2 leading-relaxed">+ <p className="text-sm text-muted-foreground line-clamp-2 leading-relaxed">{sketch.description || "No description provided"}</p></div>-<div className="mt-4 pt-4 border-t border-blue-200/50 dark:border-blue-800/30"><div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"><span className="flex items-center gap-1">@@ -287,20 +281,8 @@ function InvestigationPage() {<h2 className="text-xl font-semibold">Analyses</h2><Badge variant="outline" className="ml-2">{analysisCount}</Badge></div>- <Button- variant="outline"- size="sm"- onClick={() => navigate({- to: "/dashboard/investigations/$investigationId",- params: { investigationId: investigation.id }- })}- className="gap-2"- >- View All- <ArrowRight className="h-4 w-4" />- </Button></div>-+{analysisCount === 0 ? (<Card className="border-dashed"><CardContent className="flex flex-col items-center justify-center py-8">@@ -315,36 +297,26 @@ function InvestigationPage() {className="gap-2"><Plus className="h-4 w-4" />- Create Analysis+ Create analysis</Button></CardContent></Card>) : (<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">{investigation.analyses?.slice(0, 8).map((analysis: any) => (- <Card- key={analysis.id}- className="group py-2 relative overflow-hidden cursor-pointer transition-all duration-300 hover:scale-[1.02] hover:shadow-xl border-0 bg-gradient-to-br from-emerald-50 to-teal-100 dark:from-emerald-950/30 dark:to-teal-950/20 hover:from-emerald-100 hover:to-teal-200 dark:hover:from-emerald-900/40 dark:hover:to-teal-900/30"+ <Card+ key={analysis.id}+ className="group py-2 relative overflow-hidden cursor-pointer hover:shadow-xl border-2 border-border hover:border-secondary bg-secondary/10"onClick={() => navigate({to: "/dashboard/investigations/$investigationId/$type/$id",- params: {- investigationId: investigation.id,+ params: {+ investigationId: investigation.id,type: "analysis",- id: analysis.id+ id: analysis.id}})}>- <div className="absolute inset-0 bg-gradient-to-r from-emerald-500/10 to-teal-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300" /><CardContent className="p-6 relative">- <div className="flex items-start justify-between mb-4">- <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center shadow-lg">- <FileText className="h-5 w-5 text-white" />- </div>- <Badge variant="secondary" className="text-xs font-medium bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm">- Analysis- </Badge>- </div>-<div className="space-y-3"><h4 className="font-semibold text-gray-900 dark:text-gray-100 line-clamp-1 group-hover:text-emerald-700 dark:group-hover:text-emerald-300 transition-colors">{analysis.title}@@ -353,7 +325,7 @@ function InvestigationPage() {{analysis.description || "No description provided"}</p></div>-+<div className="mt-4 pt-4 border-t border-emerald-200/50 dark:border-emerald-800/30"><div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"><span className="flex items-center gap-1">diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsxindex 65d2d572..c5f7a445 100644--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx@@ -14,6 +14,7 @@ import { toast } from 'sonner'import { useConfirm } from '../components/use-confirm-dialog'import Loader from '@/components/loader'import { type Key as KeyType } from '@/types/key'+import { queryKeys } from '@/api/query-keys'export const Route = createFileRoute('/_auth/dashboard/vault')({component: VaultPage,})@@ -27,7 +28,7 @@ function VaultPage() {// Fetch keysconst { data: keys = [], isLoading: keysLoading } = useQuery<KeyType[]>({- queryKey: ['keys'],+ queryKey: queryKeys.keys.list,queryFn: () => KeyService.get(),})@@ -35,7 +36,7 @@ function VaultPage() {const createKeyMutation = useMutation({mutationFn: KeyService.create,onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['keys'] })+ queryClient.invalidateQueries({ queryKey: queryKeys.keys.list })setIsAddDialogOpen(false)setKeyName('')setApiKey('')@@ -51,7 +52,7 @@ function VaultPage() {const deleteKeyMutation = useMutation({mutationFn: KeyService.deleteById,onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['keys'] })+ queryClient.invalidateQueries({ queryKey: queryKeys.keys.list })toast.success('API key deleted successfully!')},onError: (error) => {diff --git a/flowsint-app/src/renderer/src/stores/graph-general-store.ts b/flowsint-app/src/renderer/src/stores/graph-general-store.tsdeleted file mode 100644index 96e6af5e..00000000--- a/flowsint-app/src/renderer/src/stores/graph-general-store.ts+++ /dev/null@@ -1,47 +0,0 @@-import { type Settings } from '@/types';-import { create } from 'zustand';-import { persist } from 'zustand/middleware';--const DEFAULT_SETTINGS = {- prefferedNodesView: {- value: "force",- options: ["table", "hierarchy", "force", "relationships"],- description: "Preferred display for the entities."- }-}--type GraphGeneralSettingsStore = {- // Settings state- settings: Settings- updateSetting: (key: string, val: any) => void- // UI State- settingsModalOpen: boolean- setSettingsModalOpen: (open: boolean) => void- keyboardShortcutsOpen: boolean- setKeyboardShortcutsOpen: (open: boolean) => void-};--export const useGraphGeneralSettingsStore = create<GraphGeneralSettingsStore>()(- persist((set) => ({- settingsModalOpen: false,- setSettingsModalOpen: (open) => set({ settingsModalOpen: open }),- keyboardShortcutsOpen: false,- setKeyboardShortcutsOpen: (open) => set({ keyboardShortcutsOpen: open }),- settings: DEFAULT_SETTINGS,- updateSetting: (key, val) => set((state) => ({- settings: {- ...state.settings,- [key]: {- ...state.settings[key],- value: val- },- },- })),- }),- {- name: 'graph-general-storage',- partialize: (state) => ({- settings: state.settings,- }),- }- ));diff --git a/flowsint-app/src/renderer/src/stores/graph-settings-store.ts b/flowsint-app/src/renderer/src/stores/graph-settings-store.tsindex 4dcd00da..058e77d9 100644--- a/flowsint-app/src/renderer/src/stores/graph-settings-store.ts+++ b/flowsint-app/src/renderer/src/stores/graph-settings-store.ts@@ -1,195 +1,319 @@-import { type Settings } from '@/types';import { create } from 'zustand';import { persist } from 'zustand/middleware';+// Centralized default settings organized by categoriesconst DEFAULT_SETTINGS = {- nodeSize: {- value: 14,- min: 1,- max: 100,- step: .1,- description: "Defined the width of the link between two nodes."- },- linkWidth: {- value: 2,- min: 1,- max: 10,- step: .1,- description: "Defined the width of the link between two nodes."- },- dagLevelDistance: {- value: 50,- min: 0,- max: 100,- step: 1,- description: "Distance between different graph depths when using DAG (directed acyclic graph) layout mode"- },- linkDirectionalArrowRelPos: {- value: 1,- min: 0,- max: 1,- step: 0.01,- description: "Position of directional arrows along the link line (0 = source node, 1 = target node, 0.5 = middle)"- },- linkDirectionalArrowLength: {- value: 3,- min: 1,- max: 100,- step: 0.1,- description: "Length of the arrow heads that indicate link direction"- },- linkDirectionalParticleSpeed: {- value: 0.005,- min: 0,- max: 0.05,- step: 0.001,- description: "Speed of moving particles along links (higher = faster movement)"+ information: {+},- cooldownTicks: {- value: 200,- min: 50,- max: 1000,- step: 10,- description: "Number of simulation frames to render before stopping and freezing the layout"+ general: {+ showMinimap: {+ type: "boolean",+ value: true,+ description: "Display the MiniMap on the graph panel."+ },+ graphViewerThreshold: {+ type: "number",+ value: 1500,+ min: 10,+ max: 20000,+ step: 5,+ description: "Threshold to switch from general graph to less interactive but more performant) viewer."+ },},- cooldownTime: {- value: 15000,- min: 1000,- max: 60000,- step: 1000,- description: "Maximum time in milliseconds to run the simulation before stopping (15000 = 15 seconds)"++ graph: {+ nodeSize: {+ type: "number",+ value: 14,+ min: 1,+ max: 100,+ step: 0.1,+ description: "Defines the width of the link between two nodes."+ },+ linkWidth: {+ type: "number",+ value: 2,+ min: 1,+ max: 10,+ step: 0.1,+ description: "Defines the width of the link between two nodes."+ },+ dagLevelDistance: {+ type: "number",+ value: 50,+ min: 0,+ max: 100,+ step: 1,+ description: "Distance between different graph depths when using DAG (directed acyclic graph) layout mode"+ },+ linkDirectionalArrowRelPos: {+ type: "number",+ value: 1,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Position of directional arrows along the link line (0 = source node, 1 = target node, 0.5 = middle)"+ },+ linkDirectionalArrowLength: {+ type: "number",+ value: 3,+ min: 1,+ max: 100,+ step: 0.1,+ description: "Length of the arrow heads that indicate link direction"+ },+ linkDirectionalParticleSpeed: {+ type: "number",+ value: 0.005,+ min: 0,+ max: 0.05,+ step: 0.001,+ description: "Speed of moving particles along links (higher = faster movement)"+ },+ cooldownTicks: {+ type: "number",+ value: 200,+ min: 50,+ max: 1000,+ step: 10,+ description: "Number of simulation frames to render before stopping and freezing the layout"+ },+ cooldownTime: {+ type: "number",+ value: 15000,+ min: 1000,+ max: 60000,+ step: 1000,+ description: "Maximum time in milliseconds to run the simulation before stopping (15000 = 15 seconds)"+ },+ d3AlphaDecay: {+ type: "number",+ value: 0.045,+ min: 0,+ max: 0.3,+ step: 0.005,+ description: "Rate at which the simulation intensity decays (higher = faster convergence, lower = longer simulation)"+ },+ d3AlphaMin: {+ type: "number",+ value: 0,+ min: 0,+ max: 0.1,+ step: 0.001,+ description: "Minimum simulation intensity threshold - simulation stops when reaching this value"+ },+ d3VelocityDecay: {+ type: "number",+ value: 0.41,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Velocity decay factor that simulates friction/resistance (higher = more damping, nodes slow down faster)"+ },+ warmupTicks: {+ type: "number",+ value: 0,+ min: 0,+ max: 100,+ step: 1,+ description: "Number of simulation cycles to run in background before starting to render (improves initial layout)"+ }},- d3AlphaDecay: {- value: 0.045,- min: 0,- max: 0.3,- step: 0.005,- description: "Rate at which the simulation intensity decays (higher = faster convergence, lower = longer simulation)"+};++// Force Presets+const FORCE_PRESETS = {+ 'Tight Clusters': {+ d3AlphaDecay: 0.1,+ d3VelocityDecay: 0.8,+ cooldownTicks: 300,+ cooldownTime: 20000},- d3AlphaMin: {- value: 0,- min: 0,- max: 0.1,- step: 0.001,- description: "Minimum simulation intensity threshold - simulation stops when reaching this value"+ 'Compact Network': {+ d3AlphaDecay: 0.08,+ d3VelocityDecay: 0.7,+ cooldownTicks: 250,+ cooldownTime: 18000},- d3VelocityDecay: {- value: 0.41,- min: 0,- max: 1,- step: 0.01,- description: "Velocity decay factor that simulates friction/resistance (higher = more damping, nodes slow down faster)"+ 'Balanced Layout': {+ d3AlphaDecay: 0.06,+ d3VelocityDecay: 0.6,+ cooldownTicks: 200,+ cooldownTime: 15000},- warmupTicks: {- value: 0,- min: 0,- max: 100,- step: 1,- description: "Number of simulation cycles to run in background before starting to render (improves initial layout)"+ 'Loose Organic': {+ d3AlphaDecay: 0.04,+ d3VelocityDecay: 0.4,+ cooldownTicks: 150,+ cooldownTime: 12000},+ 'High Energy': {+ d3AlphaDecay: 0.02,+ d3VelocityDecay: 0.3,+ cooldownTicks: 100,+ cooldownTime: 10000+ }+};-}--type GraphSettingsStore = {+type GraphGeneralSettingsStore = {// Settings state- settings: Settings- updateSetting: (key: string, val: number) => void- // UI State- settingsModalOpen: boolean- setSettingsModalOpen: (open: boolean) => void+ settings: typeof DEFAULT_SETTINGS+ forceSettings: any+ updateSetting: (category: string, key: string, value: any) => voidresetSettings: () => void- getSettings: () => any+ getSettings: () => Record<string, any>+ getCategorySettings: (category: string) => Record<string, any>+// Force PresetscurrentPreset: string | nullapplyPreset: (presetName: string) => voidgetPresets: () => Record<string, any>++ // UI State+ settingsModalOpen: boolean+ setSettingsModalOpen: (open: boolean) => void+ keyboardShortcutsOpen: boolean+ setKeyboardShortcutsOpen: (open: boolean) => void++ // Helper methods+ getSettingValue: (category: string, key: string) => any+ getSettingType: (category: string, key: string) => string | undefined+ getSettingOptions: (category: string, key: string) => { value: string; label: string }[] | undefined+ getSettingDescription: (category: string, key: string) => string | undefined+ getSettingConstraints: (category: string, key: string) => { min?: number; max?: number; step?: number } | undefined};-export const useGraphSettingsStore = create<GraphSettingsStore>()(++export const useGraphSettingsStore = create<GraphGeneralSettingsStore>()(persist((set, get) => ({- settingsModalOpen: false,+ // Settings statesettings: DEFAULT_SETTINGS,currentPreset: null,- setSettingsModalOpen: (open) => set({ settingsModalOpen: open }),- updateSetting: (key, val) => set((state) => ({- settings: {+ forceSettings: DEFAULT_SETTINGS.graph,+ // UI State+ settingsModalOpen: false,+ keyboardShortcutsOpen: false,++ // Core methods+ updateSetting: (category, key, value) => set((state) => {+ const newSettings = {...state.settings,- [key]: {- ...state.settings[key],- value: val+ [category]: {+ ...state.settings[category],+ [key]: {+ ...state.settings[category][key],+ value: value+ },},- },- currentPreset: null, // Clear preset when manually changing settings- })),- getSettings: () => {- let flatSettings = {}- Object.keys(get().settings).map((key) => {- flatSettings[key] = get().settings[key].value- })- return flatSettings- },- resetSettings: () => set({ settings: DEFAULT_SETTINGS, currentPreset: null }),-- // Force Presets Implementation- getPresets: () => ({- 'Tight Clusters': {- d3AlphaDecay: 0.1,- d3VelocityDecay: 0.8,- cooldownTicks: 300,- cooldownTime: 20000- },- 'Compact Network': {- d3AlphaDecay: 0.08,- d3VelocityDecay: 0.7,- cooldownTicks: 250,- cooldownTime: 18000- },- 'Balanced Layout': {- d3AlphaDecay: 0.06,- d3VelocityDecay: 0.6,- cooldownTicks: 200,- cooldownTime: 15000- },- 'Loose Organic': {- d3AlphaDecay: 0.04,- d3VelocityDecay: 0.4,- cooldownTicks: 150,- cooldownTime: 12000- },- 'High Energy': {- d3AlphaDecay: 0.02,- d3VelocityDecay: 0.3,- cooldownTicks: 100,- cooldownTime: 10000+ };++ // Also update forceSettings if we're updating a force setting+ let newForceSettings = state.forceSettings;+ if (category === 'force') {+ newForceSettings = {+ ...state.forceSettings,+ [key]: {+ ...state.forceSettings[key],+ value: value+ }+ };}++ return {+ settings: newSettings,+ forceSettings: newForceSettings,+ currentPreset: null, // Clear preset when manually changing settings+ };+ }),++ resetSettings: () => set({+ settings: DEFAULT_SETTINGS,+ forceSettings: DEFAULT_SETTINGS.graph,+ currentPreset: null}),+ getSettings: () => {+ const flatSettings: Record<string, any> = {};+ Object.entries(get().settings).forEach(([category, categorySettings]) => {+ Object.entries(categorySettings as Record<string, any>).forEach(([key, setting]) => {+ flatSettings[`${category}.${key}`] = (setting as any).value;+ });+ });+ return flatSettings;+ },++ getCategorySettings: (category: string) => {+ const categorySettings: Record<string, any> = {};+ const settings = get().settings[category];+ if (settings) {+ Object.entries(settings as Record<string, any>).forEach(([key, setting]) => {+ categorySettings[key] = (setting as any).value;+ });+ }+ return categorySettings;+ },++ // Force Presets+ getPresets: () => FORCE_PRESETS,+applyPreset: (presetName: string) => {- const presets = get().getPresets();- const preset = presets[presetName];+ const preset = FORCE_PRESETS[presetName as keyof typeof FORCE_PRESETS];if (!preset) return;set((state) => {const newSettings = { ...state.settings };+ const newForceSettings = { ...state.forceSettings };+Object.entries(preset).forEach(([key, value]) => {- if (newSettings[key]) {- newSettings[key] = {- ...newSettings[key],- value: value as number+ if (newSettings.graph[key]) {+ newSettings.graph[key] = {+ ...newSettings.graph[key],+ value: value+ };+ }+ if (newForceSettings[key]) {+ newForceSettings[key] = {+ ...newForceSettings[key],+ value: value};}});+return {settings: newSettings,+ forceSettings: newForceSettings,currentPreset: presetName};});+ },++ // UI State methods+ setSettingsModalOpen: (open) => set({ settingsModalOpen: open }),+ setKeyboardShortcutsOpen: (open) => set({ keyboardShortcutsOpen: open }),++ // Helper methods+ getSettingValue: (category: string, key: string) => get().settings[category]?.[key]?.value,+ getSettingType: (category: string, key: string) => get().settings[category]?.[key]?.type,+ getSettingOptions: (category: string, key: string) => get().settings[category]?.[key]?.options,+ getSettingDescription: (category: string, key: string) => get().settings[category]?.[key]?.description,+ getSettingConstraints: (category: string, key: string) => {+ const setting = get().settings[category]?.[key];+ if (setting && 'min' in setting) {+ return {+ min: setting.min,+ max: setting.max,+ step: setting.step+ };+ }+ return undefined;}}),{- name: 'graph-controls-storage',+ name: 'graph-settings-storage',partialize: (state) => ({settings: state.settings,- currentPreset: state.currentPreset+ forceSettings: state.forceSettings,+ currentPreset: state.currentPreset,}),}));diff --git a/flowsint-app/src/renderer/src/stores/graph-store.ts b/flowsint-app/src/renderer/src/stores/graph-store.tsindex a24d1a81..f27d7324 100644--- a/flowsint-app/src/renderer/src/stores/graph-store.ts+++ b/flowsint-app/src/renderer/src/stores/graph-store.ts@@ -44,10 +44,12 @@ interface GraphState {openMainDialog: booleanopenFormDialog: booleanopenAddRelationDialog: boolean+ openMergeDialog: booleanopenNodeEditorModal: booleansetOpenMainDialog: (open: boolean) => voidsetOpenFormDialog: (open: boolean) => voidsetOpenAddRelationDialog: (open: boolean) => void+ setOpenMergeDialog: (open: boolean) => voidsetOpenNodeEditorModal: (open: boolean) => void// === Action Type for Form ===@@ -235,10 +237,12 @@ export const useGraphStore = create<GraphState>()(openMainDialog: false,openFormDialog: false,openAddRelationDialog: false,+ openMergeDialog: false,openNodeEditorModal: false,setOpenMainDialog: (open) => set({ openMainDialog: open }),setOpenFormDialog: (open) => set({ openFormDialog: open }),setOpenAddRelationDialog: (open) => set({ openAddRelationDialog: open }),+ setOpenMergeDialog: (open) => set({ openMergeDialog: open }),setOpenNodeEditorModal: (open) => set({ openNodeEditorModal: open }),// === Action Type for Edit form ===diff --git a/flowsint-app/src/renderer/src/types/graph.ts b/flowsint-app/src/renderer/src/types/graph.tsindex b36a8a50..b012ab54 100644--- a/flowsint-app/src/renderer/src/types/graph.ts+++ b/flowsint-app/src/renderer/src/types/graph.ts@@ -50,6 +50,17 @@ export type GeneralSetting = {description?: string,}+// Extended setting types for the centralized store+export type ExtendedSetting = {+ value: any,+ type: string,+ min?: number,+ max?: number,+ step?: number,+ options?: { value: string; label: string }[]+ description?: string,+}+export type Settings = {- [key: string]: ForceGraphSetting | GeneralSetting,+ [key: string]: ExtendedSetting,}diff --git a/flowsint-app/src/renderer/src/types/transform.ts b/flowsint-app/src/renderer/src/types/transform.tsindex 5c63d63f..1e2470fd 100644--- a/flowsint-app/src/renderer/src/types/transform.ts+++ b/flowsint-app/src/renderer/src/types/transform.ts@@ -1,11 +1,3 @@-import type { Edge, Node } from "@xyflow/react";-import type { NodeData, EdgeData } from "./graph";-import type { Profile } from "./profile";--// ================================-// SCANNER TYPE DEFINITIONS-// ================================-export interface ScannerProperty {name: stringtype: stringdiff --git a/flowsint-app/yarn.lock b/flowsint-app/yarn.lockindex f6053f3d..dcb60f05 100644--- a/flowsint-app/yarn.lock+++ b/flowsint-app/yarn.lock@@ -941,6 +941,11 @@resolved "https://registry.yarnpkg.com/@juggle/resize-observer/-/resize-observer-3.4.0.tgz#08d6c5e20cf7e4cc02fd181c4b0c225cd31dbb60"integrity sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==+"@lukemorales/query-key-factory@^1.3.4":+ version "1.3.4"+ resolved "https://registry.yarnpkg.com/@lukemorales/query-key-factory/-/query-key-factory-1.3.4.tgz#d14001dbd781b024df93ca73bd785db590924486"+ integrity sha512-A3frRDdkmaNNQi6mxIshsDk4chRXWoXa05US8fBo4kci/H+lVmujS6QrwQLLGIkNIRFGjMqp2uKjC4XsLdydRw==+"@malept/cross-spawn-promise@^2.0.0":version "2.0.0"resolved "https://registry.yarnpkg.com/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz#d0772de1aa680a0bfb9ba2f32b4c828c7857cb9d"diff --git a/flowsint-core/poetry.lock b/flowsint-core/poetry.lockindex e56a903f..0cb2523e 100644--- a/flowsint-core/poetry.lock+++ b/flowsint-core/poetry.lock@@ -1197,25 +1197,26 @@ wmi = ["wmi (>=1.5.1)"][[package]]name = "docker"-version = "6.1.3"+version = "7.1.0"description = "A Python library for the Docker Engine API."optional = false-python-versions = ">=3.7"+python-versions = ">=3.8"groups = ["main"]files = [- {file = "docker-6.1.3-py3-none-any.whl", hash = "sha256:aecd2277b8bf8e506e484f6ab7aec39abe0038e29fa4a6d3ba86c3fe01844ed9"},- {file = "docker-6.1.3.tar.gz", hash = "sha256:aa6d17830045ba5ef0168d5eaa34d37beeb113948c413affe1d5991fc11f9a20"},+ {file = "docker-7.1.0-py3-none-any.whl", hash = "sha256:c96b93b7f0a746f9e77d325bcfb87422a3d8bd4f03136ae8a85b37f1898d5fc0"},+ {file = "docker-7.1.0.tar.gz", hash = "sha256:ad8c70e6e3f8926cb8a92619b832b4ea5299e2831c14284663184e200546fa6c"},][package.dependencies]-packaging = ">=14.0"pywin32 = {version = ">=304", markers = "sys_platform == \"win32\""}requests = ">=2.26.0"urllib3 = ">=1.26.0"-websocket-client = ">=0.32.0"[package.extras]+dev = ["coverage (==7.2.7)", "pytest (==7.4.2)", "pytest-cov (==4.1.0)", "pytest-timeout (==2.1.0)", "ruff (==0.1.8)"]+docs = ["myst-parser (==0.18.0)", "sphinx (==5.1.1)"]ssh = ["paramiko (>=2.4.3)"]+websockets = ["websocket-client (>=1.3.0)"][[package]]name = "ecdsa"@@ -1355,7 +1356,6 @@ develop = true[package.dependencies]dnspython = "^2.4"-docker = "^6.1"flowsint-core = {path = "../flowsint-core", develop = true}flowsint-types = {path = "../flowsint-types", develop = true}hibpwned = "^1.3.9"@@ -5417,23 +5417,6 @@ files = [{file = "webencodings-0.5.1.tar.gz", hash = "sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923"},]-[[package]]-name = "websocket-client"-version = "1.8.0"-description = "WebSocket client for Python with low level API options"-optional = false-python-versions = ">=3.8"-groups = ["main"]-files = [- {file = "websocket_client-1.8.0-py3-none-any.whl", hash = "sha256:17b44cc997f5c498e809b22cdf2d9c7a9e71c02c8cc2b6c56e7c2d1239bfa526"},- {file = "websocket_client-1.8.0.tar.gz", hash = "sha256:3239df9f44da632f96012472805d40a23281a991027ce11d2f45a6f24ac4c3da"},-]--[package.extras]-docs = ["Sphinx (>=6.0)", "myst-parser (>=2.0.0)", "sphinx-rtd-theme (>=1.1.0)"]-optional = ["python-socks", "wsaccel"]-test = ["websockets"]-[[package]]name = "werkzeug"version = "3.1.3"@@ -5707,4 +5690,4 @@ propcache = ">=0.2.1"[metadata]lock-version = "2.1"python-versions = ">=3.11,<3.13"-content-hash = "7dd54a3fc322bf1906c6ba2c4a50de7d3ae70b40976c4e2a5c9bc085e7de3a58"+content-hash = "481c8b5a48b2d2b3a0e94c4078b7998597f787294de986eca9bed0ece0778e9e"diff --git a/flowsint-core/pyproject.toml b/flowsint-core/pyproject.tomlindex ad7fce9e..10662a42 100644--- a/flowsint-core/pyproject.toml+++ b/flowsint-core/pyproject.toml@@ -24,6 +24,7 @@ sse-starlette = "^1.8"alembic = "1.13.0"phonenumbers = "^9.0.8"python-multipart = "^0.0.20"+docker = "^7.1.0"[tool.poetry.group.dev.dependencies]pytest = "^7.4"diff --git a/flowsint-core/src/flowsint_core/core/orchestrator.py b/flowsint-core/src/flowsint_core/core/orchestrator.pyindex 60550cc4..46081833 100644--- a/flowsint-core/src/flowsint_core/core/orchestrator.py+++ b/flowsint-core/src/flowsint_core/core/orchestrator.py@@ -12,7 +12,7 @@ import jsonimport os-class TransformOrchestrator(Scanner):+class FlowOrchestrator(Scanner):"""Orchestrator for running a list of scanners."""diff --git a/flowsint-core/src/flowsint_core/tasks/flow.py b/flowsint-core/src/flowsint_core/tasks/flow.pyindex a81b4052..f4bd6d76 100644--- a/flowsint-core/src/flowsint_core/tasks/flow.py+++ b/flowsint-core/src/flowsint_core/tasks/flow.py@@ -4,7 +4,7 @@ from dotenv import load_dotenvfrom typing import List, Optionalfrom celery import statesfrom ..core.celery import celery-from ..core.orchestrator import TransformOrchestrator+from ..core.orchestrator import FlowOrchestratorfrom ..core.postgre_db import SessionLocal, get_dbfrom ..core.graph_db import Neo4jConnectionfrom ..core.vault import Vault@@ -62,7 +62,7 @@ def run_flow()transform_branches = [FlowBranch(**branch) for branch in transform_branches]- scanner = TransformOrchestrator(+ scanner = FlowOrchestrator(sketch_id=sketch_id,scan_id=str(scan_id),transform_branches=transform_branches,diff --git a/flowsint-core/src/flowsint_core/tests/orchestrator.py b/flowsint-core/src/flowsint_core/tests/orchestrator.pyindex 7d0809a5..3c851684 100644--- a/flowsint-core/src/flowsint_core/tests/orchestrator.py+++ b/flowsint-core/src/flowsint_core/tests/orchestrator.py@@ -1,4 +1,4 @@-from flowsint_core.core.orchestrator import TransformOrchestrator+from flowsint_core.core.orchestrator import FlowOrchestratorfrom flowsint_types.domain import Domain, Domainfrom flowsint_types.whois import Whois@@ -6,7 +6,7 @@ import pytestdef test_preprocess_valid_domains():- scanner = TransformOrchestrator(+ scanner = FlowOrchestrator("123", transform_names=["domain_resolve_scanner", "domain_whois_scanner"])assert isinstance(scanner.scanners, list)@@ -17,14 +17,14 @@ def test_preprocess_valid_domains():with pytest.raises(ValueError, match="Scanner 'this_scan_is_wrong' not found in registry"):- TransformOrchestrator(+ FlowOrchestrator("123", transform_names=["domain_resolve_scanner", "this_scan_is_wrong"])def test_execute_domain_subdomains_scanner():domains = ["example.com"]- scanner = TransformOrchestrator("123", transform_names=["domain_subdomains_scanner"])+ scanner = FlowOrchestrator("123", transform_names=["domain_subdomains_scanner"])results = scanner.execute(values=domains)assert results["initial_values"] == domainsassert results["scanners"] == ["domain_subdomains_scanner"]@@ -34,7 +34,7 @@ def test_execute_domain_subdomains_scanner():def test_execute_domain_whois_scanner():domains = ["example.com"]- scanner = TransformOrchestrator("123", transform_names=["domain_whois_scanner"])+ scanner = FlowOrchestrator("123", transform_names=["domain_whois_scanner"])results = scanner.execute(values=domains)assert results["initial_values"] == domainsassert results["scanners"] == ["domain_whois_scanner"]@@ -44,7 +44,7 @@ def test_execute_domain_whois_scanner():def test_execute_ip_resolve():ips = ["91.199.212.73"]- scanner = TransformOrchestrator("123", transform_names=["ip_reverse_resolve_scanner"])+ scanner = FlowOrchestrator("123", transform_names=["ip_reverse_resolve_scanner"])results = scanner.execute(values=ips)assert results["initial_values"] == ipsassert results["scanners"] == ["ip_reverse_resolve_scanner"]@@ -55,7 +55,7 @@ def test_execute_ip_resolve():def test_execute_ip_resolve_and_whois():ips = ["91.199.212.73"]- scanner = TransformOrchestrator(+ scanner = FlowOrchestrator("123", transform_names=["ip_reverse_resolve_scanner", "domain_whois_scanner"])results = scanner.execute(values=ips)@@ -65,7 +65,7 @@ def test_execute_ip_resolve_and_whois():def test_execute_ip_resolve_and_whois_multiple():ips = ["91.199.212.73", "76.76.21.21"]- scanner = TransformOrchestrator(+ scanner = FlowOrchestrator("123", transform_names=["ip_reverse_resolve_scanner", "domain_whois_scanner"])results = scanner.execute(values=ips)@@ -76,7 +76,7 @@ def test_execute_ip_resolve_and_whois_multiple():def test_execute_ip_resolve_and_whois_multiple():ips = ["162.19.81.222"]- scanner = TransformOrchestrator(+ scanner = FlowOrchestrator("123",transform_names=["ip_reverse_resolve_scanner",@@ -95,7 +95,7 @@ def test_execute_ip_resolve_and_whois_multiple():def test_execute_domain_whois_and_subdomains():domains = ["alliage.io"]- scanner = TransformOrchestrator(+ scanner = FlowOrchestrator("123", transform_names=["domain_whois_scanner", "domain_subdomains_scanner"])results = scanner.execute(values=domains)@@ -105,7 +105,7 @@ def test_execute_domain_whois_and_subdomains():def test_execute_domain_subdomains():domains = ["alliage.io"]- scanner = TransformOrchestrator("123", transform_names=["domain_subdomains_scanner"])+ scanner = FlowOrchestrator("123", transform_names=["domain_subdomains_scanner"])results = scanner.execute(values=domains)assert results["initial_values"] == domainsassert results["scanners"] == ["domain_subdomains_scanner"]diff --git a/flowsint-transforms/src/flowsint_transforms/social/to_maigret.py b/flowsint-transforms/src/flowsint_transforms/social/to_maigret.pyindex e599885d..53d2d206 100644--- a/flowsint-transforms/src/flowsint_transforms/social/to_maigret.py+++ b/flowsint-transforms/src/flowsint_transforms/social/to_maigret.py@@ -19,7 +19,7 @@ class MaigretScanner(Scanner):@classmethoddef name(cls) -> str:- return "username_to_socials"+ return "username_to_socials_maigret"@classmethoddef category(cls) -> str:@@ -159,7 +159,9 @@ class MaigretScanner(Scanner):)# Create username node- self.create_node("username", "username", profile.username, username=profile.username)+ self.create_node(+ "username", "username", profile.username, username=profile.username+ )# Create relationshipself.create_relationship(diff --git a/flowsint-transforms/src/flowsint_transforms/social/to_sherlock.py b/flowsint-transforms/src/flowsint_transforms/social/to_sherlock.pyindex b305cb23..2303b633 100644--- a/flowsint-transforms/src/flowsint_transforms/social/to_sherlock.py+++ b/flowsint-transforms/src/flowsint_transforms/social/to_sherlock.py@@ -16,11 +16,11 @@ class SherlockScanner(Scanner):@classmethoddef name(cls) -> str:- return "username_to_socials"+ return "username_to_socials_sherlock"@classmethoddef category(cls) -> str:- return "social_account"+ return "social"@classmethoddef key(cls) -> str:diff --git a/flowsint-transforms/src/flowsint_transforms/website/to_text.py b/flowsint-transforms/src/flowsint_transforms/website/to_text.pyindex 1913ac1b..825ef88d 100644--- a/flowsint-transforms/src/flowsint_transforms/website/to_text.py+++ b/flowsint-transforms/src/flowsint_transforms/website/to_text.py@@ -49,7 +49,7 @@ class WebsiteToText(Scanner):def _extract_text(self, website_url: str) -> str:try:- response = requests.get(website_url)+ response = requests.get(website_url, timeout=8)response.raise_for_status()soup = BeautifulSoup(response.text, "html.parser")text = soup.get_text()@@ -74,7 +74,7 @@ class WebsiteToText(Scanner):caption=str(website_url),type="website",)-+# Create relationship with the specific phrase for this websiteself.create_node("phrase",diff --git a/test.js b/test.jsnew file mode 100644index 00000000..8d3f33fe--- /dev/null+++ b/test.js@@ -0,0 +1,18 @@+++export function deepObjectDiff(obj1, obj2) {+ let diffObject = {}+ // We want object 2 to be compared against object 1+ if (typeof obj1 != "object" || typeof obj2 != "object") throw Error("Items to compare mustr be objects.")+ // We map over the obj2 key:value duos+ Object.entries(obj2).forEach(([key, value]) => {+ // We check for additional keys+ if (!obj1.hasOwnProperty(key))+ diffObject = { ...diffObject, [key]: { value, new: true } }+ else {+ diffObject = { ...diffObject, [key]: { value, new: false, oldValue: obj1[key] ?? null, newValue: obj2[key] ?? null, identical: obj2[key] === obj1[key] } }+ }+ })+ return diffObject++}\ No newline at end of file