@@ -201,7 +201,21 @@ async function handleQuery(cmd) {
201201 emit ( { type : "turn_started" } ) ;
202202
203203 try {
204- for await ( const message of query ( { prompt, options } ) ) {
204+ let queryIter ;
205+ try {
206+ queryIter = query ( { prompt, options } ) ;
207+ } catch ( resumeErr ) {
208+ // Resume failed (session not found on disk) — retry without resume
209+ if ( options . resume ) {
210+ emit ( { type : "error" , message : "Session not found, starting fresh" } ) ;
211+ delete options . resume ;
212+ delete options . continue ;
213+ queryIter = query ( { prompt, options } ) ;
214+ } else {
215+ throw resumeErr ;
216+ }
217+ }
218+ for await ( const message of queryIter ) {
205219 // Abort was requested while iterating.
206220 if ( abort . signal . aborted ) break ;
207221
@@ -339,6 +353,37 @@ async function handleQuery(cmd) {
339353 } catch ( err ) {
340354 if ( abort . signal . aborted ) {
341355 // Intentional abort — not an error.
356+ } else if ( options . resume && String ( err ?. message ?? "" ) . includes ( "conversation" ) ) {
357+ // Session resume failed (session file not found) — retry without resume
358+ emit ( { type : "error" , message : "Previous session not found, starting fresh" } ) ;
359+ delete options . resume ;
360+ delete options . continue ;
361+ try {
362+ for await ( const message of query ( { prompt, options } ) ) {
363+ if ( abort . signal . aborted ) break ;
364+ // Re-process messages with the same handler logic
365+ const msgType = message . type ;
366+ if ( msgType === "system" && message . subtype === "init" ) {
367+ capturedSessionId = message . session_id ;
368+ emit ( { type : "session_ready" , sessionId : message . session_id , model : message . model || model || null } ) ;
369+ } else if ( msgType === "assistant" && message . message ?. content ) {
370+ for ( const block of message . message . content ) {
371+ if ( block . type === "text" && block . text ) {
372+ const newText = block . text . slice ( lastTextLen ) ;
373+ if ( newText ) emit ( { type : "text_delta" , text : newText } ) ;
374+ lastTextLen = block . text . length ;
375+ }
376+ }
377+ } else if ( msgType === "result" || "result" in message ) {
378+ hasCompletedQuery = true ;
379+ lastSessionId = capturedSessionId ;
380+ emit ( { type : "turn_completed" , sessionId : capturedSessionId || "" } ) ;
381+ turnEmitted = true ;
382+ }
383+ }
384+ } catch ( retryErr ) {
385+ emit ( { type : "error" , message : String ( retryErr ?. message ?? retryErr ) } ) ;
386+ }
342387 } else {
343388 emit ( { type : "error" , message : String ( err ?. message ?? err ) } ) ;
344389 }
0 commit comments