oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "errors"
6 "log/slog"
7 "slices"
8 "strconv"
9 "strings"
10 "sync"
11 "sync/atomic"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/fakeclaude"
16 "amadan.net/oficina/equipo/internal/runner"
17 "amadan.net/oficina/equipo/internal/wire"
18 "github.com/coder/websocket"
19)
20
21// fakeGlancer is a glance harness: up or not, answering reply after
22// delay, failing with err, or holding until its deadline.
23type fakeGlancer struct {
24 mu sync.Mutex
25 up bool
26 reply string
27 err error
28 delay time.Duration
29 block bool
30 prompts []string
31 warmed int
32 closed bool
33}
34
35func (g *fakeGlancer) Glance(ctx context.Context, prompt string) (string, error) {
36 g.mu.Lock()
37 g.prompts = append(g.prompts, prompt)
38 reply, err, delay, block := g.reply, g.err, g.delay, g.block
39 g.mu.Unlock()
40 if block {
41 <-ctx.Done()
42 return "", ctx.Err()
43 }
44 select {
45 case <-time.After(delay):
46 case <-ctx.Done():
47 return "", ctx.Err()
48 }
49 return reply, err
50}
51
52func (g *fakeGlancer) Warm(context.Context) error {
53 g.mu.Lock()
54 defer g.mu.Unlock()
55 g.warmed++
56 g.up = true
57 return nil
58}
59
60func (g *fakeGlancer) Up() bool {
61 g.mu.Lock()
62 defer g.mu.Unlock()
63 return g.up
64}
65
66func (g *fakeGlancer) Close() {
67 g.mu.Lock()
68 defer g.mu.Unlock()
69 g.closed, g.up = true, false
70}
71
72func (g *fakeGlancer) seen() ([]string, int) {
73 g.mu.Lock()
74 defer g.mu.Unlock()
75 return append([]string(nil), g.prompts...), g.warmed
76}
77
78// streamingCoordinator streams its first words after pause and the rest
79// after then, and replies.
80type streamingCoordinator struct{ pause, then time.Duration }
81
82func (c *streamingCoordinator) Turn(ctx context.Context, _ TurnInput, emit func(string)) TurnResult {
83 select {
84 case <-time.After(c.pause):
85 case <-ctx.Done():
86 return TurnResult{Reason: "cancelled"}
87 }
88 emit("Here ")
89 time.Sleep(c.then)
90 emit("it is.")
91 return TurnResult{Text: "Here it is."}
92}
93func (c *streamingCoordinator) Close() {}
94
95// glanceRig is an engine with one fake Assistant harness and one fake
96// glance harness; out is what went to the instance, in order.
97type glanceRig struct {
98 e *Engine
99 state *State
100 g *fakeGlancer
101 mu sync.Mutex
102 out []string
103 sent []wire.GlanceReport
104 logs strings.Builder
105 speak bool
106}
107
108func newGlanceRig(t *testing.T, g *fakeGlancer, coord Coordinator) (*glanceRig, context.Context) {
109 t.Helper()
110 ctx, cancel := context.WithCancel(context.Background())
111 state, err := OpenState(ctx, t.TempDir())
112 if err != nil {
113 t.Fatal(err)
114 }
115 r := &glanceRig{state: state, g: g, speak: true}
116 logger := slog.New(slog.NewTextHandler(writerFunc(func(p []byte) (int, error) {
117 r.mu.Lock()
118 defer r.mu.Unlock()
119 return r.logs.Write(p)
120 }), &slog.HandlerOptions{Level: slog.LevelDebug}))
121 r.e = &Engine{State: state, Logger: logger, Notify: func() {}, GlanceWithin: 400 * time.Millisecond,
122 Emit: func(d wire.DeltaReport) {
123 r.mu.Lock()
124 defer r.mu.Unlock()
125 r.out = append(r.out, "delta:"+d.Text)
126 },
127 Open: func(string, string, runner.AccountBinding) (Coordinator, error) { return coord, nil },
128 Glance: func(string, runner.AccountBinding) (Glancer, error) {
129 return g, nil
130 },
131 SendGlance: func(s wire.GlanceReport) {
132 r.mu.Lock()
133 defer r.mu.Unlock()
134 r.out = append(r.out, "glance:"+s.Text)
135 r.sent = append(r.sent, s)
136 },
137 Glances: func() bool {
138 r.mu.Lock()
139 defer r.mu.Unlock()
140 return r.speak
141 },
142 }
143 if err := r.e.Start(ctx); err != nil {
144 t.Fatal(err)
145 }
146 t.Cleanup(func() {
147 cancel()
148 r.e.Wait()
149 state.Close()
150 })
151 return r, ctx
152}
153
154// turn runs one turn and returns its phase line.
155func (r *glanceRig) turn(t *testing.T, ctx context.Context, m wire.MessageCommand) string {
156 t.Helper()
157 m.Person, m.Attempt = "ana.maria@example.com", 1
158 if err := r.state.Accept(ctx, "f-"+m.TurnID, m); err != nil {
159 t.Fatal(err)
160 }
161 r.e.Wake(m.Person, m.Lane)
162 deadline := time.Now().Add(5 * time.Second)
163 for time.Now().Before(deadline) {
164 r.mu.Lock()
165 logs := r.logs.String()
166 r.mu.Unlock()
167 for _, l := range strings.Split(logs, "\n") {
168 if strings.Contains(l, `msg="assistant turn"`) && strings.Contains(l, "turn="+m.TurnID+" ") {
169 return l
170 }
171 }
172 if m.Lane != wire.LaneAssistant && strings.Contains(r.outString(), "delta:it is.") {
173 return ""
174 }
175 time.Sleep(10 * time.Millisecond)
176 }
177 t.Fatalf("turn %s did not end:\n%s", m.TurnID, r.logs.String())
178 return ""
179}
180
181// warm warms the person's glance harness, as the turn before or the
182// Assistant's warm-up would.
183func (r *glanceRig) warm(t *testing.T) {
184 t.Helper()
185 r.e.mu.Lock()
186 w := r.e.worker(workerKey{"ana.maria@example.com", wire.LaneAssistant})
187 r.e.mu.Unlock()
188 r.e.warmGlance("ana.maria@example.com", w, runner.AccountBinding{})
189 waitWarm(t, "the glance harness", func() bool { _, n := r.g.seen(); return n > 0 })
190}
191
192func (r *glanceRig) outString() string {
193 r.mu.Lock()
194 defer r.mu.Unlock()
195 return strings.Join(r.out, "|")
196}
197
198// An Assistant person turn's glance reaches the instance before the
199// reply's first words: one clean line for the turn's attempt, written
200// from the person's newest message alone, never their name.
201func TestAssistantGlanceBeforeFirstDelta(t *testing.T) {
202 g := &fakeGlancer{up: true, reply: "**Looking** into your\nwebsite now"}
203 r, ctx := newGlanceRig(t, g, &streamingCoordinator{pause: 200 * time.Millisecond})
204 r.warm(t)
205 line := r.turn(t, ctx, wire.MessageCommand{TurnID: "ta", Lane: wire.LaneAssistant, Text: "older words\n\nMessage 2: fix my website please", PersonText: []string{"older words", "fix my website please"}, Tail: []wire.TailMessage{{Role: wire.RolePerson, Text: "tail words"}}})
206 if got := r.outString(); got != "glance:Looking into your website now|delta:Here |delta:it is." {
207 t.Fatalf("sent %s", got)
208 }
209 if s := r.sent[0]; s.TurnID != "ta" || s.Attempt != 1 {
210 t.Fatalf("glance %+v", s)
211 }
212 prompts, _ := g.seen()
213 if len(prompts) != 1 || !strings.Contains(prompts[0], "fix my website please") {
214 t.Fatalf("prompt %q", prompts)
215 }
216 for _, never := range []string{"older words", "tail words", "Ana", "maria", "example.com"} {
217 if strings.Contains(prompts[0], never) {
218 t.Fatalf("the prompt holds %q: %s", never, prompts[0])
219 }
220 }
221 if !strings.Contains(line, "glance=sent") || !strings.Contains(line, "glance_ms=") {
222 t.Fatalf("phase line %s", line)
223 }
224}
225
226// A glance that cannot be sent in time, fails, says something it must
227// not, is no progress line, or comes after the reply began is not sent
228// at all; small talk asks for none. The turn goes on as before and the
229// phase line says why. A cold harness is not started for the turn
230// (nothing waits for it) but warmed after it.
231func TestAssistantGlanceDropped(t *testing.T) {
232 for _, c := range []struct {
233 name, want string
234 g *fakeGlancer
235 pause time.Duration
236 speak bool
237 asked bool
238 message string
239 }{
240 {"timeout", "glance=timeout", &fakeGlancer{up: true, block: true}, 700 * time.Millisecond, true, true, ""},
241 {"slow", "glance=timeout", &fakeGlancer{up: true, reply: "Looking now", delay: 600 * time.Millisecond}, 900 * time.Millisecond, true, true, ""},
242 {"failed", "glance=failed", &fakeGlancer{up: true, err: errors.New("provider_failed")}, 300 * time.Millisecond, true, true, ""},
243 {"filtered", "glance=filtered", &fakeGlancer{up: true, reply: "Asking the team about it"}, 300 * time.Millisecond, true, true, ""},
244 {"empty", "glance=filtered", &fakeGlancer{up: true, reply: "**\n"}, 300 * time.Millisecond, true, true, ""},
245 {"late", "glance=late", &fakeGlancer{up: true, reply: "Looking now", delay: 200 * time.Millisecond}, 0, true, true, ""},
246 {"cold", "glance=cold", &fakeGlancer{reply: "Looking now"}, 300 * time.Millisecond, true, false, ""},
247 {"older_instance", "glance=off", &fakeGlancer{up: true, reply: "Looking now"}, 300 * time.Millisecond, false, false, ""},
248 // Small talk has no glance: the reply is the answer.
249 {"small_talk", "glance=small_talk", &fakeGlancer{up: true, reply: "Looking now"}, 300 * time.Millisecond, true, false, "Yo."},
250 {"greeting", "glance=small_talk", &fakeGlancer{up: true, reply: "Looking now"}, 300 * time.Millisecond, true, false, "Good morning, how are you today?"},
251 // A line that answers, greets or asks is not progress.
252 {"answers", "glance=filtered", &fakeGlancer{up: true, reply: "Yo, Ana."}, 300 * time.Millisecond, true, true, ""},
253 {"names", "glance=filtered", &fakeGlancer{up: true, reply: "Looking into it, Ana"}, 300 * time.Millisecond, true, true, ""},
254 {"asks", "glance=filtered", &fakeGlancer{up: true, reply: "Checking which website?"}, 300 * time.Millisecond, true, true, ""},
255 // A question past the eighth word, which GlanceText cuts away.
256 {"asks_long", "glance=filtered", &fakeGlancer{up: true, reply: "Looking into which of your many older files you mean?"}, 300 * time.Millisecond, true, true, ""},
257 } {
258 t.Run(c.name, func(t *testing.T) {
259 t.Parallel()
260 coord := &streamingCoordinator{pause: c.pause}
261 if c.name == "late" {
262 // The reply's first words come before the glance, the
263 // rest after it.
264 coord.then = 500 * time.Millisecond
265 }
266 r, ctx := newGlanceRig(t, c.g, coord)
267 r.speak = c.speak
268 if c.name != "cold" && c.speak {
269 r.warm(t)
270 }
271 message := c.message
272 if message == "" {
273 message = "fix my website please"
274 }
275 line := r.turn(t, ctx, wire.MessageCommand{TurnID: "t-" + c.name, Lane: wire.LaneAssistant, Text: message, PersonText: []string{message}})
276 time.Sleep(700 * time.Millisecond)
277 if got := r.outString(); strings.Contains(got, "glance:") || !strings.Contains(got, "it is.") {
278 t.Fatalf("sent %s", got)
279 }
280 if !strings.Contains(line, c.want) {
281 t.Fatalf("phase line %s, want %s", line, c.want)
282 }
283 prompts, warmed := c.g.seen()
284 if (len(prompts) > 0) != c.asked {
285 t.Fatalf("asked %d times", len(prompts))
286 }
287 if c.name == "cold" && warmed != 1 {
288 t.Fatalf("a cold glance harness warmed %d times after the turn", warmed)
289 }
290 })
291 }
292}
293
294// Only an Assistant person turn has a glance: never a team_update, a
295// Coordinator turn or a job's thread, and nothing is logged for them.
296func TestAssistantGlanceOnlyPersonTurns(t *testing.T) {
297 g := &fakeGlancer{up: true, reply: "Looking now"}
298 r, ctx := newGlanceRig(t, g, &streamingCoordinator{})
299 r.warm(t)
300 line := r.turn(t, ctx, wire.MessageCommand{TurnID: "tu", Lane: wire.LaneAssistant, Kind: wire.TurnTeamUpdate, Text: "news"})
301 if strings.Contains(line, "glance") {
302 t.Fatalf("a team_update has a glance: %s", line)
303 }
304 // Even with a glance harness on the Coordinator's worker, its turn
305 // asks for none.
306 r.e.mu.Lock()
307 cw := r.e.worker(workerKey{"ana.maria@example.com", wire.LaneCoordinator})
308 cw.glance = g
309 r.e.mu.Unlock()
310 r.turn(t, ctx, wire.MessageCommand{TurnID: "tc", Text: "hello", PersonText: []string{"hello"}})
311 time.Sleep(200 * time.Millisecond)
312 if prompts, _ := g.seen(); len(prompts) != 0 || strings.Contains(r.outString(), "glance:") {
313 t.Fatalf("asked %q, sent %s", prompts, r.outString())
314 }
315}
316
317// The glance harness is warmed with the Assistant's (WarmAssistants),
318// off the Assistant's own worker, and only while a glance slot is free:
319// with one slot, one person's glance is up and the other's is skipped.
320func TestAssistantGlanceWarmsWithinSlots(t *testing.T) {
321 ctx, cancel := context.WithCancel(context.Background())
322 defer cancel()
323 state, err := OpenState(ctx, t.TempDir())
324 if err != nil {
325 t.Fatal(err)
326 }
327 defer state.Close()
328 for _, p := range []string{"ana@example.com", "bob@example.com"} {
329 if err := state.saveSession(ctx, p, wire.LaneAssistant, "claude", "c1#rule-old", "s-"+p, "t0"); err != nil {
330 t.Fatal(err)
331 }
332 }
333 var mu sync.Mutex
334 glancers := map[string]*fakeGlancer{}
335 opens := &warmOpens{}
336 e := &Engine{State: state, Notify: func() {}, Emit: func(wire.DeltaReport) {}, Open: opens.open, GlanceSlots: 1,
337 Glance: func(person string, _ runner.AccountBinding) (Glancer, error) {
338 mu.Lock()
339 defer mu.Unlock()
340 g := &fakeGlancer{}
341 glancers[person] = g
342 return g, nil
343 },
344 SendGlance: func(wire.GlanceReport) {}, Glances: func() bool { return true }}
345 if err := e.Start(ctx); err != nil {
346 t.Fatal(err)
347 }
348 defer e.Wait()
349 defer cancel()
350 e.WarmAssistants()
351 warmedGlances := func() int {
352 mu.Lock()
353 defer mu.Unlock()
354 n := 0
355 for _, g := range glancers {
356 if _, w := g.seen(); w > 0 {
357 n++
358 }
359 }
360 return n
361 }
362 waitWarm(t, "both Assistants warm", func() bool {
363 a, b := opens.get("ana@example.com", wire.LaneAssistant), opens.get("bob@example.com", wire.LaneAssistant)
364 if len(a) == 0 || len(b) == 0 {
365 return false
366 }
367 wa, _ := a[0].counts()
368 wb, _ := b[0].counts()
369 return wa == 1 && wb == 1
370 })
371 waitWarm(t, "one glance warm", func() bool { return warmedGlances() == 1 })
372 time.Sleep(200 * time.Millisecond)
373 if n := warmedGlances(); n != 1 {
374 t.Fatalf("%d glance harnesses warmed with one slot", n)
375 }
376}
377
378// The glance's first name comes from the person's address as the
379// instance names members (its local part up to ".", "_", "-" or "+"),
380// and only when that looks like a name.
381func TestGlanceFirstName(t *testing.T) {
382 for in, want := range map[string]string{"paul@tito.io": "Paul", "ana.maria@example.com": "Ana", "zoë_x@example.com": "Zoë", "j@x.io": "", "info@x.io": "", "owner@example.com": "", "dev42@x.io": "", "": "", "noat": ""} {
383 if got := firstName(in); got != want {
384 t.Fatalf("firstName(%q) = %q, want %q", in, got, want)
385 }
386 }
387}
388
389// The glance prompt carries the newest message, cut to 500 bytes on a
390// character boundary, and asks for progress alone: never a reply, a
391// greeting or an answer, and no name to greet anyone by.
392func TestGlancePrompt(t *testing.T) {
393 long := strings.Repeat("é", 400)
394 p := glancePrompt(long)
395 if strings.Contains(p, strings.Repeat("é", 251)) || !strings.Contains(p, strings.Repeat("é", 250)) || !strings.HasPrefix(p, glancePrefix) {
396 t.Fatalf("prompt %q", p)
397 }
398 if glancePrefix != fakeclaude.GlancePrefix {
399 t.Fatal("the fakes do not know the glance prompt")
400 }
401 for _, want := range []string{"only what you are starting on", "never a reply, a greeting or an answer", "Looking into your request"} {
402 if !strings.Contains(p, want) {
403 t.Fatalf("the prompt lacks %q: %s", want, p)
404 }
405 }
406 // No provider's domain in the rules (the anti-goals): examples stay
407 // neutral.
408 for _, never := range []string{"greet them", "first name", "calendar", "website", "invoice"} {
409 if strings.Contains(p, never) {
410 t.Fatalf("the prompt says %q: %s", never, p)
411 }
412 }
413}
414
415// Small talk and very short messages have no glance: three words or
416// fewer, or nothing but greetings and pleasantries, in the common
417// languages. A request, however it opens, has one.
418func TestGlanceSmallTalk(t *testing.T) {
419 for in, want := range map[string]bool{
420 "Yo.": true, "hi": true, "Hey there!": true, "thanks a lot": true, "ok": true, "": true, "Fix it please": true, "Check my calendar": true,
421 "Good morning, how are you?": true, "hey how's it going today": true, "Hello Base, how are you doing?": true,
422 "Buenos días, ¿qué tal estás?": true, "Bonjour, ça va bien ?": true, "Hallo, wie geht es dir?": true, "Ciao, come stai oggi?": true, "Olá, tudo bem com você?": true,
423 "Could you look at my website?": false, "fix my website please": false, "Hello, can you check my calendar for tomorrow?": false, "Hola, ¿puedes revisar mi web?": false,
424 } {
425 if got := smallTalk(in); got != want {
426 t.Fatalf("smallTalk(%q) = %v, want %v", in, got, want)
427 }
428 }
429}
430
431// A glance describes progress on what was asked, nothing else: it opens
432// with a present participle (or "On"), never asks, and never names the
433// person; any other line is no glance.
434func TestGlanceProgress(t *testing.T) {
435 for in, want := range map[string]bool{
436 "Looking into your website": true, "Checking your calendar": true, "On your invoices now": true, "Getting your files together": true, "Revisando tu calendario": true,
437 "Yo, Paul.": false, "Hi Paul": false, "Hey there": false, "Looking into it, Paul": false, "Looking into it for paul": false, "Checking which website?": false,
438 "Sure, I can help": false, "Morning! Looking now": false, "Nothing to report": false, "Something came up": false, "Good evening": false, "": false,
439 } {
440 if got := glanceProgress(in, "Paul"); got != want {
441 t.Fatalf("glanceProgress(%q) = %v, want %v", in, got, want)
442 }
443 }
444 if !glanceProgress("Looking into Paul's site", "") {
445 t.Fatal("no name known, yet a name refused")
446 }
447}
448
449// The link sends a glance before a delta queued after it, at protocol
450// 23; at 22 it says it speaks none and sends none (Encode refuses it).
451func TestLinkSendsGlanceBeforeDelta(t *testing.T) {
452 for _, protocol := range []int{wire.ProtocolGlance, wire.ProtocolJobs} {
453 inst := newFakeInstance(t)
454 link, _, _, _ := startLink(t, inst.url, &stubCoordinator{})
455 c := <-inst.conns
456 read(t, c, wire.FrameHello)
457 write(t, c, []byte(`{"id":"i-welcome","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":`+strconv.Itoa(protocol)+`,"role":"primary"}}`))
458 read(t, c, wire.FrameSync)
459 if link.Glances() != (protocol == wire.ProtocolGlance) {
460 t.Fatalf("at %d the link speaks glances: %v", protocol, link.Glances())
461 }
462 link.Glance(wire.GlanceReport{TurnID: "t_1", Attempt: 1, Text: "Looking now"})
463 link.Delta(wire.DeltaReport{TurnID: "t_1", Attempt: 1, Text: "Hi"})
464 order(t, c, protocol)
465 // Both waiting for the same flush: the glance still goes first.
466 link.mu.Lock()
467 link.glances = append(link.glances, wire.GlanceReport{TurnID: "t_1", Attempt: 1, Text: "Looking now"})
468 link.pending = append(link.pending, wire.DeltaReport{TurnID: "t_1", Attempt: 1, Offset: 2, Text: "!"})
469 link.mu.Unlock()
470 link.Notify()
471 order(t, c, protocol)
472 }
473}
474
475// order reads frames up to the next delta and checks a glance (at 23
476// only) came before it.
477func order(t *testing.T, c *websocket.Conn, protocol int) {
478 t.Helper()
479 {
480 var kinds []string
481 for !slices.Contains(kinds, wire.FrameDelta) {
482 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
483 _, raw, err := c.Read(ctx)
484 cancel()
485 if err != nil {
486 t.Fatal(err)
487 }
488 f, body, err := wire.ParseFrame(raw)
489 if err != nil {
490 t.Fatal(err)
491 }
492 if g, ok := body.(*wire.GlanceReport); ok && (g.Attempt != 1 || g.Text != "Looking now") {
493 t.Fatalf("glance %+v", g)
494 }
495 if f.Type == wire.FrameGlance || f.Type == wire.FrameDelta {
496 kinds = append(kinds, f.Type)
497 }
498 }
499 want := []string{wire.FrameGlance, wire.FrameDelta}
500 if protocol < wire.ProtocolGlance {
501 want = want[1:]
502 }
503 if !slices.Equal(kinds, want) {
504 t.Fatalf("at %d: %v", protocol, kinds)
505 }
506 }
507}
508
509// A glance and its delta queued while a flush is under way (after it
510// took the queue) both go in the next flush, glance first: never the
511// delta in this flush and the glance after it.
512func TestLinkGlanceAndDeltaQueuedMidFlush(t *testing.T) {
513 inst := newFakeInstance(t)
514 var once sync.Once
515 var armed atomic.Pointer[Link]
516 afterTake = func() {
517 if link := armed.Load(); link != nil {
518 once.Do(func() {
519 link.Glance(wire.GlanceReport{TurnID: "t_mid", Attempt: 1, Text: "Looking now"})
520 link.Delta(wire.DeltaReport{TurnID: "t_mid", Attempt: 1, Text: "Hi"})
521 })
522 }
523 }
524 t.Cleanup(func() { afterTake = nil })
525 link, _, _, _ := startLink(t, inst.url, &stubCoordinator{})
526 c := <-inst.conns
527 read(t, c, wire.FrameHello)
528 write(t, c, []byte(`{"id":"i-welcome","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":23,"role":"primary"}}`))
529 read(t, c, wire.FrameSync)
530 armed.Store(link)
531 link.Notify()
532 order(t, c, wire.ProtocolGlance)
533}
534