SendAndWait sends a message to this session and waits until the session becomes idle. This is a convenience method that combines [Session.Send] with waiting for the session.idle event. Use this when you want to block until the assistant has finished processing the message. Events are still deliver
(ctx context.Context, options MessageOptions)
| 463 | // } |
| 464 | // } |
| 465 | func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*SessionEvent, error) { |
| 466 | if _, ok := ctx.Deadline(); !ok { |
| 467 | var cancel context.CancelFunc |
| 468 | ctx, cancel = context.WithTimeout(ctx, 60*time.Second) |
| 469 | defer cancel() |
| 470 | } |
| 471 | |
| 472 | idleCh := make(chan struct{}, 1) |
| 473 | errCh := make(chan error, 1) |
| 474 | var lastAssistantMessage *SessionEvent |
| 475 | var mu sync.Mutex |
| 476 | |
| 477 | unsubscribe := s.On(func(event SessionEvent) { |
| 478 | switch d := event.Data.(type) { |
| 479 | case *AssistantMessageData: |
| 480 | mu.Lock() |
| 481 | eventCopy := event |
| 482 | lastAssistantMessage = &eventCopy |
| 483 | mu.Unlock() |
| 484 | case *SessionIdleData: |
| 485 | select { |
| 486 | case idleCh <- struct{}{}: |
| 487 | default: |
| 488 | } |
| 489 | case *SessionErrorData: |
| 490 | select { |
| 491 | case errCh <- fmt.Errorf("session error: %s", d.Message): |
| 492 | default: |
| 493 | } |
| 494 | } |
| 495 | }) |
| 496 | defer unsubscribe() |
| 497 | |
| 498 | _, err := s.Send(ctx, options) |
| 499 | if err != nil { |
| 500 | return nil, err |
| 501 | } |
| 502 | |
| 503 | select { |
| 504 | case <-idleCh: |
| 505 | mu.Lock() |
| 506 | result := lastAssistantMessage |
| 507 | mu.Unlock() |
| 508 | return result, nil |
| 509 | case err := <-errCh: |
| 510 | return nil, err |
| 511 | case <-ctx.Done(): |
| 512 | return nil, fmt.Errorf("waiting for session.idle: %w", ctx.Err()) |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | // SendPromptAndWait is a convenience wrapper for [Session.SendAndWait] that |
| 517 | // takes a plain prompt string instead of a [MessageOptions] struct. Equivalent |