| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "slices" |
| 7 | "strconv" |
| 8 | "sync" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner" |
| 13 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "github.com/coder/websocket" |
| 16 | ) |
| 17 | |
| 18 | // warmCoordinator records its warm-ups and turns. |
| 19 | type warmCoordinator struct { |
| 20 | person string |
| 21 | mu sync.Mutex |
| 22 | warmed int |
| 23 | turns []string |
| 24 | done chan string |
| 25 | } |
| 26 | |
| 27 | func (c *warmCoordinator) Warm(context.Context) error { |
| 28 | c.mu.Lock() |
| 29 | defer c.mu.Unlock() |
| 30 | c.warmed++ |
| 31 | return nil |
| 32 | } |
| 33 | |
| 34 | func (c *warmCoordinator) Turn(_ context.Context, in TurnInput, _ func(string)) TurnResult { |
| 35 | c.mu.Lock() |
| 36 | c.turns = append(c.turns, in.TurnID) |
| 37 | c.mu.Unlock() |
| 38 | if c.done != nil { |
| 39 | c.done <- in.TurnID |
| 40 | } |
| 41 | return TurnResult{Text: "ok"} |
| 42 | } |
| 43 | func (c *warmCoordinator) Close() {} |
| 44 | |
| 45 | func (c *warmCoordinator) counts() (int, int) { |
| 46 | c.mu.Lock() |
| 47 | defer c.mu.Unlock() |
| 48 | return c.warmed, len(c.turns) |
| 49 | } |
| 50 | |
| 51 | // warmOpens is an Engine.Open that hands out warmCoordinators and |
| 52 | // remembers each one by person and lane. |
| 53 | type warmOpens struct { |
| 54 | mu sync.Mutex |
| 55 | opened map[workerKey][]*warmCoordinator |
| 56 | done chan string |
| 57 | } |
| 58 | |
| 59 | func (o *warmOpens) open(person, lane string, _ runner.AccountBinding) (Coordinator, error) { |
| 60 | o.mu.Lock() |
| 61 | defer o.mu.Unlock() |
| 62 | c := &warmCoordinator{person: person, done: o.done} |
| 63 | if o.opened == nil { |
| 64 | o.opened = map[workerKey][]*warmCoordinator{} |
| 65 | } |
| 66 | k := workerKey{person, lane} |
| 67 | o.opened[k] = append(o.opened[k], c) |
| 68 | return c, nil |
| 69 | } |
| 70 | |
| 71 | func (o *warmOpens) get(person, lane string) []*warmCoordinator { |
| 72 | o.mu.Lock() |
| 73 | defer o.mu.Unlock() |
| 74 | return append([]*warmCoordinator(nil), o.opened[workerKey{person, lane}]...) |
| 75 | } |
| 76 | |
| 77 | func (o *warmOpens) keys() []workerKey { |
| 78 | o.mu.Lock() |
| 79 | defer o.mu.Unlock() |
| 80 | var out []workerKey |
| 81 | for k := range o.opened { |
| 82 | out = append(out, k) |
| 83 | } |
| 84 | return out |
| 85 | } |
| 86 | |
| 87 | func waitWarm(t *testing.T, what string, ok func() bool) { |
| 88 | t.Helper() |
| 89 | deadline := time.Now().Add(5 * time.Second) |
| 90 | for !ok() { |
| 91 | if time.Now().After(deadline) { |
| 92 | t.Fatalf("timed out waiting for %s", what) |
| 93 | } |
| 94 | time.Sleep(10 * time.Millisecond) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // The runner warms the Assistant lane of each person who used it lately |
| 99 | // (a session or a run in the last week), and only theirs: never a |
| 100 | // person who only talks to the Coordinator, nor one whose Assistant was |
| 101 | // last used long ago. The first turn after runs on the warmed harness: |
| 102 | // no new open, no new process. |
| 103 | func TestAssistantWarmsOnlyUsedLanes(t *testing.T) { |
| 104 | ctx, cancel := context.WithCancel(context.Background()) |
| 105 | defer cancel() |
| 106 | state, err := OpenState(ctx, t.TempDir()) |
| 107 | if err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | defer state.Close() |
| 111 | ana, bob, cy, dee := "ana@example.com", "bob@example.com", "cy@example.com", "dee@example.com" |
| 112 | if err := state.saveSession(ctx, ana, wire.LaneAssistant, "claude", "c1#rule-old", "s-ana", "t0"); err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | if err := state.saveSession(ctx, bob, wire.LaneCoordinator, "claude", "c1#rule-x", "s-bob", "t0"); err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | if err := state.saveSession(ctx, cy, wire.LaneAssistant, "claude", "c1#rule-old", "s-cy", "t0"); err != nil { |
| 119 | t.Fatal(err) |
| 120 | } |
| 121 | old := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339Nano) |
| 122 | if _, err := state.db.ExecContext(ctx, "UPDATE sessions_lane SET updated_at=? WHERE person=?", old, cy); err != nil { |
| 123 | t.Fatal(err) |
| 124 | } |
| 125 | // dee's Assistant ran a turn yesterday but has no session row (it |
| 126 | // was forgotten); a finished run counts as use. |
| 127 | if _, err := state.db.ExecContext(ctx, "INSERT INTO runs(turn_id, person, attempt, state, text, tail, lane, created_at) VALUES('td', ?, 1, ?, '', '[]', ?, ?)", dee, runDone, wire.LaneAssistant, time.Now().Add(-24*time.Hour).UTC().Format(time.RFC3339Nano)); err != nil { |
| 128 | t.Fatal(err) |
| 129 | } |
| 130 | opens := &warmOpens{done: make(chan string, 4)} |
| 131 | e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: opens.open} |
| 132 | if err := e.Start(ctx); err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | defer e.Wait() |
| 136 | defer cancel() |
| 137 | e.WarmAssistants() |
| 138 | waitWarm(t, "two warm-ups", func() bool { |
| 139 | a, d := opens.get(ana, wire.LaneAssistant), opens.get(dee, wire.LaneAssistant) |
| 140 | if len(a) != 1 || len(d) != 1 { |
| 141 | return false |
| 142 | } |
| 143 | wa, _ := a[0].counts() |
| 144 | wd, _ := d[0].counts() |
| 145 | return wa == 1 && wd == 1 |
| 146 | }) |
| 147 | time.Sleep(100 * time.Millisecond) |
| 148 | keys := opens.keys() |
| 149 | if len(keys) != 2 || !slices.Contains(keys, workerKey{ana, wire.LaneAssistant}) || !slices.Contains(keys, workerKey{dee, wire.LaneAssistant}) { |
| 150 | t.Fatalf("opened %v, want only ana's and dee's Assistant", keys) |
| 151 | } |
| 152 | |
| 153 | // Warming again (a reconnect) while the harness is up opens nothing new. |
| 154 | e.WarmAssistants() |
| 155 | if err := state.Accept(ctx, "f1", wire.MessageCommand{Person: ana, TurnID: "ta", Attempt: 1, Text: "hello", Lane: wire.LaneAssistant}); err != nil { |
| 156 | t.Fatal(err) |
| 157 | } |
| 158 | e.Wake(ana, wire.LaneAssistant) |
| 159 | select { |
| 160 | case got := <-opens.done: |
| 161 | if got != "ta" { |
| 162 | t.Fatalf("ran %s", got) |
| 163 | } |
| 164 | case <-time.After(5 * time.Second): |
| 165 | t.Fatal("the Assistant's turn did not run") |
| 166 | } |
| 167 | a := opens.get(ana, wire.LaneAssistant) |
| 168 | if len(a) != 1 { |
| 169 | t.Fatalf("the first turn after the warm-up opened %d harnesses", len(a)) |
| 170 | } |
| 171 | if _, turns := a[0].counts(); turns != 1 { |
| 172 | t.Fatalf("the warmed harness ran %d turns", turns) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // chooser is a ConnChooser that gives one binding, or none. |
| 177 | type chooser struct { |
| 178 | b runner.AccountBinding |
| 179 | err error |
| 180 | } |
| 181 | |
| 182 | func (c *chooser) Choose(context.Context, string, string, string, []string) (runner.AccountBinding, connect.Choice, error) { |
| 183 | return c.b, connect.Choice{}, c.err |
| 184 | } |
| 185 | func (c *chooser) Limit(string, connect.Limit) time.Time { return time.Time{} } |
| 186 | func (c *chooser) Observe(string, connect.Limit, string) {} |
| 187 | func (c *chooser) LimitedFrom(string) *wire.Switched { return nil } |
| 188 | func (c *chooser) SignInAgain(string) {} |
| 189 | func (c *chooser) Answered(string) {} |
| 190 | func (c *chooser) NextCheck(string) time.Time { return time.Time{} } |
| 191 | |
| 192 | // A warm-up takes the connection a turn would (Conns) and runs only with |
| 193 | // the execution lease confirmed: no connection, or no lease, warms |
| 194 | // nothing and opens nothing. |
| 195 | func TestAssistantWarmNeedsConnectionAndLease(t *testing.T) { |
| 196 | for _, c := range []struct { |
| 197 | name string |
| 198 | conns *chooser |
| 199 | authorize func(context.Context) error |
| 200 | want int |
| 201 | }{ |
| 202 | {"no_connection", &chooser{err: ErrNoConnection}, nil, 0}, |
| 203 | {"no_lease", &chooser{b: runner.AccountBinding{ID: "c1", Provider: "claude"}}, func(context.Context) error { return ErrNoAuthority }, 0}, |
| 204 | {"chosen", &chooser{b: runner.AccountBinding{ID: "c1", Provider: "claude"}}, func(context.Context) error { return nil }, 1}, |
| 205 | } { |
| 206 | t.Run(c.name, func(t *testing.T) { |
| 207 | ctx, cancel := context.WithCancel(context.Background()) |
| 208 | defer cancel() |
| 209 | state, err := OpenState(ctx, t.TempDir()) |
| 210 | if err != nil { |
| 211 | t.Fatal(err) |
| 212 | } |
| 213 | defer state.Close() |
| 214 | p := "ana@example.com" |
| 215 | if err := state.saveSession(ctx, p, wire.LaneAssistant, "claude", "c1#rule-old", "s", "t0"); err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | opens := &warmOpens{} |
| 219 | e := &Engine{State: state, Conns: c.conns, Authorize: c.authorize, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: opens.open} |
| 220 | if err := e.Start(ctx); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | defer e.Wait() |
| 224 | defer cancel() |
| 225 | e.WarmAssistants() |
| 226 | if c.want > 0 { |
| 227 | waitWarm(t, "a warm-up", func() bool { |
| 228 | a := opens.get(p, wire.LaneAssistant) |
| 229 | if len(a) != 1 { |
| 230 | return false |
| 231 | } |
| 232 | w, _ := a[0].counts() |
| 233 | return w == 1 |
| 234 | }) |
| 235 | return |
| 236 | } |
| 237 | time.Sleep(300 * time.Millisecond) |
| 238 | if got := opens.keys(); len(got) != 0 { |
| 239 | t.Fatalf("opened %v", got) |
| 240 | } |
| 241 | }) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | // Opening Base (the instance's warm command, protocol 24) warms that |
| 246 | // one person's Assistant under the same rule as a sync: only an |
| 247 | // Assistant they used lately. A person who only talks to the |
| 248 | // Coordinator, whose Assistant was last used long ago, or who is |
| 249 | // unknown here warms nothing. |
| 250 | func TestAssistantWarmOnOpen(t *testing.T) { |
| 251 | ctx, cancel := context.WithCancel(context.Background()) |
| 252 | defer cancel() |
| 253 | state, err := OpenState(ctx, t.TempDir()) |
| 254 | if err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | defer state.Close() |
| 258 | ana, bob, cy := "ana@example.com", "bob@example.com", "cy@example.com" |
| 259 | for _, s := range []struct{ person, lane string }{{ana, wire.LaneAssistant}, {bob, wire.LaneCoordinator}, {cy, wire.LaneAssistant}} { |
| 260 | if err := state.saveSession(ctx, s.person, s.lane, "claude", "c1#rule", "s-"+s.person, "t0"); err != nil { |
| 261 | t.Fatal(err) |
| 262 | } |
| 263 | } |
| 264 | old := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339Nano) |
| 265 | if _, err := state.db.ExecContext(ctx, "UPDATE sessions_lane SET updated_at=? WHERE person=?", old, cy); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | opens := &warmOpens{} |
| 269 | e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: opens.open} |
| 270 | if err := e.Start(ctx); err != nil { |
| 271 | t.Fatal(err) |
| 272 | } |
| 273 | defer e.Wait() |
| 274 | defer cancel() |
| 275 | for _, p := range []string{bob, cy, "zed@example.com"} { |
| 276 | e.WarmAssistant(p) |
| 277 | } |
| 278 | time.Sleep(300 * time.Millisecond) |
| 279 | if got := opens.keys(); len(got) != 0 { |
| 280 | t.Fatalf("opened %v", got) |
| 281 | } |
| 282 | e.WarmAssistant(ana) |
| 283 | waitWarm(t, "ana's warm-up", func() bool { |
| 284 | a := opens.get(ana, wire.LaneAssistant) |
| 285 | if len(a) != 1 { |
| 286 | return false |
| 287 | } |
| 288 | w, _ := a[0].counts() |
| 289 | return w == 1 |
| 290 | }) |
| 291 | if got := opens.keys(); len(got) != 1 { |
| 292 | t.Fatalf("opened %v", got) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // The link warms on the instance's warm command at protocol 24, with |
| 297 | // the lease confirmed first, and acks it. Below 24 there is no warm |
| 298 | // command: one that came anyway warms nothing. |
| 299 | func TestLinkWarmsOnOpen(t *testing.T) { |
| 300 | for _, protocol := range []int{wire.ProtocolWarm, wire.ProtocolGlance} { |
| 301 | t.Run(strconv.Itoa(protocol), func(t *testing.T) { |
| 302 | inst := newFakeInstance(t) |
| 303 | coord := &warmCoordinator{} |
| 304 | startLink(t, inst.url, coord, func(s *State) { |
| 305 | if err := s.saveSession(context.Background(), "owner@example.com", wire.LaneAssistant, "claude", "c1#rule", "s1", "t0"); err != nil { |
| 306 | t.Fatal(err) |
| 307 | } |
| 308 | }) |
| 309 | c := <-inst.conns |
| 310 | read(t, c, wire.FrameHello) |
| 311 | write(t, c, []byte(`{"id":"i-welcome","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":`+strconv.Itoa(protocol)+`,"role":"primary"}}`)) |
| 312 | readAny(t, c, wire.FrameSync) |
| 313 | write(t, c, []byte(`{"id":"c9","type":"warm","data":{"person":"owner@example.com"}}`)) |
| 314 | if protocol < wire.ProtocolWarm { |
| 315 | ackLeases(c) |
| 316 | time.Sleep(500 * time.Millisecond) |
| 317 | if w, _ := coord.counts(); w != 0 { |
| 318 | t.Fatalf("warmed %d times at %d", w, protocol) |
| 319 | } |
| 320 | return |
| 321 | } |
| 322 | ack := readAny(t, c, wire.FrameAck) |
| 323 | var a wire.Ack |
| 324 | json.Unmarshal(ack.Data, &a) |
| 325 | if a.ID != "c9" { |
| 326 | t.Fatalf("ack %+v", a) |
| 327 | } |
| 328 | // The warm-up confirms the lease first. |
| 329 | ackLeases(c) |
| 330 | waitWarm(t, "the warm-up", func() bool { w, _ := coord.counts(); return w == 1 }) |
| 331 | }) |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | // readAny reads frames up to the first of kind, whatever its shape. |
| 336 | func readAny(t *testing.T, c *websocket.Conn, kind string) wire.Frame { |
| 337 | t.Helper() |
| 338 | for { |
| 339 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 340 | _, raw, err := c.Read(ctx) |
| 341 | cancel() |
| 342 | if err != nil { |
| 343 | t.Fatalf("waiting for %s: %v", kind, err) |
| 344 | } |
| 345 | if f, _, err := wire.ParseFrame(raw); err == nil && f.Type == kind { |
| 346 | return f |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | // ackLeases confirms every lease the runner asks for from now on, as |
| 352 | // the instance does for the current connection, and reads past the rest. |
| 353 | func ackLeases(c *websocket.Conn) { |
| 354 | go func() { |
| 355 | for { |
| 356 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 357 | _, raw, err := c.Read(ctx) |
| 358 | cancel() |
| 359 | if err != nil { |
| 360 | return |
| 361 | } |
| 362 | if f, _, err := wire.ParseFrame(raw); err == nil && f.Type == wire.FrameLease { |
| 363 | ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 364 | raw, _ := json.Marshal(ack) |
| 365 | c.Write(context.Background(), websocket.MessageText, raw) |
| 366 | } |
| 367 | } |
| 368 | }() |
| 369 | } |
| 370 | |
| 371 | // An Assistant process stays up four hours unused, warmed or after a |
| 372 | // turn, so a person who comes back within an afternoon finds it up; a |
| 373 | // Coordinator process still closes after Idle. |
| 374 | func TestAssistantIdleCloseFourHours(t *testing.T) { |
| 375 | var o ClaudeOptions |
| 376 | o.defaults() |
| 377 | if o.WarmIdle != 4*time.Hour || DefaultWarmIdle != 4*time.Hour { |
| 378 | t.Fatalf("warm idle %s", o.WarmIdle) |
| 379 | } |
| 380 | assistant := coordBase{o: o, lane: wire.LaneAssistant} |
| 381 | coordinator := coordBase{o: o, lane: wire.LaneCoordinator} |
| 382 | if assistant.idleAfterTurn() != 4*time.Hour || coordinator.idleAfterTurn() != DefaultIdle { |
| 383 | t.Fatalf("idle after a turn: Assistant %s, Coordinator %s", assistant.idleAfterTurn(), coordinator.idleAfterTurn()) |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | // upCoordinator is a warmCoordinator that says it is up. |
| 388 | type upCoordinator struct{ warmCoordinator } |
| 389 | |
| 390 | func (c *upCoordinator) Up() bool { return true } |
| 391 | |
| 392 | // A harness already up is not warmed again (nor logged as a warm-up): |
| 393 | // Base opened right after a turn finds it up and only the glance may |
| 394 | // still need warming. |
| 395 | func TestAssistantWarmSkipsUpHarness(t *testing.T) { |
| 396 | ctx, cancel := context.WithCancel(context.Background()) |
| 397 | defer cancel() |
| 398 | state, err := OpenState(ctx, t.TempDir()) |
| 399 | if err != nil { |
| 400 | t.Fatal(err) |
| 401 | } |
| 402 | defer state.Close() |
| 403 | p := "ana@example.com" |
| 404 | if err := state.saveSession(ctx, p, wire.LaneAssistant, "claude", "c1#rule", "s", "t0"); err != nil { |
| 405 | t.Fatal(err) |
| 406 | } |
| 407 | coord := &upCoordinator{} |
| 408 | g := &fakeGlancer{} |
| 409 | e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, |
| 410 | Open: func(string, string, runner.AccountBinding) (Coordinator, error) { return coord, nil }, |
| 411 | Glance: func(string, runner.AccountBinding) (Glancer, error) { return g, nil }, |
| 412 | SendGlance: func(wire.GlanceReport) {}, Glances: func() bool { return true }} |
| 413 | if err := e.Start(ctx); err != nil { |
| 414 | t.Fatal(err) |
| 415 | } |
| 416 | defer e.Wait() |
| 417 | defer cancel() |
| 418 | e.WarmAssistant(p) |
| 419 | waitWarm(t, "the glance", func() bool { _, n := g.seen(); return n == 1 }) |
| 420 | if w, _ := coord.counts(); w != 0 { |
| 421 | t.Fatalf("an up harness warmed %d times", w) |
| 422 | } |
| 423 | } |
| 424 | |