Spaces:
Paused

File size: 16,197 Bytes
b0867f8
 
 
 
 
 
 
 
7bca9a7
 
232234c
 
b0867f8
 
5eb4857
 
b0867f8
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
219e91e
 
 
 
 
 
 
 
 
 
 
 
b0867f8
5eb4857
cbe40ee
 
 
 
 
17c916b
b0867f8
 
219e91e
b0867f8
 
7bca9a7
47835df
232234c
eced686
7bca9a7
5eb4857
7bca9a7
b0867f8
 
7bca9a7
47835df
 
 
 
b0867f8
cbe40ee
232234c
b0867f8
 
47835df
 
7bca9a7
 
47835df
b0867f8
 
 
 
 
cb0eb6e
b0867f8
7bca9a7
219e91e
 
7bca9a7
219e91e
 
 
 
 
232234c
219e91e
 
 
 
7bca9a7
 
219e91e
 
 
 
 
 
cb0eb6e
219e91e
b0867f8
 
eced686
219e91e
eced686
b0867f8
cb0eb6e
b0867f8
eced686
 
 
 
 
 
 
b0867f8
 
 
 
 
 
 
 
 
 
 
 
5eb4857
04b3d6d
 
 
 
 
eced686
 
 
04b3d6d
 
 
41e5000
eced686
b0867f8
 
 
 
 
 
5eb4857
 
b0867f8
 
 
 
 
 
 
 
 
eced686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0867f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b0867f8
 
 
 
829f259
b0867f8
 
 
 
 
 
 
 
 
829f259
 
b0867f8
5eb4857
 
b0867f8
829f259
 
b0867f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b0867f8
5eb4857
4663444
232234c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
b0867f8
219e91e
 
 
 
232234c
 
 
 
 
eced686
 
 
04b3d6d
232234c
 
41e5000
eced686
219e91e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eced686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219e91e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4663444
232234c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219e91e
 
 
 
b0867f8
 
 
 
 
eced686
b0867f8
 
 
 
 
 
