@trustgraph/react-state 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +722 -0
  3. package/dist/NotificationProvider.d.ts +31 -0
  4. package/dist/NotificationProvider.d.ts.map +1 -0
  5. package/dist/hooks/useActivity.d.ts +18 -0
  6. package/dist/hooks/useActivity.d.ts.map +1 -0
  7. package/dist/hooks/useNotification.d.ts +27 -0
  8. package/dist/hooks/useNotification.d.ts.map +1 -0
  9. package/dist/index.cjs +6079 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +60 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.esm.js +6019 -0
  14. package/dist/index.esm.js.map +1 -0
  15. package/dist/index.js +6018 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/model/document-metadata.d.ts +15 -0
  18. package/dist/model/document-metadata.d.ts.map +1 -0
  19. package/dist/model/entity.d.ts +9 -0
  20. package/dist/model/entity.d.ts.map +1 -0
  21. package/dist/model/llm-models.d.ts +13 -0
  22. package/dist/model/llm-models.d.ts.map +1 -0
  23. package/dist/model/message.d.ts +6 -0
  24. package/dist/model/message.d.ts.map +1 -0
  25. package/dist/model/settings-types.d.ts +28 -0
  26. package/dist/model/settings-types.d.ts.map +1 -0
  27. package/dist/state/agent-tools.d.ts +18 -0
  28. package/dist/state/agent-tools.d.ts.map +1 -0
  29. package/dist/state/chat-query.d.ts +13 -0
  30. package/dist/state/chat-query.d.ts.map +1 -0
  31. package/dist/state/chat-session.d.ts +20 -0
  32. package/dist/state/chat-session.d.ts.map +1 -0
  33. package/dist/state/chat.d.ts +13 -0
  34. package/dist/state/chat.d.ts.map +1 -0
  35. package/dist/state/collections.d.ts +31 -0
  36. package/dist/state/collections.d.ts.map +1 -0
  37. package/dist/state/conversation.d.ts +13 -0
  38. package/dist/state/conversation.d.ts.map +1 -0
  39. package/dist/state/embeddings.d.ts +17 -0
  40. package/dist/state/embeddings.d.ts.map +1 -0
  41. package/dist/state/entity-query.d.ts +24 -0
  42. package/dist/state/entity-query.d.ts.map +1 -0
  43. package/dist/state/flow-classes.d.ts +63 -0
  44. package/dist/state/flow-classes.d.ts.map +1 -0
  45. package/dist/state/flow-parameters.d.ts +65 -0
  46. package/dist/state/flow-parameters.d.ts.map +1 -0
  47. package/dist/state/flows.d.ts +32 -0
  48. package/dist/state/flows.d.ts.map +1 -0
  49. package/dist/state/graph-embeddings.d.ts +19 -0
  50. package/dist/state/graph-embeddings.d.ts.map +1 -0
  51. package/dist/state/graph-query.d.ts +29 -0
  52. package/dist/state/graph-query.d.ts.map +1 -0
  53. package/dist/state/inference.d.ts +38 -0
  54. package/dist/state/inference.d.ts.map +1 -0
  55. package/dist/state/knowledge-cores.d.ts +23 -0
  56. package/dist/state/knowledge-cores.d.ts.map +1 -0
  57. package/dist/state/library.d.ts +25 -0
  58. package/dist/state/library.d.ts.map +1 -0
  59. package/dist/state/llm-models.d.ts +29 -0
  60. package/dist/state/llm-models.d.ts.map +1 -0
  61. package/dist/state/load.d.ts +33 -0
  62. package/dist/state/load.d.ts.map +1 -0
  63. package/dist/state/mcp-tools.d.ts +18 -0
  64. package/dist/state/mcp-tools.d.ts.map +1 -0
  65. package/dist/state/nlp-query.d.ts +24 -0
  66. package/dist/state/nlp-query.d.ts.map +1 -0
  67. package/dist/state/node-details.d.ts +60 -0
  68. package/dist/state/node-details.d.ts.map +1 -0
  69. package/dist/state/objects-query.d.ts +24 -0
  70. package/dist/state/objects-query.d.ts.map +1 -0
  71. package/dist/state/ontologies.d.ts +76 -0
  72. package/dist/state/ontologies.d.ts.map +1 -0
  73. package/dist/state/processing.d.ts +13 -0
  74. package/dist/state/processing.d.ts.map +1 -0
  75. package/dist/state/progress.d.ts +9 -0
  76. package/dist/state/progress.d.ts.map +1 -0
  77. package/dist/state/prompts.d.ts +22 -0
  78. package/dist/state/prompts.d.ts.map +1 -0
  79. package/dist/state/schemas.d.ts +13 -0
  80. package/dist/state/schemas.d.ts.map +1 -0
  81. package/dist/state/search.d.ts +9 -0
  82. package/dist/state/search.d.ts.map +1 -0
  83. package/dist/state/session.d.ts +9 -0
  84. package/dist/state/session.d.ts.map +1 -0
  85. package/dist/state/settings.d.ts +21 -0
  86. package/dist/state/settings.d.ts.map +1 -0
  87. package/dist/state/structured-query.d.ts +24 -0
  88. package/dist/state/structured-query.d.ts.map +1 -0
  89. package/dist/state/token-costs.d.ts +28 -0
  90. package/dist/state/token-costs.d.ts.map +1 -0
  91. package/dist/state/triples.d.ts +21 -0
  92. package/dist/state/triples.d.ts.map +1 -0
  93. package/dist/state/vector-search.d.ts +19 -0
  94. package/dist/state/vector-search.d.ts.map +1 -0
  95. package/dist/state/workbench.d.ts +20 -0
  96. package/dist/state/workbench.d.ts.map +1 -0
  97. package/dist/types.d.ts +27 -0
  98. package/dist/types.d.ts.map +1 -0
  99. package/dist/utils/document-encoding.d.ts +23 -0
  100. package/dist/utils/document-encoding.d.ts.map +1 -0
  101. package/dist/utils/knowledge-graph-viz.d.ts +23 -0
  102. package/dist/utils/knowledge-graph-viz.d.ts.map +1 -0
  103. package/dist/utils/knowledge-graph.d.ts +22 -0
  104. package/dist/utils/knowledge-graph.d.ts.map +1 -0
  105. package/dist/utils/row.d.ts +16 -0
  106. package/dist/utils/row.d.ts.map +1 -0
  107. package/dist/utils/vector-search.d.ts +2 -0
  108. package/dist/utils/vector-search.d.ts.map +1 -0
  109. package/package.json +89 -0
