package thintest import ( "context" "io" "net/http" "net/url" "regexp" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // Try again (Paul, 2026-11-22): the note under a failed reply says why, // names the account it ran on, and offers Try again: a new turn takes // the failed turn's exchange over as its next attempt (chat.Retry). The // message is never sent twice, and its words never ride again as // unanswered. // retryRig is a rig whose runner is online with conns (toolHello's one // Claude connection, claude-a, labelled with the owner's email, when nil). func retryRig(t *testing.T, conns []wire.HeldConnection) (*rig, *FakeRunner) { t.Helper() r := newRig(t) runner := r.dial(0) hello := toolHello(runner.Welcome.Generation) if conns != nil { hello.Connections = conns } if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) return r, runner } // running is the next message frame, acked, once its turn runs. func (r *rig) running(runner *FakeRunner) *wire.MessageCommand { r.t.Helper() f, body, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { r.t.Fatal(err) } runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) cmd := body.(*wire.MessageCommand) r.turnIs(cmd.TurnID, wire.TurnRunning) return cmd } // say sends text and returns its running turn's frame. func (r *rig) say(runner *FakeRunner, text, key string) *wire.MessageCommand { r.t.Helper() if _, err := r.client.Send(r.ctx, text, key); err != nil { r.t.Fatal(err) } return r.running(runner) } // attempt is a turn's current attempt (a retry is its failed turn's next). func (r *rig) attempt(id string) int64 { r.t.Helper() v, err := r.client.Turn(r.ctx, id) if err != nil { r.t.Fatal(err) } return v.Attempt } // failOn fails a running turn for reason; local names the connection // its attempt ran on (a usage row, as a runner reports one), or none. func (r *rig) failOn(runner *FakeRunner, id, reason, local string) { r.t.Helper() attempt := r.attempt(id) if local != "" { runner.Send(r.ctx, "u-"+id, wire.FrameUsage, wire.UsageReport{TurnID: id, Rows: []wire.Usage{{Provider: wire.ProviderClaude, Connection: local, Model: "claude-sonnet", Attempt: attempt, Outcome: wire.OutcomeFailed}}}) } runner.Send(r.ctx, "f-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: attempt, State: wire.TurnFailed, Reason: reason}) r.turnIs(id, wire.TurnFailed) } // tryAgain posts the page's Try again as the owner's browser, from site. func (r *rig) tryAgain(id, site string) (int, string) { r.t.Helper() req, _ := http.NewRequest("POST", r.inst.URL+"/conversation/turns/"+id+"/retry", strings.NewReader(url.Values{}.Encode())) req.AddCookie(r.inst.Cookie()) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") origin := r.inst.URL if site != "same-origin" { origin = "https://foreign.example" } req.Header.Set("Origin", origin) req.Header.Set("Sec-Fetch-Site", site) res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) if err != nil { r.t.Fatal(err) } io.Copy(io.Discard, res.Body) res.Body.Close() return res.StatusCode, res.Header.Get("Location") } func (r *rig) count(query string, args ...any) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow(query, args...).Scan(&n); err != nil { r.t.Fatal(err) } return n } func retryForm(id string) string { return `

Claude (owner@example.com) stopped before finishing the reply. Try again.

`+retryForm(failed)) { t.Fatal("the failed reply's note lacks its account or Try again") } // Production's policy refuses inline styles and scripts. _, note, _ := strings.Cut(page, `data-ended="`+failed) note, _, _ = strings.Cut(note, "") if inlineStyle.MatchString(note) || regexp.MustCompile(`(?i)\son[a-z]+=|

The reply ran out of time on your runner. Try again, or ask for less at once.

`+retryForm(retried.ID)) { t.Fatal("a failed retry's note") } if again, err := r.client.Retry(r.ctx, retried.ID); err != nil || again.ID == retried.ID { t.Fatalf("retrying the retry %+v %v", again, err) } else if cmd := r.running(runner); strings.Join(cmd.PersonText, "|") != words { t.Fatalf("the second retry %q", cmd.PersonText) } else { r.failOn(runner, cmd.TurnID, "policy_rejected", "") } next := r.say(runner, "Any news?", "k2") if strings.Join(next.PersonText, "|") != words+"|Any news?" || strings.Count(next.Text, words) != 1 { t.Fatalf("the unanswered words %q %q", next.PersonText, next.Text) } } // Only the latest failed turn can be tried again, while nothing of the // person's runs, and only by them; a reason another try cannot mend has // no Try again. func TestContractRetryRefused(t *testing.T) { r, runner := retryRig(t, nil) first := r.say(runner, "One", "k1").TurnID r.failOn(runner, first, "provider_failed", "") second := r.say(runner, "Two", "k2").TurnID r.failOn(runner, second, "superseded", "") if _, err := r.client.Retry(r.ctx, first); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "not_retryable") { t.Fatalf("an older failed turn: %v", err) } if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+second+`">

The coordinator could not answer this message.

`+retryForm(second)) { t.Fatal("an unknown reason's note offers Try again") } // Someone else's turn is not theirs to try. const member = "member@example.com" if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil { t.Fatal(err) } other := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member)) if _, err := other.Retry(r.ctx, second); Status(err) != http.StatusNotFound { t.Fatalf("another member's retry: %v", err) } if _, err := NewClient(r.inst.URL, "").Retry(r.ctx, second); Status(err) != http.StatusUnauthorized { t.Fatalf("no bearer: %v", err) } // From another site, nothing happens. if status, _ := r.tryAgain(second, "cross-site"); status != http.StatusForbidden { t.Fatalf("cross-site Try again: %d", status) } if n := r.count("SELECT count(*) FROM chat_turns WHERE coalesce(retry_of, '') <> ''"); n != 0 { t.Fatalf("%d retries queued by refused requests", n) } // A newer message running: the failed turn is history. third := r.say(runner, "Three", "k3").TurnID if _, err := r.client.Retry(r.ctx, second); Status(err) != http.StatusConflict { t.Fatalf("with a newer turn running: %v", err) } if status, at := r.tryAgain(second, "same-origin"); status != http.StatusSeeOther || at != "/conversation" { t.Fatalf("a stale Try again: %d %s", status, at) } r.failOn(runner, third, wire.ReasonAttachmentUnavailable, "") page := r.inst.Get(t, "/conversation") if !strings.Contains(page, `data-ended="`+third+`">

A file did not arrive whole on your runner. Attach it again.

`) { t.Fatal("a missing file's note offers an action") } if _, err := r.client.Retry(r.ctx, third); Status(err) != http.StatusConflict { t.Fatalf("retrying a missing file: %v", err) } if n := r.count("SELECT count(*) FROM chat_turns WHERE coalesce(retry_of, '') <> ''"); n != 0 { t.Fatalf("%d retries queued by refused requests", n) } } // Sign in again: the account's own row on Connections, not Try again. // A limit that has reset: Try again. func TestContractRetryAccountActions(t *testing.T) { reset := time.Now().Add(-time.Minute).UTC() r, runner := retryRig(t, []wire.HeldConnection{ {LocalID: "claude-a", Person: Owner, Provider: "claude", Kind: "subscription", Label: Owner, State: wire.ConnSignInAgain}, {LocalID: "claude-b", Person: Owner, Provider: "claude", Kind: "subscription", Label: "second@example.com", State: wire.ConnLimited, Headroom: &wire.Headroom{ResetsAt: &reset}}, }) conns, err := r.client.Connections(r.ctx) if err != nil { t.Fatal(err) } var signIn string for _, c := range conns.Items { if c.LocalID == "claude-a" { signIn = c.ID } } first := r.say(runner, "One", "k1").TurnID r.failOn(runner, first, "sign_in_again", "claude-a") page := r.inst.Get(t, "/conversation") if signIn == "" || !strings.Contains(page, `data-ended="`+first+`">

Claude (owner@example.com) needs you to sign in again.

Sign in again`) { t.Fatal("sign in again") } second := r.say(runner, "Two", "k2").TurnID r.failOn(runner, second, "limited", "claude-b") if page = r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+second+`">

Claude (second@example.com) reached its usage limit. Try again once it resets, or add another account.

`+retryForm(second)) { t.Fatal("a limit that has reset") } } // A retry waiting behind a move-in that gives way is a queued turn with // messages of its own, like any: a message sent meanwhile joins it as a // batch, and nothing in dispatch reads retry_of, so an instance rolled // back to a version without retries (which ignores the column) sends it // just the same. The dispatch code is that version's (8dc096b4). func TestContractRetryWaitingJoinsAndRollsBack(t *testing.T) { r := newMoveInRig(t) if _, err := r.client.Send(r.ctx, "hello", "k1"); err != nil { t.Fatal(err) } failed := r.dispatched(wire.TurnPerson).TurnID r.failOn(r.runner, failed, "policy_rejected", "") moving := r.moveIn("r-mi-1", wire.TurnMoveIn) retried, err := r.client.Retry(r.ctx, failed) if err != nil || retried.State != wire.TurnQueued { t.Fatalf("retry behind the move-in %+v %v", retried, err) } later, err := r.client.Send(r.ctx, "and this", "k2") if err != nil || later.Turn.ID != retried.ID { t.Fatalf("a message sent meanwhile %+v %v", later.Turn, err) } if own, left := r.count("SELECT count(*) FROM chat_messages WHERE turn_id = ? AND role = 'person'", retried.ID), r.count("SELECT count(*) FROM chat_messages WHERE turn_id = ?", failed); own != 2 || left != 0 { t.Fatalf("the retry holds %d messages, the failed turn %d", own, left) } // The rolled-back version knows nothing of retry_of. if _, err := r.inst.DB.Writer().Exec("UPDATE chat_turns SET retry_of = NULL"); err != nil { t.Fatal(err) } if err := r.runner.Send(r.ctx, "r-t-y", wire.FrameTurn, wire.TurnReport{TurnID: moving.TurnID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}); err != nil { t.Fatal(err) } if cmd := r.dispatched(wire.TurnPerson); cmd.TurnID != retried.ID || strings.Join(cmd.PersonText, "|") != "hello|and this" { t.Fatalf("the retry's frame %s %q", cmd.TurnID, cmd.PersonText) } } // A retry the person stopped: they stopped those words, which ride no // further, as a stopped turn's never do. func TestContractRetryStoppedCarriesNothing(t *testing.T) { r, runner := retryRig(t, nil) failed := r.say(runner, "Old words", "k1").TurnID r.failOn(runner, failed, "policy_rejected", "") retried, err := r.client.Retry(r.ctx, failed) if err != nil { t.Fatal(err) } r.running(runner) if _, err := r.client.Cancel(r.ctx, retried.ID); err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameCancel) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) runner.Send(r.ctx, "c-"+retried.ID, wire.FrameTurn, wire.TurnReport{TurnID: retried.ID, Attempt: retried.Attempt, State: wire.TurnCancelled, Reason: "cancelled"}) r.turnIs(retried.ID, wire.TurnCancelled) if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+retried.ID+`">

Stopped.

`) { t.Fatal("a stopped retry's note") } if next := r.say(runner, "New words", "k2"); strings.Join(next.PersonText, "|") != "New words" { t.Fatalf("a stopped retry's words rode on %q", next.PersonText) } }