This repository was archived by the owner on Mar 24, 2026. It is now read-only.
forked from Synapsr/Vexa-Dashboard
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdecisions-panel.tsx
More file actions
651 lines (592 loc) · 22.2 KB
/
decisions-panel.tsx
File metadata and controls
651 lines (592 loc) · 22.2 KB
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
"use client";
import { useEffect, useRef, useState, useCallback } from "react";
import {
CheckCircle2,
XCircle,
Pencil,
Plus,
ChevronDown,
ChevronUp,
Zap,
ClipboardList,
Cpu,
Check,
X,
Lightbulb,
Timer,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { toast } from "sonner";
import { useRuntimeConfig } from "@/hooks/use-runtime-config";
import { cn } from "@/lib/utils";
// ────────────────────────────────────────────────────────────────────────────
// Types
// ────────────────────────────────────────────────────────────────────────────
export type DecisionItemType =
| "decision"
| "action_item"
| "architecture_statement"
| "key_insight"
| "commitment";
export interface DecisionItem {
id: string; // client-generated UUID
type: DecisionItemType;
summary: string;
speaker?: string;
confidence?: number;
meeting_id?: string;
status: "pending" | "approved" | "discarded";
editedSummary?: string; // set when user edits before approving
isManual?: boolean;
}
// ────────────────────────────────────────────────────────────────────────────
// Helpers
// ────────────────────────────────────────────────────────────────────────────
function uid() {
return Math.random().toString(36).slice(2) + Date.now().toString(36);
}
/**
* Jaccard similarity on significant words (>3 chars).
* Returns 0–1. Threshold of 0.65 catches near-duplicate LLM phrasings.
*/
function wordSimilarity(a: string, b: string): number {
const tokenize = (s: string) =>
new Set(
s
.toLowerCase()
.replace(/[^a-z0-9\s]/g, "")
.split(/\s+/)
.filter((w) => w.length > 3)
);
const wa = tokenize(a);
const wb = tokenize(b);
if (wa.size === 0 && wb.size === 0) return 1;
const intersection = [...wa].filter((w) => wb.has(w)).length;
const union = new Set([...wa, ...wb]).size;
return union === 0 ? 0 : intersection / union;
}
const SIMILARITY_THRESHOLD = 0.65;
const TYPE_META: Record<
DecisionItemType,
{ label: string; icon: React.ReactNode; badgeClass: string }
> = {
decision: {
label: "Decision",
icon: <CheckCircle2 className="h-3.5 w-3.5" />,
badgeClass: "bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",
},
action_item: {
label: "Action Item",
icon: <ClipboardList className="h-3.5 w-3.5" />,
badgeClass: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
},
architecture_statement: {
label: "Architecture",
icon: <Cpu className="h-3.5 w-3.5" />,
badgeClass: "bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300",
},
key_insight: {
label: "Key Insight",
icon: <Lightbulb className="h-3.5 w-3.5" />,
badgeClass: "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",
},
commitment: {
label: "Commitment",
icon: <Timer className="h-3.5 w-3.5" />,
badgeClass: "bg-rose-100 text-rose-800 dark:bg-rose-900/40 dark:text-rose-300",
},
};
// ────────────────────────────────────────────────────────────────────────────
// Notification sound (tiny inline beep)
// ────────────────────────────────────────────────────────────────────────────
function playNotificationSound() {
try {
const ctx = new AudioContext();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = 880;
osc.type = "sine";
gain.gain.setValueAtTime(0, ctx.currentTime);
gain.gain.linearRampToValueAtTime(0.18, ctx.currentTime + 0.02);
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.35);
osc.start(ctx.currentTime);
osc.stop(ctx.currentTime + 0.35);
osc.onended = () => ctx.close();
} catch {
// audio not available — silently ignore
}
}
// ────────────────────────────────────────────────────────────────────────────
// Single item row
// ────────────────────────────────────────────────────────────────────────────
function DecisionRow({
item,
onApprove,
onDiscard,
onEdit,
}: {
item: DecisionItem;
onApprove: (id: string, summary: string) => void;
onDiscard: (id: string) => void;
onEdit: (id: string, summary: string) => void;
}) {
const meta = TYPE_META[item.type];
const [isEditing, setIsEditing] = useState(false);
const [draft, setDraft] = useState(item.editedSummary ?? item.summary);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleEditStart = () => {
setDraft(item.editedSummary ?? item.summary);
setIsEditing(true);
setTimeout(() => textareaRef.current?.focus(), 0);
};
const handleEditSave = () => {
if (draft.trim()) {
onEdit(item.id, draft.trim());
}
setIsEditing(false);
};
const handleEditCancel = () => {
setDraft(item.editedSummary ?? item.summary);
setIsEditing(false);
};
const displayText = item.editedSummary ?? item.summary;
if (item.status === "discarded") return null;
return (
<div
className={cn(
"rounded-lg border p-3 space-y-2 transition-all",
item.status === "approved"
? "bg-muted/30 opacity-70"
: "bg-card"
)}
>
{/* Header row */}
<div className="flex items-center gap-2 flex-wrap">
<span
className={cn(
"inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full",
meta.badgeClass
)}
>
{meta.icon}
{meta.label}
</span>
{item.speaker && (
<span className="text-[10px] text-muted-foreground">
{item.speaker}
</span>
)}
{item.confidence != null && (
<span className="text-[10px] text-muted-foreground ml-auto">
{Math.round(item.confidence * 100)}%
</span>
)}
{item.isManual && (
<Badge variant="outline" className="text-[9px] h-4 px-1 ml-auto">
manual
</Badge>
)}
{item.status === "approved" && (
<Badge className="text-[9px] h-4 px-1 ml-auto bg-green-500 text-white">
approved
</Badge>
)}
</div>
{/* Content */}
{isEditing ? (
<div className="space-y-2">
<Textarea
ref={textareaRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}
className="min-h-[60px] text-sm resize-none"
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleEditSave();
if (e.key === "Escape") handleEditCancel();
}}
/>
<div className="flex gap-1.5">
<Button
size="sm"
className="h-7 text-xs gap-1"
onClick={handleEditSave}
disabled={!draft.trim()}
>
<Check className="h-3 w-3" />
Save
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 text-xs gap-1"
onClick={handleEditCancel}
>
<X className="h-3 w-3" />
Cancel
</Button>
</div>
</div>
) : (
<p className="text-sm leading-snug">{displayText}</p>
)}
{/* Actions — only show when pending */}
{item.status === "pending" && !isEditing && (
<div className="flex gap-1.5 pt-0.5">
<Button
size="sm"
className="h-7 text-xs gap-1 bg-green-600 hover:bg-green-700 text-white"
onClick={() => onApprove(item.id, item.editedSummary ?? item.summary)}
>
<CheckCircle2 className="h-3 w-3" />
Approve
</Button>
<Button
size="sm"
variant="outline"
className="h-7 text-xs gap-1"
onClick={handleEditStart}
>
<Pencil className="h-3 w-3" />
Edit
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 text-xs gap-1 text-destructive hover:text-destructive"
onClick={() => onDiscard(item.id)}
>
<XCircle className="h-3 w-3" />
Discard
</Button>
</div>
)}
</div>
);
}
// ────────────────────────────────────────────────────────────────────────────
// Manual add form
// ────────────────────────────────────────────────────────────────────────────
function AddManualForm({ onAdd }: { onAdd: (item: Omit<DecisionItem, "id" | "status">) => void }) {
const [open, setOpen] = useState(false);
const [text, setText] = useState("");
const [type, setType] = useState<DecisionItemType>("decision");
const handleSubmit = () => {
const trimmed = text.trim();
if (!trimmed) return;
onAdd({ type, summary: trimmed, isManual: true });
setText("");
setOpen(false);
};
if (!open) {
return (
<Button
variant="outline"
size="sm"
className="w-full h-8 text-xs gap-1.5 mt-1"
onClick={() => setOpen(true)}
>
<Plus className="h-3.5 w-3.5" />
Add manually
</Button>
);
}
return (
<div className="rounded-lg border p-3 space-y-2 bg-muted/20">
<div className="flex gap-1.5 flex-wrap">
{(["decision", "action_item", "architecture_statement"] as DecisionItemType[]).map(
(t) => (
<button
key={t}
onClick={() => setType(t)}
className={cn(
"inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full transition-opacity",
TYPE_META[t].badgeClass,
type !== t && "opacity-40"
)}
>
{TYPE_META[t].icon}
{TYPE_META[t].label}
</button>
)
)}
</div>
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Describe the decision, action item, or architecture note…"
className="min-h-[70px] text-sm resize-none"
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleSubmit();
if (e.key === "Escape") setOpen(false);
}}
/>
<div className="flex gap-1.5">
<Button size="sm" className="h-7 text-xs" onClick={handleSubmit} disabled={!text.trim()}>
Add
</Button>
<Button size="sm" variant="ghost" className="h-7 text-xs" onClick={() => setOpen(false)}>
Cancel
</Button>
</div>
</div>
);
}
// ────────────────────────────────────────────────────────────────────────────
// Main panel
// ────────────────────────────────────────────────────────────────────────────
interface DecisionsPanelProps {
meetingId: string;
isActive: boolean; // whether meeting is live
embedded?: boolean; // when true, renders without Card wrapper / collapse toggle
}
export function DecisionsPanel({ meetingId, isActive, embedded }: DecisionsPanelProps) {
const { config } = useRuntimeConfig();
const decisionListenerUrl = config?.decisionListenerUrl ?? "http://localhost:8765";
const [items, setItems] = useState<DecisionItem[]>([]);
const [isCollapsed, setIsCollapsed] = useState(false);
const [connected, setConnected] = useState(false);
const esRef = useRef<EventSource | null>(null);
// Keep a ref to current items for use inside SSE handler without stale closure
const itemsRef = useRef<DecisionItem[]>([]);
itemsRef.current = items;
// ── SSE connection ──────────────────────────────────────────────────────
const connectSSE = useCallback(() => {
if (esRef.current) return; // already connected
const url = `${decisionListenerUrl}/decisions/${meetingId}`;
const es = new EventSource(url);
esRef.current = es;
es.onopen = () => setConnected(true);
es.onmessage = (ev) => {
try {
const data = JSON.parse(ev.data);
if (!data.type || data.type === "no_match") return;
const incomingSummary = (data.summary ?? "").trim();
// Fuzzy dedup: skip if a non-discarded item of same type is already similar
const alreadyExists = itemsRef.current
.filter((it) => it.status !== "discarded" && it.type === data.type)
.some((it) =>
wordSimilarity(it.editedSummary ?? it.summary, incomingSummary) >= SIMILARITY_THRESHOLD
);
if (alreadyExists) return;
const newItem: DecisionItem = {
id: uid(),
type: data.type as DecisionItemType,
summary: incomingSummary,
speaker: data.speaker,
confidence: data.confidence,
meeting_id: data.meeting_id,
status: "pending",
};
setItems((prev) => [newItem, ...prev]);
playNotificationSound();
toast.success(`New ${TYPE_META[newItem.type].label} detected`, {
description:
newItem.summary.length > 90
? newItem.summary.slice(0, 90) + "…"
: newItem.summary,
duration: 6000,
});
} catch {
// ignore parse errors
}
};
es.onerror = () => {
setConnected(false);
es.close();
esRef.current = null;
// Reconnect after 5 s if still active
setTimeout(() => {
if (isActive) connectSSE();
}, 5000);
};
}, [decisionListenerUrl, meetingId, isActive]);
useEffect(() => {
if (!isActive) return;
connectSSE();
return () => {
esRef.current?.close();
esRef.current = null;
};
}, [isActive, connectSSE]);
// ── Load existing decisions on mount ────────────────────────────────────
useEffect(() => {
const load = async () => {
try {
const res = await fetch(
`${decisionListenerUrl}/decisions/${meetingId}/all`
);
if (!res.ok) return;
const data = await res.json();
const loaded: DecisionItem[] = (data.items ?? [])
.filter((d: { type?: string }) => d.type && d.type !== "no_match")
.map((d: {
type: DecisionItemType;
summary?: string;
speaker?: string;
confidence?: number;
}) => ({
id: uid(),
type: d.type,
summary: d.summary ?? "",
speaker: d.speaker,
confidence: d.confidence,
status: "approved" as const,
}));
if (loaded.length > 0) {
setItems(loaded.reverse()); // oldest first → newest on top after state set
}
} catch {
// silently ignore if listener not available
}
};
load();
}, [decisionListenerUrl, meetingId]);
// ── Item actions ─────────────────────────────────────────────────────────
const handleApprove = (id: string, _summary: string) => {
setItems((prev) =>
prev.map((it) => (it.id === id ? { ...it, status: "approved" } : it))
);
toast.success("Decision approved");
};
const handleDiscard = (id: string) => {
setItems((prev) =>
prev.map((it) => (it.id === id ? { ...it, status: "discarded" } : it))
);
};
const handleEdit = (id: string, summary: string) => {
setItems((prev) =>
prev.map((it) => (it.id === id ? { ...it, editedSummary: summary } : it))
);
};
const handleAddManual = (partial: Omit<DecisionItem, "id" | "status">) => {
const newItem: DecisionItem = {
...partial,
id: uid(),
status: "pending",
};
setItems((prev) => [newItem, ...prev]);
};
// ── Derived counts ───────────────────────────────────────────────────────
const visibleItems = items.filter((it) => it.status !== "discarded");
const pendingCount = items.filter((it) => it.status === "pending").length;
// ── Status indicator (shared) ─────────────────────────────────────────────
const statusIndicator = isActive && (
<span
className={cn(
"inline-flex items-center gap-1 text-[10px] font-medium",
connected ? "text-green-600" : "text-muted-foreground"
)}
>
<span
className={cn(
"h-1.5 w-1.5 rounded-full",
connected ? "bg-green-500 animate-pulse" : "bg-muted-foreground"
)}
/>
{connected ? "live" : "connecting…"}
</span>
);
// ── Embedded mode (inside slide-over panel) ───────────────────────────────
if (embedded) {
return (
<div className="flex flex-col h-full space-y-3">
{/* Status bar */}
<div className="flex items-center justify-between">
{statusIndicator}
{pendingCount > 0 && (
<span className="inline-flex items-center justify-center h-5 min-w-[20px] px-1.5 rounded-full bg-amber-500 text-[10px] font-bold text-white">
{pendingCount} pending
</span>
)}
</div>
{/* Items */}
<div className="flex-1 space-y-2 overflow-y-auto min-h-0">
{visibleItems.length === 0 ? (
<p className="text-xs text-muted-foreground italic">
{isActive
? "Listening for decisions, action items, and architecture statements…"
: "No items detected."}
</p>
) : (
visibleItems.map((item) => (
<DecisionRow
key={item.id}
item={item}
onApprove={handleApprove}
onDiscard={handleDiscard}
onEdit={handleEdit}
/>
))
)}
</div>
{visibleItems.length > 0 && <Separator />}
<AddManualForm onAdd={handleAddManual} />
</div>
);
}
// ── Card mode (legacy / sidebar widget) ──────────────────────────────────
return (
<Card className={cn(isActive && pendingCount > 0 && "border-amber-400/60 shadow-amber-400/10 shadow-md")}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2 text-sm">
<Zap className="h-4 w-4 text-amber-500" />
Decisions
{pendingCount > 0 && (
<span className="inline-flex items-center justify-center h-4 min-w-[16px] px-1 rounded-full bg-amber-500 text-[9px] font-bold text-white">
{pendingCount}
</span>
)}
</CardTitle>
<div className="flex items-center gap-1.5">
{statusIndicator}
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={() => setIsCollapsed((v) => !v)}
>
{isCollapsed ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronUp className="h-3.5 w-3.5" />
)}
</Button>
</div>
</div>
</CardHeader>
{!isCollapsed && (
<CardContent className="space-y-2 pt-0">
{visibleItems.length === 0 ? (
<p className="text-xs text-muted-foreground italic">
{isActive
? "Listening for decisions, action items, and architecture statements…"
: "No items detected."}
</p>
) : (
<div className="space-y-2 max-h-[420px] overflow-y-auto pr-0.5">
{visibleItems.map((item) => (
<DecisionRow
key={item.id}
item={item}
onApprove={handleApprove}
onDiscard={handleDiscard}
onEdit={handleEdit}
/>
))}
</div>
)}
{visibleItems.length > 0 && <Separator />}
<AddManualForm onAdd={handleAddManual} />
</CardContent>
)}
</Card>
);
}