eced686
b0867f8
 
 
 
 
 
 
219e91e
b0867f8
 
 
5eb4857
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
import React, { useState, useEffect, useCallback } from 'react';
import { useAuth, api } from '@nexus/shared';
import { 
  ShieldCheck, 
  Activity, 
  Clock, 
  Filter, 
  RefreshCcw,
  Fingerprint,
  ChevronLeft,
  ChevronRight,
  Search
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import styles from './ForensicsView.module.css';

interface AuditLog {
  id: string;
  workspace_id: string | null;
  entity_type: string;
  entity_id: string;
  action: string;
  user_id: string | null;
  actor_name: string;
  old_value: any;
  new_value: any;
  metadata_json: any;
  created_at: string;
}

interface AIInteraction {
  id: string;
  agent_name: string;
  model_info: string;
  input_data: any;
  output_data: any;
  status: string;
  duration_ms: any;
  usage_metadata: any;
  created_at: string;
}

type ForensicsTab = 'ai' | 'security';

interface ForensicsViewProps {
  workspaceId?: string;
}

export const ForensicsView: React.FC<ForensicsViewProps> = ({ workspaceId }) => {
  useAuth();
  const [activeTab, setActiveTab] = useState<ForensicsTab>('security');
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [aiTraces, setAiTraces] = useState<AIInteraction[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState<string>('');
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [localSearch, setLocalSearch] = useState<string>('');
  const LIMIT = 20; // Smaller limit for better pagination feel

  const fetchAuditLogs = useCallback(async (targetPage = 1) => {
    setLoading(true);
    try {
      const currentOffset = (targetPage - 1) * LIMIT;
      const params: any = {
        limit: LIMIT,
        offset: currentOffset
      };
      if (filterType) params.entity_type = filterType;
      if (workspaceId) params.workspace_id = workspaceId;
      if (searchTerm) params.entity_id = searchTerm; // Support searching by entity ID
      
      const res = await api.get('system/audit/', { params });
      const newLogs = res.data || [];
      
      setLogs(newLogs);
      setPage(targetPage);
      setHasMore(newLogs.length === LIMIT);
    } catch (err) {
      console.error('Forensics fetch failed', err);
    } finally {
      setLoading(false);
    }
  }, [filterType, workspaceId, searchTerm]);

  const fetchAIInteractions = useCallback(async (targetPage = 1) => {
    setLoading(true);
    try {
      const currentOffset = (targetPage - 1) * LIMIT;
      const params: any = {
        limit: LIMIT,
        offset: currentOffset
      };
      if (workspaceId) params.workspace_id = workspaceId;
      if (searchTerm) params.ticket_id = searchTerm; // Neural traces search by ticket ID
      
      const res = await api.get('system/interactions/', { params });
      const newTraces = res.data || [];
      
      setAiTraces(newTraces);
      setPage(targetPage);
      setHasMore(newTraces.length === LIMIT);
    } catch (err) {
      console.error('AI Forensics fetch failed', err);
    } finally {
      setLoading(false);
    }
  }, [workspaceId, searchTerm]);

  useEffect(() => {
    if (activeTab === 'security') {
      fetchAuditLogs(page);
    } else {
      fetchAIInteractions(page);
    }
  }, [activeTab, filterType, searchTerm, workspaceId, page, fetchAuditLogs, fetchAIInteractions]);

  const handleSearchKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      setPage(1);
      setSearchTerm(localSearch);
    }
  };

  const renderSecurityAudit = () => (
    <div className={styles.auditContainer}>
      <div className={styles.auditHeader}>
        <div className={styles.filters}>
          <div className={styles.filterItem}>
            <Filter size={14} />
            <select value={filterType} onChange={(e) => setFilterType(e.target.value)}>
              <option value="">ALL ENTITIES</option>
              <option value="user">USER MANAGEMENT</option>
              <option value="ticket">TICKET ACTIONS</option>
              <option value="workspace">WORKSPACE CONFIG</option>
            </select>
          </div>
          <div className={styles.filterItem}>
            <Search size={14} />
            <input 
              type="text" 
              placeholder="SEARCH ENTITY ID..." 
              value={localSearch}
              onChange={(e) => setLocalSearch(e.target.value)}
              onKeyDown={handleSearchKeyDown}
              style={{ background: 'transparent', border: 'none', color: 'inherit', fontSize: '11px', outline: 'none', width: '150px' }}
            />
          </div>
          <button className={styles.refreshBtn} onClick={() => fetchAuditLogs(1)} disabled={loading}>
            <RefreshCcw size={14} className={loading ? styles.spinning : ''} />
          </button>
        </div>
        <div className={styles.auditBadge}>
          <ShieldCheck size={14} />
          <span>RECURSIVE INTEGRITY CHECK: PASSED</span>
        </div>
      </div>

      <div className={styles.auditTable}>
        <div className={styles.tableHeader}>
          <div className={styles.col}>TIMESTAMP</div>
          <div className={styles.col}>ACTOR</div>
          <div className={styles.col}>ACTION</div>
          <div className={styles.col}>ENTITY</div>
          <div className={styles.col}>INTELLIGENCE</div>
        </div>
        
        <div className={`${styles.tableBody} ${loading ? styles.loading : ''}`}>
          <AnimatePresence>
            {loading && (
              <motion.div 
                className={styles.loadingOverlay}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
              >
                <RefreshCcw size={24} className={styles.spinning} />
                <span>FILTERING AUDIT TRAILS...</span>
              </motion.div>
            )}
          </AnimatePresence>
          <div className={styles.tableScroll}>
          <AnimatePresence mode="popLayout">
            {logs.map((log, idx) => (
              <motion.div 
                key={log.id} 
                className={styles.tableRow}
                initial={{ opacity: 0, x: -10 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: idx * 0.03 }}
              >
                <div className={styles.col}>
                  <div className={styles.timeWrapper}>
                    <Clock size={12} />
                    {new Date(log.created_at).toLocaleTimeString()}
                  </div>
                  <div className={styles.dateLabel}>{new Date(log.created_at).toLocaleDateString()}</div>
                </div>
                
                <div className={styles.col}>
                  <div className={styles.actorCell}>
                    <div className={styles.actorAvatar}>
                      {log.actor_name?.[0] || 'S'}
                    </div>
                    <div className={styles.actorInfo}>
                      <span className={styles.actorName}>{log.actor_name}</span>
                      <span className={styles.actorId}>{log.user_id?.slice(0, 8) || 'SYSTEM'}</span>
                    </div>
                  </div>
                </div>

                <div className={styles.col}>
                  <div className={`${styles.actionPill} ${(log.action || '').includes('failure') ? styles.fail : styles.pass}`}>
                    {(log.action || 'system_action').replace(/_/g, ' ').toUpperCase()}
                  </div>
                </div>

                <div className={styles.col}>
                  <span className={styles.entityTag}>{(log.entity_type || 'system').toUpperCase()}</span>
                  <span className={styles.entityId}>#{log.entity_id?.slice(0, 8) || '0000'}</span>
                </div>

                <div className={styles.col}>
                  <div className={styles.detailBox}>
                    {log.new_value ? (
                      <pre className={styles.jsonDetail}>{JSON.stringify(log.new_value, null, 2)}</pre>
                    ) : (
                      <span className={styles.noData}>Stateless interaction record</span>
                    )}
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
          
          {logs.length === 0 && !loading && (
            <div className={styles.emptyState}>
              <Fingerprint size={48} opacity={0.2} />
              <p>No security events found matching current filter.</p>
            </div>
          )}
        </div>
      </div>

        <div className={styles.paginationFooter}>
          <div className={styles.pagination}>
            <button 
              className={styles.pageBtn} 
              onClick={() => fetchAuditLogs(page - 1)}
              disabled={page === 1 || loading}
            >
              <ChevronLeft size={16} />
            </button>
            <div className={styles.pageIndicator}>
              PAGE <span>{page}</span>
            </div>
            <button 
              className={styles.pageBtn}
              onClick={() => fetchAuditLogs(page + 1)}
              disabled={!hasMore || loading}
            >
              <ChevronRight size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  const renderNeuralTrace = () => (
    <div className={styles.auditContainer}>
      <div className={styles.auditHeader}>
        <div className={styles.filters}>
          <div className={styles.filterItem}>
            <Search size={14} />
            <input 
              type="text" 
              placeholder="SEARCH TICKET ID..." 
              value={localSearch}
              onChange={(e) => setLocalSearch(e.target.value)}
              onKeyDown={handleSearchKeyDown}
              style={{ background: 'transparent', border: 'none', color: 'inherit', fontSize: '11px', outline: 'none', width: '180px' }}
            />
          </div>
          <button className={styles.refreshBtn} onClick={() => fetchAIInteractions(1)} disabled={loading}>
            <RefreshCcw size={14} className={loading ? styles.spinning : ''} />
          </button>
        </div>
        <div className={styles.aiBadge}>
          <Activity size={14} />
          <span>NEURAL STREAM: ACTIVE</span>
        </div>
      </div>

      <div className={styles.auditTable}>
        <div className={styles.tableHeader}>
          <div className={styles.col}>TIMESTAMP</div>
          <div className={styles.col}>AGENT / MODEL</div>
          <div className={styles.col}>METRICS</div>
          <div className={styles.col}>STATUS</div>
          <div className={styles.col}>INTELLIGENCE</div>
        </div>
        
        <div className={`${styles.tableBody} ${loading ? styles.loading : ''}`}>
          <AnimatePresence>
            {loading && (
              <motion.div 
                className={styles.loadingOverlay}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
              >
                <Activity size={24} className={styles.spinning} />
                <span>ISOLATING NEURAL TRACES...</span>
              </motion.div>
            )}
          </AnimatePresence>
          <div className={styles.tableScroll}>
          <AnimatePresence mode="popLayout">
            {aiTraces.map((trace, idx) => (
              <motion.div 
                key={trace.id} 
                className={styles.tableRow}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: idx * 0.02 }}
              >
                <div className={styles.col}>
                  <div className={styles.timeWrapper}>
                    <Clock size={12} />
                    {new Date(trace.created_at).toLocaleTimeString()}
                  </div>
                  <div className={styles.dateLabel}>{new Date(trace.created_at).toLocaleDateString()}</div>
                </div>
                
                <div className={styles.col}>
                  <div className={styles.agentInfo}>
                    <span className={styles.agentName}>{trace.agent_name.replace(/_/g, ' ').toUpperCase()}</span>
                    <span className={styles.modelInfo}>{trace.model_info || 'NEURAL_CORE_V1'}</span>
                  </div>
                </div>

                <div className={styles.col}>
                  <div className={styles.metricStack}>
                    <div className={styles.metricItem}>
                      <span className={styles.mLabel}>LATENCY:</span>
                      <span className={styles.mValue}>{trace.duration_ms?.total || trace.duration_ms || 0}ms</span>
                    </div>
                    <div className={styles.metricItem}>
                      <span className={styles.mLabel}>TOKENS:</span>
                      <span className={styles.mValue}>{trace.usage_metadata?.total_tokens || 0}</span>
                    </div>
                  </div>
                </div>

                <div className={styles.col}>
                  <div className={`${styles.actionPill} ${trace.status === 'error' ? styles.fail : styles.pass}`}>
                    {(trace.status || 'SUCCESS').toUpperCase()}
                  </div>
                </div>

                <div className={styles.col}>
                  <div className={styles.detailBox}>
                    <div className={styles.traceSection}>
                      <span className={styles.traceLabel}>PROMPT_GUIDE:</span>
                      <pre className={styles.jsonDetail}>{JSON.stringify(trace.input_data, null, 2)}</pre>
                    </div>
                    <div className={styles.traceDivider} />
                    <div className={styles.traceSection}>
                      <span className={styles.traceLabel}>RESULTANT_INFERENCE:</span>
                      <pre className={styles.jsonDetail}>{JSON.stringify(trace.output_data, null, 2)}</pre>
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
          
          {aiTraces.length === 0 && !loading && (
            <div className={styles.emptyState}>
              <Activity size={48} opacity={0.2} />
              <p>No neural traces found in current temporal window.</p>
            </div>
          )}
        </div>
      </div>

        <div className={styles.paginationFooter}>
          <div className={styles.pagination}>
            <button 
              className={styles.pageBtn} 
              onClick={() => fetchAIInteractions(page - 1)}
              disabled={page === 1 || loading}
            >
              <ChevronLeft size={16} />
            </button>
            <div className={styles.pageIndicator}>
              PAGE <span>{page}</span>
            </div>
            <button 
              className={styles.pageBtn}
              onClick={() => fetchAIInteractions(page + 1)}
              disabled={!hasMore || loading}
            >
              <ChevronRight size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className={styles.container}>
      <nav className={styles.tabNav}>
        <button 
          className={`${styles.tabBtn} ${activeTab === 'security' ? styles.active : ''}`}
          onClick={() => { setActiveTab('security'); setLocalSearch(''); setSearchTerm(''); setPage(1); }}
        >
          <ShieldCheck size={18} />
          SECURITY AUDIT LOG
        </button>
        <button 
          className={`${styles.tabBtn} ${activeTab === 'ai' ? styles.active : ''}`}
          onClick={() => { setActiveTab('ai'); setLocalSearch(''); setSearchTerm(''); setPage(1); }}
        >
          <Activity size={18} />
          NEURAL TRACE FORENSICS
        </button>
      </nav>

      <div className={styles.content}>
        {activeTab === 'security' ? renderSecurityAudit() : renderNeuralTrace()}
      </div>
    </div>
  );
};