-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathClaudeCodeSession.tsx
More file actions
1774 lines (1597 loc) · 67.7 KB
/
ClaudeCodeSession.tsx
File metadata and controls
1774 lines (1597 loc) · 67.7 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useRef, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
Copy,
ChevronDown,
GitBranch,
ChevronUp,
X,
Hash,
Wrench
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Popover } from "@/components/ui/popover";
import { api, type Session } from "@/lib/api";
import { cn } from "@/lib/utils";
import {
isImeComposingKeydown,
createCompositionHandlers,
type IMECompositionRefs,
} from "@/utils/ime";
// Conditional imports for Tauri APIs
let tauriListen: any;
type UnlistenFn = () => void;
try {
if (typeof window !== 'undefined' && window.__TAURI__) {
tauriListen = require("@tauri-apps/api/event").listen;
}
} catch (e) {
console.log('[ClaudeCodeSession] Tauri APIs not available, using web mode');
}
// Web-compatible replacements
const listen = tauriListen || ((eventName: string, callback: (event: any) => void) => {
console.log('[ClaudeCodeSession] Setting up DOM event listener for:', eventName);
// In web mode, listen for DOM events
const domEventHandler = (event: any) => {
console.log('[ClaudeCodeSession] DOM event received:', eventName, event.detail);
// Simulate Tauri event structure
callback({ payload: event.detail });
};
window.addEventListener(eventName, domEventHandler);
// Return unlisten function
return Promise.resolve(() => {
console.log('[ClaudeCodeSession] Removing DOM event listener for:', eventName);
window.removeEventListener(eventName, domEventHandler);
});
});
import { StreamMessage } from "./StreamMessage";
import { FloatingPromptInput, type FloatingPromptInputRef } from "./FloatingPromptInput";
import { ErrorBoundary } from "./ErrorBoundary";
import { TimelineNavigator } from "./TimelineNavigator";
import { CheckpointSettings } from "./CheckpointSettings";
import { SlashCommandsManager } from "./SlashCommandsManager";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { TooltipProvider, TooltipSimple } from "@/components/ui/tooltip-modern";
import { SplitPane } from "@/components/ui/split-pane";
import { WebviewPreview } from "./WebviewPreview";
import type { ClaudeStreamMessage } from "./AgentExecution";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useTrackEvent, useComponentMetrics, useWorkflowTracking } from "@/hooks";
import { SessionPersistenceService } from "@/services/sessionPersistence";
interface ClaudeCodeSessionProps {
/**
* Optional session to resume (when clicking from SessionList)
*/
session?: Session;
/**
* Initial project path (for new sessions)
*/
initialProjectPath?: string;
/**
* Callback to go back
*/
onBack: () => void;
/**
* Callback to open hooks configuration
*/
onProjectSettings?: (projectPath: string) => void;
/**
* Optional className for styling
*/
className?: string;
/**
* Callback when streaming state changes
*/
onStreamingChange?: (isStreaming: boolean, sessionId: string | null) => void;
/**
* Callback when project path changes
*/
onProjectPathChange?: (path: string) => void;
}
/**
* ClaudeCodeSession component for interactive Claude Code sessions
*
* @example
* <ClaudeCodeSession onBack={() => setView('projects')} />
*/
export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
session,
initialProjectPath = "",
className,
onStreamingChange,
onProjectPathChange,
}) => {
const [projectPath] = useState(initialProjectPath || session?.project_path || "");
const [messages, setMessages] = useState<ClaudeStreamMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [rawJsonlOutput, setRawJsonlOutput] = useState<string[]>([]);
const [copyPopoverOpen, setCopyPopoverOpen] = useState(false);
const [isFirstPrompt, setIsFirstPrompt] = useState(!session);
const [totalTokens, setTotalTokens] = useState(0);
const [extractedSessionInfo, setExtractedSessionInfo] = useState<{ sessionId: string; projectId: string } | null>(null);
const [claudeSessionId, setClaudeSessionId] = useState<string | null>(null);
const [showTimeline, setShowTimeline] = useState(false);
const [timelineVersion, setTimelineVersion] = useState(0);
const [showSettings, setShowSettings] = useState(false);
const [showForkDialog, setShowForkDialog] = useState(false);
const [showSlashCommandsSettings, setShowSlashCommandsSettings] = useState(false);
const [forkCheckpointId, setForkCheckpointId] = useState<string | null>(null);
const [forkSessionName, setForkSessionName] = useState("");
// Queued prompts state
const [queuedPrompts, setQueuedPrompts] = useState<Array<{ id: string; prompt: string; model: "sonnet" | "opus" }>>([]);
// New state for preview feature
const [showPreview, setShowPreview] = useState(false);
const [previewUrl, setPreviewUrl] = useState("");
const [showPreviewPrompt, setShowPreviewPrompt] = useState(false);
const [splitPosition, setSplitPosition] = useState(50);
const [isPreviewMaximized, setIsPreviewMaximized] = useState(false);
// Add collapsed state for queued prompts
const [queuedPromptsCollapsed, setQueuedPromptsCollapsed] = useState(false);
const parentRef = useRef<HTMLDivElement>(null);
const unlistenRefs = useRef<UnlistenFn[]>([]);
const hasActiveSessionRef = useRef(false);
const floatingPromptRef = useRef<FloatingPromptInputRef>(null);
const queuedPromptsRef = useRef<Array<{ id: string; prompt: string; model: "sonnet" | "opus" }>>([]);
const isMountedRef = useRef(true);
const isListeningRef = useRef(false);
const sessionStartTime = useRef<number>(Date.now());
// Tracks IME composition state
const isComposingRef = useRef(false);
const justEndedRef = useRef(false);
// Session metrics state for enhanced analytics
const sessionMetrics = useRef({
firstMessageTime: null as number | null,
promptsSent: 0,
toolsExecuted: 0,
toolsFailed: 0,
filesCreated: 0,
filesModified: 0,
filesDeleted: 0,
codeBlocksGenerated: 0,
errorsEncountered: 0,
lastActivityTime: Date.now(),
toolExecutionTimes: [] as number[],
checkpointCount: 0,
wasResumed: !!session,
modelChanges: [] as Array<{ from: string; to: string; timestamp: number }>,
});
// Analytics tracking
const trackEvent = useTrackEvent();
useComponentMetrics('ClaudeCodeSession');
// const aiTracking = useAIInteractionTracking('sonnet'); // Default model
const workflowTracking = useWorkflowTracking('claude_session');
// Call onProjectPathChange when component mounts with initial path
useEffect(() => {
if (onProjectPathChange && projectPath) {
onProjectPathChange(projectPath);
}
}, []); // Only run on mount
// Keep ref in sync with state
useEffect(() => {
queuedPromptsRef.current = queuedPrompts;
}, [queuedPrompts]);
// Get effective session info (from prop or extracted) - use useMemo to ensure it updates
const effectiveSession = useMemo(() => {
if (session) return session;
if (extractedSessionInfo) {
return {
id: extractedSessionInfo.sessionId,
project_id: extractedSessionInfo.projectId,
project_path: projectPath,
created_at: Date.now(),
} as Session;
}
return null;
}, [session, extractedSessionInfo, projectPath]);
// Filter out messages that shouldn't be displayed
const displayableMessages = useMemo(() => {
return messages.filter((message, index) => {
// Skip meta messages that don't have meaningful content
if (message.isMeta && !message.leafUuid && !message.summary) {
return false;
}
// Skip user messages that only contain tool results that are already displayed
if (message.type === "user" && message.message) {
if (message.isMeta) return false;
const msg = message.message;
if (!msg.content || (Array.isArray(msg.content) && msg.content.length === 0)) {
return false;
}
if (Array.isArray(msg.content)) {
let hasVisibleContent = false;
for (const content of msg.content) {
if (content.type === "text") {
hasVisibleContent = true;
break;
}
if (content.type === "tool_result") {
let willBeSkipped = false;
if (content.tool_use_id) {
// Look for the matching tool_use in previous assistant messages
for (let i = index - 1; i >= 0; i--) {
const prevMsg = messages[i];
if (prevMsg.type === 'assistant' && prevMsg.message?.content && Array.isArray(prevMsg.message.content)) {
const toolUse = prevMsg.message.content.find((c: any) =>
c.type === 'tool_use' && c.id === content.tool_use_id
);
if (toolUse) {
const toolName = toolUse.name?.toLowerCase();
const toolsWithWidgets = [
'task', 'edit', 'multiedit', 'todowrite', 'ls', 'read',
'glob', 'bash', 'write', 'grep'
];
if (toolsWithWidgets.includes(toolName) || toolUse.name?.startsWith('mcp__')) {
willBeSkipped = true;
}
break;
}
}
}
}
if (!willBeSkipped) {
hasVisibleContent = true;
break;
}
}
}
if (!hasVisibleContent) {
return false;
}
}
}
return true;
});
}, [messages]);
const rowVirtualizer = useVirtualizer({
count: displayableMessages.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 150, // Estimate, will be dynamically measured
overscan: 5,
});
// Debug logging
useEffect(() => {
console.log('[ClaudeCodeSession] State update:', {
projectPath,
session,
extractedSessionInfo,
effectiveSession,
messagesCount: messages.length,
isLoading
});
}, [projectPath, session, extractedSessionInfo, effectiveSession, messages.length, isLoading]);
// Load session history if resuming
useEffect(() => {
if (session) {
// Set the claudeSessionId immediately when we have a session
setClaudeSessionId(session.id);
// Load session history first, then check for active session
const initializeSession = async () => {
await loadSessionHistory();
// After loading history, check if the session is still active
if (isMountedRef.current) {
await checkForActiveSession();
}
};
initializeSession();
}
}, [session]); // Remove hasLoadedSession dependency to ensure it runs on mount
// Report streaming state changes
useEffect(() => {
onStreamingChange?.(isLoading, claudeSessionId);
}, [isLoading, claudeSessionId, onStreamingChange]);
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
if (displayableMessages.length > 0) {
// Use a more precise scrolling method to ensure content is fully visible
setTimeout(() => {
const scrollElement = parentRef.current;
if (scrollElement) {
// First, scroll using virtualizer to get close to the bottom
rowVirtualizer.scrollToIndex(displayableMessages.length - 1, { align: 'end', behavior: 'auto' });
// Then use direct scroll to ensure we reach the absolute bottom
requestAnimationFrame(() => {
scrollElement.scrollTo({
top: scrollElement.scrollHeight,
behavior: 'smooth'
});
});
}
}, 50);
}
}, [displayableMessages.length, rowVirtualizer]);
// Calculate total tokens from messages
useEffect(() => {
const tokens = messages.reduce((total, msg) => {
if (msg.message?.usage) {
return total + msg.message.usage.input_tokens + msg.message.usage.output_tokens;
}
if (msg.usage) {
return total + msg.usage.input_tokens + msg.usage.output_tokens;
}
return total;
}, 0);
setTotalTokens(tokens);
}, [messages]);
const loadSessionHistory = async () => {
if (!session) return;
try {
setIsLoading(true);
setError(null);
const history = await api.loadSessionHistory(session.id, session.project_id);
// Save session data for restoration
if (history && history.length > 0) {
SessionPersistenceService.saveSession(
session.id,
session.project_id,
session.project_path,
history.length
);
}
// Convert history to messages format
const loadedMessages: ClaudeStreamMessage[] = history.map(entry => ({
...entry,
type: entry.type || "assistant"
}));
setMessages(loadedMessages);
setRawJsonlOutput(history.map(h => JSON.stringify(h)));
// After loading history, we're continuing a conversation
setIsFirstPrompt(false);
// Scroll to bottom after loading history
setTimeout(() => {
if (loadedMessages.length > 0) {
const scrollElement = parentRef.current;
if (scrollElement) {
// Use the same improved scrolling method
rowVirtualizer.scrollToIndex(loadedMessages.length - 1, { align: 'end', behavior: 'auto' });
requestAnimationFrame(() => {
scrollElement.scrollTo({
top: scrollElement.scrollHeight,
behavior: 'auto'
});
});
}
}
}, 100);
} catch (err) {
console.error("Failed to load session history:", err);
setError("Failed to load session history");
} finally {
setIsLoading(false);
}
};
const checkForActiveSession = async () => {
// If we have a session prop, check if it's still active
if (session) {
try {
const activeSessions = await api.listRunningClaudeSessions();
const activeSession = activeSessions.find((s: any) => {
if ('process_type' in s && s.process_type && 'ClaudeSession' in s.process_type) {
return (s.process_type as any).ClaudeSession.session_id === session.id;
}
return false;
});
if (activeSession) {
// Session is still active, reconnect to its stream
console.log('[ClaudeCodeSession] Found active session, reconnecting:', session.id);
// IMPORTANT: Set claudeSessionId before reconnecting
setClaudeSessionId(session.id);
// Don't add buffered messages here - they've already been loaded by loadSessionHistory
// Just set up listeners for new messages
// Set up listeners for the active session
reconnectToSession(session.id);
}
} catch (err) {
console.error('Failed to check for active sessions:', err);
}
}
};
const reconnectToSession = async (sessionId: string) => {
console.log('[ClaudeCodeSession] Reconnecting to session:', sessionId);
// Prevent duplicate listeners
if (isListeningRef.current) {
console.log('[ClaudeCodeSession] Already listening to session, skipping reconnect');
return;
}
// Clean up previous listeners
unlistenRefs.current.forEach(unlisten => unlisten());
unlistenRefs.current = [];
// IMPORTANT: Set the session ID before setting up listeners
setClaudeSessionId(sessionId);
// Mark as listening
isListeningRef.current = true;
// Set up session-specific listeners
const outputUnlisten = await listen(`claude-output:${sessionId}`, async (event: any) => {
try {
console.log('[ClaudeCodeSession] Received claude-output on reconnect:', event.payload);
if (!isMountedRef.current) return;
// Store raw JSONL
setRawJsonlOutput(prev => [...prev, event.payload]);
// Parse and display
const message = JSON.parse(event.payload) as ClaudeStreamMessage;
setMessages(prev => [...prev, message]);
} catch (err) {
console.error("Failed to parse message:", err, event.payload);
}
});
const errorUnlisten = await listen(`claude-error:${sessionId}`, (event: any) => {
console.error("Claude error:", event.payload);
if (isMountedRef.current) {
setError(event.payload);
}
});
const completeUnlisten = await listen(`claude-complete:${sessionId}`, async (event: any) => {
console.log('[ClaudeCodeSession] Received claude-complete on reconnect:', event.payload);
if (isMountedRef.current) {
setIsLoading(false);
hasActiveSessionRef.current = false;
}
});
unlistenRefs.current = [outputUnlisten, errorUnlisten, completeUnlisten];
// Mark as loading to show the session is active
if (isMountedRef.current) {
setIsLoading(true);
hasActiveSessionRef.current = true;
}
};
// Project path selection handled by parent tab controls
const handleSendPrompt = async (prompt: string, model: "sonnet" | "opus") => {
console.log('[ClaudeCodeSession] handleSendPrompt called with:', { prompt, model, projectPath, claudeSessionId, effectiveSession });
if (!projectPath) {
setError("Please select a project directory first");
return;
}
// If already loading, queue the prompt
if (isLoading) {
const newPrompt = {
id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
prompt,
model
};
setQueuedPrompts(prev => [...prev, newPrompt]);
return;
}
try {
setIsLoading(true);
setError(null);
hasActiveSessionRef.current = true;
// For resuming sessions, ensure we have the session ID
if (effectiveSession && !claudeSessionId) {
setClaudeSessionId(effectiveSession.id);
}
// Only clean up and set up new listeners if not already listening
if (!isListeningRef.current) {
// Clean up previous listeners
unlistenRefs.current.forEach(unlisten => unlisten());
unlistenRefs.current = [];
// Mark as setting up listeners
isListeningRef.current = true;
// --------------------------------------------------------------------
// 1️⃣ Event Listener Setup Strategy
// --------------------------------------------------------------------
// Claude Code may emit a *new* session_id even when we pass --resume. If
// we listen only on the old session-scoped channel we will miss the
// stream until the user navigates away & back. To avoid this we:
// • Always start with GENERIC listeners (no suffix) so we catch the
// very first "system:init" message regardless of the session id.
// • Once that init message provides the *actual* session_id, we
// dynamically switch to session-scoped listeners and stop the
// generic ones to prevent duplicate handling.
// --------------------------------------------------------------------
console.log('[ClaudeCodeSession] Setting up generic event listeners first');
let currentSessionId: string | null = claudeSessionId || effectiveSession?.id || null;
// Helper to attach session-specific listeners **once we are sure**
const attachSessionSpecificListeners = async (sid: string) => {
console.log('[ClaudeCodeSession] Attaching session-specific listeners for', sid);
const specificOutputUnlisten = await listen(`claude-output:${sid}`, (evt: any) => {
handleStreamMessage(evt.payload);
});
const specificErrorUnlisten = await listen(`claude-error:${sid}`, (evt: any) => {
console.error('Claude error (scoped):', evt.payload);
setError(evt.payload);
});
const specificCompleteUnlisten = await listen(`claude-complete:${sid}`, (evt: any) => {
console.log('[ClaudeCodeSession] Received claude-complete (scoped):', evt.payload);
processComplete(evt.payload);
});
// Replace existing unlisten refs with these new ones (after cleaning up)
unlistenRefs.current.forEach((u) => u());
unlistenRefs.current = [specificOutputUnlisten, specificErrorUnlisten, specificCompleteUnlisten];
};
// Generic listeners (catch-all)
const genericOutputUnlisten = await listen('claude-output', async (event: any) => {
handleStreamMessage(event.payload);
// Attempt to extract session_id on the fly (for the very first init)
try {
const msg = JSON.parse(event.payload) as ClaudeStreamMessage;
if (msg.type === 'system' && msg.subtype === 'init' && msg.session_id) {
if (!currentSessionId || currentSessionId !== msg.session_id) {
console.log('[ClaudeCodeSession] Detected new session_id from generic listener:', msg.session_id);
currentSessionId = msg.session_id;
setClaudeSessionId(msg.session_id);
// If we haven't extracted session info before, do it now
if (!extractedSessionInfo) {
const projectId = projectPath.replace(/[^a-zA-Z0-9]/g, '-');
setExtractedSessionInfo({ sessionId: msg.session_id, projectId });
// Save session data for restoration
SessionPersistenceService.saveSession(
msg.session_id,
projectId,
projectPath,
messages.length
);
}
// Switch to session-specific listeners
await attachSessionSpecificListeners(msg.session_id);
}
}
} catch {
/* ignore parse errors */
}
});
// Helper to process any JSONL stream message string or object
function handleStreamMessage(payload: string | ClaudeStreamMessage) {
try {
// Don't process if component unmounted
if (!isMountedRef.current) return;
let message: ClaudeStreamMessage;
let rawPayload: string;
if (typeof payload === 'string') {
// Tauri mode: payload is a JSON string
rawPayload = payload;
message = JSON.parse(payload) as ClaudeStreamMessage;
} else {
// Web mode: payload is already parsed object
message = payload;
rawPayload = JSON.stringify(payload);
}
console.log('[ClaudeCodeSession] handleStreamMessage - message type:', message.type);
// Store raw JSONL
setRawJsonlOutput((prev) => [...prev, rawPayload]);
// Track enhanced tool execution
if (message.type === 'assistant' && message.message?.content) {
const toolUses = message.message.content.filter((c: any) => c.type === 'tool_use');
toolUses.forEach((toolUse: any) => {
// Increment tools executed counter
sessionMetrics.current.toolsExecuted += 1;
sessionMetrics.current.lastActivityTime = Date.now();
// Track file operations
const toolName = toolUse.name?.toLowerCase() || '';
if (toolName.includes('create') || toolName.includes('write')) {
sessionMetrics.current.filesCreated += 1;
} else if (toolName.includes('edit') || toolName.includes('multiedit') || toolName.includes('search_replace')) {
sessionMetrics.current.filesModified += 1;
} else if (toolName.includes('delete')) {
sessionMetrics.current.filesDeleted += 1;
}
// Track tool start - we'll track completion when we get the result
workflowTracking.trackStep(toolUse.name);
});
}
// Track tool results
if (message.type === 'user' && message.message?.content) {
const toolResults = message.message.content.filter((c: any) => c.type === 'tool_result');
toolResults.forEach((result: any) => {
const isError = result.is_error || false;
// Note: We don't have execution time here, but we can track success/failure
if (isError) {
sessionMetrics.current.toolsFailed += 1;
sessionMetrics.current.errorsEncountered += 1;
trackEvent.enhancedError({
error_type: 'tool_execution',
error_code: 'tool_failed',
error_message: result.content,
context: `Tool execution failed`,
user_action_before_error: 'executing_tool',
recovery_attempted: false,
recovery_successful: false,
error_frequency: 1,
stack_trace_hash: undefined
});
}
});
}
// Track code blocks generated
if (message.type === 'assistant' && message.message?.content) {
const codeBlocks = message.message.content.filter((c: any) =>
c.type === 'text' && c.text?.includes('```')
);
if (codeBlocks.length > 0) {
// Count code blocks in text content
codeBlocks.forEach((block: any) => {
const matches = (block.text.match(/```/g) || []).length;
sessionMetrics.current.codeBlocksGenerated += Math.floor(matches / 2);
});
}
}
// Track errors in system messages
if (message.type === 'system' && (message.subtype === 'error' || message.error)) {
sessionMetrics.current.errorsEncountered += 1;
}
setMessages((prev) => [...prev, message]);
} catch (err) {
console.error('Failed to parse message:', err, payload);
}
}
// Helper to handle completion events (both generic and scoped)
const processComplete = async (success: boolean) => {
setIsLoading(false);
hasActiveSessionRef.current = false;
isListeningRef.current = false; // Reset listening state
// Track enhanced session stopped metrics when session completes
if (effectiveSession && claudeSessionId) {
const sessionStartTimeValue = messages.length > 0 ? messages[0].timestamp || Date.now() : Date.now();
const duration = Date.now() - sessionStartTimeValue;
const metrics = sessionMetrics.current;
const timeToFirstMessage = metrics.firstMessageTime
? metrics.firstMessageTime - sessionStartTime.current
: undefined;
const idleTime = Date.now() - metrics.lastActivityTime;
const avgResponseTime = metrics.toolExecutionTimes.length > 0
? metrics.toolExecutionTimes.reduce((a, b) => a + b, 0) / metrics.toolExecutionTimes.length
: undefined;
trackEvent.enhancedSessionStopped({
// Basic metrics
duration_ms: duration,
messages_count: messages.length,
reason: success ? 'completed' : 'error',
// Timing metrics
time_to_first_message_ms: timeToFirstMessage,
average_response_time_ms: avgResponseTime,
idle_time_ms: idleTime,
// Interaction metrics
prompts_sent: metrics.promptsSent,
tools_executed: metrics.toolsExecuted,
tools_failed: metrics.toolsFailed,
files_created: metrics.filesCreated,
files_modified: metrics.filesModified,
files_deleted: metrics.filesDeleted,
// Content metrics
total_tokens_used: totalTokens,
code_blocks_generated: metrics.codeBlocksGenerated,
errors_encountered: metrics.errorsEncountered,
// Session context
model: metrics.modelChanges.length > 0
? metrics.modelChanges[metrics.modelChanges.length - 1].to
: 'sonnet',
has_checkpoints: metrics.checkpointCount > 0,
checkpoint_count: metrics.checkpointCount,
was_resumed: metrics.wasResumed,
// Agent context (if applicable)
agent_type: undefined, // TODO: Pass from agent execution
agent_name: undefined, // TODO: Pass from agent execution
agent_success: success,
// Stop context
stop_source: 'completed',
final_state: success ? 'success' : 'failed',
has_pending_prompts: queuedPrompts.length > 0,
pending_prompts_count: queuedPrompts.length,
});
}
if (effectiveSession && success) {
try {
const settings = await api.getCheckpointSettings(
effectiveSession.id,
effectiveSession.project_id,
projectPath
);
if (settings.auto_checkpoint_enabled) {
await api.checkAutoCheckpoint(
effectiveSession.id,
effectiveSession.project_id,
projectPath,
prompt
);
// Reload timeline to show new checkpoint
setTimelineVersion((v) => v + 1);
}
} catch (err) {
console.error('Failed to check auto checkpoint:', err);
}
}
// Process queued prompts after completion
if (queuedPromptsRef.current.length > 0) {
const [nextPrompt, ...remainingPrompts] = queuedPromptsRef.current;
setQueuedPrompts(remainingPrompts);
// Small delay to ensure UI updates
setTimeout(() => {
handleSendPrompt(nextPrompt.prompt, nextPrompt.model);
}, 100);
}
};
const genericErrorUnlisten = await listen('claude-error', (evt: any) => {
console.error('Claude error:', evt.payload);
setError(evt.payload);
});
const genericCompleteUnlisten = await listen('claude-complete', (evt: any) => {
console.log('[ClaudeCodeSession] Received claude-complete (generic):', evt.payload);
processComplete(evt.payload);
});
// Store the generic unlisteners for now; they may be replaced later.
unlistenRefs.current = [genericOutputUnlisten, genericErrorUnlisten, genericCompleteUnlisten];
// --------------------------------------------------------------------
// 2️⃣ Auto-checkpoint logic moved after listener setup (unchanged)
// --------------------------------------------------------------------
// Add the user message immediately to the UI (after setting up listeners)
const userMessage: ClaudeStreamMessage = {
type: "user",
message: {
content: [
{
type: "text",
text: prompt
}
]
}
};
setMessages(prev => [...prev, userMessage]);
// Update session metrics
sessionMetrics.current.promptsSent += 1;
sessionMetrics.current.lastActivityTime = Date.now();
if (!sessionMetrics.current.firstMessageTime) {
sessionMetrics.current.firstMessageTime = Date.now();
}
// Track model changes
const lastModel = sessionMetrics.current.modelChanges.length > 0
? sessionMetrics.current.modelChanges[sessionMetrics.current.modelChanges.length - 1].to
: (sessionMetrics.current.wasResumed ? 'sonnet' : model); // Default to sonnet if resumed
if (lastModel !== model) {
sessionMetrics.current.modelChanges.push({
from: lastModel,
to: model,
timestamp: Date.now()
});
}
// Track enhanced prompt submission
const codeBlockMatches = prompt.match(/```[\s\S]*?```/g) || [];
const hasCode = codeBlockMatches.length > 0;
const conversationDepth = messages.filter(m => m.user_message).length;
const sessionAge = sessionStartTime.current ? Date.now() - sessionStartTime.current : 0;
const wordCount = prompt.split(/\s+/).filter(word => word.length > 0).length;
trackEvent.enhancedPromptSubmitted({
prompt_length: prompt.length,
model: model,
has_attachments: false, // TODO: Add attachment support when implemented
source: 'keyboard', // TODO: Track actual source (keyboard vs button)
word_count: wordCount,
conversation_depth: conversationDepth,
prompt_complexity: wordCount < 20 ? 'simple' : wordCount < 100 ? 'moderate' : 'complex',
contains_code: hasCode,
language_detected: hasCode ? codeBlockMatches?.[0]?.match(/```(\w+)/)?.[1] : undefined,
session_age_ms: sessionAge
});
// Execute the appropriate command
if (effectiveSession && !isFirstPrompt) {
console.log('[ClaudeCodeSession] Resuming session:', effectiveSession.id);
trackEvent.sessionResumed(effectiveSession.id);
trackEvent.modelSelected(model);
await api.resumeClaudeCode(projectPath, effectiveSession.id, prompt, model);
} else {
console.log('[ClaudeCodeSession] Starting new session');
setIsFirstPrompt(false);
trackEvent.sessionCreated(model, 'prompt_input');
trackEvent.modelSelected(model);
await api.executeClaudeCode(projectPath, prompt, model);
}
}
} catch (err) {
console.error("Failed to send prompt:", err);
setError("Failed to send prompt");
setIsLoading(false);
hasActiveSessionRef.current = false;
}
};
const handleCopyAsJsonl = async () => {
const jsonl = rawJsonlOutput.join('\n');
await navigator.clipboard.writeText(jsonl);
setCopyPopoverOpen(false);
};
const handleCopyAsMarkdown = async () => {
let markdown = `# Claude Code Session\n\n`;
markdown += `**Project:** ${projectPath}\n`;
markdown += `**Date:** ${new Date().toISOString()}\n\n`;
markdown += `---\n\n`;
for (const msg of messages) {
if (msg.type === "system" && msg.subtype === "init") {
markdown += `## System Initialization\n\n`;
markdown += `- Session ID: \`${msg.session_id || 'N/A'}\`\n`;
markdown += `- Model: \`${msg.model || 'default'}\`\n`;
if (msg.cwd) markdown += `- Working Directory: \`${msg.cwd}\`\n`;
if (msg.tools?.length) markdown += `- Tools: ${msg.tools.join(', ')}\n`;
markdown += `\n`;
} else if (msg.type === "assistant" && msg.message) {
markdown += `## Assistant\n\n`;
for (const content of msg.message.content || []) {
if (content.type === "text") {
const textContent = typeof content.text === 'string'
? content.text
: (content.text?.text || JSON.stringify(content.text || content));
markdown += `${textContent}\n\n`;
} else if (content.type === "tool_use") {
markdown += `### Tool: ${content.name}\n\n`;
markdown += `\`\`\`json\n${JSON.stringify(content.input, null, 2)}\n\`\`\`\n\n`;
}
}
if (msg.message.usage) {
markdown += `*Tokens: ${msg.message.usage.input_tokens} in, ${msg.message.usage.output_tokens} out*\n\n`;
}
} else if (msg.type === "user" && msg.message) {
markdown += `## User\n\n`;
for (const content of msg.message.content || []) {
if (content.type === "text") {
const textContent = typeof content.text === 'string'
? content.text
: (content.text?.text || JSON.stringify(content.text));
markdown += `${textContent}\n\n`;
} else if (content.type === "tool_result") {
markdown += `### Tool Result\n\n`;
let contentText = '';
if (typeof content.content === 'string') {
contentText = content.content;
} else if (content.content && typeof content.content === 'object') {
if (content.content.text) {
contentText = content.content.text;
} else if (Array.isArray(content.content)) {
contentText = content.content
.map((c: any) => (typeof c === 'string' ? c : c.text || JSON.stringify(c)))
.join('\n');
} else {
contentText = JSON.stringify(content.content, null, 2);
}
}
markdown += `\`\`\`\n${contentText}\n\`\`\`\n\n`;
}
}
} else if (msg.type === "result") {
markdown += `## Execution Result\n\n`;
if (msg.result) {
markdown += `${msg.result}\n\n`;
}
if (msg.error) {
markdown += `**Error:** ${msg.error}\n\n`;
}
}
}
await navigator.clipboard.writeText(markdown);
setCopyPopoverOpen(false);
};
const handleCheckpointSelect = async () => {
// Reload messages from the checkpoint
await loadSessionHistory();
// Ensure timeline reloads to highlight current checkpoint
setTimelineVersion((v) => v + 1);
};
const handleCheckpointCreated = () => {
// Update checkpoint count in session metrics
sessionMetrics.current.checkpointCount += 1;
};
const handleCancelExecution = async () => {
if (!claudeSessionId || !isLoading) return;
try {
const sessionStartTime = messages.length > 0 ? messages[0].timestamp || Date.now() : Date.now();
const duration = Date.now() - sessionStartTime;
await api.cancelClaudeExecution(claudeSessionId);
// Calculate metrics for enhanced analytics
const metrics = sessionMetrics.current;