66import { useRef , useState } from 'react' ;
77import { JupyterFrontEnd } from '@jupyterlab/application' ;
88import { INotebookTracker } from '@jupyterlab/notebook' ;
9+ import { IDocumentManager } from '@jupyterlab/docmanager' ;
910import { UUID } from '@lumino/coreutils' ;
1011import { IStreamlitPreviewManager } from '../../AppPreview/StreamlitPreviewPlugin' ;
1112import { CompletionWebsocketClient } from '../../../websockets/completions/CompletionsWebsocketClient' ;
@@ -18,6 +19,7 @@ import { getCodeBlockFromMessage } from '../../../utils/strings';
1819import { getAIOptimizedCellsInNotebookPanel , setActiveCellByIDInNotebookPanel } from '../../../utils/notebook' ;
1920import { AgentReviewStatus } from '../ChatTaskpane' ;
2021import { LoadingStatus } from './useChatState' ;
22+ import { ensureNotebookExists } from '../utils' ;
2123
2224export type AgentExecutionStatus = 'working' | 'stopping' | 'idle' ;
2325
@@ -28,6 +30,7 @@ interface UseAgentExecutionProps {
2830 app : JupyterFrontEnd ;
2931 streamlitPreviewManager : IStreamlitPreviewManager ;
3032 websocketClient : CompletionWebsocketClient ;
33+ documentManager : IDocumentManager ;
3134 chatHistoryManagerRef : React . MutableRefObject < ChatHistoryManager > ;
3235 activeThreadIdRef : React . MutableRefObject < string > ;
3336 activeRequestControllerRef : React . MutableRefObject < AbortController | null > ;
@@ -63,6 +66,7 @@ export const useAgentExecution = ({
6366 app,
6467 streamlitPreviewManager,
6568 websocketClient,
69+ documentManager,
6670 chatHistoryManagerRef,
6771 activeThreadIdRef,
6872 activeRequestControllerRef,
@@ -133,7 +137,10 @@ export const useAgentExecution = ({
133137 messageIndex ?: number ,
134138 additionalContext ?: Array < { type : string , value : string } >
135139 ) : Promise < void > => {
136- agentTargetNotebookPanelRef . current = notebookTracker . currentWidget ;
140+
141+ // Ensure a notebook exists before proceeding with agent execution
142+ const agentTargetNotebookPanel = await ensureNotebookExists ( notebookTracker , documentManager ) ;
143+ agentTargetNotebookPanelRef . current = agentTargetNotebookPanel ;
137144
138145 agentReview . acceptAllAICode ( ) ;
139146 agentReview . setNotebookSnapshotPreAgentExecution ( getAIOptimizedCellsInNotebookPanel ( agentTargetNotebookPanelRef . current ) ) ;
0 commit comments