@@ -545,28 +545,41 @@ end
545545
546546--- Handle working directory changes by restarting the server and loading the appropriate session.
547547--- This function performs the following steps:
548- --- 1. Shuts down the existing opencode server
549- --- 2. Starts a new server instance
550- --- 3. Clears the active session and context
551- --- 4. Loads the last workspace session for the new directory, or creates a new one if none exists
552548--- @return Promise<void>
553549M .handle_directory_change = Promise .async (function ()
554550 local log = require (' opencode.log' )
555551
556552 if state .opencode_server then
557553 vim .notify (' Directory changed, restarting Opencode server...' , vim .log .levels .INFO )
558554 log .info (' Shutting down Opencode server due to directory change...' )
555+
559556 state .opencode_server :shutdown ():await ()
560- server_job .ensure_server ():await ()
561- state .active_session = nil
562- vim .notify (' Loading last session for new working dir' , vim .log .levels .INFO )
563- state .last_sent_context = nil
564- context .unload_attachments ()
565-
566- state .active_session = session .get_last_workspace_session ():await ()
567- if not state .active_session then
568- state .active_session = M .create_new_session ():await ()
569- end
557+
558+ vim .defer_fn (
559+ Promise .async (function ()
560+ state .opencode_server = nil
561+ server_job .ensure_server ():await ()
562+
563+ vim .notify (' Loading last session for new working dir [' .. vim .fn .getcwd () .. ' ]' , vim .log .levels .INFO )
564+
565+ state .active_session = nil
566+ state .last_sent_context = nil
567+ context .unload_attachments ()
568+
569+ local is_new = false
570+ state .active_session = session .get_last_workspace_session ():await ()
571+
572+ if not state .active_session then
573+ is_new = true
574+ state .active_session = M .create_new_session ():await ()
575+ end
576+
577+ log .debug (
578+ ' Loaded session for new working dir' .. vim .inspect ({ session = state .active_session , is_new = is_new })
579+ )
580+ end ),
581+ 200
582+ )
570583 end
571584end )
572585
0 commit comments