| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "regexp" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // Try again (Paul, 2026-11-22): the note under a failed reply says why, |
| 19 | // names the account it ran on, and offers Try again: a new turn takes |
| 20 | // the failed turn's exchange over as its next attempt (chat.Retry). The |
| 21 | // message is never sent twice, and its words never ride again as |
| 22 | // unanswered. |
| 23 | |
| 24 | // retryRig is a rig whose runner is online with conns (toolHello's one |
| 25 | // Claude connection, claude-a, labelled with the owner's email, when nil). |
| 26 | func retryRig(t *testing.T, conns []wire.HeldConnection) (*rig, *FakeRunner) { |
| 27 | t.Helper() |
| 28 | r := newRig(t) |
| 29 | runner := r.dial(0) |
| 30 | hello := toolHello(runner.Welcome.Generation) |
| 31 | if conns != nil { |
| 32 | hello.Connections = conns |
| 33 | } |
| 34 | if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) |
| 38 | return r, runner |
| 39 | } |
| 40 | |
| 41 | // running is the next message frame, acked, once its turn runs. |
| 42 | func (r *rig) running(runner *FakeRunner) *wire.MessageCommand { |
| 43 | r.t.Helper() |
| 44 | f, body, err := runner.Expect(r.ctx, wire.FrameMessage) |
| 45 | if err != nil { |
| 46 | r.t.Fatal(err) |
| 47 | } |
| 48 | runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 49 | cmd := body.(*wire.MessageCommand) |
| 50 | r.turnIs(cmd.TurnID, wire.TurnRunning) |
| 51 | return cmd |
| 52 | } |
| 53 | |
| 54 | // say sends text and returns its running turn's frame. |
| 55 | func (r *rig) say(runner *FakeRunner, text, key string) *wire.MessageCommand { |
| 56 | r.t.Helper() |
| 57 | if _, err := r.client.Send(r.ctx, text, key); err != nil { |
| 58 | r.t.Fatal(err) |
| 59 | } |
| 60 | return r.running(runner) |
| 61 | } |
| 62 | |
| 63 | // attempt is a turn's current attempt (a retry is its failed turn's next). |
| 64 | func (r *rig) attempt(id string) int64 { |
| 65 | r.t.Helper() |
| 66 | v, err := r.client.Turn(r.ctx, id) |
| 67 | if err != nil { |
| 68 | r.t.Fatal(err) |
| 69 | } |
| 70 | return v.Attempt |
| 71 | } |
| 72 | |
| 73 | // failOn fails a running turn for reason; local names the connection |
| 74 | // its attempt ran on (a usage row, as a runner reports one), or none. |
| 75 | func (r *rig) failOn(runner *FakeRunner, id, reason, local string) { |
| 76 | r.t.Helper() |
| 77 | attempt := r.attempt(id) |
| 78 | if local != "" { |
| 79 | 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}}}) |
| 80 | } |
| 81 | runner.Send(r.ctx, "f-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: attempt, State: wire.TurnFailed, Reason: reason}) |
| 82 | r.turnIs(id, wire.TurnFailed) |
| 83 | } |
| 84 | |
| 85 | // tryAgain posts the page's Try again as the owner's browser, from site. |
| 86 | func (r *rig) tryAgain(id, site string) (int, string) { |
| 87 | r.t.Helper() |
| 88 | req, _ := http.NewRequest("POST", r.inst.URL+"/conversation/turns/"+id+"/retry", strings.NewReader(url.Values{}.Encode())) |
| 89 | req.AddCookie(r.inst.Cookie()) |
| 90 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 91 | origin := r.inst.URL |
| 92 | if site != "same-origin" { |
| 93 | origin = "https://foreign.example" |
| 94 | } |
| 95 | req.Header.Set("Origin", origin) |
| 96 | req.Header.Set("Sec-Fetch-Site", site) |
| 97 | res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) |
| 98 | if err != nil { |
| 99 | r.t.Fatal(err) |
| 100 | } |
| 101 | io.Copy(io.Discard, res.Body) |
| 102 | res.Body.Close() |
| 103 | return res.StatusCode, res.Header.Get("Location") |
| 104 | } |
| 105 | |
| 106 | func (r *rig) count(query string, args ...any) int { |
| 107 | r.t.Helper() |
| 108 | var n int |
| 109 | if err := r.inst.DB.Writer().QueryRow(query, args...).Scan(&n); err != nil { |
| 110 | r.t.Fatal(err) |
| 111 | } |
| 112 | return n |
| 113 | } |
| 114 | |
| 115 | func retryForm(id string) string { |
| 116 | return `<form method="post" action="/conversation/turns/` + id + `/retry"` |
| 117 | } |
| 118 | |
| 119 | func TestContractRetryAnswersAgain(t *testing.T) { |
| 120 | r, runner := retryRig(t, nil) |
| 121 | const words = "Where is the login bug?" |
| 122 | failed := r.say(runner, words, "k1").TurnID |
| 123 | r.failOn(runner, failed, "provider_failed", "claude-a") |
| 124 | page := r.inst.Get(t, "/conversation") |
| 125 | if !strings.Contains(page, `data-ended="`+failed+`"><p>Claude (owner@example.com) stopped before finishing the reply. Try again.</p>`+retryForm(failed)) { |
| 126 | t.Fatal("the failed reply's note lacks its account or Try again") |
| 127 | } |
| 128 | // Production's policy refuses inline styles and scripts. |
| 129 | _, note, _ := strings.Cut(page, `data-ended="`+failed) |
| 130 | note, _, _ = strings.Cut(note, "</li>") |
| 131 | if inlineStyle.MatchString(note) || regexp.MustCompile(`(?i)\son[a-z]+=|<script|javascript:`).MatchString(note) { |
| 132 | t.Fatalf("the note is not CSP-clean: %s", note) |
| 133 | } |
| 134 | ids := r.turnIs(failed, wire.TurnFailed).MessageIDs |
| 135 | if status, at := r.tryAgain(failed, "same-origin"); status != http.StatusSeeOther || at != "/conversation" { |
| 136 | t.Fatalf("Try again: %d %s", status, at) |
| 137 | } |
| 138 | cmd := r.running(runner) |
| 139 | if cmd.TurnID == failed || cmd.Attempt != 2 || strings.Join(cmd.PersonText, "|") != words || withoutProjectContext(t, cmd.Text) != words { |
| 140 | t.Fatalf("the retry's frame %s %d %q %q", cmd.TurnID, cmd.Attempt, cmd.PersonText, cmd.Text) |
| 141 | } |
| 142 | for _, m := range cmd.Tail { |
| 143 | if m.Text == words { |
| 144 | t.Fatal("the retried words ride in the tail too") |
| 145 | } |
| 146 | } |
| 147 | retried := cmd.TurnID |
| 148 | // A double tap, and a device asking too: one turn. |
| 149 | if status, _ := r.tryAgain(failed, "same-origin"); status != http.StatusSeeOther { |
| 150 | t.Fatalf("second Try again: %d", status) |
| 151 | } |
| 152 | if again, err := r.client.Retry(r.ctx, failed); err != nil || again.ID != retried || !slices.Equal(again.MessageIDs, ids) { |
| 153 | t.Fatalf("the device's retry %+v %v", again, err) |
| 154 | } |
| 155 | // The failed turn keeps its reason, and its messages are the retry's. |
| 156 | if old := r.turnIs(failed, wire.TurnFailed); old.Reason != "provider_failed" || len(old.MessageIDs) != 0 { |
| 157 | t.Fatalf("the failed turn after Try again %+v", old) |
| 158 | } |
| 159 | if n := r.count("SELECT count(*) FROM chat_turns WHERE retry_of = ?", failed); n != 1 { |
| 160 | t.Fatalf("%d retries queued", n) |
| 161 | } |
| 162 | if n := r.count("SELECT count(*) FROM chat_messages WHERE text = ?", words); n != 1 { |
| 163 | t.Fatalf("the message is there %d times", n) |
| 164 | } |
| 165 | // The note and its action go once the retry runs; the message shows once. |
| 166 | page = r.inst.Get(t, "/conversation") |
| 167 | if strings.Contains(page, `data-ended="`+failed) || strings.Contains(page, "/retry") || strings.Count(page, words) != 1 || !strings.Contains(page, `data-turn="`+retried+`"`) { |
| 168 | t.Fatal("the page after Try again") |
| 169 | } |
| 170 | runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: retried, Attempt: cmd.Attempt, Text: "It is in the session check."}) |
| 171 | r.turnIs(retried, wire.TurnReplied) |
| 172 | // Answered now: the words are in the transcript, carried no further. |
| 173 | next := r.say(runner, "Thanks", "k2") |
| 174 | if strings.Join(next.PersonText, "|") != "Thanks" || strings.Contains(next.Text, words) { |
| 175 | t.Fatalf("the answered words rode again %q %q", next.PersonText, next.Text) |
| 176 | } |
| 177 | var tail []string |
| 178 | for _, m := range next.Tail { |
| 179 | tail = append(tail, m.Text) |
| 180 | } |
| 181 | if strings.Join(tail, "|") != words+"|It is in the session check." { |
| 182 | t.Fatalf("the tail after the retry %q", tail) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // A retry that also fails before the model ran leaves the words |
| 187 | // unanswered once: the next message carries them, once. |
| 188 | func TestContractRetryFailedAgainCarriesOnce(t *testing.T) { |
| 189 | r, runner := retryRig(t, nil) |
| 190 | const words = "Please check the build" |
| 191 | failed := r.say(runner, words, "k1").TurnID |
| 192 | r.failOn(runner, failed, "policy_rejected", "") |
| 193 | retried, err := r.client.Retry(r.ctx, failed) |
| 194 | if err != nil || retried.State != wire.TurnQueued && retried.State != wire.TurnRunning { |
| 195 | t.Fatalf("retry %+v %v", retried, err) |
| 196 | } |
| 197 | if cmd := r.running(runner); cmd.TurnID != retried.ID || strings.Contains(cmd.Text, "Not yet answered") { |
| 198 | t.Fatalf("the retry carried its own words %q", cmd.Text) |
| 199 | } |
| 200 | r.failOn(runner, retried.ID, "turn_timeout", "") |
| 201 | // The retried turn is the latest: its note, and Try again again. |
| 202 | page := r.inst.Get(t, "/conversation") |
| 203 | if !strings.Contains(page, `data-ended="`+retried.ID+`"><p>The reply ran out of time on your runner. Try again, or ask for less at once.</p>`+retryForm(retried.ID)) { |
| 204 | t.Fatal("a failed retry's note") |
| 205 | } |
| 206 | if again, err := r.client.Retry(r.ctx, retried.ID); err != nil || again.ID == retried.ID { |
| 207 | t.Fatalf("retrying the retry %+v %v", again, err) |
| 208 | } else if cmd := r.running(runner); strings.Join(cmd.PersonText, "|") != words { |
| 209 | t.Fatalf("the second retry %q", cmd.PersonText) |
| 210 | } else { |
| 211 | r.failOn(runner, cmd.TurnID, "policy_rejected", "") |
| 212 | } |
| 213 | next := r.say(runner, "Any news?", "k2") |
| 214 | if strings.Join(next.PersonText, "|") != words+"|Any news?" || strings.Count(next.Text, words) != 1 { |
| 215 | t.Fatalf("the unanswered words %q %q", next.PersonText, next.Text) |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | // Only the latest failed turn can be tried again, while nothing of the |
| 220 | // person's runs, and only by them; a reason another try cannot mend has |
| 221 | // no Try again. |
| 222 | func TestContractRetryRefused(t *testing.T) { |
| 223 | r, runner := retryRig(t, nil) |
| 224 | first := r.say(runner, "One", "k1").TurnID |
| 225 | r.failOn(runner, first, "provider_failed", "") |
| 226 | second := r.say(runner, "Two", "k2").TurnID |
| 227 | r.failOn(runner, second, "superseded", "") |
| 228 | if _, err := r.client.Retry(r.ctx, first); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "not_retryable") { |
| 229 | t.Fatalf("an older failed turn: %v", err) |
| 230 | } |
| 231 | if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+second+`"><p>The coordinator could not answer this message.</p>`+retryForm(second)) { |
| 232 | t.Fatal("an unknown reason's note offers Try again") |
| 233 | } |
| 234 | // Someone else's turn is not theirs to try. |
| 235 | const member = "member@example.com" |
| 236 | if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | other := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member)) |
| 240 | if _, err := other.Retry(r.ctx, second); Status(err) != http.StatusNotFound { |
| 241 | t.Fatalf("another member's retry: %v", err) |
| 242 | } |
| 243 | if _, err := NewClient(r.inst.URL, "").Retry(r.ctx, second); Status(err) != http.StatusUnauthorized { |
| 244 | t.Fatalf("no bearer: %v", err) |
| 245 | } |
| 246 | // From another site, nothing happens. |
| 247 | if status, _ := r.tryAgain(second, "cross-site"); status != http.StatusForbidden { |
| 248 | t.Fatalf("cross-site Try again: %d", status) |
| 249 | } |
| 250 | if n := r.count("SELECT count(*) FROM chat_turns WHERE coalesce(retry_of, '') <> ''"); n != 0 { |
| 251 | t.Fatalf("%d retries queued by refused requests", n) |
| 252 | } |
| 253 | // A newer message running: the failed turn is history. |
| 254 | third := r.say(runner, "Three", "k3").TurnID |
| 255 | if _, err := r.client.Retry(r.ctx, second); Status(err) != http.StatusConflict { |
| 256 | t.Fatalf("with a newer turn running: %v", err) |
| 257 | } |
| 258 | if status, at := r.tryAgain(second, "same-origin"); status != http.StatusSeeOther || at != "/conversation" { |
| 259 | t.Fatalf("a stale Try again: %d %s", status, at) |
| 260 | } |
| 261 | r.failOn(runner, third, wire.ReasonAttachmentUnavailable, "") |
| 262 | page := r.inst.Get(t, "/conversation") |
| 263 | if !strings.Contains(page, `data-ended="`+third+`"><p>A file did not arrive whole on your runner. Attach it again.</p></li>`) { |
| 264 | t.Fatal("a missing file's note offers an action") |
| 265 | } |
| 266 | if _, err := r.client.Retry(r.ctx, third); Status(err) != http.StatusConflict { |
| 267 | t.Fatalf("retrying a missing file: %v", err) |
| 268 | } |
| 269 | if n := r.count("SELECT count(*) FROM chat_turns WHERE coalesce(retry_of, '') <> ''"); n != 0 { |
| 270 | t.Fatalf("%d retries queued by refused requests", n) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // Sign in again: the account's own row on Connections, not Try again. |
| 275 | // A limit that has reset: Try again. |
| 276 | func TestContractRetryAccountActions(t *testing.T) { |
| 277 | reset := time.Now().Add(-time.Minute).UTC() |
| 278 | r, runner := retryRig(t, []wire.HeldConnection{ |
| 279 | {LocalID: "claude-a", Person: Owner, Provider: "claude", Kind: "subscription", Label: Owner, State: wire.ConnSignInAgain}, |
| 280 | {LocalID: "claude-b", Person: Owner, Provider: "claude", Kind: "subscription", Label: "second@example.com", State: wire.ConnLimited, Headroom: &wire.Headroom{ResetsAt: &reset}}, |
| 281 | }) |
| 282 | conns, err := r.client.Connections(r.ctx) |
| 283 | if err != nil { |
| 284 | t.Fatal(err) |
| 285 | } |
| 286 | var signIn string |
| 287 | for _, c := range conns.Items { |
| 288 | if c.LocalID == "claude-a" { |
| 289 | signIn = c.ID |
| 290 | } |
| 291 | } |
| 292 | first := r.say(runner, "One", "k1").TurnID |
| 293 | r.failOn(runner, first, "sign_in_again", "claude-a") |
| 294 | page := r.inst.Get(t, "/conversation") |
| 295 | if signIn == "" || !strings.Contains(page, `data-ended="`+first+`"><p>Claude (owner@example.com) needs you to sign in again.</p><a rst-btn href="/conversation/settings/connections#connection-`+signIn+`" equipo-ended-action data-sign-in-again>Sign in again</a></li>`) { |
| 296 | t.Fatal("sign in again") |
| 297 | } |
| 298 | second := r.say(runner, "Two", "k2").TurnID |
| 299 | r.failOn(runner, second, "limited", "claude-b") |
| 300 | if page = r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+second+`"><p>Claude (second@example.com) reached its usage limit. Try again once it resets, or add another account.</p>`+retryForm(second)) { |
| 301 | t.Fatal("a limit that has reset") |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // A retry waiting behind a move-in that gives way is a queued turn with |
| 306 | // messages of its own, like any: a message sent meanwhile joins it as a |
| 307 | // batch, and nothing in dispatch reads retry_of, so an instance rolled |
| 308 | // back to a version without retries (which ignores the column) sends it |
| 309 | // just the same. The dispatch code is that version's (8dc096b4). |
| 310 | func TestContractRetryWaitingJoinsAndRollsBack(t *testing.T) { |
| 311 | r := newMoveInRig(t) |
| 312 | if _, err := r.client.Send(r.ctx, "hello", "k1"); err != nil { |
| 313 | t.Fatal(err) |
| 314 | } |
| 315 | failed := r.dispatched(wire.TurnPerson).TurnID |
| 316 | r.failOn(r.runner, failed, "policy_rejected", "") |
| 317 | moving := r.moveIn("r-mi-1", wire.TurnMoveIn) |
| 318 | retried, err := r.client.Retry(r.ctx, failed) |
| 319 | if err != nil || retried.State != wire.TurnQueued { |
| 320 | t.Fatalf("retry behind the move-in %+v %v", retried, err) |
| 321 | } |
| 322 | later, err := r.client.Send(r.ctx, "and this", "k2") |
| 323 | if err != nil || later.Turn.ID != retried.ID { |
| 324 | t.Fatalf("a message sent meanwhile %+v %v", later.Turn, err) |
| 325 | } |
| 326 | 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 { |
| 327 | t.Fatalf("the retry holds %d messages, the failed turn %d", own, left) |
| 328 | } |
| 329 | // The rolled-back version knows nothing of retry_of. |
| 330 | if _, err := r.inst.DB.Writer().Exec("UPDATE chat_turns SET retry_of = NULL"); err != nil { |
| 331 | t.Fatal(err) |
| 332 | } |
| 333 | 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 { |
| 334 | t.Fatal(err) |
| 335 | } |
| 336 | if cmd := r.dispatched(wire.TurnPerson); cmd.TurnID != retried.ID || strings.Join(cmd.PersonText, "|") != "hello|and this" { |
| 337 | t.Fatalf("the retry's frame %s %q", cmd.TurnID, cmd.PersonText) |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // A retry the person stopped: they stopped those words, which ride no |
| 342 | // further, as a stopped turn's never do. |
| 343 | func TestContractRetryStoppedCarriesNothing(t *testing.T) { |
| 344 | r, runner := retryRig(t, nil) |
| 345 | failed := r.say(runner, "Old words", "k1").TurnID |
| 346 | r.failOn(runner, failed, "policy_rejected", "") |
| 347 | retried, err := r.client.Retry(r.ctx, failed) |
| 348 | if err != nil { |
| 349 | t.Fatal(err) |
| 350 | } |
| 351 | r.running(runner) |
| 352 | if _, err := r.client.Cancel(r.ctx, retried.ID); err != nil { |
| 353 | t.Fatal(err) |
| 354 | } |
| 355 | f, _, err := runner.Expect(r.ctx, wire.FrameCancel) |
| 356 | if err != nil { |
| 357 | t.Fatal(err) |
| 358 | } |
| 359 | runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 360 | runner.Send(r.ctx, "c-"+retried.ID, wire.FrameTurn, wire.TurnReport{TurnID: retried.ID, Attempt: retried.Attempt, State: wire.TurnCancelled, Reason: "cancelled"}) |
| 361 | r.turnIs(retried.ID, wire.TurnCancelled) |
| 362 | if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+retried.ID+`"><p>Stopped.</p></li>`) { |
| 363 | t.Fatal("a stopped retry's note") |
| 364 | } |
| 365 | if next := r.say(runner, "New words", "k2"); strings.Join(next.PersonText, "|") != "New words" { |
| 366 | t.Fatalf("a stopped retry's words rode on %q", next.PersonText) |
| 367 | } |
| 368 | } |
| 369 | |