1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
|
"use client"
import {
calculateSemanticSimilarity,
getConnectionVisualProps,
getMagicalConnectionColor,
} from "@/lib/similarity"
import { useMemo, useRef, useEffect } from "react"
import { colors, LAYOUT_CONSTANTS, SIMILARITY_CONFIG } from "@/constants"
import type {
DocumentsResponse,
DocumentWithMemories,
GraphEdge,
GraphNode,
MemoryEntry,
MemoryRelation,
} from "@/types"
export function useGraphData(
data: DocumentsResponse | null,
selectedSpace: string,
nodePositions: Map<
string,
{
x: number
y: number
parentDocId?: string
offsetX?: number
offsetY?: number
}
>,
draggingNodeId: string | null,
memoryLimit?: number,
maxNodes?: number,
) {
// Cache nodes to preserve d3-force mutations (x, y, vx, vy, fx, fy)
const nodeCache = useRef<Map<string, GraphNode>>(new Map())
// Cleanup nodeCache to prevent memory leak
useEffect(() => {
if (!data?.documents) return
// Build set of current node IDs
const currentNodeIds = new Set<string>()
data.documents.forEach((doc) => {
currentNodeIds.add(doc.id)
doc.memoryEntries.forEach((mem) => {
currentNodeIds.add(`${mem.id}`)
})
})
// Remove stale nodes from cache
for (const [id] of nodeCache.current.entries()) {
if (!currentNodeIds.has(id)) {
nodeCache.current.delete(id)
}
}
}, [data, selectedSpace])
// Memo 1: Filter documents by selected space and apply node limits
const filteredDocuments = useMemo(() => {
if (!data?.documents) return []
// Sort documents by most recent first
const sortedDocs = [...data.documents].sort((a, b) => {
const dateA = new Date(a.updatedAt || a.createdAt).getTime()
const dateB = new Date(b.updatedAt || b.createdAt).getTime()
return dateB - dateA // Most recent first
})
// Filter by space and prepare documents
let processedDocs = sortedDocs.map((doc) => {
let memories =
selectedSpace === "all"
? doc.memoryEntries
: doc.memoryEntries.filter(
(memory) =>
(memory.spaceContainerTag ?? memory.spaceId ?? "default") ===
selectedSpace,
)
// Sort memories by relevance score (if available) or recency
memories = memories.sort((a, b) => {
// Prioritize sourceRelevanceScore if available
if (a.sourceRelevanceScore != null && b.sourceRelevanceScore != null) {
return b.sourceRelevanceScore - a.sourceRelevanceScore // Higher score first
}
// Fall back to most recent
const dateA = new Date(a.updatedAt || a.createdAt).getTime()
const dateB = new Date(b.updatedAt || b.createdAt).getTime()
return dateB - dateA // Most recent first
})
return {
...doc,
memoryEntries: memories,
}
})
// Apply maxNodes limit using Option B (dynamic cap per document)
if (maxNodes && maxNodes > 0) {
const totalDocs = processedDocs.length
if (totalDocs > 0) {
// Calculate memories per document to stay within maxNodes budget
const memoriesPerDoc = Math.floor(maxNodes / totalDocs)
// If we need to limit, slice memories for each document
if (memoriesPerDoc > 0) {
let totalNodes = 0
processedDocs = processedDocs.map((doc) => {
// Limit memories to calculated amount per doc
const limitedMemories = doc.memoryEntries.slice(0, memoriesPerDoc)
totalNodes += limitedMemories.length
return {
...doc,
memoryEntries: limitedMemories,
}
})
// If we still have budget left, distribute remaining nodes to first docs
let remainingBudget = maxNodes - totalNodes
if (remainingBudget > 0) {
for (
let i = 0;
i < processedDocs.length && remainingBudget > 0;
i++
) {
const doc = processedDocs[i]
if (!doc) continue
const originalDoc = sortedDocs.find((d) => d.id === doc.id)
if (!originalDoc) continue
const currentMemCount = doc.memoryEntries.length
const originalMemCount = originalDoc.memoryEntries.filter(
(m) =>
selectedSpace === "all" ||
(m.spaceContainerTag ?? m.spaceId ?? "default") ===
selectedSpace,
).length
// Can we add more memories to this doc?
const canAdd = originalMemCount - currentMemCount
if (canAdd > 0) {
const toAdd = Math.min(canAdd, remainingBudget)
const additionalMems = doc.memoryEntries.slice(
0,
currentMemCount + toAdd,
)
processedDocs[i] = {
...doc,
memoryEntries: originalDoc.memoryEntries
.filter(
(m) =>
selectedSpace === "all" ||
(m.spaceContainerTag ?? m.spaceId ?? "default") ===
selectedSpace,
)
.sort((a, b) => {
if (
a.sourceRelevanceScore != null &&
b.sourceRelevanceScore != null
) {
return b.sourceRelevanceScore - a.sourceRelevanceScore
}
const dateA = new Date(
a.updatedAt || a.createdAt,
).getTime()
const dateB = new Date(
b.updatedAt || b.createdAt,
).getTime()
return dateB - dateA
})
.slice(0, currentMemCount + toAdd),
}
remainingBudget -= toAdd
}
}
}
} else {
// If memoriesPerDoc is 0, we need to limit the number of documents shown
// Show at least 1 memory per document, up to maxNodes documents
processedDocs = processedDocs.slice(0, maxNodes).map((doc) => ({
...doc,
memoryEntries: doc.memoryEntries.slice(0, 1),
}))
}
}
}
// Apply legacy memoryLimit if provided and a specific space is selected
else if (selectedSpace !== "all" && memoryLimit && memoryLimit > 0) {
processedDocs = processedDocs.map((doc) => ({
...doc,
memoryEntries: doc.memoryEntries.slice(0, memoryLimit),
}))
}
return processedDocs
}, [data, selectedSpace, memoryLimit, maxNodes])
// Memo 2: Calculate similarity edges using k-NN approach
const similarityEdges = useMemo(() => {
const edges: GraphEdge[] = []
// k-NN: Each document compares with k neighbors (configurable)
const { maxComparisonsPerDoc, threshold } = SIMILARITY_CONFIG
for (let i = 0; i < filteredDocuments.length; i++) {
const docI = filteredDocuments[i]
if (!docI) continue
// Only compare with next k documents (k-nearest neighbors approach)
const endIdx = Math.min(
i + maxComparisonsPerDoc + 1,
filteredDocuments.length,
)
for (let j = i + 1; j < endIdx; j++) {
const docJ = filteredDocuments[j]
if (!docJ) continue
const sim = calculateSemanticSimilarity(
docI.summaryEmbedding ? Array.from(docI.summaryEmbedding) : null,
docJ.summaryEmbedding ? Array.from(docJ.summaryEmbedding) : null,
)
if (sim > threshold) {
edges.push({
id: `doc-doc-${docI.id}-${docJ.id}`,
source: docI.id,
target: docJ.id,
similarity: sim,
visualProps: getConnectionVisualProps(sim),
color: getMagicalConnectionColor(sim, 200),
edgeType: "doc-doc",
})
}
}
}
return edges
}, [filteredDocuments])
// Memo 3: Build full graph data (nodes + edges)
return useMemo(() => {
if (!data?.documents || filteredDocuments.length === 0) {
return { nodes: [], edges: [] }
}
const allNodes: GraphNode[] = []
const allEdges: GraphEdge[] = []
// Group documents by space for better clustering
const documentsBySpace = new Map<string, typeof filteredDocuments>()
filteredDocuments.forEach((doc) => {
const docSpace =
doc.memoryEntries[0]?.spaceContainerTag ??
doc.memoryEntries[0]?.spaceId ??
"default"
if (!documentsBySpace.has(docSpace)) {
documentsBySpace.set(docSpace, [])
}
const spaceDocsArr = documentsBySpace.get(docSpace)
if (spaceDocsArr) {
spaceDocsArr.push(doc)
}
})
// Enhanced Layout with Space Separation
const { centerX, centerY, clusterRadius } = LAYOUT_CONSTANTS
/* 1. Build DOCUMENT nodes with space-aware clustering */
const documentNodes: GraphNode[] = []
let spaceIndex = 0
documentsBySpace.forEach((spaceDocs) => {
spaceDocs.forEach((doc, docIndex) => {
// Simple grid-like layout that physics will naturally organize
// Start documents near the center with some random offset
const gridSize = Math.ceil(Math.sqrt(spaceDocs.length))
const row = Math.floor(docIndex / gridSize)
const col = docIndex % gridSize
// Loose grid spacing - physics will organize it better
const spacing = 200
const defaultX =
centerX + (col - gridSize / 2) * spacing + (Math.random() - 0.5) * 50
const defaultY =
centerY + (row - gridSize / 2) * spacing + (Math.random() - 0.5) * 50
const customPos = nodePositions.get(doc.id)
// Check if node exists in cache (preserves d3-force mutations)
let node = nodeCache.current.get(doc.id)
if (node) {
// Update existing node's data, preserve physics properties (x, y, vx, vy, fx, fy)
node.data = doc
node.isDragging = draggingNodeId === doc.id
// Don't reset x/y - they're managed by d3-force
} else {
// Create new node with initial position
node = {
id: doc.id,
type: "document",
x: customPos?.x ?? defaultX,
y: customPos?.y ?? defaultY,
data: doc,
size: 58,
color: colors.document.primary,
isHovered: false,
isDragging: draggingNodeId === doc.id,
} satisfies GraphNode
nodeCache.current.set(doc.id, node)
}
documentNodes.push(node)
})
spaceIndex++
})
/* 2. Manual collision avoidance removed - now handled by d3-force simulation */
// The initial circular layout provides good starting positions
// D3-force will handle collision avoidance and spacing dynamically
allNodes.push(...documentNodes)
/* 3. Add memories around documents WITH doc-memory connections */
documentNodes.forEach((docNode) => {
const memoryNodeMap = new Map<string, GraphNode>()
const doc = docNode.data as DocumentWithMemories
doc.memoryEntries.forEach((memory, memIndex) => {
const memoryId = `${memory.id}`
const customMemPos = nodePositions.get(memoryId)
// Simple circular positioning around parent doc
// Physics will naturally cluster them better
const angle = (memIndex / doc.memoryEntries.length) * Math.PI * 2
const distance = clusterRadius * 1 // Closer to parent, let physics separate
const defaultMemX = docNode.x + Math.cos(angle) * distance
const defaultMemY = docNode.y + Math.sin(angle) * distance
// Calculate final position
let finalMemX = defaultMemX
let finalMemY = defaultMemY
if (customMemPos) {
// If memory was manually positioned and has stored offset relative to parent
if (
customMemPos.parentDocId === docNode.id &&
customMemPos.offsetX !== undefined &&
customMemPos.offsetY !== undefined
) {
// Apply the stored offset to the current document position
finalMemX = docNode.x + customMemPos.offsetX
finalMemY = docNode.y + customMemPos.offsetY
} else {
// Fallback: use absolute position (for backward compatibility or if parent changed)
finalMemX = customMemPos.x
finalMemY = customMemPos.y
}
}
if (!memoryNodeMap.has(memoryId)) {
// Check if memory node exists in cache (preserves d3-force mutations)
let memoryNode = nodeCache.current.get(memoryId)
if (memoryNode) {
// Update existing node's data, preserve physics properties
memoryNode.data = memory
memoryNode.isDragging = draggingNodeId === memoryId
// Don't reset x/y - they're managed by d3-force
} else {
// Create new node with initial position
memoryNode = {
id: memoryId,
type: "memory",
x: finalMemX,
y: finalMemY,
data: memory,
size: Math.max(
32,
Math.min(48, (memory.memory?.length || 50) * 0.5),
),
color: colors.memory.primary,
isHovered: false,
isDragging: draggingNodeId === memoryId,
}
nodeCache.current.set(memoryId, memoryNode)
}
memoryNodeMap.set(memoryId, memoryNode)
allNodes.push(memoryNode)
}
// Create doc-memory edge with similarity
allEdges.push({
id: `edge-${docNode.id}-${memory.id}`,
source: docNode.id,
target: memoryId,
similarity: 1,
visualProps: getConnectionVisualProps(1),
color: colors.connection.memory,
edgeType: "doc-memory",
})
})
})
// Build mapping of memoryId -> nodeId for version chains
const memNodeIdMap = new Map<string, string>()
allNodes.forEach((n) => {
if (n.type === "memory") {
memNodeIdMap.set((n.data as MemoryEntry).id, n.id)
}
})
// Add version-chain edges (old -> new)
data.documents.forEach((doc) => {
doc.memoryEntries.forEach((mem: MemoryEntry) => {
// Support both new object structure and legacy array/single parent fields
let parentRelations: Record<string, MemoryRelation> =
(mem.memoryRelations ?? {}) as Record<string, MemoryRelation>
if (
mem.memoryRelations &&
Array.isArray(mem.memoryRelations) &&
mem.memoryRelations.length > 0
) {
// Convert array to Record
parentRelations = mem.memoryRelations.reduce(
(acc, rel) => {
acc[rel.targetMemoryId] = rel.relationType
return acc
},
{} as Record<string, MemoryRelation>,
)
} else if (mem.parentMemoryId) {
parentRelations = {
[mem.parentMemoryId]: "updates" as MemoryRelation,
}
}
Object.entries(parentRelations).forEach(([pid, relationType]) => {
const fromId = memNodeIdMap.get(pid)
const toId = memNodeIdMap.get(mem.id)
if (fromId && toId) {
allEdges.push({
id: `version-${fromId}-${toId}`,
source: fromId,
target: toId,
similarity: 1,
visualProps: {
opacity: 0.8,
thickness: 1,
glow: 0,
pulseDuration: 3000,
},
// choose color based on relation type
color: colors.relations[relationType] ?? colors.relations.updates,
edgeType: "version",
relationType: relationType as MemoryRelation,
})
}
})
})
})
// Append similarity edges (calculated in separate memo)
allEdges.push(...similarityEdges)
return { nodes: allNodes, edges: allEdges }
}, [data, filteredDocuments, nodePositions, draggingNodeId, similarityEdges])
}
|