11export type ThreadNotificationKind = "input" | "completion" ;
22
33export interface ThreadNotificationObservation {
4- /** Run and status key while the thread needs attention, otherwise null. */
4+ /** Run, status and request key while the thread needs attention, otherwise null. */
55 readonly attention : string | null ;
6+ /** The pending request's id, when it has one; null whenever attention is. */
7+ readonly requestId : string | null ;
68 /** The thread is idle and its latest run completed. */
79 readonly settled : boolean ;
810 /** When the latest run completed, if it did. */
@@ -17,6 +19,24 @@ export function createThreadNotificationGate<Key>(
1719 const skip = ( key : Key , at : number | null ) => {
1820 if ( at !== null && at > ( handled . get ( key ) ?? - Infinity ) ) handled . set ( key , at ) ;
1921 } ;
22+ // Attention keys with a request id seen since the thread last stopped needing attention.
23+ const attended = new Map < Key , Set < string > > ( ) ;
24+ const attend = (
25+ key : Key ,
26+ prior : ThreadNotificationObservation | undefined ,
27+ next : ThreadNotificationObservation ,
28+ ) : boolean => {
29+ if ( next . attention === null ) {
30+ attended . delete ( key ) ;
31+ return false ;
32+ }
33+ if ( next . requestId === null ) return next . attention !== prior ?. attention ;
34+ const seen = attended . get ( key ) ;
35+ if ( seen ?. has ( next . attention ) ) return false ;
36+ if ( seen ) seen . add ( next . attention ) ;
37+ else attended . set ( key , new Set ( [ next . attention ] ) ) ;
38+ return true ;
39+ } ;
2040 return {
2141 observe (
2242 key : Key ,
@@ -26,8 +46,9 @@ export function createThreadNotificationGate<Key>(
2646 ) : void {
2747 // The first sighting, archived threads, and stopped or silent runs never notify completion.
2848 if ( ! prior || options . archived || options . quiet ) skip ( key , next . completedAt ) ;
49+ const fresh = attend ( key , prior , next ) ;
2950 if ( ! prior || options . archived ) return ;
30- if ( next . attention && next . attention !== prior . attention ) {
51+ if ( fresh ) {
3152 notify ( key , "input" ) ;
3253 return ;
3354 }
@@ -39,9 +60,11 @@ export function createThreadNotificationGate<Key>(
3960 /** Forgets threads that left the snapshot. */
4061 retain ( keys : ReadonlySet < Key > ) : void {
4162 for ( const key of handled . keys ( ) ) if ( ! keys . has ( key ) ) handled . delete ( key ) ;
63+ for ( const key of attended . keys ( ) ) if ( ! keys . has ( key ) ) attended . delete ( key ) ;
4264 } ,
4365 clear ( ) : void {
4466 handled . clear ( ) ;
67+ attended . clear ( ) ;
4568 } ,
4669 } ;
4770}
0 commit comments