11import { writable , get , type Readable } from "svelte/store"
2+ import posthog from "posthog-js"
23import {
34 streamChat ,
45 chatGenerateId ,
@@ -134,7 +135,7 @@ export function createChatSessionStore(
134135 } ) )
135136 }
136137
137- function beginStreaming ( text : string ) {
138+ function beginStreaming ( text : string , isRetry = false ) {
138139 removeErrors ( )
139140 const currentMessages = get ( persisted ) . messages
140141 const traceId =
@@ -165,6 +166,16 @@ export function createChatSessionStore(
165166 lastSentAppState : currentAppState ,
166167 } ) )
167168
169+ posthog . capture ( "chat_message_sent" , {
170+ is_new_conversation : ! traceId && ! isRetry ,
171+ message_length : text . length ,
172+ has_app_context_header : ! ! header ,
173+ message_count : currentMessages . length ,
174+ } )
175+ if ( ! traceId && ! isRetry ) {
176+ posthog . capture ( "chat_conversation_started" )
177+ }
178+
168179 combined . update ( ( s ) => ( {
169180 ...s ,
170181 toolExecuting : false ,
@@ -284,6 +295,7 @@ export function createChatSessionStore(
284295
285296 function stop ( ) : void {
286297 if ( abortController ) {
298+ posthog . capture ( "chat_stopped" )
287299 abortController . abort ( )
288300 }
289301 }
@@ -299,12 +311,13 @@ export function createChatSessionStore(
299311 }
300312 }
301313 if ( lastUserIdx === - 1 ) return
314+ posthog . capture ( "chat_retry" )
302315 const userText = msgs [ lastUserIdx ] . content ?? ""
303316 persisted . update ( ( p ) => ( {
304317 ...p ,
305318 messages : p . messages . slice ( 0 , lastUserIdx ) ,
306319 } ) )
307- beginStreaming ( userText )
320+ beginStreaming ( userText , true )
308321 }
309322
310323 function reset ( ) : void {
@@ -390,8 +403,17 @@ export function createChatSessionStore(
390403 resolver ( decisions )
391404 }
392405
406+ function toolNameForCallId ( toolCallId : string ) : string | undefined {
407+ return get ( combined ) . toolApprovalWaiter ?. payload . items . find (
408+ ( i ) => i . toolCallId === toolCallId ,
409+ ) ?. toolName
410+ }
411+
393412 function applyToolApprovalRun ( toolCallId : string ) : void {
394413 if ( ! get ( combined ) . toolApprovalWaiter ) return
414+ posthog . capture ( "chat_tool_approval_run" , {
415+ tool_name : toolNameForCallId ( toolCallId ) ,
416+ } )
395417 combined . update ( ( s ) => ( {
396418 ...s ,
397419 toolApprovalPicks : { ...s . toolApprovalPicks , [ toolCallId ] : true } ,
@@ -401,6 +423,9 @@ export function createChatSessionStore(
401423
402424 function applyToolApprovalSkip ( toolCallId : string ) : void {
403425 if ( ! get ( combined ) . toolApprovalWaiter ) return
426+ posthog . capture ( "chat_tool_approval_skip" , {
427+ tool_name : toolNameForCallId ( toolCallId ) ,
428+ } )
404429 combined . update ( ( s ) => ( {
405430 ...s ,
406431 toolApprovalPicks : { ...s . toolApprovalPicks , [ toolCallId ] : false } ,
0 commit comments