package/README.md ADDED
@@ -0,0 +1,722 @@
1
+ # @trustgraph/react-state
2
+
3
+ React state management hooks for TrustGraph applications. Provides TanStack Query hooks and Zustand stores for managing application state with a pluggable notification system.
4
+
5
+ ## Features
6
+
7
+ - 🔌 **Pluggable Notifications** - Component-free notification system with provider pattern
8
+ - 📊 **TanStack Query Hooks** - Data fetching and caching for all TrustGraph operations
9
+ - 🗃️ **Zustand Stores** - Lightweight state management for UI state
10
+ - 🎯 **TypeScript Support** - Full type definitions included
11
+ - 🚫 **Zero UI Dependencies** - Bring your own notification/toast UI
12
+ - 🔗 **WebSocket Integration** - Works seamlessly with @trustgraph/react-provider
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @trustgraph/react-state @trustgraph/react-provider @trustgraph/client
18
+ ```
19
+
20
+ ## Building from Scratch
21
+
22
+ New to TrustGraph? Here's how to build your first app from a blank slate.
23
+
24
+ ### 1. Create a new React + TypeScript project
25
+
26
+ ```bash
27
+ # Create a new Vite project with React + TypeScript
28
+ npm create vite@latest my-trustgraph-app -- --template react-ts
29
+ cd my-trustgraph-app
30
+ ```
31
+
32
+ ### 2. Install TrustGraph dependencies
33
+
34
+ ```bash
35
+ # Vite scaffolds with React 19, but TrustGraph currently uses React 18
36
+ npm install react@^18.0.0 react-dom@^18.0.0
37
+
38
+ # Install TrustGraph packages
39
+ npm install @trustgraph/react-state @trustgraph/react-provider @trustgraph/client
40
+
41
+ # Install required peer dependencies
42
+ npm install @tanstack/react-query zustand
43
+
44
+ # Install a toast/notification library (optional, we'll use console for this example)
45
+ ```
46
+
47
+ ### 3. Configure WebSocket proxy
48
+
49
+ The TrustGraph client connects to `ws://HOSTNAME:PORT/api/socket` in your application's address space. You need to proxy this to the TrustGraph API gateway (typically port 8088, path `/api/v1/socket`).
50
+
51
+ For Vite, create or update `vite.config.ts`:
52
+
53
+ ```typescript
54
+ import { defineConfig } from "vite";
55
+ import react from "@vitejs/plugin-react";
56
+
57
+ export default defineConfig({
58
+ plugins: [react()],
59
+ server: {
60
+ proxy: {
61
+ "/api/socket": {
62
+ target: "ws://localhost:8088",
63
+ ws: true,
64
+ rewrite: (path) => path.replace(/^\/api\/socket/, "/api/v1/socket"),
65
+ },
66
+ },
67
+ },
68
+ });
69
+ ```
70
+
71
+ **For production deployments**, configure your web server (nginx, Apache, etc.) to proxy `/api/socket` to your TrustGraph API gateway:
72
+
73
+ ```nginx
74
+ # nginx example
75
+ location /api/socket {
76
+ proxy_pass http://trustgraph-api:8088/api/v1/socket;
77
+ proxy_http_version 1.1;
78
+ proxy_set_header Upgrade $http_upgrade;
79
+ proxy_set_header Connection "upgrade";
80
+ }
81
+ ```
82
+
83
+ ### 4. Set up the provider wrapper
84
+
85
+ Create or update `src/App.tsx`:
86
+
87
+ ```typescript
88
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
89
+ import { SocketProvider } from "@trustgraph/react-provider";
90
+ import { NotificationProvider, NotificationHandler } from "@trustgraph/react-state";
91
+ import MyFirstComponent from "./MyFirstComponent";
92
+
93
+ // Simple console-based notification handler for development
94
+ const notificationHandler: NotificationHandler = {
95
+ success: (msg) => console.log("✓", msg),
96
+ error: (msg) => console.error("✗", msg),
97
+ warning: (msg) => console.warn("⚠", msg),
98
+ info: (msg) => console.info("ℹ", msg),
99
+ };
100
+
101
+ const queryClient = new QueryClient();
102
+
103
+ function App() {
104
+ return (
105
+ <QueryClientProvider client={queryClient}>
106
+ <NotificationProvider handler={notificationHandler}>
107
+ <SocketProvider user="my-user" apiKey="">
108
+ <MyFirstComponent />
109
+ </SocketProvider>
110
+ </NotificationProvider>
111
+ </QueryClientProvider>
112
+ );
113
+ }
114
+
115
+ export default App;
116
+ ```
117
+
118
+ ### 5. Create your first component
119
+
120
+ Create `src/MyFirstComponent.tsx`:
121
+
122
+ ```typescript
123
+ import { useFlows, useSettings } from "@trustgraph/react-state";
124
+
125
+ function MyFirstComponent() {
126
+ const { flows, isLoading } = useFlows();
127
+ const { settings } = useSettings();
128
+
129
+ if (isLoading) return <div>Loading flows...</div>;
130
+
131
+ return (
132
+ <div>
133
+ <h1>My TrustGraph App</h1>
134
+ <p>User: {settings.user}</p>
135
+ <p>Collection: {settings.collection}</p>
136
+ <h2>Available Flows:</h2>
137
+ <ul>
138
+ {flows?.map((flow) => (
139
+ <li key={flow.id}>{flow.id}</li>
140
+ ))}
141
+ </ul>
142
+ </div>
143
+ );
144
+ }
145
+
146
+ export default MyFirstComponent;
147
+ ```
148
+
149
+ ### 6. Run your app
150
+
151
+ ```bash
152
+ npm run dev
153
+ ```
154
+
155
+ Open http://localhost:5173 and you should see your flows!
156
+
157
+ ### 7. Next Steps
158
+
159
+ - Add a chat interface with `useConversation` and `useChatSession`
160
+ - Query knowledge graphs with `useEntityDetail` and `useGraphSubgraph`
161
+ - Upload documents with `useLibrary`
162
+ - Perform vector searches with `useVectorSearch`
163
+
164
+ ## Quick Start
165
+
166
+ ### 1. Set up providers
167
+
168
+ ```typescript
169
+ import { SocketProvider } from "@trustgraph/react-provider";
170
+ import { NotificationProvider, NotificationHandler } from "@trustgraph/react-state";
171
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
172
+
173
+ // Create your notification handler (example with toast library)
174
+ const notificationHandler: NotificationHandler = {
175
+ success: (message) => toast.success(message),
176
+ error: (message) => toast.error(message),
177
+ warning: (message) => toast.warning(message),
178
+ info: (message) => toast.info(message),
179
+ };
180
+
181
+ const queryClient = new QueryClient();
182
+
183
+ function App() {
184
+ return (
185
+ <QueryClientProvider client={queryClient}>
186
+ <NotificationProvider handler={notificationHandler}>
187
+ <SocketProvider user="your-user" apiKey="optional-api-key">
188
+ <YourApp />
189
+ </SocketProvider>
190
+ </NotificationProvider>
191
+ </QueryClientProvider>
192
+ );
193
+ }
194
+ ```
195
+
196
+ ### 2. Use state hooks in your components
197
+
198
+ ```typescript
199
+ import { useLibrary, useFlows, useSettings } from "@trustgraph/react-state";
200
+
201
+ function MyComponent() {
202
+ const { documents, deleteDocuments, isLoading } = useLibrary();
203
+ const { flows, startFlow } = useFlows();
204
+ const { settings, updateSetting } = useSettings();
205
+
206
+ return (
207
+ <div>
208
+ {isLoading ? "Loading..." : `${documents?.length} documents`}
209
+ </div>
210
+ );
211
+ }
212
+ ```
213
+
214
+ ## Notification System
215
+
216
+ The package uses a pluggable notification system that allows you to integrate any toast/notification UI library.
217
+
218
+ ### NotificationHandler Interface
219
+
220
+ ```typescript
221
+ interface NotificationHandler {
222
+ success: (message: string) => void;
223
+ error: (message: string) => void;
224
+ warning: (message: string) => void;
225
+ info: (message: string) => void;
226
+ }
227
+ ```
228
+
229
+ ### Example Implementations
230
+
231
+ **With Chakra UI:**
232
+
233
+ ```typescript
234
+ import { toaster } from "@chakra-ui/react";
235
+
236
+ const handler: NotificationHandler = {
237
+ success: (msg) => toaster.create({ title: msg, type: "success" }),
238
+ error: (msg) => toaster.create({ title: `Error: ${msg}`, type: "error" }),
239
+ warning: (msg) =>
240
+ toaster.create({ title: `Warning: ${msg}`, type: "warning" }),
241
+ info: (msg) => toaster.create({ title: msg, type: "info" }),
242
+ };
243
+ ```
244
+
245
+ **With react-hot-toast:**
246
+
247
+ ```typescript
248
+ import toast from "react-hot-toast";
249
+
250
+ const handler: NotificationHandler = {
251
+ success: (msg) => toast.success(msg),
252
+ error: (msg) => toast.error(msg),
253
+ warning: (msg) => toast(msg, { icon: "⚠️" }),
254
+ info: (msg) => toast(msg),
255
+ };
256
+ ```
257
+
258
+ **With console (testing):**
259
+
260
+ ```typescript
261
+ const handler: NotificationHandler = {
262
+ success: (msg) => console.log("✓", msg),
263
+ error: (msg) => console.error("✗", msg),
264
+ warning: (msg) => console.warn("⚠", msg),
265
+ info: (msg) => console.info("ℹ", msg),
266
+ };
267
+ ```
268
+
269
+ ## Available Hooks
270
+
271
+ ### TanStack Query Hooks
272
+
273
+ #### Document & Library Management
274
+
275
+ - `useLibrary()` - Manage documents, upload files, submit for processing
276
+ - `useProcessing()` - Track document processing status
277
+
278
+ #### Knowledge Graph Operations
279
+
280
+ - `useTriples()` - Query RDF triples
281
+ - `useGraphSubgraph()` - Retrieve graph subgraphs
282
+ - `useGraphEmbeddings()` - Query graph embeddings
283
+ - `useVectorSearch()` - Perform vector similarity search
284
+ - `useEntityDetail()` - Get entity details
285
+ - `useNodeDetails()` - Get node information
286
+
287
+ #### Flow Management
288
+
289
+ - `useFlows()` - Manage processing flows
290
+ - `useFlowClasses()` - Get available flow classes
291
+ - `useFlowParameters()` - Get flow parameter schemas
292
+
293
+ #### Collections & Organization
294
+
295
+ - `useCollections()` - Manage document collections
296
+ - `useKnowledgeCores()` - Manage knowledge cores
297
+
298
+ #### Chat & Inference
299
+
300
+ - `useConversation()` - Chat conversation state (messages, input, mode)
301
+ - `useInference()`- Low-level LLM inference (graphRag, textCompletion, agent)
302
+ - `useChatSession()` / `useChat()` - High-level chat session management
303
+ - `useStructuredQuery()` - Structured query operations
304
+ - `useObjectsQuery()` - Object queries
305
+ - `useNlpQuery()` - Natural language processing queries
306
+
307
+ #### Configuration
308
+
309
+ - `useSettings()` - Application settings management
310
+ - `usePrompts()` - Manage prompts
311
+ - `useSchemas()` - Manage schemas
312
+ - `useOntologies()` - Manage ontologies
313
+ - `useLLMModels()` - LLM model configuration
314
+ - `useTokenCosts()` - Token cost tracking
315
+
316
+ #### Tools
317
+
318
+ - `useAgentTools()` - Agent tool management
319
+ - `useMcpTools()` - MCP tool management
320
+
321
+ #### Utilities
322
+
323
+ - `useEmbeddings()` - Generate text embeddings
324
+
325
+ ### Zustand Stores
326
+
327
+ - `useProgressStateStore()` - Activity indicators and error state
328
+ - `useSessionStore()` - Session and flow state
329
+ - `useConversation()` - Chat conversation state (messages, input, chat mode)
330
+ - `useWorkbenchStateStore()` - Workbench UI state (selected entity, tool, etc.)
331
+ - `useLoadStateStore()` - Document loading state
332
+ - `useSearchStateStore()` - Search results state
333
+
334
+ ### Utility Hooks
335
+
336
+ - `useNotification()` - Access notification handler
337
+ - `useActivity()` - Show/hide activity indicators
338
+
339
+ ## Example Usage
340
+
341
+ ### Managing Documents
342
+
343
+ ```typescript
344
+ import { useLibrary, useSettings } from "@trustgraph/react-state";
345
+
346
+ function DocumentManager() {
347
+ const { settings } = useSettings();
348
+ const {
349
+ documents,
350
+ isLoading,
351
+ deleteDocuments,
352
+ uploadFiles,
353
+ submitDocuments,
354
+ } = useLibrary();
355
+
356
+ const handleDelete = (ids: string[]) => {
357
+ deleteDocuments({
358
+ ids,
359
+ onSuccess: () => console.log("Deleted successfully"),
360
+ });
361
+ };
362
+
363
+ const handleUpload = (files: File[]) => {
364
+ uploadFiles({
365
+ files,
366
+ params: { title: "My Document", keywords: [] },
367
+ mimeType: "application/pdf",
368
+ onSuccess: () => console.log("Uploaded successfully"),
369
+ });
370
+ };
371
+
372
+ const handleSubmit = (ids: string[]) => {
373
+ submitDocuments({
374
+ ids,
375
+ flow: "my-flow",
376
+ tags: ["important"],
377
+ collection: settings.collection,
378
+ onSuccess: () => console.log("Submitted for processing"),
379
+ });
380
+ };
381
+
382
+ if (isLoading) return <div>Loading...</div>;
383
+
384
+ return (
385
+ <div>
386
+ {documents?.map((doc) => (
387
+ <div key={doc.id}>{doc.title}</div>
388
+ ))}
389
+ </div>
390
+ );
391
+ }
392
+ ```
393
+
394
+ ### Settings Management
395
+
396
+ ```typescript
397
+ import { useSettings } from "@trustgraph/react-state";
398
+
399
+ function SettingsPanel() {
400
+ const { settings, updateSetting, saveSettings, exportSettings } = useSettings();
401
+
402
+ return (
403
+ <div>
404
+ <input
405
+ value={settings.user}
406
+ onChange={(e) => updateSetting("user", e.target.value)}
407
+ />
408
+ <input
409
+ value={settings.collection}
410
+ onChange={(e) => updateSetting("collection", e.target.value)}
411
+ />
412
+ <button onClick={() => console.log(exportSettings())}>
413
+ Export Settings
414
+ </button>
415
+ </div>
416
+ );
417
+ }
418
+ ```
419
+
420
+ ### Chat Interface (3-Hook Architecture)
421
+
422
+ The chat system is split into three composable hooks:
423
+
424
+ ```typescript
425
+ import { useConversation, useInference, useChatSession, useSettings } from "@trustgraph/react-state";
426
+
427
+ // Option 1: High-level chat (easiest)
428
+ function SimpleChatUI() {
429
+ const messages = useConversation((state) => state.messages);
430
+ const input = useConversation((state) => state.input);
431
+ const setInput = useConversation((state) => state.setInput);
432
+ const { submitMessage, isSubmitting } = useChatSession();
433
+
434
+ return (
435
+ <div>
436
+ {messages.map((msg, i) => (
437
+ <div key={i}>{msg.role}: {msg.text}</div>
438
+ ))}
439
+ <input value={input} onChange={(e) => setInput(e.target.value)} />
440
+ <button onClick={() => submitMessage({ input })} disabled={isSubmitting}>
441
+ Send
442
+ </button>
443
+ </div>
444
+ );
445
+ }
446
+
447
+ // Option 2: Low-level inference (for custom UIs)
448
+ function CustomInferenceUI() {
449
+ const { settings } = useSettings();
450
+ const inference = useInference();
451
+ const [result, setResult] = useState("");
452
+
453
+ const handleQuery = async () => {
454
+ const response = await inference.graphRag({
455
+ input: "What is TrustGraph?",
456
+ options: {
457
+ entityLimit: 10,
458
+ tripleLimit: 10,
459
+ },
460
+ collection: settings.collection,
461
+ });
462
+ setResult(response.response);
463
+ };
464
+
465
+ return (
466
+ <div>
467
+ <button onClick={handleQuery}>Query</button>
468
+ <div>{result}</div>
469
+ </div>
470
+ );
471
+ }
472
+ ```
473
+
474
+ ### Multi-Collection Apps
475
+
476
+ Query multiple collections side-by-side:
477
+
478
+ ```typescript
479
+ import { useEntityDetail, useSessionStore, useSettings } from "@trustgraph/react-state";
480
+
481
+ function MultiCollectionView({ entityUri }: { entityUri: string }) {
482
+ const flowId = useSessionStore((state) => state.flowId);
483
+ const { settings } = useSettings();
484
+
485
+ // Query same entity from different collections
486
+ const prodData = useEntityDetail(entityUri, flowId, "production");
487
+ const stagingData = useEntityDetail(entityUri, flowId, "staging");
488
+ const defaultData = useEntityDetail(entityUri, flowId, settings.collection);
489
+
490
+ return (
491
+ <div>
492
+ <div>
493
+ <h3>Production</h3>
494
+ {prodData.detail?.triples.length} triples
495
+ </div>
496
+ <div>
497
+ <h3>Staging</h3>
498
+ {stagingData.detail?.triples.length} triples
499
+ </div>
500
+ <div>
501
+ <h3>Default ({settings.collection})</h3>
502
+ {defaultData.detail?.triples.length} triples
503
+ </div>
504
+ </div>
505
+ );
506
+ }
507
+ ```
508
+
509
+ ### Using Progress Indicators
510
+
511
+ ```typescript
512
+ import { useProgressStateStore, useActivity } from "@trustgraph/react-state";
513
+
514
+ function MyComponent() {
515
+ const [isLoading, setIsLoading] = useState(false);
516
+
517
+ // Automatically shows "Processing data" in activity indicators while isLoading is true
518
+ useActivity(isLoading, "Processing data");
519
+
520
+ // Access all current activities
521
+ const activities = useProgressStateStore((state) => state.activity);
522
+
523
+ return (
524
+ <div>
525
+ {activities.size > 0 && (
526
+ <div>Active: {Array.from(activities).join(", ")}</div>
527
+ )}
528
+ </div>
529
+ );
530
+ }
531
+ ```
532
+
533
+ ## Common Patterns
534
+
535
+ ### Handling Settings Loading State
536
+
537
+ Settings are loaded asynchronously. Always check `isLoaded` before accessing settings values:
538
+
539
+ ```typescript
540
+ import { useSettings, useEntityDetail } from "@trustgraph/react-state";
541
+
542
+ function EntityView({ entityUri }: { entityUri: string }) {
543
+ const { settings, isLoaded } = useSettings();
544
+ const flowId = useSessionStore((state) => state.flowId);
545
+
546
+ // Wait for settings to load before querying
547
+ const { detail } = useEntityDetail(
548
+ entityUri,
549
+ flowId,
550
+ settings?.collection || "default"
551
+ );
552
+
553
+ if (!isLoaded) {
554
+ return <div>Loading settings...</div>;
555
+ }
556
+
557
+ return <div>{detail?.triples.length} triples</div>;
558
+ }
559
+ ```
560
+
561
+ ### Using Default Collection from Settings
562
+
563
+ Most hooks require an explicit `collection` parameter. Use settings as the default source:
564
+
565
+ ```typescript
566
+ import { useSettings, useLibrary } from "@trustgraph/react-state";
567
+
568
+ function DocumentSubmit() {
569
+ const { settings } = useSettings();
570
+ const library = useLibrary();
571
+
572
+ const handleSubmit = (ids: string[], flow: string) => {
573
+ library.submitDocuments({
574
+ ids,
575
+ flow,
576
+ tags: ["important"],
577
+ collection: settings?.collection || "default", // Use settings with fallback
578
+ onSuccess: () => console.log("Submitted"),
579
+ });
580
+ };
581
+
582
+ return <button onClick={() => handleSubmit(["doc1"], "flow1")}>Submit</button>;
583
+ }
584
+ ```
585
+
586
+ ### Querying Multiple Collections
587
+
588
+ Override the default collection to query multiple collections side-by-side:
589
+
590
+ ```typescript
591
+ import { useEntityDetail, useSettings } from "@trustgraph/react-state";
592
+
593
+ function MultiCollectionComparison({ entityUri }: { entityUri: string }) {
594
+ const { settings } = useSettings();
595
+ const flowId = useSessionStore((state) => state.flowId);
596
+
597
+ // Query same entity from different collections
598
+ const prod = useEntityDetail(entityUri, flowId, "production");
599
+ const staging = useEntityDetail(entityUri, flowId, "staging");
600
+ const defaultData = useEntityDetail(entityUri, flowId, settings?.collection || "default");
601
+
602
+ return (
603
+ <div>
604
+ <h3>Production: {prod.detail?.triples.length} triples</h3>
605
+ <h3>Staging: {staging.detail?.triples.length} triples</h3>
606
+ <h3>Default: {defaultData.detail?.triples.length} triples</h3>
607
+ </div>
608
+ );
609
+ }
610
+ ```
611
+
612
+ ### Composing Inference and Conversation Hooks
613
+
614
+ For custom chat UIs, compose the low-level hooks directly:
615
+
616
+ ```typescript
617
+ import { useConversation, useInference, useSettings } from "@trustgraph/react-state";
618
+
619
+ function CustomChatUI() {
620
+ const messages = useConversation((state) => state.messages);
621
+ const input = useConversation((state) => state.input);
622
+ const setInput = useConversation((state) => state.setInput);
623
+ const addMessage = useConversation((state) => state.addMessage);
624
+
625
+ const { settings } = useSettings();
626
+ const inference = useInference();
627
+
628
+ const handleSubmit = async () => {
629
+ addMessage("user", input);
630
+ setInput("");
631
+
632
+ const result = await inference.graphRag({
633
+ input,
634
+ options: { entityLimit: 10, tripleLimit: 10 },
635
+ collection: settings?.collection || "default",
636
+ });
637
+
638
+ addMessage("ai", result.response);
639
+ };
640
+
641
+ return (
642
+ <div>
643
+ {messages.map((msg, i) => (
644
+ <div key={i}>{msg.role}: {msg.text}</div>
645
+ ))}
646
+ <input value={input} onChange={(e) => setInput(e.target.value)} />
647
+ <button onClick={handleSubmit}>Send</button>
648
+ </div>
649
+ );
650
+ }
651
+ ```
652
+
653
+ ## Type Exports
654
+
655
+ The package re-exports types from `@trustgraph/client` for convenience:
656
+
657
+ ```typescript
658
+ import type {
659
+ Triple,
660
+ Value,
661
+ Entity,
662
+ Message,
663
+ Settings,
664
+ NotificationHandler,
665
+ // ... and more
666
+ } from "@trustgraph/react-state";
667
+ ```
668
+
669
+ ## Utility Functions
670
+
671
+ The package also exports utility functions:
672
+
673
+ ```typescript
674
+ import {
675
+ fileToBase64,
676
+ textToBase64,
677
+ vectorSearch,
678
+ getTriples,
679
+ prepareMetadata,
680
+ createDocId,
681
+ } from "@trustgraph/react-state";
682
+ ```
683
+
684
+ ## Development
685
+
686
+ ```bash
687
+ # Install dependencies
688
+ npm install
689
+
690
+ # Build the package
691
+ npm run build
692
+
693
+ # Run tests
694
+ npm test
695
+
696
+ # Run linting
697
+ npm run lint
698
+
699
+ # Type checking
700
+ npm run typecheck
701
+ ```
702
+
703
+ ## Dependencies
704
+
705
+ ### Peer Dependencies (required in your app)
706
+
707
+ - `react` ^18.0.0
708
+ - `@tanstack/react-query` ^5.0.0
709
+ - `@trustgraph/client` ^0.1.0
710
+ - `@trustgraph/react-provider` ^0.1.0
711
+ - `zustand` ^4.0.0 || ^5.0.0
712
+
713
+ ### Runtime Dependencies
714
+
715
+ - `compute-cosine-similarity` - Vector similarity calculations
716
+ - `uuid` - Unique ID generation
717
+
718
+ ## License
719
+
720
+ Apache 2.0
721
+
722
+ (c) KnowNext Inc., KnowNext Limited 2025