@@ -64,10 +64,36 @@ type SessionAuthPort = {
6464 recreate ( chatId : string ) : Promise < StartSessionResult > ;
6565} ;
6666
67+ /** What a `.out` subscription asks of the browser when it wakes. */
68+ type SessionWakeKind =
69+ /** The tab was hidden only briefly: wake any in-flight backoff. */
70+ | "retry"
71+ /** The connection is likely dead (a long-hidden tab, a network return, a bfcache restore): reconnect. */
72+ | "reconnect" ;
73+
74+ /** Where a `.out` subscription hears the page wake: the browser's visibility, network and bfcache events. */
75+ type SessionWakePort = {
76+ /**
77+ * Starts listening and returns what stops it. A page with no `document` or no
78+ * `window` has nothing to hear, and the returned function does nothing.
79+ */
80+ listen ( onWake : ( kind : SessionWakeKind ) => void ) : ( ) => void ;
81+ } ;
82+
83+ /** Where a chat's tab claim goes: the host's multi-tab coordinator, when it has one. */
84+ type SessionTabsPort = {
85+ /** Gives up the chat's claim so another tab can take it. */
86+ release ( chatId : string ) : void ;
87+ /** Tells the other tabs where this one's `.out` cursor is. */
88+ broadcastSession ( chatId : string , session : { lastEventId ?: string } ) : void ;
89+ } ;
90+
6791export type SessionPorts = {
6892 endpoint : SessionEndpointPort ;
6993 auth : SessionAuthPort ;
7094 starter : SessionStarterPort ;
95+ wake : SessionWakePort ;
96+ tabs : SessionTabsPort ;
7197} ;
7298
7399/**
@@ -88,6 +114,8 @@ export type BrowserSessionHost = {
88114 | ( ( params : StartSessionParams < Record < string , unknown > > ) => Promise < StartSessionResult > )
89115 | undefined ;
90116 clientData ( ) : Record < string , unknown > | undefined ;
117+ /** The multi-tab coordinator, read on each call: `dispose` drops it, and a transport without `multiTab` has none. */
118+ coordinator ( ) : SessionTabsPort | null ;
91119} ;
92120
93121/** The wire form of a record written to `.in`. */
@@ -177,6 +205,60 @@ export function browserSessionPorts(host: BrowserSessionHost): SessionPorts {
177205 "TriggerChatTransport: `startSession` is required to call `start()` / `preload()`. Either provide it or pre-hydrate the session via `sessions: { ... }`."
178206 ) ,
179207 } ,
208+ wake : { listen : listenForBrowserWake } ,
209+ tabs : {
210+ release : ( chatId ) => host . coordinator ( ) ?. release ( chatId ) ,
211+ broadcastSession : ( chatId , session ) => host . coordinator ( ) ?. broadcastSession ( chatId , session ) ,
212+ } ,
213+ } ;
214+ }
215+
216+ /** A tab hidden at least this long likely lost its TCP socket to the OS. */
217+ const FORCE_RECONNECT_AFTER_HIDDEN_MS = 30_000 ;
218+
219+ /**
220+ * Hears the browser's wake events for a live `.out` subscription:
221+ * - `online`: the network came back. The connection might be silently dead:
222+ * reconnect.
223+ * - `visibilitychange` to visible after a long hidden spell: reconnect.
224+ * - `visibilitychange` to visible after a short one: a cheap wake of any
225+ * in-flight backoff.
226+ * - `pageshow` with `event.persisted`: a bfcache restore (mobile Safari
227+ * back/forward, app-switcher resume). The socket is definitely dead:
228+ * reconnect.
229+ */
230+ function listenForBrowserWake ( onWake : ( kind : SessionWakeKind ) => void ) : ( ) => void {
231+ if ( typeof document === "undefined" || typeof window === "undefined" ) return ( ) => { } ;
232+
233+ let hiddenSince : number | null = null ;
234+
235+ const onVisibilityChange = ( ) => {
236+ if ( typeof document === "undefined" ) return ;
237+ if ( document . visibilityState === "hidden" ) {
238+ hiddenSince = Date . now ( ) ;
239+ return ;
240+ }
241+ const wasHiddenForMs = hiddenSince ? Date . now ( ) - hiddenSince : 0 ;
242+ hiddenSince = null ;
243+ onWake ( wasHiddenForMs >= FORCE_RECONNECT_AFTER_HIDDEN_MS ? "reconnect" : "retry" ) ;
244+ } ;
245+
246+ const onPageShow = ( event : Event ) => {
247+ // PageTransitionEvent in browsers; type guard via `persisted`.
248+ if ( ( event as PageTransitionEvent ) . persisted ) {
249+ onWake ( "reconnect" ) ;
250+ }
251+ } ;
252+
253+ const onOnline = ( ) => onWake ( "reconnect" ) ;
254+
255+ document . addEventListener ( "visibilitychange" , onVisibilityChange ) ;
256+ window . addEventListener ( "online" , onOnline ) ;
257+ window . addEventListener ( "pageshow" , onPageShow ) ;
258+ return ( ) => {
259+ document . removeEventListener ( "visibilitychange" , onVisibilityChange ) ;
260+ window . removeEventListener ( "online" , onOnline ) ;
261+ window . removeEventListener ( "pageshow" , onPageShow ) ;
180262 } ;
181263}
182264
@@ -199,6 +281,16 @@ function startWithHost(
199281 } ) ;
200282}
201283
284+ /**
285+ * Detect 401/403 from realtime/input-stream calls without relying on `instanceof`
286+ * (Vitest can load duplicate `@trigger.dev/core` copies, which breaks subclass checks).
287+ */
288+ export function isAuthError ( error : unknown ) : boolean {
289+ if ( error === null || typeof error !== "object" ) return false ;
290+ const e = error as { name ?: string ; status ?: number } ;
291+ return e . name === "TriggerApiError" && ( e . status === 401 || e . status === 403 ) ;
292+ }
293+
202294/** The refusal of an append, in the `TriggerApiError` shape callers classify by `name` and `status`. */
203295function appendRefusal ( status : number , text : string ) : Error {
204296 const err = new Error ( `appendToSessionStream failed: ${ status } ${ text } ` ) as Error & {
0 commit comments