@@ -35,15 +35,33 @@ export function GreetWidget() {
3535 const [ greeting , setGreeting ] = useState ( '' ) ;
3636 const [ isLoading , setIsLoading ] = useState ( false ) ;
3737
38- // Hydrate from initial tool output
38+ // Hydrate from initial tool output and listen for updates
3939 useEffect ( ( ) => {
40- const toolOutput = ( window . openai ?. toolOutput as ToolOutput ) || { } ;
41- if ( toolOutput . greeting ) {
42- setGreeting ( toolOutput . greeting ) ;
43- }
44- if ( toolOutput . name ) {
45- setName ( toolOutput . name ) ;
46- }
40+ const updateFromToolOutput = ( ) => {
41+ const toolOutput = ( window . openai ?. toolOutput as ToolOutput ) || { } ;
42+ if ( toolOutput . greeting ) {
43+ setGreeting ( toolOutput . greeting ) ;
44+ }
45+ if ( toolOutput . name ) {
46+ setName ( toolOutput . name ) ;
47+ }
48+ } ;
49+
50+ // Initial load
51+ updateFromToolOutput ( ) ;
52+
53+ // Listen for updates from the host
54+ const handleSetGlobals = ( event : Event ) => {
55+ const customEvent = event as CustomEvent < { globals ?: Partial < { toolOutput ?: ToolOutput } > } > ;
56+ if ( customEvent . detail ?. globals ?. toolOutput !== undefined ) {
57+ updateFromToolOutput ( ) ;
58+ }
59+ } ;
60+
61+ window . addEventListener ( 'openai:set_globals' , handleSetGlobals ) ;
62+ return ( ) => {
63+ window . removeEventListener ( 'openai:set_globals' , handleSetGlobals ) ;
64+ } ;
4765 } , [ ] ) ;
4866
4967 const handleGreet = async ( ) => {
@@ -150,11 +168,32 @@ export function GreetWidget() {
150168 ) ;
151169}
152170
153- // Mount the component when used standalone (for MCP server build)
154- if ( typeof window !== 'undefined' && ! document . getElementById ( 'root' ) ) {
155- const root = document . createElement ( 'div' ) ;
156- document . body . appendChild ( root ) ;
157- const reactRoot = createRoot ( root ) ;
158- reactRoot . render ( < GreetWidget /> ) ;
171+ // Wait for window.openai to be available before mounting
172+ function waitForOpenAI ( ) {
173+ if ( window . openai ) {
174+ mountComponent ( ) ;
175+ } else {
176+ // Listen for the openai:set_globals event
177+ window . addEventListener ( 'openai:set_globals' , mountComponent , { once : true } ) ;
178+ // Fallback: check periodically (in case event doesn't fire)
179+ const checkInterval = setInterval ( ( ) => {
180+ if ( window . openai ) {
181+ clearInterval ( checkInterval ) ;
182+ mountComponent ( ) ;
183+ }
184+ } , 50 ) ;
185+ // Cleanup after 5 seconds if still not available
186+ setTimeout ( ( ) => clearInterval ( checkInterval ) , 5000 ) ;
187+ }
159188}
160189
190+ function mountComponent ( ) {
191+ const root = document . getElementById ( 'root' ) ;
192+ if ( root ) {
193+ const reactRoot = createRoot ( root ) ;
194+ reactRoot . render ( < GreetWidget /> ) ;
195+ }
196+ }
197+
198+ waitForOpenAI ( ) ;
199+
0 commit comments