package thin import ( "context" "errors" "log/slog" "slices" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" "github.com/coder/websocket" ) // fakeGlancer is a glance harness: up or not, answering reply after // delay, failing with err, or holding until its deadline. type fakeGlancer struct { mu sync.Mutex up bool reply string err error delay time.Duration block bool prompts []string warmed int closed bool } func (g *fakeGlancer) Glance(ctx context.Context, prompt string) (string, error) { g.mu.Lock() g.prompts = append(g.prompts, prompt) reply, err, delay, block := g.reply, g.err, g.delay, g.block g.mu.Unlock() if block { <-ctx.Done() return "", ctx.Err() } select { case <-time.After(delay): case <-ctx.Done(): return "", ctx.Err() } return reply, err } func (g *fakeGlancer) Warm(context.Context) error { g.mu.Lock() defer g.mu.Unlock() g.warmed++ g.up = true return nil } func (g *fakeGlancer) Up() bool { g.mu.Lock() defer g.mu.Unlock() return g.up } func (g *fakeGlancer) Close() { g.mu.Lock() defer g.mu.Unlock() g.closed, g.up = true, false } func (g *fakeGlancer) seen() ([]string, int) { g.mu.Lock() defer g.mu.Unlock() return append([]string(nil), g.prompts...), g.warmed } // streamingCoordinator streams its first words after pause and the rest // after then, and replies. type streamingCoordinator struct{ pause, then time.Duration } func (c *streamingCoordinator) Turn(ctx context.Context, _ TurnInput, emit func(string)) TurnResult { select { case <-time.After(c.pause): case <-ctx.Done(): return TurnResult{Reason: "cancelled"} } emit("Here ") time.Sleep(c.then) emit("it is.") return TurnResult{Text: "Here it is."} } func (c *streamingCoordinator) Close() {} // glanceRig is an engine with one fake Assistant harness and one fake // glance harness; out is what went to the instance, in order. type glanceRig struct { e *Engine state *State g *fakeGlancer mu sync.Mutex out []string sent []wire.GlanceReport logs strings.Builder speak bool } func newGlanceRig(t *testing.T, g *fakeGlancer, coord Coordinator) (*glanceRig, context.Context) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } r := &glanceRig{state: state, g: g, speak: true} logger := slog.New(slog.NewTextHandler(writerFunc(func(p []byte) (int, error) { r.mu.Lock() defer r.mu.Unlock() return r.logs.Write(p) }), &slog.HandlerOptions{Level: slog.LevelDebug})) r.e = &Engine{State: state, Logger: logger, Notify: func() {}, GlanceWithin: 400 * time.Millisecond, Emit: func(d wire.DeltaReport) { r.mu.Lock() defer r.mu.Unlock() r.out = append(r.out, "delta:"+d.Text) }, Open: func(string, string, runner.AccountBinding) (Coordinator, error) { return coord, nil }, Glance: func(string, runner.AccountBinding) (Glancer, error) { return g, nil }, SendGlance: func(s wire.GlanceReport) { r.mu.Lock() defer r.mu.Unlock() r.out = append(r.out, "glance:"+s.Text) r.sent = append(r.sent, s) }, Glances: func() bool { r.mu.Lock() defer r.mu.Unlock() return r.speak }, } if err := r.e.Start(ctx); err != nil { t.Fatal(err) } t.Cleanup(func() { cancel() r.e.Wait() state.Close() }) return r, ctx } // turn runs one turn and returns its phase line. func (r *glanceRig) turn(t *testing.T, ctx context.Context, m wire.MessageCommand) string { t.Helper() m.Person, m.Attempt = "ana.maria@example.com", 1 if err := r.state.Accept(ctx, "f-"+m.TurnID, m); err != nil { t.Fatal(err) } r.e.Wake(m.Person, m.Lane) deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { r.mu.Lock() logs := r.logs.String() r.mu.Unlock() for _, l := range strings.Split(logs, "\n") { if strings.Contains(l, `msg="assistant turn"`) && strings.Contains(l, "turn="+m.TurnID+" ") { return l } } if m.Lane != wire.LaneAssistant && strings.Contains(r.outString(), "delta:it is.") { return "" } time.Sleep(10 * time.Millisecond) } t.Fatalf("turn %s did not end:\n%s", m.TurnID, r.logs.String()) return "" } // warm warms the person's glance harness, as the turn before or the // Assistant's warm-up would. func (r *glanceRig) warm(t *testing.T) { t.Helper() r.e.mu.Lock() w := r.e.worker(workerKey{"ana.maria@example.com", wire.LaneAssistant}) r.e.mu.Unlock() r.e.warmGlance("ana.maria@example.com", w, runner.AccountBinding{}) waitWarm(t, "the glance harness", func() bool { _, n := r.g.seen(); return n > 0 }) } func (r *glanceRig) outString() string { r.mu.Lock() defer r.mu.Unlock() return strings.Join(r.out, "|") } // An Assistant person turn's glance reaches the instance before the // reply's first words: one clean line for the turn's attempt, written // from the person's newest message alone, never their name. func TestAssistantGlanceBeforeFirstDelta(t *testing.T) { g := &fakeGlancer{up: true, reply: "**Looking** into your\nwebsite now"} r, ctx := newGlanceRig(t, g, &streamingCoordinator{pause: 200 * time.Millisecond}) r.warm(t) 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"}}}) if got := r.outString(); got != "glance:Looking into your website now|delta:Here |delta:it is." { t.Fatalf("sent %s", got) } if s := r.sent[0]; s.TurnID != "ta" || s.Attempt != 1 { t.Fatalf("glance %+v", s) } prompts, _ := g.seen() if len(prompts) != 1 || !strings.Contains(prompts[0], "fix my website please") { t.Fatalf("prompt %q", prompts) } for _, never := range []string{"older words", "tail words", "Ana", "maria", "example.com"} { if strings.Contains(prompts[0], never) { t.Fatalf("the prompt holds %q: %s", never, prompts[0]) } } if !strings.Contains(line, "glance=sent") || !strings.Contains(line, "glance_ms=") { t.Fatalf("phase line %s", line) } } // A glance that cannot be sent in time, fails, says something it must // not, is no progress line, or comes after the reply began is not sent // at all; small talk asks for none. The turn goes on as before and the // phase line says why. A cold harness is not started for the turn // (nothing waits for it) but warmed after it. func TestAssistantGlanceDropped(t *testing.T) { for _, c := range []struct { name, want string g *fakeGlancer pause time.Duration speak bool asked bool message string }{ {"timeout", "glance=timeout", &fakeGlancer{up: true, block: true}, 700 * time.Millisecond, true, true, ""}, {"slow", "glance=timeout", &fakeGlancer{up: true, reply: "Looking now", delay: 600 * time.Millisecond}, 900 * time.Millisecond, true, true, ""}, {"failed", "glance=failed", &fakeGlancer{up: true, err: errors.New("provider_failed")}, 300 * time.Millisecond, true, true, ""}, {"filtered", "glance=filtered", &fakeGlancer{up: true, reply: "Asking the team about it"}, 300 * time.Millisecond, true, true, ""}, {"empty", "glance=filtered", &fakeGlancer{up: true, reply: "**\n"}, 300 * time.Millisecond, true, true, ""}, {"late", "glance=late", &fakeGlancer{up: true, reply: "Looking now", delay: 200 * time.Millisecond}, 0, true, true, ""}, {"cold", "glance=cold", &fakeGlancer{reply: "Looking now"}, 300 * time.Millisecond, true, false, ""}, {"older_instance", "glance=off", &fakeGlancer{up: true, reply: "Looking now"}, 300 * time.Millisecond, false, false, ""}, // Small talk has no glance: the reply is the answer. {"small_talk", "glance=small_talk", &fakeGlancer{up: true, reply: "Looking now"}, 300 * time.Millisecond, true, false, "Yo."}, {"greeting", "glance=small_talk", &fakeGlancer{up: true, reply: "Looking now"}, 300 * time.Millisecond, true, false, "Good morning, how are you today?"}, // A line that answers, greets or asks is not progress. {"answers", "glance=filtered", &fakeGlancer{up: true, reply: "Yo, Ana."}, 300 * time.Millisecond, true, true, ""}, {"names", "glance=filtered", &fakeGlancer{up: true, reply: "Looking into it, Ana"}, 300 * time.Millisecond, true, true, ""}, {"asks", "glance=filtered", &fakeGlancer{up: true, reply: "Checking which website?"}, 300 * time.Millisecond, true, true, ""}, // A question past the eighth word, which GlanceText cuts away. {"asks_long", "glance=filtered", &fakeGlancer{up: true, reply: "Looking into which of your many older files you mean?"}, 300 * time.Millisecond, true, true, ""}, } { t.Run(c.name, func(t *testing.T) { t.Parallel() coord := &streamingCoordinator{pause: c.pause} if c.name == "late" { // The reply's first words come before the glance, the // rest after it. coord.then = 500 * time.Millisecond } r, ctx := newGlanceRig(t, c.g, coord) r.speak = c.speak if c.name != "cold" && c.speak { r.warm(t) } message := c.message if message == "" { message = "fix my website please" } line := r.turn(t, ctx, wire.MessageCommand{TurnID: "t-" + c.name, Lane: wire.LaneAssistant, Text: message, PersonText: []string{message}}) time.Sleep(700 * time.Millisecond) if got := r.outString(); strings.Contains(got, "glance:") || !strings.Contains(got, "it is.") { t.Fatalf("sent %s", got) } if !strings.Contains(line, c.want) { t.Fatalf("phase line %s, want %s", line, c.want) } prompts, warmed := c.g.seen() if (len(prompts) > 0) != c.asked { t.Fatalf("asked %d times", len(prompts)) } if c.name == "cold" && warmed != 1 { t.Fatalf("a cold glance harness warmed %d times after the turn", warmed) } }) } } // Only an Assistant person turn has a glance: never a team_update, a // Coordinator turn or a job's thread, and nothing is logged for them. func TestAssistantGlanceOnlyPersonTurns(t *testing.T) { g := &fakeGlancer{up: true, reply: "Looking now"} r, ctx := newGlanceRig(t, g, &streamingCoordinator{}) r.warm(t) line := r.turn(t, ctx, wire.MessageCommand{TurnID: "tu", Lane: wire.LaneAssistant, Kind: wire.TurnTeamUpdate, Text: "news"}) if strings.Contains(line, "glance") { t.Fatalf("a team_update has a glance: %s", line) } // Even with a glance harness on the Coordinator's worker, its turn // asks for none. r.e.mu.Lock() cw := r.e.worker(workerKey{"ana.maria@example.com", wire.LaneCoordinator}) cw.glance = g r.e.mu.Unlock() r.turn(t, ctx, wire.MessageCommand{TurnID: "tc", Text: "hello", PersonText: []string{"hello"}}) time.Sleep(200 * time.Millisecond) if prompts, _ := g.seen(); len(prompts) != 0 || strings.Contains(r.outString(), "glance:") { t.Fatalf("asked %q, sent %s", prompts, r.outString()) } } // The glance harness is warmed with the Assistant's (WarmAssistants), // off the Assistant's own worker, and only while a glance slot is free: // with one slot, one person's glance is up and the other's is skipped. func TestAssistantGlanceWarmsWithinSlots(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() for _, p := range []string{"ana@example.com", "bob@example.com"} { if err := state.saveSession(ctx, p, wire.LaneAssistant, "claude", "c1#rule-old", "s-"+p, "t0"); err != nil { t.Fatal(err) } } var mu sync.Mutex glancers := map[string]*fakeGlancer{} opens := &warmOpens{} e := &Engine{State: state, Notify: func() {}, Emit: func(wire.DeltaReport) {}, Open: opens.open, GlanceSlots: 1, Glance: func(person string, _ runner.AccountBinding) (Glancer, error) { mu.Lock() defer mu.Unlock() g := &fakeGlancer{} glancers[person] = g return g, nil }, SendGlance: func(wire.GlanceReport) {}, Glances: func() bool { return true }} if err := e.Start(ctx); err != nil { t.Fatal(err) } defer e.Wait() defer cancel() e.WarmAssistants() warmedGlances := func() int { mu.Lock() defer mu.Unlock() n := 0 for _, g := range glancers { if _, w := g.seen(); w > 0 { n++ } } return n } waitWarm(t, "both Assistants warm", func() bool { a, b := opens.get("ana@example.com", wire.LaneAssistant), opens.get("bob@example.com", wire.LaneAssistant) if len(a) == 0 || len(b) == 0 { return false } wa, _ := a[0].counts() wb, _ := b[0].counts() return wa == 1 && wb == 1 }) waitWarm(t, "one glance warm", func() bool { return warmedGlances() == 1 }) time.Sleep(200 * time.Millisecond) if n := warmedGlances(); n != 1 { t.Fatalf("%d glance harnesses warmed with one slot", n) } } // The glance's first name comes from the person's address as the // instance names members (its local part up to ".", "_", "-" or "+"), // and only when that looks like a name. func TestGlanceFirstName(t *testing.T) { 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": ""} { if got := firstName(in); got != want { t.Fatalf("firstName(%q) = %q, want %q", in, got, want) } } } // The glance prompt carries the newest message, cut to 500 bytes on a // character boundary, and asks for progress alone: never a reply, a // greeting or an answer, and no name to greet anyone by. func TestGlancePrompt(t *testing.T) { long := strings.Repeat("é", 400) p := glancePrompt(long) if strings.Contains(p, strings.Repeat("é", 251)) || !strings.Contains(p, strings.Repeat("é", 250)) || !strings.HasPrefix(p, glancePrefix) { t.Fatalf("prompt %q", p) } if glancePrefix != fakeclaude.GlancePrefix { t.Fatal("the fakes do not know the glance prompt") } for _, want := range []string{"only what you are starting on", "never a reply, a greeting or an answer", "Looking into your request"} { if !strings.Contains(p, want) { t.Fatalf("the prompt lacks %q: %s", want, p) } } // No provider's domain in the rules (the anti-goals): examples stay // neutral. for _, never := range []string{"greet them", "first name", "calendar", "website", "invoice"} { if strings.Contains(p, never) { t.Fatalf("the prompt says %q: %s", never, p) } } } // Small talk and very short messages have no glance: three words or // fewer, or nothing but greetings and pleasantries, in the common // languages. A request, however it opens, has one. func TestGlanceSmallTalk(t *testing.T) { for in, want := range map[string]bool{ "Yo.": true, "hi": true, "Hey there!": true, "thanks a lot": true, "ok": true, "": true, "Fix it please": true, "Check my calendar": true, "Good morning, how are you?": true, "hey how's it going today": true, "Hello Base, how are you doing?": true, "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, "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, } { if got := smallTalk(in); got != want { t.Fatalf("smallTalk(%q) = %v, want %v", in, got, want) } } } // A glance describes progress on what was asked, nothing else: it opens // with a present participle (or "On"), never asks, and never names the // person; any other line is no glance. func TestGlanceProgress(t *testing.T) { for in, want := range map[string]bool{ "Looking into your website": true, "Checking your calendar": true, "On your invoices now": true, "Getting your files together": true, "Revisando tu calendario": true, "Yo, Paul.": false, "Hi Paul": false, "Hey there": false, "Looking into it, Paul": false, "Looking into it for paul": false, "Checking which website?": false, "Sure, I can help": false, "Morning! Looking now": false, "Nothing to report": false, "Something came up": false, "Good evening": false, "": false, } { if got := glanceProgress(in, "Paul"); got != want { t.Fatalf("glanceProgress(%q) = %v, want %v", in, got, want) } } if !glanceProgress("Looking into Paul's site", "") { t.Fatal("no name known, yet a name refused") } } // The link sends a glance before a delta queued after it, at protocol // 23; at 22 it says it speaks none and sends none (Encode refuses it). func TestLinkSendsGlanceBeforeDelta(t *testing.T) { for _, protocol := range []int{wire.ProtocolGlance, wire.ProtocolJobs} { inst := newFakeInstance(t) link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}) c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, []byte(`{"id":"i-welcome","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":`+strconv.Itoa(protocol)+`,"role":"primary"}}`)) read(t, c, wire.FrameSync) if link.Glances() != (protocol == wire.ProtocolGlance) { t.Fatalf("at %d the link speaks glances: %v", protocol, link.Glances()) } link.Glance(wire.GlanceReport{TurnID: "t_1", Attempt: 1, Text: "Looking now"}) link.Delta(wire.DeltaReport{TurnID: "t_1", Attempt: 1, Text: "Hi"}) order(t, c, protocol) // Both waiting for the same flush: the glance still goes first. link.mu.Lock() link.glances = append(link.glances, wire.GlanceReport{TurnID: "t_1", Attempt: 1, Text: "Looking now"}) link.pending = append(link.pending, wire.DeltaReport{TurnID: "t_1", Attempt: 1, Offset: 2, Text: "!"}) link.mu.Unlock() link.Notify() order(t, c, protocol) } } // order reads frames up to the next delta and checks a glance (at 23 // only) came before it. func order(t *testing.T, c *websocket.Conn, protocol int) { t.Helper() { var kinds []string for !slices.Contains(kinds, wire.FrameDelta) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) _, raw, err := c.Read(ctx) cancel() if err != nil { t.Fatal(err) } f, body, err := wire.ParseFrame(raw) if err != nil { t.Fatal(err) } if g, ok := body.(*wire.GlanceReport); ok && (g.Attempt != 1 || g.Text != "Looking now") { t.Fatalf("glance %+v", g) } if f.Type == wire.FrameGlance || f.Type == wire.FrameDelta { kinds = append(kinds, f.Type) } } want := []string{wire.FrameGlance, wire.FrameDelta} if protocol < wire.ProtocolGlance { want = want[1:] } if !slices.Equal(kinds, want) { t.Fatalf("at %d: %v", protocol, kinds) } } } // A glance and its delta queued while a flush is under way (after it // took the queue) both go in the next flush, glance first: never the // delta in this flush and the glance after it. func TestLinkGlanceAndDeltaQueuedMidFlush(t *testing.T) { inst := newFakeInstance(t) var once sync.Once var armed atomic.Pointer[Link] afterTake = func() { if link := armed.Load(); link != nil { once.Do(func() { link.Glance(wire.GlanceReport{TurnID: "t_mid", Attempt: 1, Text: "Looking now"}) link.Delta(wire.DeltaReport{TurnID: "t_mid", Attempt: 1, Text: "Hi"}) }) } } t.Cleanup(func() { afterTake = nil }) link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}) c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, []byte(`{"id":"i-welcome","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":23,"role":"primary"}}`)) read(t, c, wire.FrameSync) armed.Store(link) link.Notify() order(t, c, wire.ProtocolGlance) }