From d54d59c7f8096277bff50037c22beebfd6d5a9f3 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:35:14 +0100 Subject: [PATCH 01/13] AI-3594: a scheduled reply wait reads how the turn ended from the conversation Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_delivery.go | 76 ++++++++++--------- .../internal/api/scheduled_thread_delivery.go | 22 +----- .../internal/conversation/authorizations.go | 9 +++ .../internal/conversation/conversation.go | 10 +++ acceleration/internal/session/session.go | 10 +++ 5 files changed, 71 insertions(+), 56 deletions(-) diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index 8b24fa114d..21c30cfc79 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -497,19 +497,16 @@ func (s *Server) captureReply(ctx context.Context, found *session.Session, deliv ticker := time.NewTicker(250 * time.Millisecond) defer ticker.Stop() for { + ended := false select { case <-ctx.Done(): return "", nil, ctx.Err() case event, open := <-events: if !open { - return captured(said, files) + ended = true + break } active, last = true, time.Now() - // A turn the organization may not pay for ends with the model's refusal, which no - // reply follows: the run records the money, not an agent that said nothing. - if refusal := turnRefusal(event); refusal != nil { - return "", nil, refusal - } if text := spokenOf(event); text != "" && (len(said) == 0 || said[len(said)-1] != text) { said = append(said, text) } @@ -519,12 +516,15 @@ func (s *Server) captureReply(ctx context.Context, found *session.Session, deliv if found.Busy() { active = true } - switch { - case time.Now().After(deadline): - return captured(said, files) - case active && !found.Busy() && time.Since(last) >= scheduledReplySettle: - return captured(said, files) - } + ended = time.Now().After(deadline) || active && !found.Busy() && time.Since(last) >= scheduledReplySettle + } + // A turn the organization may not pay for ends with the model's refusal, which no reply + // follows: the run records the money, not an agent that said nothing. + if refusal := turnRefusal(found, delivery.CommandID); refusal != nil { + return "", nil, refusal + } + if ended { + return captured(said, files) } } } @@ -545,36 +545,33 @@ func (s *Server) followUpInConversation(ctx context.Context, found *session.Sess _, _, known := found.FollowUpReply(delivery.CommandID) events, detach := found.Watch() defer detach() - if err := s.followUpWithin(ctx, found, delivery); err != nil || known { + if err := s.followUpWithin(ctx, found, delivery); err != nil { return err } + if known { + return turnRefusal(found, delivery.CommandID) + } deadline := time.Now().Add(scheduledReplyWindow) ticker := time.NewTicker(s.replyPoll) defer ticker.Stop() for { + // An event or a tick is when to look: how the turn ended is read from the conversation, + // which records it before the session sends watchers the event (Session.consume), so a + // watcher that has fallen behind and lost it still settles the same. select { case <-ctx.Done(): return ctx.Err() - case event, open := <-events: + case _, open := <-events: if !open { return nil } - if refusal := turnRefusal(event); refusal != nil { - return refusal - } - // The conversation records the agent.Error that fails a turn before the session sends - // it to watchers (Session.consume), so the turn has failed by now if it was this one. - if _, erred := event.(agent.Error); erred { - if state, _, _ := found.FollowUpReply(delivery.CommandID); replyEnded(state) { - return nil - } - } case <-ticker.C: - // A failed turn is told by its agent.Error, which says whether it was the money. - state, _, _ := found.FollowUpReply(delivery.CommandID) - if state != "failed" && replyEnded(state) || time.Now().After(deadline) { - return nil - } + } + if state, _, _ := found.FollowUpReply(delivery.CommandID); replyEnded(state) { + return turnRefusal(found, delivery.CommandID) + } + if time.Now().After(deadline) { + return nil } } } @@ -596,14 +593,14 @@ type turnRefused struct{ error } func (e turnRefused) Unwrap() error { return e.error } -// turnRefusal is the failure a text turn's event ends it with, when the event is the model's -// refusal for money (unpaid), and nil otherwise: any other agent.Error, such as a tool's, leaves -// the turn running. -func turnRefusal(event session.Event) error { - if failed, erred := event.(agent.Error); erred { - if _, refused := moneyError(failed.Err); refused { - return unpaid(turnRefused{failed.Err}) - } +// turnRefusal is the failure the reply to the follow-up under id in found ends with, when the +// conversation records it failed on the model's refusal for money (unpaid), and nil otherwise: +// a reply still running, one that ended any other way, or a failure a watcher alone was told of, +// such as a tool's (Session.Report), which leaves the turn running. +func turnRefusal(found *session.Session, id string) error { + failure := found.FollowUpFailure(id) + if _, refused := moneyError(failure); refused { + return unpaid(turnRefused{failure}) } return nil } @@ -663,6 +660,11 @@ func (s *Server) readBackReply(ctx context.Context, found *session.Session, id s } return reply, nil case "cancelled", "interrupted", "failed": + // A turn the organization may not pay for failed on the model's refusal: the run records + // the money, as the attempt that ran the turn would have. + if refusal := turnRefusal(found, id); refusal != nil { + return conversation.FinishedReply{}, refusal + } return conversation.FinishedReply{}, undelivered(scheduling.ReasonReplyFailed, fmt.Errorf("the reply to this occurrence was %s", state)) } if time.Now().After(deadline) { diff --git a/acceleration/internal/api/scheduled_thread_delivery.go b/acceleration/internal/api/scheduled_thread_delivery.go index 3e944cc9c9..ceb7add915 100644 --- a/acceleration/internal/api/scheduled_thread_delivery.go +++ b/acceleration/internal/api/scheduled_thread_delivery.go @@ -99,31 +99,15 @@ func (s *Server) deliverOnThread(ctx context.Context, delivery scheduledDelivery // A retried occurrence whose turn the thread already holds is a duplicate follow-up, which // runs nothing (Session.FollowUp); its reply is read back, and sent unless it went out. _, _, retried := found.FollowUpReply(delivery.CommandID) - events, detach := found.Watch() - defer detach() if err := s.followUpWithin(turn, found, delivery); err != nil { return "", "", err } // The reply as the conversation stored it, with its files: as it finished, or read back - // for a follow-up that finished on an earlier attempt. + // for a follow-up that finished on an earlier attempt. A turn refused for money fails under + // the money (readBackReply). reply, err := s.readBackReply(turn, found, delivery.CommandID) if err != nil { - // A turn the organization may not pay for failed on the model's refusal, which the - // conversation does not keep: the run records the money, as a text channel's does. - for { - select { - case event, open := <-events: - // A session that ended closes its watchers: nothing more comes. - if !open { - return "", "", err - } - if refusal := turnRefusal(event); refusal != nil { - return "", "", refusal - } - default: - return "", "", err - } - } + return "", "", err } if !retried { select { diff --git a/acceleration/internal/conversation/authorizations.go b/acceleration/internal/conversation/authorizations.go index fcfdd11102..d88c63d0ac 100644 --- a/acceleration/internal/conversation/authorizations.go +++ b/acceleration/internal/conversation/authorizations.go @@ -94,6 +94,15 @@ func (c *Conversation) FollowUpReply(id string) (state, text string, known bool) return record.State, record.Reply, known } +// FollowUpFailure is the error the reply to the follow-up under id failed on, as the +// agent.Error that ended it carried. It is nil for a reply that has not failed, and for one that +// failed before the conversation was opened again (commandsIn). +func (c *Conversation) FollowUpFailure(id string) error { + c.mu.Lock() + defer c.mu.Unlock() + return c.data.Commands[id].Failure +} + // FollowUpFinished is the reply to the follow-up under id as OnFinishedReply tells it, with // its files, for a follow-up delivered again to send rather than run twice. One the // conversation does not hold has no message id, text or files. diff --git a/acceleration/internal/conversation/conversation.go b/acceleration/internal/conversation/conversation.go index 356a1684a7..54c29fedaa 100644 --- a/acceleration/internal/conversation/conversation.go +++ b/acceleration/internal/conversation/conversation.go @@ -162,6 +162,10 @@ type commandRecord struct { // Heard is what the voice note sent with the command said, for a retry to carry rather // than hear it again (CheckBegin). Heard string `json:",omitempty"` + // Failure is the error the agent.Error that failed the command's reply carried + // (FollowUpFailure). It is kept in memory only: a conversation opened again reads no + // failure back. + Failure error `json:"-"` } var ErrCommandNotFound = errors.New("command not found") @@ -2022,6 +2026,12 @@ func (c *Conversation) Observe(event agent.Event) { if e.TurnID != "" && c.acceptTurn(e.TurnID, false) { refuse(m) } + // Kept beside the state, so a delivery reads why the reply failed without watching for + // this event, which a watcher that has fallen behind never gets. + if record, ok := c.data.Commands[m.CommandID]; ok { + record.Failure = e.Err + c.data.Commands[m.CommandID] = record + } c.finish("failed") return case agent.Interrupted: diff --git a/acceleration/internal/session/session.go b/acceleration/internal/session/session.go index 69de0b9822..ca7cf5b643 100644 --- a/acceleration/internal/session/session.go +++ b/acceleration/internal/session/session.go @@ -1141,6 +1141,16 @@ func (s *Session) FollowUpReply(id string) (state, text string, known bool) { return s.persisted.FollowUpReply(id) } +// FollowUpFailure is the error the reply to the follow-up under id failed on +// (persistent.Conversation.FollowUpFailure). The conversation records it before any watcher is +// sent the agent.Error (consume), and a watcher that has fallen behind never gets that event. +func (s *Session) FollowUpFailure(id string) error { + if s.persisted == nil { + return nil + } + return s.persisted.FollowUpFailure(id) +} + // FollowUpFinished is the reply to the follow-up under id as the conversation told it once it // finished, with its files (persistent.Conversation.FollowUpFinished). func (s *Session) FollowUpFinished(id string) persistent.FinishedReply { From c1572fa238b051be8b769f74ffac9dcbd359b762 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:45:14 +0100 Subject: [PATCH 02/13] AI-3594: test reply waits whose turn ended unwatched Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_unpaid_test.go | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 7c61b1dd8b..9101d03db9 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -5,6 +5,7 @@ package api import ( "context" "errors" + "fmt" "log/slog" "net/http" "net/http/httptest" @@ -787,6 +788,131 @@ func (s *TelnyxUnpaidSuite) TestATextTurnFailedNotForMoneyIsNotRunAgainOnItsRetr s.False(rerun, "a reply that failed not for money is not run again") } +// followUpIn is the session opened, and the delivery of a task of user's on channel due in it, +// on its first attempt: the attempt before it, if any, recorded no reason about money. +func (s *TelnyxUnpaidSuite) followUpIn(user *testClient, opened Session, channel string) (*session.Session, scheduledDelivery) { + task := s.userTask(user, opened.Id, channel) + found, running := s.router.sessions.Get(opened.Id, session.Owner{CustomerID: s.customerID(), UserID: user.userID, Kind: auth.KindAuthenticated}) + s.Require().True(running) + return found, scheduledDelivery{CustomerID: s.customerID(), ConfigID: s.config.ID, UserID: user.userID, + CallerKind: "authenticated", TaskID: task.ID, RunID: "run", CommandID: "st_run", Text: "stretch"} +} + +// failedBefore runs delivery's turn in found as an attempt cut short once it began the turn +// does, such as one a draining router stops, and waits until the turn's reply has failed. The +// attempt after it watches none of the turn's events: it can only read how the turn ended. +func (s *TelnyxUnpaidSuite) failedBefore(found *session.Session, delivery scheduledDelivery) { + s.Require().NoError(s.router.followUpWithin(scheduledOwnerContext(context.Background(), delivery), found, delivery)) + s.Require().Eventually(func() bool { + state, _, _ := found.FollowUpReply(delivery.CommandID) + return state == "failed" + }, deliveryWait, 10*time.Millisecond, "the turn never failed") +} + +// A conversation task whose turn the model refused for money while no attempt watched it fails +// under the refusal's code on the attempt after, and is not tried again: how the turn ended is +// the conversation's to say, not an event the attempt may never have been sent (AI-3594). +func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedForMoneyUnwatchedFailsUnderTheMoney() { + user, opened := s.spentAfterOpening() + found, delivery := s.followUpIn(user, opened, "conversation") + s.failedBefore(found, delivery) + + _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + store.ScheduledTaskDeliveredConversation) + + var failure *scheduling.Failure + s.Require().ErrorAs(err, &failure, "the turn the user got nothing from is not delivered") + s.Equal(codeInsufficientCredits, failure.Reason) + s.True(failure.Final, "spent credit outlasts every retry of the run") +} + +// A conversation task whose turn was refused, while no attempt watched it, because the money +// could not be checked is tried again (AI-3594). +func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedUncheckedUnwatchedIsRetried() { + user, opened := s.uncheckableAfterOpening() + found, delivery := s.followUpIn(user, opened, "conversation") + s.failedBefore(found, delivery) + + _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + store.ScheduledTaskDeliveredConversation) + + var failure *scheduling.Failure + s.Require().ErrorAs(err, &failure) + s.Equal(codeSpendCheckUnavailable, failure.Reason) + s.False(failure.Final, "the check passes again on its own") +} + +// A text channel's turn the model refused for money while no attempt watched it fails under the +// refusal's code on the attempt after, not as a reply that failed (AI-3594). +func (s *TelnyxUnpaidSuite) TestATextTurnRefusedForMoneyUnwatchedFailsUnderTheMoney() { + user, opened := s.spentAfterOpening() + found, delivery := s.followUpIn(user, opened, "sms") + s.failedBefore(found, delivery) + + _, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + + var failure *scheduling.Failure + s.Require().ErrorAs(err, &failure) + s.Equal(codeInsufficientCredits, failure.Reason) + s.True(failure.Final, "spent credit outlasts every retry of the run") + s.True(refusedTurn(err), "the next text channel would only read the same turn back") +} + +// A text channel's turn refused, while no attempt watched it, because the money could not be +// checked is tried again, and its retry runs the turn again (replyCommand) (AI-3594). +func (s *TelnyxUnpaidSuite) TestATextTurnRefusedUncheckedUnwatchedIsRetried() { + user, opened := s.uncheckableAfterOpening() + found, delivery := s.followUpIn(user, opened, "sms") + s.failedBefore(found, delivery) + + _, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + + var failure *scheduling.Failure + s.Require().ErrorAs(err, &failure) + s.Equal(codeSpendCheckUnavailable, failure.Reason) + s.False(failure.Final, "the check passes again on its own") +} + +// A thread task whose turn the model refused for money while no attempt watched it fails under +// the refusal's code on the attempt after, not as a reply that failed (AI-3594). +func (s *TelnyxUnpaidSuite) TestAThreadTurnRefusedForMoneyUnwatchedFailsUnderTheMoney() { + person := "+1347" + digits(s.utils.uuid()) + s.teamed() + channel := s.creditedThread(person) + s.serverClient.createSession(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel}) + found, running := s.router.sessions.ByConversationWhere(chatlog.ChannelType+":"+channel, func(string, int64) bool { return true }) + s.Require().True(running) + s.teamSpent(person) + task := s.threadTask(channel) + delivery := scheduledDelivery{CustomerID: s.customerID(), ConfigID: s.config.ID, UserID: task.UserID, + CallerKind: "server", TaskID: task.ID, RunID: "run", CommandID: "st_run", Text: "stretch"} + s.failedBefore(found, delivery) + + _, _, err := s.router.deliverOnThread(scheduledOwnerContext(context.Background(), delivery), delivery, channel) + + var failure *scheduling.Failure + s.Require().ErrorAs(err, &failure) + s.Equal(codeSpendLimitReached, failure.Reason) + s.True(failure.Final, "a spent team limit outlasts every retry of the run") +} + +// A refusal for money the session reports to its watchers that ended no turn of the delivery's, +// such as a person's own command refused on the socket, leaves the delivery's turn to end on its +// own: the conversation channel delivers the reply once it does (AI-3594). +func (s *TelnyxUnpaidSuite) TestAConversationTurnOutlivesARefusalReportedForAnotherCommand() { + found, done := s.heldConversationTurn(context.Background()) + found.Report(fmt.Errorf("the command was refused: %w", policy.ErrNoCredits), "command") + + s.Never(func() bool { return len(done) > 0 }, time.Second, 20*time.Millisecond, "settled on another command's refusal") + s.holding.answers() + select { + case err := <-done: + s.NoError(err) + case <-time.After(deliveryWait): + s.Fail("the delivery never settled once the turn ended") + } +} + // creditedOpening is a user who texts the agent's SMS line, on model, and a session they opened on // the agent while the organization has credit. func (s *TelnyxUnpaidSuite) creditedOpening(model string) (*testClient, Session) { From 30b5725ec535e28b786147918a4b00e9c1eecedd Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 20:02:30 +0100 Subject: [PATCH 03/13] AI-3594: document that every reply wait reads the turn's end from the conversation Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .claude/skills/scheduled-tasks/SKILL.md | 2 +- acceleration/internal/api/scheduled_delivery.go | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 1cf299b9fa..eb222cd7bd 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -201,7 +201,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `no_agent_number` | The config has no SMS line to ring from | yes | | `not_answered` | Nobody picked up within the 90 s ring | no | | `already_called` | A call was placed for this occurrence already, and its end is not recorded; no channel after `phone` is tried. That call may have carried the task out, so the run leaves the failure streak as it is and the task moves on as after a run that did not fail (a one-shot is `completed`) | no | -| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (an `agent.Error` in `captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end and reads it from the session's events; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread` reads it from the session's events), or its call. The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:334`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:355`) | +| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way. The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:334`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:355`) | | `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st__r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was | yes (`unpaid` leaves it retryable) | | `task_paused` | On a `missed` run: a one-shot whose time came while it was paused, or an occurrence the cut-over of a move skipped whose run the source had started | — | diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index 21c30cfc79..de9559bc04 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -534,10 +534,13 @@ func (s *Server) captureReply(ctx context.Context, found *session.Session, deliv // refusal, which leaves the user nothing: the run records the money (turnRefusal), as a text // channel's does. Any other end leaves the reply in the conversation as it stands, delivered: a // turn that finished or failed for another reason, one still running at scheduledReplyWindow, or a -// session that ended. A follow-up the conversation already holds runs nothing, so nothing is -// waited for: it stands as it is, except a rerun after a refusal for money (replyCommand) that -// failed too, which left the user nothing again. That one fails the attempt under the earlier -// reason, tried again until the run's attempts are spent, as a text channel's is. +// session that ended. How the turn ended is read from the conversation (turnRefusal), never from +// the events alone, which a watcher that falls behind loses. A follow-up the conversation already +// holds runs nothing, so nothing is waited for: it stands as it is, except one whose turn was +// refused for money while no attempt watched it, which fails under the money too, and a rerun +// after a refusal for money (replyCommand) that failed too, which left the user nothing again. +// That one fails the attempt under the earlier reason, tried again until the run's attempts are +// spent, as a text channel's is. func (s *Server) followUpInConversation(ctx context.Context, found *session.Session, delivery scheduledDelivery) error { if err := refusedAgain(found, delivery); err != nil { return err From 82136ab4fec2b10da1eed46b0d5def5e764d41ac Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 20:55:01 +0100 Subject: [PATCH 04/13] AI-3594: a conversation retry waits out the turn an earlier attempt began R1.1: followUpInConversation returned at once for a follow-up the conversation already held, so a retry after an attempt cut short mid-turn recorded delivered while the turn ran. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_delivery.go | 14 ++++----- .../internal/api/scheduled_unpaid_test.go | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index de9559bc04..f3366d3cad 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -536,24 +536,20 @@ func (s *Server) captureReply(ctx context.Context, found *session.Session, deliv // turn that finished or failed for another reason, one still running at scheduledReplyWindow, or a // session that ended. How the turn ended is read from the conversation (turnRefusal), never from // the events alone, which a watcher that falls behind loses. A follow-up the conversation already -// holds runs nothing, so nothing is waited for: it stands as it is, except one whose turn was -// refused for money while no attempt watched it, which fails under the money too, and a rerun -// after a refusal for money (replyCommand) that failed too, which left the user nothing again. -// That one fails the attempt under the earlier reason, tried again until the run's attempts are -// spent, as a text channel's is. +// holds runs nothing: its turn, which an earlier attempt began, is waited out the same, and one +// already ended settles at once, failing under the money when it was refused for money while no +// attempt watched it. A rerun after a refusal for money (replyCommand) that failed too left the +// user nothing again: it fails the attempt under the earlier reason, tried again until the run's +// attempts are spent, as a text channel's is. func (s *Server) followUpInConversation(ctx context.Context, found *session.Session, delivery scheduledDelivery) error { if err := refusedAgain(found, delivery); err != nil { return err } - _, _, known := found.FollowUpReply(delivery.CommandID) events, detach := found.Watch() defer detach() if err := s.followUpWithin(ctx, found, delivery); err != nil { return err } - if known { - return turnRefusal(found, delivery.CommandID) - } deadline := time.Now().Add(scheduledReplyWindow) ticker := time.NewTicker(s.replyPoll) defer ticker.Stop() diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 9101d03db9..3d3d9ab8b3 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -1043,6 +1043,35 @@ func (s *TelnyxUnpaidSuite) TestAConversationTurnCutShortIsNotDelivered() { } } +// The retry of a conversation delivery cut short while its turn runs waits that turn out, as the +// attempt it follows did, rather than settling delivered on a turn that may still be refused +// (AI-3594 R1.1). +func (s *TelnyxUnpaidSuite) TestAConversationRetryWaitsOutTheTurnAnEarlierAttemptBegan() { + ctx, cancel := context.WithCancel(context.Background()) + found, done := s.heldConversationTurn(ctx) + cancel() + s.Require().ErrorIs(<-done, context.Canceled) + delivery := scheduledDelivery{CustomerID: s.customerID(), ConfigID: s.config.ID, UserID: found.Spec().Caller.UserID, + CallerKind: "authenticated", TaskID: "task", RunID: "run", CommandID: "st_run", Text: "stretch"} + retried := make(chan error, 1) + go func() { + _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + store.ScheduledTaskDeliveredConversation) + retried <- err + }() + + s.Never(func() bool { return len(retried) > 0 }, time.Second, 20*time.Millisecond, "settled while the turn ran") + s.holding.answers() + select { + case err := <-retried: + s.NoError(err) + state, _, _ := found.FollowUpReply("st_run") + s.Equal("completed", state, "settled before the turn ended") + case <-time.After(deliveryWait): + s.Fail("the retry never settled once the turn ended") + } +} + // A conversation turn whose session ends while it runs is delivered, as it always was: nothing // more comes from the session to say otherwise. func (s *TelnyxUnpaidSuite) TestAConversationTurnWhoseSessionEndsIsDelivered() { From 282da2ca4aca72672c33c6ed19639d370446fccb Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:07:27 +0100 Subject: [PATCH 05/13] AI-3594: a text channel carries only its own follow-up's reply R1.2: captureReply watched the session before followUpWithin waited behind a busy turn, so that turn's words were texted as the scheduled reply. It now reads the follow-up's reply back from the conversation once its turn ends (readBackReply), as a retry already did; the event-joining helpers it alone used are gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_delivery.go | 89 +++---------------- .../internal/api/scheduled_reply_test.go | 14 --- .../internal/api/scheduled_unpaid_test.go | 68 ++++++++++++++ 3 files changed, 78 insertions(+), 93 deletions(-) diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index f3366d3cad..8a0d52b1cf 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -13,7 +13,6 @@ import ( "github.com/google/uuid" - "github.com/GetStream/Vision-Agents/acceleration/internal/agent" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" "github.com/GetStream/Vision-Agents/acceleration/internal/channels" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" @@ -40,11 +39,6 @@ const scheduledPeerPath = "/internal/scheduled-tasks/deliver" // a window spent is an attempt, not a lost occurrence. const scheduledWindow = 10 * time.Minute -// scheduledReplySettle is how long the agent stays quiet, with nothing left -// running, before what it said is taken as its answer: a channel's own -// reading of a turn (channels.settleGap), over the same words. -var scheduledReplySettle = 2 * time.Second - // scheduledReplyWindow bounds reading an answer for a channel. The lease is // renewed while a delivery runs, so a slow turn is waited out; one still // running at the window's end fails the channel, not the conversation. @@ -469,64 +463,23 @@ func (s *Server) waitOutCall(ctx context.Context, found *session.Session, window return nil } -// captureReply runs the follow-up in found and reads what the agent -// answers, and the files its code made, settled the way a channel's replies -// settle: quiet for the settle gap, with nothing left running. The words are -// the conversation's own; a channel carries them out, holding no second copy -// of the turn. A follow-up the conversation already holds is not run again: -// its words and files are read back. +// captureReply runs the follow-up in found and reads what the agent answers to it, and the files +// its code made, once its turn has ended (readBackReply). The words are the conversation's own, +// of this follow-up alone: another turn the follow-up waited behind (followUpWithin) is not +// carried. A channel carries them out, holding no second copy of the turn. A follow-up the +// conversation already holds is not run again: its words and files are read back the same. func (s *Server) captureReply(ctx context.Context, found *session.Session, delivery scheduledDelivery) (string, []sandbox.Attachment, error) { delivery.CommandID = replyCommand(found, delivery.CommandID, delivery.Earlier) if err := refusedAgain(found, delivery); err != nil { return "", nil, err } - if _, _, known := found.FollowUpReply(delivery.CommandID); known { - reply, err := s.readBackReply(ctx, found, delivery.CommandID) - return reply.Text, reply.Files, err - } - events, detach := found.Watch() - defer detach() - if err := s.followUpWithin(ctx, found, delivery); err != nil { - return "", nil, err - } - var said []string - var files []sandbox.Attachment - active := found.Busy() - last := time.Now() - deadline := time.Now().Add(scheduledReplyWindow) - ticker := time.NewTicker(250 * time.Millisecond) - defer ticker.Stop() - for { - ended := false - select { - case <-ctx.Done(): - return "", nil, ctx.Err() - case event, open := <-events: - if !open { - ended = true - break - } - active, last = true, time.Now() - if text := spokenOf(event); text != "" && (len(said) == 0 || said[len(said)-1] != text) { - said = append(said, text) - } - // Merged as the conversation keeps them, so a retry reading them back sends the same. - files = conversation.MergeFiles(files, madeBy(event)) - case <-ticker.C: - if found.Busy() { - active = true - } - ended = time.Now().After(deadline) || active && !found.Busy() && time.Since(last) >= scheduledReplySettle - } - // A turn the organization may not pay for ends with the model's refusal, which no reply - // follows: the run records the money, not an agent that said nothing. - if refusal := turnRefusal(found, delivery.CommandID); refusal != nil { - return "", nil, refusal - } - if ended { - return captured(said, files) + if _, _, known := found.FollowUpReply(delivery.CommandID); !known { + if err := s.followUpWithin(ctx, found, delivery); err != nil { + return "", nil, err } } + reply, err := s.readBackReply(ctx, found, delivery.CommandID) + return reply.Text, reply.Files, err } // followUpInConversation puts the follow-up to found, whose conversation carries the reply, and @@ -686,28 +639,6 @@ func captured(said []string, files []sandbox.Attachment) (string, []sandbox.Atta return text, files, nil } -// spokenOf is what an event is worth carrying out, if anything: the agent's -// finished reply. Settled work's own words are not: the agent's next turn -// tells them, and the conversation keeps only the reply, which a retry reads -// back. -func spokenOf(event session.Event) string { - if happened, ok := event.(agent.Responded); ok { - return happened.Text - } - return "" -} - -// madeBy is the files an event hands back: what the code a tool or settled work ran made. -func madeBy(event session.Event) []sandbox.Attachment { - switch happened := event.(type) { - case agent.ToolRan: - return happened.Files - case agent.TaskSettled: - return happened.Files - } - return nil -} - // reachableText says whether a channel would carry the task's words to its // user now, the words aside. func (s *Server) reachableText(ctx context.Context, delivery scheduledDelivery, channel string) error { diff --git a/acceleration/internal/api/scheduled_reply_test.go b/acceleration/internal/api/scheduled_reply_test.go index 001e6415f6..d4c3e9259a 100644 --- a/acceleration/internal/api/scheduled_reply_test.go +++ b/acceleration/internal/api/scheduled_reply_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/GetStream/Vision-Agents/acceleration/internal/agent" "github.com/GetStream/Vision-Agents/acceleration/internal/sandbox" "github.com/GetStream/Vision-Agents/acceleration/internal/scheduling" ) @@ -36,16 +35,3 @@ func TestAReplyOfTwoTurnsIsJoinedAsTheConversationJoinsThem(t *testing.T) { require.NoError(t, err) require.Equal(t, "First.\n\nSecond.", text) } - -func TestTheFilesCodeHandedBackAreThoseOfARunAndOfSettledWork(t *testing.T) { - chart := sandbox.Attachment{Name: "chart.png", MIME: "image/png", URL: "https://cdn.example/chart.png"} - - require.Equal(t, []sandbox.Attachment{chart}, madeBy(agent.ToolRan{Files: []sandbox.Attachment{chart}})) - require.Equal(t, []sandbox.Attachment{chart}, madeBy(agent.TaskSettled{Files: []sandbox.Attachment{chart}})) - require.Nil(t, madeBy(agent.Responded{Text: "Here is the chart."})) -} - -func TestSettledWorksOwnWordsAreNotCarriedButTheAgentsReplyIs(t *testing.T) { - require.Empty(t, spokenOf(agent.TaskSettled{Text: "steps: 9,214"})) - require.Equal(t, "You walked 9,214 steps today.", spokenOf(agent.Responded{Text: "You walked 9,214 steps today."})) -} diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 3d3d9ab8b3..8450a4c12c 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -913,6 +913,74 @@ func (s *TelnyxUnpaidSuite) TestAConversationTurnOutlivesARefusalReportedForAnot } } +// A text channel's reply that waited behind another turn of the session carries only its own +// words, not the words of the turn it waited for (AI-3594 R1.2). +func (s *TelnyxUnpaidSuite) TestATextReplyCarriesOnlyItsOwnTurnsWords() { + s.saying("Words of the earlier turn.") + found, done := s.heldConversationTurn(context.Background()) + delivery := scheduledDelivery{CustomerID: s.customerID(), ConfigID: s.config.ID, UserID: found.Spec().Caller.UserID, + CallerKind: "authenticated", TaskID: "task2", RunID: "run2", CommandID: "st_run2", Text: "drink water"} + type reply struct { + text string + err error + } + captured := make(chan reply, 1) + go func() { + text, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + captured <- reply{text, err} + }() + s.Never(func() bool { return len(captured) > 0 }, time.Second, 20*time.Millisecond, "the reply did not wait behind the busy turn") + s.saying("The scheduled words.") + s.holding.answers() + s.Require().NoError(<-done) + + select { + case got := <-captured: + s.Require().NoError(got.err) + s.Equal("The scheduled words.", got.text) + case <-time.After(deliveryWait): + s.Fail("the reply never came") + } +} + +// A text channel's reply with no other turn ahead of it is texted as it always was, word for +// word, and as soon as its turn ends, not at the end of the reply window (AI-3594 R1.2, R1.3). +func (s *TelnyxUnpaidSuite) TestATextReplyIsTextedAsItWasOnceItsTurnEnds() { + user, opened := s.creditedOpening("recites/recites-model") + found, delivery := s.followUpIn(user, opened, "sms") + type reply struct { + text string + err error + } + captured := make(chan reply, 1) + go func() { + text, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + captured <- reply{text, err} + }() + + select { + case got := <-captured: + s.Require().NoError(got.err) + s.Equal("user: stretch", got.text, "what the reciting model was handed: the follow-up alone") + case <-time.After(deliveryWait): + s.Fail("the reply waited out the window though its turn had ended") + } +} + +// saying has the holding model answer every turn it begins from now with text, until the test +// ends. +func (s *TelnyxUnpaidSuite) saying(text string) { + s.holding.mu.Lock() + defer s.holding.mu.Unlock() + before := s.holding.reply + s.holding.reply = text + s.T().Cleanup(func() { + s.holding.mu.Lock() + defer s.holding.mu.Unlock() + s.holding.reply = before + }) +} + // creditedOpening is a user who texts the agent's SMS line, on model, and a session they opened on // the agent while the organization has credit. func (s *TelnyxUnpaidSuite) creditedOpening(model string) (*testClient, Session) { From f8f5877369d3aa1a199169cef40420baadf737d6 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:09:24 +0100 Subject: [PATCH 06/13] AI-3594: test a refused conversation follow-up and an interrupted reply R1.3: two of the reviewer's surviving mutants were not equivalent: followUpInConversation ignoring followUpWithin's error, and replyEnded without interrupted. The third (capture with no settle gap) went with the event loop R1.2 removed; TestATextReplyIsTextedAsItWasOnceItsTurnEnds keeps its row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_reply_test.go | 12 ++++++++++++ .../internal/api/scheduled_unpaid_test.go | 16 ++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/acceleration/internal/api/scheduled_reply_test.go b/acceleration/internal/api/scheduled_reply_test.go index d4c3e9259a..9edef30947 100644 --- a/acceleration/internal/api/scheduled_reply_test.go +++ b/acceleration/internal/api/scheduled_reply_test.go @@ -35,3 +35,15 @@ func TestAReplyOfTwoTurnsIsJoinedAsTheConversationJoinsThem(t *testing.T) { require.NoError(t, err) require.Equal(t, "First.\n\nSecond.", text) } + +// A reply ends however its turn did, interrupted included: a regenerate or an edit during the +// turn interrupts it (Conversation.switchTo) while the session stays open, and a wait that took +// it for running would hold its worker to the end of the reply window (AI-3594 R1.3). +func TestAReplyEndsHoweverItsTurnEnded(t *testing.T) { + for _, state := range []string{"completed", "cancelled", "interrupted", "failed"} { + require.True(t, replyEnded(state), state) + } + for _, state := range []string{"", "thinking", "writing", "tools", "queued"} { + require.False(t, replyEnded(state), state) + } +} diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 8450a4c12c..b09a5d9034 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -1140,6 +1140,22 @@ func (s *TelnyxUnpaidSuite) TestAConversationRetryWaitsOutTheTurnAnEarlierAttemp } } +// A conversation follow-up the session refuses to run, such as one with nothing to answer, fails +// the attempt: no turn ran, so nothing is delivered once the reply window passes (AI-3594 R1.3). +func (s *TelnyxUnpaidSuite) TestAConversationFollowUpTheSessionRefusesIsNotDelivered() { + window := scheduledReplyWindow + scheduledReplyWindow = 2 * time.Second + s.T().Cleanup(func() { scheduledReplyWindow = window }) + user, opened := s.creditedOpening("holding/holding-model") + found, delivery := s.followUpIn(user, opened, "conversation") + delivery.Text = "" + + _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + store.ScheduledTaskDeliveredConversation) + + s.ErrorContains(err, "there is nothing to answer") +} + // A conversation turn whose session ends while it runs is delivered, as it always was: nothing // more comes from the session to say otherwise. func (s *TelnyxUnpaidSuite) TestAConversationTurnWhoseSessionEndsIsDelivered() { From 4d16fc24c4f938e9eafa7a6a52977b278099f40b Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:10:50 +0100 Subject: [PATCH 07/13] AI-3594: the skill row claims the unwatched end only while the session is open R1.4: the reply's failure is kept in memory only, so a reopened conversation retry still records reply_failed or delivered; say so as a known gap. R1.6: deliveryReason and unpaid line numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .claude/skills/scheduled-tasks/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index eb222cd7bd..3c71924c33 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -201,7 +201,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `no_agent_number` | The config has no SMS line to ring from | yes | | `not_answered` | Nobody picked up within the 90 s ring | no | | `already_called` | A call was placed for this occurrence already, and its end is not recorded; no channel after `phone` is tried. That call may have carried the task out, so the run leaves the failure streak as it is and the task moves on as after a run that did not fail (a one-shot is `completed`) | no | -| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way. The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:334`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:355`) | +| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:340`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:384`) | | `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st__r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was | yes (`unpaid` leaves it retryable) | | `task_paused` | On a `missed` run: a one-shot whose time came while it was paused, or an occurrence the cut-over of a move skipped whose run the source had started | — | From fb7afe0a183c5da51317e567e6266056e2fba13e Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:11:25 +0100 Subject: [PATCH 08/13] AI-3594: the unwatched-end tests name an attempt cut short in an open session R1.4: a draining router reopens the conversation elsewhere, which the in-memory failure does not survive. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/api/scheduled_unpaid_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index b09a5d9034..96311856da 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -799,8 +799,9 @@ func (s *TelnyxUnpaidSuite) followUpIn(user *testClient, opened Session, channel } // failedBefore runs delivery's turn in found as an attempt cut short once it began the turn -// does, such as one a draining router stops, and waits until the turn's reply has failed. The -// attempt after it watches none of the turn's events: it can only read how the turn ended. +// does, such as one whose context is cancelled, and waits until the turn's reply has failed. The +// attempt after it, in the same open session, watches none of the turn's events: it can only read +// how the turn ended. func (s *TelnyxUnpaidSuite) failedBefore(found *session.Session, delivery scheduledDelivery) { s.Require().NoError(s.router.followUpWithin(scheduledOwnerContext(context.Background(), delivery), found, delivery)) s.Require().Eventually(func() bool { From d2f952309efecd4a00a050bf48046ea0907762e6 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:12:58 +0100 Subject: [PATCH 09/13] AI-3594: test a text follow-up the session refuses R1.2: captureReply returns followUpWithin's error rather than waiting for a reply nobody writes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_unpaid_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 96311856da..73665d8262 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -1157,6 +1157,21 @@ func (s *TelnyxUnpaidSuite) TestAConversationFollowUpTheSessionRefusesIsNotDeliv s.ErrorContains(err, "there is nothing to answer") } +// A text channel's follow-up the session refuses to run fails the attempt with why, not as a +// reply nobody wrote once the reply window passes (AI-3594 R1.2). +func (s *TelnyxUnpaidSuite) TestATextFollowUpTheSessionRefusesFailsWithWhy() { + window := scheduledReplyWindow + scheduledReplyWindow = 2 * time.Second + s.T().Cleanup(func() { scheduledReplyWindow = window }) + user, opened := s.creditedOpening("holding/holding-model") + found, delivery := s.followUpIn(user, opened, "sms") + delivery.Text = "" + + _, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + + s.ErrorContains(err, "there is nothing to answer") +} + // A conversation turn whose session ends while it runs is delivered, as it always was: nothing // more comes from the session to say otherwise. func (s *TelnyxUnpaidSuite) TestAConversationTurnWhoseSessionEndsIsDelivered() { From 7c3505e6b6fbf9560d5d9c36ceaea3555b0495c0 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:21:49 +0100 Subject: [PATCH 10/13] AI-3594: a text task texts its reply as the conversation keeps it R1.2 follow-on: the text channel now reads its reply back, so a turn of two rounds texts both rounds' words, as a thread task already does (reportReply), and a reply cut off before it was written fails as the reply that was cancelled (reply_failed), as its retry read it back. The retry still runs the turn again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/api/scheduled_tasks_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 8aa6c68841..5e9eea2046 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -3295,7 +3295,9 @@ func (s *ScheduledTasksSuite) TestATaskTextedBySMSCarriesTheFileItsCodeMade() { s.Equal("sms", run.DeliveredTo) s.Require().Eventually(func() bool { return len(s.sink.mediaTo(writer)) > 0 }, 10*time.Second, 50*time.Millisecond, "no file was texted to %s", writer) - s.Equal([]string{"Done."}, s.sink.to(writer)) + // The words of both rounds, as the conversation keeps them and a thread task texts them + // (reportReply). + s.Equal([]string{"Done.\n\nDone."}, s.sink.to(writer)) s.Equal([]string{report}, s.sink.mediaTo(writer)) } @@ -3328,7 +3330,7 @@ func (s *ScheduledTasksSuite) TestATaskWhoseFileTheLineRefusesTextsItsWordsOnce( run := s.delivered(s.tasksOf(user)[0]) s.Equal("sms", run.DeliveredTo) s.Never(func() bool { return len(s.sink.to(writer)) > 1 }, dropped, 20*time.Millisecond, "texted once") - s.Equal([]string{"Done."}, s.sink.to(writer)) + s.Equal([]string{"Done.\n\nDone."}, s.sink.to(writer), "the words of both rounds, as the conversation keeps them") s.Empty(s.sink.mediaTo(writer), "the file was refused") } @@ -3819,7 +3821,7 @@ func (s *ScheduledTasksSuite) TestATurnCancelledBeforeItsReplyRunsAgainOnTheRetr task, found := s.onWhatsApp(writer, "whatsapp") run := s.manualRun(task) _, err := s.cutOff(s.router, task, run, found.Interrupt) - s.Equal(scheduling.ReasonNoReply, scheduling.ReasonOf(err), "%v", err) + s.Equal(scheduling.ReasonReplyFailed, scheduling.ReasonOf(err), "%v", err) deliveredTo, err := s.deliverRun(task, run) @@ -3856,7 +3858,7 @@ func (s *ScheduledTasksSuite) TestATurnWhoseProviderBrokeAsItWasCancelledRunsAga } }) _, err := s.cutOff(s.router, task, run, found.Interrupt) - s.Equal(scheduling.ReasonNoReply, scheduling.ReasonOf(err), "%v", err) + s.Equal(scheduling.ReasonReplyFailed, scheduling.ReasonOf(err), "%v", err) state, _, _ := found.FollowUpReply(command) s.Equal("cancelled", state) From dded58268db3b4729f025df51d68ee2720b03fcd Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:31:25 +0100 Subject: [PATCH 11/13] AI-3594: the skill row's line numbers after the merge of main R1.6: deliveryReason is at scheduled_delivery.go:355, unpaid at :399. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .claude/skills/scheduled-tasks/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index dde86c2464..5634aa71f9 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -203,7 +203,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `no_agent_number` | The config has no SMS line to ring from | yes | | `not_answered` | Nobody picked up within the 90 s ring | no | | `already_called` | A call was placed for this occurrence already, and its end is not recorded; no channel after `phone` is tried. That call may have carried the task out, so the run leaves the failure streak as it is and the task moves on as after a run that did not fail (a one-shot is `completed`) | no | -| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:340`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:384`) | +| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:355`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:399`) | | `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st__r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was | yes (`unpaid` leaves it retryable) | | `task_paused` | On a `missed` run: a one-shot whose time came while it was paused, or an occurrence the cut-over of a move skipped whose run the source had started | — | From 5815da5ba3dae3edf62413a2b991df629717c7df Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 22:04:32 +0100 Subject: [PATCH 12/13] AI-3594: the reply_failed row names a text channel's first cut-off too Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .claude/skills/scheduled-tasks/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 5634aa71f9..245e3132a1 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -198,7 +198,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `thread_gone` | A thread task's thread no longer exists, or is not its user's thread of its customer | no | | `connection_removed` | A thread task's line (its connection) was removed | no | | `no_reply` | The agent said nothing and made no file to carry | yes | -| `reply_failed` | The reply failed, or was cancelled or interrupted and, when run once more under `st__r1`, was cut off again (a thread task's first cut-off also gives it, and the retry runs it again) | yes | +| `reply_failed` | The reply failed, or was cancelled or interrupted and, when run once more under `st__r1`, was cut off again (a text channel's or a thread task's first cut-off also gives it, and the retry runs it again) | yes | | `no_phone_number` | The user never texted this agent by SMS; a number used only on WhatsApp is not rung | yes | | `no_agent_number` | The config has no SMS line to ring from | yes | | `not_answered` | Nobody picked up within the 90 s ring | no | From b64e9b998e3ad71b55b8618e743b7dbc7b004244 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:15:02 +0100 Subject: [PATCH 13/13] AI-3594: the money row cites deliveryReason and unpaid at their lines Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .claude/skills/scheduled-tasks/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index f3171b994d..a8adc142ae 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -203,7 +203,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `no_agent_number` | The config has no SMS line to ring from | yes | | `not_answered` | Nobody picked up within the 90 s ring | no | | `already_called` | A call was placed for this occurrence already, and its end is not recorded; no channel after `phone` is tried. That call may have carried the task out, so the run leaves the failure streak as it is and the task moves on as after a run that did not fail (a one-shot is `completed`) | no | -| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call, placed or not: a placed call whose session cannot open fails under the refusal's code (`carryOutOnCall`); on an answered call, a turn refused before the agent answered anything hangs up (`carryOutAnswered`, which reads its events), and a refusal after that is a later turn's, still `delivered`. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:355`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:399`) | +| `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), or its call, placed or not: a placed call whose session cannot open fails under the refusal's code (`carryOutOnCall`); on an answered call, a turn refused before the agent answered anything hangs up (`carryOutAnswered`, which reads its events), and a refusal after that is a later turn's, still `delivered`. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:356`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:400`) | | `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st__r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was. A placed call is rung once: refused this way, its session or its answered turn fails the run under this code, final, with the call kept on the run (`callEnded`), so the user is not rung again | yes (`unpaid` leaves it retryable) | | `task_paused` | On a `missed` run: a one-shot whose time came while it was paused, or an occurrence the cut-over of a move skipped whose run the source had started | — |