@@ -42,6 +42,7 @@ const nearTopBottom = computed(() => {
4242
4343const threadIdRef = useThreadIdRef ()
4444const isThreadFrozen = computed (() => chatContext .activeThread .value ?.frozen )
45+ const fetchKey = ref (0 )
4546
4647const cachedThreadsMessages: {
4748 [threadId : string ]: Array <CustomMessage >
@@ -52,10 +53,10 @@ const streamingMessages = ref(0)
5253const isFetching = ref (false )
5354const chatInput = ref (' ' )
5455
55- // Fetch messages and resume streams
56+ // Fetch messages as needed and resume streams
5657const { ignoreUpdates : ignorePathUpdate } = watchIgnorable (
57- threadIdRef ,
58- async (threadId , oldThreadId ) => {
58+ [ threadIdRef , fetchKey ] ,
59+ async ([ threadId ], [ oldThreadId ] ) => {
5960 if (oldThreadId )
6061 cachedThreadsMessages [oldThreadId ] = messages .value
6162
@@ -65,7 +66,7 @@ const { ignoreUpdates: ignorePathUpdate } = watchIgnorable(
6566
6667 if (threadId ) {
6768 isFetching .value = true
68- await convex .query (api .messages .list , { threadId: threadId as Doc <' threads' >[' _id' ], lockerKey: getLockerKey (threadId ) })
69+ await convex .query (api .messages .listByThread , { threadId: threadId as Doc <' threads' >[' _id' ], lockerKey: getLockerKey (threadId ) })
6970 .then ((existingMessages ) => {
7071 if (threadIdRef .value === threadId ) {
7172 messages .value = existingMessages .map (customMessageTransform )
@@ -77,7 +78,6 @@ const { ignoreUpdates: ignorePathUpdate } = watchIgnorable(
7778
7879 // If the owner have deleted the thread, remove it locally
7980 // (or the demo crons cleaned it)
80- console .log ({ a: getConvexErrorMessage (e ), e })
8181 if (getConvexErrorMessage (e ) === ' Thread not found' ) {
8282 toast ({ variant: ' destructive' , description: t (' chat.toast.threadRemovedExternal' ) })
8383
@@ -109,6 +109,23 @@ const { ignoreUpdates: ignorePathUpdate } = watchIgnorable(
109109 { immediate: true },
110110)
111111
112+ // Subscribe to a counter to check for messages from other concurrent sessions
113+ watchImmediate (threadIdRef , (threadId ) => {
114+ console .log (` Subscribing to messages count of: ${threadId } ` )
115+ const { unsubscribe } = convex .onUpdate (
116+ api .messages .countByThread ,
117+ { threadId: threadId as Id <' threads' >, lockerKey: getLockerKey (threadId ) },
118+ (count ) => {
119+ if (count > messages .value .length )
120+ ++ fetchKey .value
121+ },
122+ )
123+ watchOnce (threadIdRef , () => {
124+ unsubscribe ()
125+ console .log (` Unsubscribed from ${threadId } ` )
126+ })
127+ })
128+
112129interface HandleSubmitArgs {
113130 input: string
114131 confirmMultiStream? : boolean
0 commit comments