@@ -17,6 +17,7 @@ import {
1717 type ClientOrchestrationCommand ,
1818 type ModelSelection ,
1919 type OrchestrationLatestTurnState ,
20+ type OrchestrationMessage ,
2021 OrchestrationMessageRole ,
2122 type OrchestrationProjectShell ,
2223 OrchestrationSessionStatus ,
@@ -219,22 +220,31 @@ export const findModelOffers = (
219220 } ) ;
220221
221222/**
222- * How the turn requested at `requestedAt` ended, or undefined while it runs.
223- * `requestedAt` is the sent message's `createdAt`. The server gives the turn
224- * that message starts the same `latestTurn.requestedAt`. A turn that fails to
225- * start sets the session to error with that same timestamp instead.
223+ * How the message sent at `sentAt` was handled, or undefined while it may
224+ * still run. `sentAt` is the message's server `createdAt`, which the turn it
225+ * starts copies into `latestTurn.requestedAt`. The server holds the session
226+ * at "starting" while a turn start is pending, so an idle session updated
227+ * after `sentAt` means the message was handled without a turn of its own: a
228+ * failed start, a provider command, or a steer into another client's turn.
226229 */
227230export const turnOutcome = (
228231 thread : OrchestrationThreadShell ,
229- requestedAt : string ,
232+ sentAt : string ,
230233) : Exclude < OrchestrationLatestTurnState , "running" > | "needs-input" | undefined => {
231234 if ( thread . hasPendingApprovals || thread . hasPendingUserInput ) return "needs-input" ;
235+ if ( isThreadBusy ( thread ) ) return undefined ;
232236 const turn = thread . latestTurn ;
233- if ( turn ?. requestedAt === requestedAt ) {
237+ if ( turn ?. requestedAt === sentAt ) {
234238 return turn . state === "running" ? undefined : turn . state ;
235239 }
236- if ( thread . session ?. status === "error" && thread . session . updatedAt === requestedAt ) {
237- return "error" ;
240+ const since = Date . parse ( sentAt ) ;
241+ // A later turn only starts after this message's turn has ended.
242+ if ( turn !== null && Date . parse ( turn . requestedAt ) > since ) return "completed" ;
243+ const session = thread . session ;
244+ if ( session !== null && Date . parse ( session . updatedAt ) >= since ) {
245+ return session . status === "error" || session . status === "interrupted"
246+ ? session . status
247+ : "completed" ;
238248 }
239249 return undefined ;
240250} ;
@@ -371,13 +381,13 @@ const connectLiveServer = Effect.fn("connectThreadCliServer")(function* (
371381 : Effect . succeed ( thread ) ;
372382 } ) ,
373383 ) ,
374- /** Reads the messages of the latest `turns` user turns. */
375- threadDetail : ( threadId : ThreadId , turns : number ) =>
384+ /** Reads the messages of `turns` user turns, the latest ones or those before `beforeCursor` . */
385+ threadDetail : ( threadId : ThreadId , turns : number , beforeCursor ?: string ) =>
376386 call (
377387 client . orchestration . threadSnapshot ( {
378388 headers,
379389 params : { threadId } ,
380- payload : { turnLimit : turns } ,
390+ payload : { turnLimit : turns , ... ( beforeCursor === undefined ? { } : { beforeCursor } ) } ,
381391 } ) ,
382392 ) . pipe (
383393 Effect . catchIf (
@@ -414,20 +424,43 @@ const pollThread = <A>(
414424 } ) ;
415425
416426/**
417- * Waits for the turn that `messageId` started to end and returns the agent's
427+ * Reads pages of the thread, newest first, until it finds `messageId`.
428+ * Returns that message and the messages after it, until the next user message.
429+ * Dispatch returns after the projection commits, so a sent message is there.
430+ */
431+ const readSentTurn = ( server : LiveServer , threadId : ThreadId , messageId : MessageId ) =>
432+ Effect . gen ( function * ( ) {
433+ let newer : ReadonlyArray < OrchestrationMessage > = [ ] ;
434+ let beforeCursor : string | undefined ;
435+ for ( ; ; ) {
436+ const { thread, page } = yield * server . threadDetail ( threadId , 1 , beforeCursor ) ;
437+ const messages = [ ...thread . messages , ...newer ] ;
438+ const index = messages . findIndex ( ( message ) => message . id === messageId ) ;
439+ const sent = messages [ index ] ;
440+ if ( sent !== undefined ) {
441+ const after = messages . slice ( index + 1 ) ;
442+ const nextUser = after . findIndex ( ( message ) => message . role === "user" ) ;
443+ return { sent, replies : nextUser === - 1 ? after : after . slice ( 0 , nextUser ) } ;
444+ }
445+ if ( page ?. beforeCursor == null ) {
446+ return yield * Effect . die (
447+ new Error ( `Sent message ${ messageId } is missing from the thread.` ) ,
448+ ) ;
449+ }
450+ newer = messages ;
451+ beforeCursor = page . beforeCursor ;
452+ }
453+ } ) ;
454+
455+ /**
456+ * Waits until the server has handled `messageId` and returns the agent's
418457 * final reply. Fails when the turn fails, is interrupted, or needs the user.
419458 */
420459const waitForReply = ( server : LiveServer , threadId : ThreadId , messageId : MessageId ) =>
421460 Effect . gen ( function * ( ) {
422461 // The server replaces the command's createdAt with its own clock, so
423- // read the stamp back from the message. Dispatch returns after the
424- // projection commits, so the message is already there.
425- const sent = ( yield * server . threadDetail ( threadId , 1 ) ) . thread . messages . find (
426- ( message ) => message . id === messageId ,
427- ) ;
428- if ( sent === undefined ) {
429- return yield * Effect . die ( new Error ( `Sent message ${ messageId } is missing from the thread.` ) ) ;
430- }
462+ // read the stamp back from the message.
463+ const { sent } = yield * readSentTurn ( server , threadId , messageId ) ;
431464 const ended = yield * pollThread ( server , threadId , ( candidate ) => {
432465 const outcome = turnOutcome ( candidate , sent . createdAt ) ;
433466 return outcome === undefined ? undefined : { outcome, thread : candidate } ;
@@ -438,13 +471,8 @@ const waitForReply = (server: LiveServer, threadId: ThreadId, messageId: Message
438471 detail : ended . thread . session ?. lastError ?? null ,
439472 } ) ;
440473 }
441- const turnId = ended . thread . latestTurn ?. turnId ;
442- const { thread : detail } = yield * server . threadDetail ( threadId , 1 ) ;
443- return (
444- detail . messages . findLast (
445- ( message ) => message . role === "assistant" && message . turnId === turnId ,
446- ) ?. text ?? ""
447- ) ;
474+ const { replies } = yield * readSentTurn ( server , threadId , messageId ) ;
475+ return replies . findLast ( ( message ) => message . role === "assistant" ) ?. text ?? "" ;
448476 } ) ;
449477
450478/** Runs `run` against the live server and prints what it returns. */
@@ -467,7 +495,7 @@ const runWithLiveServer = <E, R>(
467495 EnvironmentAuth . runtimeLayer . pipe (
468496 Layer . provideMerge ( FetchHttpClient . layer ) ,
469497 Layer . provide ( ServerConfig . layer ( config ) ) ,
470- Layer . provide ( Layer . succeed ( References . MinimumLogLevel , logLevel ) ) ,
498+ Layer . provideMerge ( Layer . succeed ( References . MinimumLogLevel , logLevel ) ) ,
471499 ) ,
472500 ) ,
473501 ) ;
0 commit comments