1+ import { EventEmitter } from 'node:events'
12import { afterEach , beforeEach , describe , expect , it , vi } from 'vitest'
23import { createSecureWebPreferences } from '@/main/window-preferences'
34
@@ -7,7 +8,12 @@ import { BrowserWindow, dialog, screen, systemPreferences, WebContentsView } fro
78import { registerAgentWebContents } from '@/main/browser-agent/registry'
89import type { ConfigStore } from '@/main/config'
910import type { EventRecorder } from '@/main/observability'
10- import { createMainWindow , resolvePermission , setupPermissionHandlers } from '@/main/window'
11+ import {
12+ createMainWindow ,
13+ detachVisibilityListenersOnClose ,
14+ resolvePermission ,
15+ setupPermissionHandlers ,
16+ } from '@/main/window'
1117
1218const APP = 'https://sim.ai'
1319
@@ -195,3 +201,36 @@ describe('createMainWindow', () => {
195201 expect ( event . preventDefault ) . toHaveBeenCalledOnce ( )
196202 } )
197203} )
204+
205+ describe ( 'detachVisibilityListenersOnClose' , ( ) => {
206+ /** A window wired the way Electron wires every BrowserWindow: its visibility listener reads the native window. */
207+ function electronLikeWindow ( ) {
208+ let destroyed = false
209+ const win = Object . assign ( new EventEmitter ( ) , {
210+ isVisible : ( ) => {
211+ if ( destroyed ) throw new TypeError ( 'Object has been destroyed' )
212+ return true
213+ } ,
214+ destroy : ( ) => {
215+ destroyed = true
216+ win . emit ( 'closed' )
217+ } ,
218+ } )
219+ const visibilityChanged = ( ) => win . isVisible ( )
220+ for ( const event of [ 'show' , 'hide' , 'minimize' , 'maximize' , 'restore' ] ) {
221+ win . on ( event , visibilityChanged )
222+ }
223+ return win
224+ }
225+
226+ it ( 'a visibility event delivered after the window closed no longer throws' , ( ) => {
227+ const win = electronLikeWindow ( )
228+ detachVisibilityListenersOnClose ( win as never )
229+
230+ win . emit ( 'show' )
231+ win . destroy ( )
232+
233+ expect ( ( ) => win . emit ( 'show' ) ) . not . toThrow ( )
234+ expect ( ( ) => win . emit ( 'hide' ) ) . not . toThrow ( )
235+ } )
236+ } )
0 commit comments