| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "log/slog" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | ) |
| 14 | |
| 15 | // packRig is a person's Assistant conversation to build packs from. |
| 16 | type packRig struct { |
| 17 | t *testing.T |
| 18 | h *abilitiesHarness |
| 19 | n int |
| 20 | now time.Time |
| 21 | } |
| 22 | |
| 23 | func newPackRig(t *testing.T) *packRig { |
| 24 | h := newAbilitiesHarness(t) |
| 25 | r := &packRig{t: t, h: h, now: time.Date(2026, 11, 28, 9, 30, 0, 0, time.UTC)} |
| 26 | if err := h.s.db.G.Create(&zoneRecord{Person: abPerson, Zone: "Europe/Dublin", Source: ZoneDevice, UpdatedAt: r.now}).Error; err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | return r |
| 30 | } |
| 31 | |
| 32 | // say is a person turn at ago before now with one composer message; |
| 33 | // looked marks it as having run a lookup in state. |
| 34 | func (r *packRig) say(text string, ago time.Duration, looked string) turnRecord { |
| 35 | r.t.Helper() |
| 36 | r.n++ |
| 37 | at := r.now.Add(-ago) |
| 38 | turn := turnRecord{ID: "t" + strconv.Itoa(r.n), Person: abPerson, State: wire.TurnReplied, Kind: wire.TurnPerson, Lane: wire.LaneAssistant, CreatedAt: at, UpdatedAt: at} |
| 39 | m := messageRecord{ID: "m" + strconv.Itoa(r.n), Person: abPerson, IdempotencyKey: "k" + strconv.Itoa(r.n), Role: wire.RolePerson, Origin: originComposer, Text: text, TurnID: turn.ID, Lane: wire.LaneAssistant, CreatedAt: at} |
| 40 | for _, row := range []any{&turn, &m} { |
| 41 | if err := r.h.s.db.G.Create(row).Error; err != nil { |
| 42 | r.t.Fatal(err) |
| 43 | } |
| 44 | } |
| 45 | if looked != "" { |
| 46 | if err := r.h.s.db.G.Create(&lookupRecord{ID: "lk" + strconv.Itoa(r.n), Person: abPerson, TurnID: turn.ID, Attempt: 1, CallID: "c" + strconv.Itoa(r.n), State: looked, CreatedAt: at}).Error; err != nil { |
| 47 | r.t.Fatal(err) |
| 48 | } |
| 49 | } |
| 50 | return turn |
| 51 | } |
| 52 | |
| 53 | func (r *packRig) pack(turn turnRecord) wire.LookupPack { |
| 54 | r.t.Helper() |
| 55 | var out wire.LookupPack |
| 56 | if err := r.h.s.tx(context.Background(), func(t *txn) error { |
| 57 | var err error |
| 58 | var ok bool |
| 59 | out, ok, err = t.lookupPack(abPerson, turn, r.now) |
| 60 | if err == nil && !ok { |
| 61 | r.t.Fatal("no pack") |
| 62 | } |
| 63 | return err |
| 64 | }); err != nil { |
| 65 | r.t.Fatal(err) |
| 66 | } |
| 67 | return out |
| 68 | } |
| 69 | |
| 70 | // The pack is the question now, the zone's city and today's date there. |
| 71 | func TestQuestionPackContents(t *testing.T) { |
| 72 | r := newPackRig(t) |
| 73 | p := r.pack(r.say("What's the weather in Dublin?", 0, "")) |
| 74 | if p.Question != "What's the weather in Dublin?" || p.City != "Dublin" || p.Date != "2026-11-28, Saturday" || p.Earlier != nil { |
| 75 | t.Errorf("pack %+v", p) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // Earlier messages that didn't run a lookup, or are older than 30 |
| 80 | // minutes, never reach the pack, even for a follow-up. |
| 81 | func TestPackExcludesUnrelatedHistory(t *testing.T) { |
| 82 | r := newPackRig(t) |
| 83 | r.say("My test results came back, what do they mean?", 10*time.Minute, "") |
| 84 | r.say("What's the weather in Galway?", 40*time.Minute, lookupShown) |
| 85 | if p := r.pack(r.say("And tomorrow?", 0, "")); p.Earlier != nil { |
| 86 | t.Errorf("pack %+v", p) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | func TestPackFollowUpOnly(t *testing.T) { |
| 91 | r := newPackRig(t) |
| 92 | r.say("What's the weather in Dublin?", 5*time.Minute, lookupShown) |
| 93 | for _, q := range []string{"And tomorrow?", "What about Cork?", "¿Y mañana?"} { |
| 94 | if p := r.pack(r.say(q, 0, "")); len(p.Earlier) != 1 || p.Earlier[0] != "What's the weather in Dublin?" { |
| 95 | t.Errorf("%q: %+v", q, p) |
| 96 | } |
| 97 | } |
| 98 | r = newPackRig(t) |
| 99 | r.say("Is the medical clinic on Main Street open?", 5*time.Minute, lookupShown) |
| 100 | for _, q := range []string{"How much is a flight to Lisbon?", "Bitcoin price?", "Dublin weather?", "Tomorrow?", "And can you also tell me what the best way to get there would be?", "Andorra weather"} { |
| 101 | if p := r.pack(r.say(q, 0, "")); p.Earlier != nil { |
| 102 | t.Errorf("%q held %v", q, p.Earlier) |
| 103 | } |
| 104 | } |
| 105 | // A chain of follow-ups holds at most 2, the second only because the |
| 106 | // first was a follow-up itself. |
| 107 | r = newPackRig(t) |
| 108 | r.say("What's the weather in Dublin?", 9*time.Minute, lookupShown) |
| 109 | r.say("And tomorrow?", 6*time.Minute, lookupShown) |
| 110 | r.say("And Sunday?", 3*time.Minute, lookupFailed) |
| 111 | if p := r.pack(r.say("And Monday?", 0, "")); len(p.Earlier) != 2 || p.Earlier[0] != "And Sunday?" || p.Earlier[1] != "And tomorrow?" { |
| 112 | t.Errorf("chain: %+v", p.Earlier) |
| 113 | } |
| 114 | r = newPackRig(t) |
| 115 | r.say("Weather in Cork?", 6*time.Minute, lookupShown) |
| 116 | r.say("What's the weather in Dublin?", 3*time.Minute, lookupShown) |
| 117 | if p := r.pack(r.say("And tomorrow?", 0, "")); len(p.Earlier) != 1 { |
| 118 | t.Errorf("the second came though the first wasn't a follow-up: %+v", p.Earlier) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // A message from before the person's last reset never comes in. |
| 123 | func TestPackAfterReset(t *testing.T) { |
| 124 | r := newPackRig(t) |
| 125 | r.say("What's the weather in Dublin?", 10*time.Minute, lookupShown) |
| 126 | if err := r.h.s.db.G.Create(&commandRecord{Person: abPerson, Kind: wire.FrameReset, Body: "{}", CreatedAt: r.now.Add(-5 * time.Minute)}).Error; err != nil { |
| 127 | t.Fatal(err) |
| 128 | } |
| 129 | if p := r.pack(r.say("And tomorrow?", 0, "")); p.Earlier != nil { |
| 130 | t.Errorf("before the reset: %+v", p.Earlier) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func TestPackZoneCityAndDate(t *testing.T) { |
| 135 | for zone, want := range map[string]string{"Europe/Dublin": "Dublin", "America/Argentina/Buenos_Aires": "Buenos Aires", "UTC": "", "Etc/GMT+3": ""} { |
| 136 | if got := zoneCity(zone); got != want { |
| 137 | t.Errorf("%s: %q", zone, got) |
| 138 | } |
| 139 | } |
| 140 | r := newPackRig(t) |
| 141 | r.now = time.Date(2026, 11, 28, 23, 30, 0, 0, time.UTC) |
| 142 | if err := r.h.s.db.G.Model(&zoneRecord{}).Where("person = ?", abPerson).Update("zone", "Pacific/Auckland").Error; err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | if p := r.pack(r.say("Weather?", 0, "")); p.City != "Auckland" || p.Date != "2026-11-29, Sunday" { |
| 146 | t.Errorf("pack %+v", p) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | func TestPackFourKiB(t *testing.T) { |
| 151 | r := newPackRig(t) |
| 152 | r.say(strings.Repeat("Dublin weather today? ", 210), 5*time.Minute, lookupShown) |
| 153 | p := r.pack(r.say("And tomorrow?", 0, "")) |
| 154 | if packSize(p) > wire.MaxLookupPack || p.Question != "And tomorrow?" || p.Earlier != nil { |
| 155 | t.Errorf("%d bytes, %+v", packSize(p), p.Earlier) |
| 156 | } |
| 157 | r = newPackRig(t) |
| 158 | p = r.pack(r.say(strings.Repeat("é", 4000), 0, "")) |
| 159 | if packSize(p) > wire.MaxLookupPack || !strings.HasPrefix(p.Question, "éé") { |
| 160 | t.Errorf("%d bytes", packSize(p)) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func TestPackRespectsEpoch(t *testing.T) { |
| 165 | t.Skip("MCP Task 34 (the lane epoch) has not landed; the reset rule (TestPackAfterReset) stands in until it does") |
| 166 | } |
| 167 | |
| 168 | // A lookup step goes live to the primary's current connection: never to |
| 169 | // runner_commands or a log; its answer counts only from that connection |
| 170 | // and for that nonce; a connection that ends fails it, and nothing is |
| 171 | // resent. |
| 172 | func TestLookupStepEphemeral(t *testing.T) { |
| 173 | h := newAbilitiesHarness(t) |
| 174 | var logs bytes.Buffer |
| 175 | h.s.SetLogger(slog.New(slog.NewTextHandler(&logs, nil))) |
| 176 | const sentinel = "SENTINEL-PAGE-TEXT-77" |
| 177 | sent := make(chan wire.LookupStep, 4) |
| 178 | live, detach := h.s.attachLive("RUNNER1", wire.ProtocolLookup, func(_ context.Context, f wire.Frame) error { |
| 179 | body, err := f.Decode() |
| 180 | if err == nil && f.Type == wire.FrameLookupStep && !f.Durable() { |
| 181 | sent <- *body.(*wire.LookupStep) |
| 182 | } |
| 183 | return err |
| 184 | }) |
| 185 | step := wire.LookupStep{Lookup: "lk1", Attempt: 1, Stage: wire.LookupStageAnswer, Pages: []wire.LookupPage{{URL: "https://www.met.ie/", Text: sentinel}}, Results: []wire.SearchResult{{}}} |
| 186 | done := make(chan wire.LookupResult, 1) |
| 187 | go func() { |
| 188 | r, _ := h.s.lookupStep(context.Background(), abPerson, step) |
| 189 | done <- r |
| 190 | }() |
| 191 | got := <-sent |
| 192 | if got.Person != abPerson || got.Nonce == "" { |
| 193 | t.Fatalf("step %+v", got) |
| 194 | } |
| 195 | // A stale answer (another nonce), and one from another runner, are |
| 196 | // dropped; the right one is taken. |
| 197 | h.s.deliverLookup(live, wire.LookupResult{Lookup: "lk1", Attempt: 1, Nonce: "old", Stage: wire.LookupStageAnswer, Answer: "stale"}) |
| 198 | h.s.deliverLookup(&liveConn{runner: "RUNNER1"}, wire.LookupResult{Lookup: "lk1", Attempt: 1, Nonce: got.Nonce, Stage: wire.LookupStageAnswer, Answer: "elsewhere"}) |
| 199 | h.s.deliverLookup(live, wire.LookupResult{Lookup: "lk1", Attempt: 1, Nonce: got.Nonce, Stage: wire.LookupStageAnswer, Answer: "Rain."}) |
| 200 | if r := <-done; r.Answer != "Rain." || r.Code != "" { |
| 201 | t.Errorf("result %+v", r) |
| 202 | } |
| 203 | var n int64 |
| 204 | if err := h.s.db.G.Model(&commandRecord{}).Where("body LIKE ?", "%"+sentinel+"%").Count(&n).Error; err != nil || n != 0 { |
| 205 | t.Errorf("runner_commands holds the page: %d %v", n, err) |
| 206 | } |
| 207 | // The connection ends while a step waits: it fails, and isn't sent |
| 208 | // again. |
| 209 | go func() { |
| 210 | r, _ := h.s.lookupStep(context.Background(), abPerson, wire.LookupStep{Lookup: "lk2", Attempt: 1, Stage: wire.LookupStageQuery}) |
| 211 | done <- r |
| 212 | }() |
| 213 | <-sent |
| 214 | detach() |
| 215 | if r := <-done; r.Code != wire.CodeLookupFailed { |
| 216 | t.Errorf("after the connection ended: %+v", r) |
| 217 | } |
| 218 | select { |
| 219 | case s := <-sent: |
| 220 | t.Errorf("resent: %+v", s) |
| 221 | default: |
| 222 | } |
| 223 | // No connection, or one below 36: failed at once. |
| 224 | if r, _ := h.s.lookupStep(context.Background(), abPerson, step); r.Code != wire.CodeLookupFailed { |
| 225 | t.Errorf("no connection: %+v", r) |
| 226 | } |
| 227 | _, old := h.s.attachLive("RUNNER1", wire.Protocol35, func(context.Context, wire.Frame) error { t.Error("sent below 36"); return nil }) |
| 228 | defer old() |
| 229 | if r, _ := h.s.lookupStep(context.Background(), abPerson, step); r.Code != wire.CodeLookupFailed { |
| 230 | t.Errorf("below 36: %+v", r) |
| 231 | } |
| 232 | if strings.Contains(logs.String(), sentinel) { |
| 233 | t.Error("a log line holds the page") |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // With no zone known, no city is made up and the date is UTC's (Astra |
| 238 | // phase 3 round 1, P2). |
| 239 | func TestPackNoZoneNoCity(t *testing.T) { |
| 240 | r := newPackRig(t) |
| 241 | if err := r.h.s.db.G.Where("person = ?", abPerson).Delete(&zoneRecord{}).Error; err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | r.now = time.Date(2026, 11, 28, 23, 59, 59, 0, time.UTC) |
| 245 | if p := r.pack(r.say("Weather?", 0, "")); p.City != "" || p.Date != "2026-11-28, Saturday" { |
| 246 | t.Errorf("pack %+v", p) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // A connection replaced while its step waits: the step fails, and an |
| 251 | // answer that comes on the old connection afterwards counts for nothing |
| 252 | // (Astra phase 3 round 2, P2). |
| 253 | func TestLookupStepConnectionReplaced(t *testing.T) { |
| 254 | h := newAbilitiesHarness(t) |
| 255 | sent := make(chan wire.LookupStep, 2) |
| 256 | send := func(_ context.Context, f wire.Frame) error { |
| 257 | body, err := f.Decode() |
| 258 | if err == nil { |
| 259 | sent <- *body.(*wire.LookupStep) |
| 260 | } |
| 261 | return err |
| 262 | } |
| 263 | old, _ := h.s.attachLive("RUNNER1", wire.ProtocolLookup, send) |
| 264 | done := make(chan wire.LookupResult, 1) |
| 265 | go func() { |
| 266 | r, _ := h.s.lookupStep(context.Background(), abPerson, wire.LookupStep{Lookup: "lk", Attempt: 1, Stage: wire.LookupStageQuery}) |
| 267 | done <- r |
| 268 | }() |
| 269 | step := <-sent |
| 270 | _, detach := h.s.attachLive("RUNNER1", wire.ProtocolLookup, send) |
| 271 | defer detach() |
| 272 | h.s.deliverLookup(old, wire.LookupResult{Lookup: "lk", Attempt: 1, Nonce: step.Nonce, Stage: wire.LookupStageQuery, Queries: []string{"q"}}) |
| 273 | if r := <-done; r.Code != wire.CodeLookupFailed || r.Queries != nil { |
| 274 | t.Errorf("result %+v", r) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // A private message batched into an earlier lookup turn never comes in: |
| 279 | // that turn's question is its newest composer message (Astra phase 3 |
| 280 | // round 3, P1). |
| 281 | func TestPackSkipsBatchedMessages(t *testing.T) { |
| 282 | r := newPackRig(t) |
| 283 | r.say("What's the weather in Dublin?", 9*time.Minute, lookupShown) |
| 284 | turn := r.say("My test results came back positive.", 6*time.Minute, lookupShown) |
| 285 | if err := r.h.s.db.G.Create(&messageRecord{ID: "batched", Person: abPerson, IdempotencyKey: "kb", Role: wire.RolePerson, Origin: originComposer, Text: "And Cork?", TurnID: turn.ID, Lane: wire.LaneAssistant, CreatedAt: r.now.Add(-6 * time.Minute)}).Error; err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | p := r.pack(r.say("And tomorrow?", 0, "")) |
| 289 | if len(p.Earlier) != 2 || p.Earlier[0] != "And Cork?" || p.Earlier[1] != "What's the weather in Dublin?" { |
| 290 | t.Errorf("earlier %v", p.Earlier) |
| 291 | } |
| 292 | for _, e := range p.Earlier { |
| 293 | if strings.Contains(e, "test results") { |
| 294 | t.Errorf("the batched message came in: %v", p.Earlier) |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |