11import { createLogger } from '@sim/logger'
22import { toError } from '@sim/utils/errors'
3+ import { generateId } from '@sim/utils/id'
34import { getRedisClient } from '@/lib/core/config/redis'
45
56/**
@@ -8,7 +9,8 @@ import { getRedisClient } from '@/lib/core/config/redis'
89 * A chat view starts client-routed workflow tools from the stream it reads. The original send
910 * knows in-process whether its own response is still attached; a view that re-attached through
1011 * the reconnect route (a reload, a chat switch back, another tab) may sit on another instance,
11- * so it marks itself here for as long as it stays attached.
12+ * so each attachment holds its own entry here, scored by when it lapses, for as long as it
13+ * stays attached. Leaving removes the entry at once; a reader that dies without leaving lapses.
1214 */
1315
1416const logger = createLogger ( 'SessionStreamViewer' )
@@ -17,32 +19,48 @@ const logger = createLogger('SessionStreamViewer')
1719const STREAM_VIEWER_TTL_MS = 10_000
1820const STREAM_VIEWER_REFRESH_MS = 3_000
1921
20- function getViewerKey ( streamId : string ) {
21- return `mothership_stream:${ streamId } :viewer `
22+ function getViewersKey ( streamId : string ) {
23+ return `mothership_stream:${ streamId } :viewers `
2224}
2325
24- async function markStreamViewer ( streamId : string ) : Promise < void > {
26+ async function markStreamViewer ( streamId : string , attachmentId : string ) : Promise < void > {
2527 const redis = getRedisClient ( )
2628 if ( ! redis ) return
27- await redis . set ( getViewerKey ( streamId ) , '1' , 'PX' , STREAM_VIEWER_TTL_MS )
29+ const key = getViewersKey ( streamId )
30+ await redis
31+ . multi ( )
32+ . zadd ( key , Date . now ( ) + STREAM_VIEWER_TTL_MS , attachmentId )
33+ . pexpire ( key , STREAM_VIEWER_TTL_MS )
34+ . exec ( )
35+ }
36+
37+ async function unmarkStreamViewer ( streamId : string , attachmentId : string ) : Promise < void > {
38+ const redis = getRedisClient ( )
39+ if ( ! redis ) return
40+ await redis . zrem ( getViewersKey ( streamId ) , attachmentId )
41+ }
42+
43+ function warnMarkFailed ( streamId : string , error : unknown ) {
44+ logger . warn ( 'Could not record a chat stream reader' , {
45+ streamId,
46+ error : toError ( error ) . message ,
47+ } )
2848}
2949
3050/**
31- * Marks a reader attached to the stream until the returned release runs. The mark lapses on
32- * its own a few seconds after release , so a crashed reader never holds it.
51+ * Records a reader attached to the stream until the returned release runs. Resolves once the
52+ * first mark is written , so the reader counts before it reads its first event .
3353 */
34- export function holdStreamViewer ( streamId : string ) : ( ) => void {
35- const refresh = ( ) => {
36- markStreamViewer ( streamId ) . catch ( ( error ) => {
37- logger . warn ( 'Could not mark a chat stream reader attached' , {
38- streamId,
39- error : toError ( error ) . message ,
40- } )
41- } )
42- }
43- refresh ( )
54+ export async function holdStreamViewer ( streamId : string ) : Promise < ( ) => void > {
55+ const attachmentId = generateId ( )
56+ const refresh = ( ) =>
57+ markStreamViewer ( streamId , attachmentId ) . catch ( ( error ) => warnMarkFailed ( streamId , error ) )
58+ await refresh ( )
4459 const interval = setInterval ( refresh , STREAM_VIEWER_REFRESH_MS )
45- return ( ) => clearInterval ( interval )
60+ return ( ) => {
61+ clearInterval ( interval )
62+ unmarkStreamViewer ( streamId , attachmentId ) . catch ( ( error ) => warnMarkFailed ( streamId , error ) )
63+ }
4664}
4765
4866/**
@@ -53,7 +71,7 @@ export async function hasStreamViewer(streamId: string): Promise<boolean> {
5371 const redis = getRedisClient ( )
5472 if ( ! redis ) return true
5573 try {
56- return ( await redis . exists ( getViewerKey ( streamId ) ) ) > 0
74+ return ( await redis . zcount ( getViewersKey ( streamId ) , Date . now ( ) , '+inf' ) ) > 0
5775 } catch ( error ) {
5876 logger . warn ( 'Could not read whether a chat stream reader is attached' , {
5977 streamId,
0 commit comments