-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSessionTable.tsx
More file actions
910 lines (844 loc) · 41 KB
/
Copy pathSessionTable.tsx
File metadata and controls
910 lines (844 loc) · 41 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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
/**
* components/overview/SessionTable.tsx — Live session table with filtering, search, and bulk actions.
*/
import React, { Fragment, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
import { SessionMobileCard } from './SessionMobileCard';
import type { SessionsPaginationState, SessionRowViewModel } from './sessionTableUtils';
import { matchesSearch, formatStatusLabel } from './sessionTableUtils';
import { AgentFilter } from '../agents/AgentFilter';
import type { MouseEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import {
ChevronDown,
ChevronLeft,
ChevronRight,
FolderOpen,
Search,
Sparkles,
Filter,
} from 'lucide-react';
import {
quickApprove,
getAllSessionsHealth,
getSessionStatusCounts,
getSessions,
interrupt,
killSession,
quickReject,
} from '../../api/client';
import { useSseAwarePolling } from '../../hooks/useSseAwarePolling';
import { useToastStore } from '../../store/useToastStore';
import { useStore } from '../../store/useStore';
import { useApprovalStore } from '../../store/useApprovalStore';
import type { RowHealth, SessionStatusCounts, SessionStatusFilter } from '../../types';
import { ConfirmDialog } from '../ConfirmDialog';
import RealtimeBadge from './RealtimeBadge';
import { SessionPreviewCard } from '../session/SessionPreviewCard';
import { VirtualizedSessionList } from './VirtualizedSessionList';
import type { VirtualizedRowData } from './VirtualizedSessionList';
import { useT } from '../../i18n/context';
const FALLBACK_POLL_INTERVAL_MS = 5_000;
const SSE_HEALTHY_POLL_INTERVAL_MS = 30_000;
const PAGE_SIZE = 20;
const SEARCH_SCAN_LIMIT = 100;
const EMPTY_COUNTS: SessionStatusCounts = {
all: 0,
idle: 0,
working: 0,
compacting: 0,
context_warning: 0,
waiting_for_input: 0,
permission_prompt: 0,
plan_mode: 0,
ask_question: 0,
bash_approval: 0,
settings: 0,
error: 0,
rate_limit: 0,
pending: 0,
awaiting_approval: 0,
unknown: 0,
killed: 0,
completed: 0,
crashed: 0,
};
const STATUS_FILTERS: SessionStatusFilter[] = [
'all',
'idle',
'working',
'compacting',
'context_warning',
'waiting_for_input',
'permission_prompt',
'plan_mode',
'ask_question',
'bash_approval',
'settings',
'error',
'rate_limit',
'unknown',
];
// Types moved to sessionTableUtils.ts
const extractDirKey = (workDir: string): string => {
const normalized = workDir.replace(/\\/g, '/');
const segments = normalized.replace(/[\\/]+$/, '').split('/');
return segments[segments.length - 1] || workDir;
};
// Utilities moved to sessionTableUtils.ts
interface SessionTableProps {
maxRows?: number;
}
export default React.memo(function SessionTable({ maxRows }: SessionTableProps = {}) {
const t = useT();
const sessions = useStore((s) => s.sessions);
const healthMap = useStore((s) => s.healthMap);
const sseConnected = useStore((s) => s.sseConnected);
const latestActivity = useStore((s) => s.activities[0] ?? null);
const sseError = useStore((s) => s.sseError);
const setSessionsAndHealth = useStore((s) => s.setSessionsAndHealth);
const addToast = useToastStore((t) => t.addToast);
const navigate = useNavigate();
const [focusedIndex, setFocusedIndex] = useState(-1);
const [groupByDir, setGroupByDir] = useState(true);
const [workDirFilter, setWorkDirFilter] = useState<string>('all');
const [agentFilter, setAgentFilter] = useState<string | null>(null);
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set());
const uniqueWorkDirs = useMemo(() => {
const dirs = new Map<string, string>();
for (const s of sessions) {
const key = extractDirKey(s.workDir);
if (!dirs.has(key)) dirs.set(key, s.workDir);
}
return Array.from(dirs.entries()).sort((a, b) => a[0].localeCompare(b[0]));
}, [sessions]);
// Keyboard shortcuts: arrows navigate, Enter opens, Delete kills
useEffect(() => {
const handler = (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
const isInput =
target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.tagName === 'SELECT' ||
target.isContentEditable;
if (isInput) return;
const list = sessions;
if (list.length === 0) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setFocusedIndex((prev) => (prev < list.length - 1 ? prev + 1 : prev));
break;
case 'ArrowUp':
e.preventDefault();
setFocusedIndex((prev) => (prev > 0 ? prev - 1 : 0));
break;
case 'Enter':
if (e.ctrlKey || e.metaKey) return;
if (focusedIndex >= 0 && focusedIndex < list.length) {
e.preventDefault();
navigate(`/sessions/${encodeURIComponent(list[focusedIndex].id)}`);
}
break;
case 'Delete':
case 'Backspace':
if (focusedIndex >= 0 && focusedIndex < list.length) {
const id = list[focusedIndex].id;
if (window.confirm(`Kill session ${id}?`)) {
killSession(id)
.then(() => addToast('success', 'Session killed', id))
.catch(() => addToast('error', 'Kill failed', id));
}
}
break;
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [sessions, focusedIndex, navigate, addToast]);
const [actionLoading, setActionLoading] = useState<Record<string, string | null>>({});
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [bulkAction, setBulkAction] = useState<'interrupt' | 'kill' | null>(null);
const [confirmKill, setConfirmKill] = useState<{ type: 'single'; id: string } | { type: 'bulk'; count: number } | null>(null);
const [statusFilter, setStatusFilter] = useState<SessionStatusFilter>('all');
const [statusCounts, setStatusCounts] = useState<SessionStatusCounts>(EMPTY_COUNTS);
const [searchInput, setSearchInput] = useState('');
const deferredSearch = useDeferredValue(searchInput.trim().toLowerCase());
const [pagination, setPagination] = useState<SessionsPaginationState>({
page: 1,
limit: PAGE_SIZE,
total: 0,
totalPages: 0,
});
const [page, setPage] = useState(1);
const [isLoading, setIsLoading] = useState(true);
const [searchCapped, setSearchCapped] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [hoveredSessionId, setHoveredSessionId] = useState<string | null>(null);
const hoveredRowRef = useRef<HTMLElement | null>(null);
const hoveredSession = sessions.find((s) => s.id === hoveredSessionId) ?? null;
// Demo sessions state
function handleSurpriseMe() {
// Trigger re-render by updating a dummy state
setPage((p) => p);
addToast('success', 'Demo sessions created', 'Three example sessions added (auto-expire in 24h)');
}
const fetchSessions = useCallback(async () => {
setIsLoading(true);
try {
const isSearching = deferredSearch.length > 0;
const listPromise = getSessions({
page: isSearching ? 1 : page,
limit: isSearching ? SEARCH_SCAN_LIMIT : PAGE_SIZE,
status: statusFilter === 'all' ? undefined : statusFilter,
});
const [list, counts] = await Promise.all([listPromise, getSessionStatusCounts()]);
const filteredSessions = isSearching
? list.sessions.filter((session) => matchesSearch(session, deferredSearch))
: list.sessions;
const nextHealthMap: Record<string, RowHealth> = {};
try {
const healthResults = await getAllSessionsHealth();
const liveIds = new Set(filteredSessions.map((session) => session.id));
for (const [id, health] of Object.entries(healthResults)) {
if (liveIds.has(id)) {
nextHealthMap[id] = { alive: health.alive, loading: false };
}
}
} catch {
// Health fetch failed — show sessions without health indicators.
}
setSessionsAndHealth(filteredSessions, nextHealthMap);
// Sync pending approvals to global store
useApprovalStore.getState().setFromSessions(filteredSessions);
setStatusCounts(counts);
setSearchCapped(isSearching && list.pagination.total > list.sessions.length);
setLoadError(null);
setPagination(
isSearching
? {
page: 1,
limit: filteredSessions.length,
total: filteredSessions.length,
totalPages: filteredSessions.length > 0 ? 1 : 0,
}
: list.pagination,
);
} catch (e: unknown) {
setLoadError(
e instanceof Error && e.message
? `Unable to load sessions: ${e.message}`
: 'Unable to load sessions.',
);
} finally {
setIsLoading(false);
}
}, [deferredSearch, page, setSessionsAndHealth, statusFilter]);
useSseAwarePolling({
refresh: fetchSessions,
sseConnected,
eventTrigger: latestActivity,
fallbackPollIntervalMs: FALLBACK_POLL_INTERVAL_MS,
healthyPollIntervalMs: SSE_HEALTHY_POLL_INTERVAL_MS,
});
useEffect(() => {
const visibleIds = new Set(sessions.map((session) => session.id));
setSelectedIds((prev) => prev.filter((id) => visibleIds.has(id)));
}, [sessions]);
const withLoading = useCallback(async (id: string, action: string, fn: () => Promise<void>) => {
setActionLoading((prev) => ({ ...prev, [id]: action }));
try {
await fn();
} finally {
setActionLoading((prev) => ({ ...prev, [id]: null }));
}
}, []);
const handleApprove = useCallback(async (e: MouseEvent, id: string) => {
e.preventDefault();
await withLoading(id, 'approve', async () => {
try {
await quickApprove(id);
await fetchSessions();
} catch (err: unknown) {
addToast('error', 'Approve failed', err instanceof Error ? err.message : undefined);
}
});
}, [addToast, fetchSessions, withLoading]);
const handleReject = useCallback(async (e: MouseEvent, id: string) => {
e.preventDefault();
await withLoading(id, 'reject', async () => {
try {
await quickReject(id);
await fetchSessions();
} catch (err: unknown) {
addToast('error', 'Reject failed', err instanceof Error ? err.message : undefined);
}
});
}, [addToast, fetchSessions, withLoading]);
const handleInterrupt = useCallback(async (e: MouseEvent, id: string) => {
e.preventDefault();
await withLoading(id, 'interrupt', async () => {
try {
await interrupt(id);
await fetchSessions();
} catch (err: unknown) {
addToast('error', 'Interrupt failed', err instanceof Error ? err.message : undefined);
}
});
}, [addToast, fetchSessions, withLoading]);
const handleKill = useCallback((e: MouseEvent, id: string) => {
e.preventDefault();
setConfirmKill({ type: 'single', id });
}, []);
const executeKill = useCallback(async (id: string) => {
await withLoading(id, 'kill', async () => {
try {
await killSession(id);
await fetchSessions();
} catch (err: unknown) {
addToast('error', 'Failed to kill session', err instanceof Error ? err.message : undefined);
}
});
}, [addToast, fetchSessions, withLoading]);
const handleToggleSelect = useCallback((id: string, checked: boolean) => {
setSelectedIds((prev) => {
if (checked) {
return prev.includes(id) ? prev : [...prev, id];
}
return prev.filter((candidate) => candidate !== id);
});
}, []);
const handleToggleSelectAll = useCallback((checked: boolean) => {
if (!checked) {
setSelectedIds([]);
return;
}
setSelectedIds(sessions.map((session) => session.id));
}, [sessions]);
const executeBulkAction = useCallback(async (action: 'interrupt' | 'kill') => {
setBulkAction(action);
setActionLoading((prev) => {
const next = { ...prev };
for (const id of selectedIds) {
next[id] = action;
}
return next;
});
try {
const results = await Promise.allSettled(
selectedIds.map((id) => (action === 'interrupt' ? interrupt(id) : killSession(id))),
);
const successCount = results.filter((result) => result.status === 'fulfilled').length;
const failureCount = results.length - successCount;
if (successCount > 0) {
addToast(
'success',
action === 'interrupt' ? 'Bulk interrupt complete' : 'Bulk kill complete',
`${successCount} session${successCount === 1 ? '' : 's'} updated.`,
);
}
if (failureCount > 0) {
addToast(
'warning',
`Some sessions failed to ${action}`,
`${failureCount} session${failureCount === 1 ? '' : 's'} could not be updated.`,
);
}
setSelectedIds([]);
await fetchSessions();
} finally {
setBulkAction(null);
setActionLoading((prev) => {
const next = { ...prev };
for (const id of selectedIds) {
next[id] = null;
}
return next;
});
}
}, [addToast, fetchSessions, selectedIds]);
const runBulkAction = useCallback((action: 'interrupt' | 'kill') => {
if (selectedIds.length === 0) {
return;
}
if (action === 'kill') {
setConfirmKill({ type: 'bulk', count: selectedIds.length });
return;
}
void executeBulkAction(action);
}, [selectedIds, executeBulkAction]);
const selectedIdSet = useMemo(() => new Set(selectedIds), [selectedIds]);
const handleConfirmKill = useCallback(() => {
if (!confirmKill) return;
if (confirmKill.type === 'single') {
void executeKill(confirmKill.id);
} else {
void executeBulkAction('kill');
}
setConfirmKill(null);
}, [confirmKill, executeKill, executeBulkAction]);
const confirmKillMessage = confirmKill
? confirmKill.type === 'single'
? 'Kill this session? This action cannot be undone.'
: `Kill ${confirmKill.count} selected session${confirmKill.count === 1 ? '' : 's'}? This action cannot be undone.`
: '';
const rowViewModels = useMemo<SessionRowViewModel[]>(() => {
let source = sessions;
if (agentFilter) {
source = source.filter((s) => {
const rn = s.runnerName;
if (rn) return rn === agentFilter;
// Heuristic: infer from model field
const m = (s.model ?? '').toLowerCase();
if (agentFilter === 'claude-code') return m.includes('claude');
if (agentFilter === 'codex') return m.includes('gpt') || m.includes('o1') || m.includes('o3') || m.includes('o4');
if (agentFilter === 'gemini-cli') return m.includes('gemini');
if (agentFilter === 'qwen') return m.includes('qwen');
return false;
});
}
if (workDirFilter !== 'all') {
source = source.filter((s) => extractDirKey(s.workDir) === workDirFilter || s.workDir === workDirFilter);
}
const baseSessions = maxRows ? source.slice(0, maxRows) : source;
return baseSessions.map((session, idx) => {
const health = healthMap[session.id];
return {
session,
isAlive: health ? health.alive : false,
health: health?.health ?? null,
selected: selectedIdSet.has(session.id),
currentAction: actionLoading[session.id] ?? null,
isFocused: idx === focusedIndex,
};
});
}, [actionLoading, healthMap, selectedIdSet, sessions, focusedIndex, maxRows, workDirFilter]);
const groupedRowModels = useMemo(() => {
if (!groupByDir) return null;
const groups = new Map<string, SessionRowViewModel[]>();
for (const vm of rowViewModels) {
const key = extractDirKey(vm.session.workDir);
const list = groups.get(key) ?? [];
list.push(vm);
groups.set(key, list);
}
return groups;
}, [rowViewModels, groupByDir]);
const toggleGroup = useCallback((key: string) => {
setCollapsedGroups((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}, []);
const allVisibleSelected = sessions.length > 0 && sessions.every((session) => selectedIdSet.has(session.id));
const hasActiveFilters = statusFilter !== 'all' || deferredSearch.length > 0;
if (isLoading && sessions.length === 0 && !loadError) {
return (
<div className="card-glass p-16 text-center flex flex-col items-center justify-center min-h-[400px]">
<div className="w-16 h-16 rounded-full border-2 border-[var(--color-accent)]/20 border-t-[var(--color-accent)] animate-spin mb-6 shadow-[0_0_15px_rgba(255,184,0,0.4)]" />
<h3 className="text-xl font-bold tracking-tight text-[var(--color-text-primary)] drop-shadow-md">{t('sessionTable.wakingAgents')}</h3>
<p className="mt-2 text-sm text-[var(--color-text-muted)]">{t('sessionTable.wakingAgentsDescription')}</p>
</div>
);
}
if (loadError && sessions.length === 0) {
return (
<div className="rounded-lg border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/10 p-6">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="text-sm text-[var(--color-warning-glow)]">{loadError}</p>
<button
type="button"
onClick={() => {
setIsLoading(true);
setLoadError(null);
void fetchSessions();
}}
aria-label={t("aria.retryLoading")}
className="rounded-md border border-[var(--color-warning)]/40 px-3 py-2 text-sm text-[var(--color-warning)] dark:text-[var(--color-warning-glow)] transition-colors hover:border-[var(--color-warning)] hover:text-[var(--color-warning)] dark:hover:text-white"
>
Retry
</button>
</div>
</div>
);
}
const showStatusRow = Boolean(loadError) || Boolean(!sseConnected && sseError);
return (
<div className="space-y-6 relative">
<div className="card-glass w-full shadow-[var(--shadow-card)]">
<div className="flex flex-col gap-4 border-b border-[var(--color-overlay-border)] bg-[var(--color-overlay-bg)] p-4 backdrop-blur-md xl:flex-row xl:items-start xl:justify-between">
<div className="flex-1 space-y-3">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
<label className="flex min-w-0 flex-1 items-center gap-2 rounded-lg border border-[var(--color-overlay-border-strong)] bg-[var(--color-void)] px-3 py-3 min-h-[44px] text-sm text-[var(--color-text-primary)] focus-within:border-[var(--color-accent-cyan)] focus-within:ring-1 focus-within:ring-[var(--color-accent-cyan)]/30 transition-all shadow-inner">
<Search className="h-4 w-4 text-[var(--color-text-muted)]" />
<input
value={searchInput}
onChange={(e) => {
setSearchInput(e.target.value);
setPage(1);
}}
placeholder={t('sessionTable.searchPlaceholder')}
className="min-h-[44px] w-full bg-transparent text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
aria-label={t("aria.searchSessions")}
/>
</label>
<label className="flex items-center gap-2 text-sm text-[var(--color-text-muted)]">
<span>{t('sessionTable.status')}</span>
<select
value={statusFilter}
onChange={(e) => {
setStatusFilter(e.target.value as SessionStatusFilter);
setPage(1);
}}
aria-label={t("aria.filterByStatus")}
className="min-h-[44px] rounded-md border border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] px-3 py-2 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-cyan)]"
>
{STATUS_FILTERS.map((status) => (
<option key={status} value={status}>
{formatStatusLabel(status)} ({statusCounts[status] ?? 0})
</option>
))}
</select>
</label>
<button
type="button"
onClick={() => setGroupByDir((prev) => !prev)}
aria-label={groupByDir ? 'Show ungrouped session list' : 'Group sessions by directory'}
aria-pressed={groupByDir}
className={`flex min-h-[36px] items-center gap-1.5 rounded-md border px-3 py-2 text-xs font-medium transition-colors ${groupByDir
? 'border-[var(--color-accent-cyan)] bg-[var(--color-cta-bg)]/10 text-[var(--color-accent-cyan)]'
: 'border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] text-[var(--color-text-muted)] hover:border-[var(--color-accent-cyan)]/40 hover:text-[var(--color-text-primary)]'}`}
>
<FolderOpen className="h-3.5 w-3.5" />
{groupByDir ? 'Ungroup' : 'By Directory'}
</button>
{uniqueWorkDirs.length > 1 && (
<label className="flex items-center gap-2 text-sm text-[var(--color-text-muted)]">
<Filter className="h-3.5 w-3.5" />
<select
value={workDirFilter}
onChange={(e) => {
setWorkDirFilter(e.target.value);
setPage(1);
}}
aria-label={t("aria.filterByDirectory")}
className="min-h-[36px] rounded-md border border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] px-2 py-1 text-xs text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-cyan)] max-w-[180px]"
>
<option value="all">{t("aria.allDirectories")} ({sessions.length})</option>
{uniqueWorkDirs.map(([key, full]) => (
<option key={key} value={key} title={full}>
{key}
</option>
))}
</select>
</label>
)}
<AgentFilter
value={agentFilter}
onChange={(v) => { setAgentFilter(v); setPage(1); }}
/>
</div>
<div className="flex flex-wrap gap-2" role="group" aria-label={t("aria.filterByStatusGroup")}>
{STATUS_FILTERS.filter((status) => status === 'all' || (statusCounts[status] ?? 0) > 0).map((status) => {
const isActive = statusFilter === status;
return (
<button
key={status}
type="button"
aria-pressed={isActive}
aria-label={`${formatStatusLabel(status)}, ${statusCounts[status] ?? 0} sessions`}
onClick={() => {
setStatusFilter(status);
setPage(1);
}}
className={`min-h-[44px] rounded-full border px-3 py-1.5 text-xs transition-colors ${isActive
? 'border-[var(--color-accent-cyan)] bg-[var(--color-cta-bg)]/10 text-[var(--color-accent-cyan)]'
: 'border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] text-[var(--color-text-muted)] hover:border-[var(--color-accent-cyan)]/40 hover:text-[var(--color-text-primary)]'}`}
>
{formatStatusLabel(status)} <span className="text-[var(--color-text-muted)]">{statusCounts[status] ?? 0}</span>
</button>
);
})}
</div>
</div>
<div className="text-right text-xs text-[var(--color-text-muted)]">
<div>
Showing <span className="text-[var(--color-text-primary)]">{sessions.length}</span>
{deferredSearch.length > 0
? ` matching session${sessions.length === 1 ? '' : 's'}`
: ` of ${pagination.total} session${pagination.total === 1 ? '' : 's'}`}
</div>
{searchCapped && (
<div className="mt-2 flex items-center gap-1.5 rounded-lg border border-[var(--color-warning)]/30 bg-[var(--color-warning)]/10 px-3 py-2 text-xs text-[var(--color-warning)]" role="alert">
<svg className="h-3.5 w-3.5 shrink-0" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fillRule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clipRule="evenodd"/></svg>
<span>
Only the first <strong>{SEARCH_SCAN_LIMIT}</strong> sessions were searched. Use status filters or session ID to narrow results.
</span>
</div>
)}
</div>
</div>
{showStatusRow && (
<div
role="status"
aria-live="polite"
className="mt-4 flex flex-wrap items-center justify-between gap-2 rounded-md border border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] px-3 py-2"
>
<div className="text-xs text-[var(--color-text-muted)]">{loadError ?? 'Session data is using polling fallback while real-time updates recover.'}</div>
{!sseConnected && sseError && <RealtimeBadge mode="polling" message={sseError} />}
</div>
)}
{selectedIds.length > 0 && (
<div className="mt-4 flex flex-col gap-3 rounded-md border border-[var(--color-accent-cyan)]/20 bg-[var(--color-cta-bg)]/5 p-3 lg:flex-row lg:items-center lg:justify-between">
<div className="text-sm text-[var(--color-text-primary)]">
{selectedIds.length} session{selectedIds.length === 1 ? '' : 's'} selected
</div>
<div className="flex flex-wrap items-center gap-2" role="group" aria-label={t("aria.bulkActions")}>
<button
type="button"
onClick={() => runBulkAction('interrupt')}
disabled={bulkAction !== null}
aria-label={`Interrupt ${selectedIds.length} selected session${selectedIds.length === 1 ? '' : 's'}`}
className="min-h-[44px] rounded-md bg-[var(--color-warning)]/15 px-3 py-2 text-sm font-medium text-[var(--color-warning-glow)] transition-colors hover:bg-[var(--color-warning)]/25 disabled:pointer-events-none disabled:opacity-40"
>
Interrupt Selected
</button>
<button
type="button"
onClick={() => runBulkAction('kill')}
disabled={bulkAction !== null}
aria-label={`Kill ${selectedIds.length} selected session${selectedIds.length === 1 ? '' : 's'}`}
className="min-h-[44px] rounded-md bg-[var(--color-danger)]/15 px-3 py-2 text-sm font-medium text-[var(--color-danger-glow)] transition-colors hover:bg-[var(--color-danger)]/25 disabled:pointer-events-none disabled:opacity-40"
>
Kill Selected
</button>
<button
type="button"
onClick={() => setSelectedIds([])}
disabled={bulkAction !== null}
aria-label={t("aria.clearSelection")}
className="min-h-[44px] rounded-md border border-[var(--color-void-lighter)] px-3 py-2 text-sm text-[var(--color-text-muted)] transition-colors hover:border-[var(--color-void-lighter)] hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-40"
>
Clear
</button>
</div>
</div>
)}
</div>
{isLoading && sessions.length === 0 ? (
/* Bento-style Loading Skeleton */
<div className="card-glass relative overflow-hidden p-12 flex flex-col items-center justify-center h-[420px] overflow-hidden border border-[var(--color-overlay-border)] ">
<div className="w-16 h-16 rounded-2xl bg-[var(--color-overlay-bg)] mb-6" />
<div className="w-48 h-4 bg-[var(--color-overlay-bg-hover)] rounded-full mb-3" />
<div className="w-64 h-3 bg-[var(--color-overlay-bg)] rounded-full" />
</div>
) : sessions.length === 0 ? (
<div className="card-glass relative overflow-hidden p-12 text-center flex flex-col items-center justify-center h-[420px] overflow-hidden border border-[var(--color-overlay-border)] shadow-[inset_0_0_60px_rgba(var(--color-void-rgb, 0,0,0), 0.5)]">
{/* Ambient glow */}
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(6,182,212,0.06),transparent_60%)] pointer-events-none" />
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-64 h-px bg-gradient-to-r from-transparent via-[var(--color-accent-cyan)]/30 to-transparent" />
{/* Icon diamond */}
<div className="relative z-10 w-20 h-20 mb-6 rounded-2xl bg-[var(--color-overlay-bg)] border border-[var(--color-overlay-border-strong)] flex items-center justify-center shadow-[var(--shadow-accent-cyan)] transform rotate-45">
<span className="text-2xl transform -rotate-45 block text-[var(--color-text-muted)]">⌘</span>
</div>
<h3 className="relative z-10 text-xl font-bold tracking-tight text-[var(--color-text-primary)] drop-shadow-md mb-2">
{hasActiveFilters ? 'No Matching Directives' : 'Agent Standby Mode'}
</h3>
<p className="relative z-10 max-w-sm text-sm text-[var(--color-text-muted)] dark:text-[var(--color-text-muted)] leading-relaxed mb-6">
{hasActiveFilters
? 'No sessions match your current filter. Try broadening the search scope.'
: 'The orchestrator is online. No agents are currently deployed.'}
</p>
{!hasActiveFilters && (
<div className="relative z-10 flex flex-col items-center gap-3">
<button
type="button"
onClick={() => window.dispatchEvent(new CustomEvent('aegis:create-session'))}
className="inline-flex items-center gap-2 rounded-lg bg-[var(--color-accent-cyan)] px-5 py-2.5 text-sm font-semibold text-[var(--color-text-primary)] shadow-[0_0_20px_rgba(6,182,212,0.35)] transition-all hover:bg-[var(--color-accent-cyan)] hover:shadow-[0_0_30px_rgba(6,182,212,0.5)] active:scale-95"
>
<span className="text-base leading-none">⊕</span>
Deploy New Agent
</button>
<div className="flex items-center gap-2 text-[var(--color-text-muted)]">
<div className="h-px w-12 bg-[var(--color-overlay-bg-hover)]" />
<span className="text-[10px] uppercase tracking-widest">or</span>
<div className="h-px w-12 bg-[var(--color-overlay-bg-hover)]" />
</div>
<button
type="button"
onClick={handleSurpriseMe}
className="inline-flex items-center gap-2 rounded-lg border border-[var(--color-accent-cyan)]/30 bg-[var(--color-accent-cyan)]/5 px-4 py-2 text-sm font-medium text-[var(--color-accent-cyan-glow)] transition-all hover:bg-[var(--color-accent-cyan)]/10 active:scale-95"
>
<Sparkles className="h-4 w-4" />
Surprise me
</button>
<code className="mt-2 px-4 py-2 font-mono text-xs text-[var(--color-accent-cyan-glow)]/70 bg-[var(--color-accent-cyan)]/20 border border-[var(--color-accent-cyan)]/40 rounded-lg">
$ ag create "brief"
</code>
</div>
)}
</div>
) : (
<>
<div className="flex flex-col gap-3 md:hidden">
<div className="flex items-center justify-between rounded-md border border-[var(--color-void-lighter)] bg-[var(--color-surface)] px-4 py-3 text-sm text-[var(--color-text-muted)]">
<label className="flex items-center gap-2">
<input
type="checkbox"
aria-label={t("aria.selectAll")}
checked={allVisibleSelected}
onChange={(e) => handleToggleSelectAll(e.target.checked)}
className="h-4 w-4 rounded border border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] text-[var(--color-accent-cyan)] focus:ring-1 focus:ring-[var(--color-accent-cyan)]"
/>
Select visible
</label>
<span>{sessions.length} visible</span>
</div>
{groupedRowModels
? Array.from(groupedRowModels.entries()).map(([dirKey, groupRows]) => {
const isCollapsed = collapsedGroups.has(dirKey);
return (
<Fragment key={`group-${dirKey}`}>
<button
type="button"
className="flex min-h-[44px] items-center gap-2 w-full rounded-md border border-[var(--color-void-lighter)] bg-[var(--color-void)] px-4 py-2 text-sm text-[var(--color-text-muted)] transition-colors hover:border-[var(--color-accent-cyan)]/40 hover:text-[var(--color-text-primary)]"
onClick={() => toggleGroup(dirKey)}
aria-expanded={!isCollapsed}
>
{isCollapsed ? <ChevronRight className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
<FolderOpen className="h-3.5 w-3.5" />
<span className="font-medium font-mono text-xs">{dirKey}</span>
<span className="text-[10px] text-[var(--color-text-muted)] tabular-nums">{groupRows.length}</span>
</button>
{!isCollapsed && groupRows.map((row) => (
<SessionMobileCard
key={row.session.id}
session={row.session}
isAlive={row.isAlive}
health={row.health}
selected={row.selected}
currentAction={row.currentAction}
estimatedCostUsd={row.estimatedCostUsd ?? 0}
isFocused={row.isFocused}
onToggleSelect={handleToggleSelect}
onApprove={handleApprove}
onReject={handleReject}
onInterrupt={handleInterrupt}
onKill={handleKill}
/>
))}
</Fragment>
);
})
: rowViewModels.map((row) => (
<SessionMobileCard
key={row.session.id}
session={row.session}
isAlive={row.isAlive}
health={row.health}
selected={row.selected}
currentAction={row.currentAction}
estimatedCostUsd={row.estimatedCostUsd ?? 0}
isFocused={row.isFocused}
onToggleSelect={handleToggleSelect}
onApprove={handleApprove}
onReject={handleReject}
onInterrupt={handleInterrupt}
onKill={handleKill}
/>
))
}
</div>
<div className="hidden overflow-x-auto rounded-lg border border-[var(--color-void-lighter)] bg-[var(--color-surface)] md:block" tabIndex={0} aria-label={t("aria.sessionsTableScroll")}>
<table className="w-full text-left text-sm" aria-label={t("aria.sessionsTable")}>
<thead>
<tr className="border-b border-[var(--color-void-lighter)] bg-[var(--color-void)]">
<th scope="col" className="px-4 py-2.5">
<input
type="checkbox"
aria-label={t("aria.selectAll")}
checked={allVisibleSelected}
onChange={(e) => handleToggleSelectAll(e.target.checked)}
className="h-4 w-4 rounded border border-[var(--color-void-lighter)] bg-[var(--color-void-dark)] text-[var(--color-accent-cyan)] focus:ring-1 focus:ring-[var(--color-accent-cyan)]"
/>
</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.status')}</th>
<th scope="col" className="hidden md:table-cell px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.createdBy')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.name')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.workDir')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.age')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.lastActivity')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.permission')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.cost')}</th>
<th scope="col" className="px-4 py-2.5 text-[11px] font-[590] uppercase tracking-[0.08em] text-[var(--color-text-muted)]">{t('sessionTable.actions')}</th>
</tr>
</thead>
<tbody className="sr-only">
{/* Kept for accessibility: screen readers associate headers with the table */}
<tr><td colSpan={10}>Virtualized session list rendered below via react-window</td></tr>
</tbody>
</table>
<VirtualizedSessionList
rowViewModels={rowViewModels as VirtualizedRowData[]}
groupedRowModels={groupedRowModels as Map<string, VirtualizedRowData[]> | null}
collapsedGroups={collapsedGroups}
allVisibleSelected={allVisibleSelected}
onToggleGroup={toggleGroup}
onToggleSelect={handleToggleSelect}
onToggleSelectAll={handleToggleSelectAll}
onApprove={handleApprove}
onReject={handleReject}
onInterrupt={handleInterrupt}
onKill={handleKill}
showHeader={false}
/>
</div>
{deferredSearch.length === 0 && pagination.totalPages > 1 && (
<div className="flex items-center justify-between rounded-lg border border-[var(--color-void-lighter)] bg-[var(--color-surface)] px-4 py-3 text-sm text-[var(--color-text-muted)]">
<span>
Page {pagination.page} of {pagination.totalPages}
</span>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setPage((current) => Math.max(1, current - 1))}
disabled={pagination.page <= 1}
aria-label={t("aria.prevPage")}
className="flex min-h-[44px] items-center gap-1 rounded-md border border-[var(--color-void-lighter)] px-3 py-2 transition-colors hover:border-[var(--color-void-lighter)] hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-40"
>
<ChevronLeft className="h-4 w-4" /> {t('sessions.board.previousPage')}
</button>
<button
type="button"
onClick={() => setPage((current) => Math.min(pagination.totalPages, current + 1))}
disabled={pagination.page >= pagination.totalPages}
aria-label={t("aria.nextPage")}
className="flex min-h-[44px] items-center gap-1 rounded-md border border-[var(--color-void-lighter)] px-3 py-2 transition-colors hover:border-[var(--color-void-lighter)] hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-40"
>
{t('sessions.board.nextPage')} <ChevronRight className="h-4 w-4" />
</button>
</div>
</div>
)}
</>
)}
<ConfirmDialog
open={confirmKill !== null}
title={t('aria.killSessions')}
message={confirmKillMessage}
confirmLabel="Kill"
variant="danger"
onConfirm={handleConfirmKill}
onCancel={() => setConfirmKill(null)}
/>
{hoveredSession && (
<SessionPreviewCard
session={hoveredSession}
anchorRef={hoveredRowRef}
onClose={() => setHoveredSessionId(null)}
/>
)}
</div>
);
});